sqlite-engine.js 1.2 KB

123456789101112131415161718192021222324252627282930313233
  1. 'use strict';
  2. /**
  3. * SQLite 引擎适配。
  4. *
  5. * Node 侧用内置 node:sqlite 的 DatabaseSync;bun 编译产物里没有这个内置模块,只有 bun:sqlite。
  6. * 两者能力已用 scripts/sqlite-engine-probe.mjs 逐项实测对等(WAL、busy_timeout、CHECK、外键、
  7. * 显式事务、upsert、只读模式),差异只在构造签名,这里抹平后调用方沿用 DatabaseSync 的写法即可。
  8. *
  9. * `.get()` 未命中时 node 返回 undefined、bun 返回 null,两者在本仓库的调用点(`?.` 与 `|| null`)
  10. * 行为一致,因此不额外包装 Statement。
  11. */
  12. const isBun = typeof globalThis.Bun !== 'undefined';
  13. function resolveDatabaseSync() {
  14. if (!isBun) return require('node:sqlite').DatabaseSync;
  15. const { Database } = require('bun:sqlite');
  16. return class BunDatabaseSync extends Database {
  17. constructor(filePath, options = {}) {
  18. // bun 用全小写 readonly;且不给任何 open flag 会直接抛 SQLITE_MISUSE
  19. super(filePath, options.readOnly
  20. ? { readonly: true }
  21. : { create: true, readwrite: true });
  22. }
  23. };
  24. }
  25. module.exports = {
  26. DatabaseSync: resolveDatabaseSync(),
  27. sqliteEngine: isBun ? 'bun:sqlite' : 'node:sqlite',
  28. };