nx-kv 0.28.0 → 0.32.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +198 -0
- package/README.md +15 -1
- package/assets/kv-get/SKILL.md +3 -1
- package/assets/kv-get/references/localget.md +4 -3
- package/assets/kv-get/references/timegoal.md +2 -1
- package/assets/kv-get/references/wait-workflow.md +44 -14
- package/assets/kv-get/references/waitloop.md +6 -4
- package/bin/cli.mjs +18 -1
- package/package.json +7 -4
- package/src/core/atomic-file.js +45 -0
- package/src/core/attachmentdb.js +726 -0
- package/src/core/attachstore.js +123 -80
- package/src/core/config.js +83 -13
- package/src/core/db/bootstrap.js +424 -0
- package/src/core/db/driver.js +234 -0
- package/src/core/db/errors.js +144 -0
- package/src/core/db/import-json.js +1224 -0
- package/src/core/db/index.js +122 -0
- package/src/core/db/migrations/index.js +103 -0
- package/src/core/db/migrations/v1.sql +850 -0
- package/src/core/db/migrations/v2-data.js +149 -0
- package/src/core/db/migrations/v2.sql +89 -0
- package/src/core/db/migrator.js +203 -0
- package/src/core/db/quiet.js +19 -0
- package/src/core/db/seed-templates.js +265 -0
- package/src/core/db/settings.js +54 -0
- package/src/core/db/time.js +96 -0
- package/src/core/db/tx.js +188 -0
- package/src/core/db/verify.js +295 -0
- package/src/core/db/version.js +59 -0
- package/src/core/errors.js +7 -0
- package/src/core/instruction-template.js +129 -94
- package/src/core/keys.js +21 -20
- package/src/core/localatt.js +76 -57
- package/src/core/paths.js +39 -2
- package/src/core/topic-key.js +43 -0
- package/src/core/workflow/project.js +3 -2
- package/src/core/workflow/readiness.js +13 -6
- package/src/core/workflow/types.js +6 -5
- package/src/modules/db/index.js +54 -0
- package/src/modules/db/service.js +273 -0
- package/src/modules/docs/brief.js +11 -1
- package/src/modules/docs/index.js +292 -7
- package/src/modules/docs/knowledge.js +8 -1
- package/src/modules/docs/paths.js +2 -1
- package/src/modules/docs/refs.js +1 -1
- package/src/modules/docs/store.js +19 -1
- package/src/modules/file/index.js +20 -0
- package/src/modules/file/service.js +68 -0
- package/src/modules/localtask/deletion.js +14 -10
- package/src/modules/localtask/events.js +16 -7
- package/src/modules/localtask/index.js +161 -81
- package/src/modules/localtask/move-prims.js +68 -38
- package/src/modules/localtask/move.js +1 -1
- package/src/modules/localtask/panel-presence.js +5 -5
- package/src/modules/localtask/paths.js +16 -18
- package/src/modules/localtask/repo/goals.js +154 -0
- package/src/modules/localtask/repo/index.js +42 -0
- package/src/modules/localtask/repo/links.js +136 -0
- package/src/modules/localtask/repo/open.js +71 -0
- package/src/modules/localtask/repo/presence.js +117 -0
- package/src/modules/localtask/repo/rows.js +157 -0
- package/src/modules/localtask/repo/settings.js +384 -0
- package/src/modules/localtask/repo/snapshot.js +154 -0
- package/src/modules/localtask/repo/tasks.js +333 -0
- package/src/modules/localtask/repo/topics.js +293 -0
- package/src/modules/localtask/service.js +15 -0
- package/src/modules/localtask/store/index.js +8 -9
- package/src/modules/localtask/store/topic-adapter.js +8 -43
- package/src/modules/localtask/store-io.js +19 -161
- package/src/modules/localtask/task-lifecycle.js +216 -148
- package/src/modules/localtask/task-ops.js +195 -114
- package/src/modules/localtask/task-remove.js +151 -79
- package/src/modules/localtask/task-templates.js +41 -62
- package/src/modules/localtask/task-view.js +165 -151
- package/src/modules/localtask/topics.js +89 -80
- package/src/modules/localtask/waiters.js +6 -14
- package/src/modules/localtask/waiting.js +31 -44
- package/src/modules/repos/boards.js +44 -14
- package/src/modules/repos/index.js +28 -2
- package/src/modules/repos/keys.js +2 -1
- package/src/modules/repos/ref.js +6 -6
- package/src/modules/repos/repo/index.js +53 -0
- package/src/modules/repos/repo/open.js +84 -0
- package/src/modules/repos/repo/refs.js +165 -0
- package/src/modules/repos/repo/repos.js +177 -0
- package/src/modules/repos/repo/rows.js +174 -0
- package/src/modules/repos/service.js +375 -130
- package/src/modules/repos/transfer.js +43 -14
- package/src/modules/tasktool/attach.js +732 -86
- package/src/modules/tasktool/delivery-template.js +50 -64
- package/src/modules/tasktool/get.js +6 -27
- package/src/modules/tasktool/groupctx.js +5 -2
- package/src/modules/tasktool/plugins/timegoal-store.js +476 -363
- package/src/modules/tasktool/plugins/waitgoal-config.js +1 -1
- package/src/modules/tasktool/preview.js +28 -34
- package/src/modules/tasktool/system-blocks.js +78 -0
- package/src/modules/tasktool/wait.js +113 -125
- package/src/modules/templates/index.js +19 -4
- package/src/modules/templates/repo/index.js +16 -0
- package/src/modules/templates/repo/open.js +65 -0
- package/src/modules/templates/repo/templates.js +133 -0
- package/src/modules/templates/service.js +130 -119
- package/src/runtime/registry.js +2 -1
- package/src/shared/prompt-blocks.js +307 -0
- package/src/shared/repo-key.js +57 -0
- package/src/shared/task-status.js +105 -0
- package/src/web/frontend/App.jsx +78 -45
- package/src/web/frontend/components/Introduction/docs-modal.jsx +306 -0
- package/src/web/frontend/components/Introduction/index.jsx +23 -72
- package/src/web/frontend/components/Introduction/style.css +35 -28
- package/src/web/frontend/components/board/member-picker.jsx +13 -3
- package/src/web/frontend/components/button/index.jsx +91 -0
- package/src/web/frontend/components/button/style.css +45 -0
- package/src/web/frontend/components/doc/doc-head.jsx +110 -0
- package/src/web/frontend/components/layout/breadcrumb.jsx +24 -13
- package/src/web/frontend/components/layout/crumbs.js +22 -0
- package/src/web/frontend/components/layout/route-crumb.jsx +2 -2
- package/src/web/frontend/components/md/attach-area.jsx +307 -0
- package/src/web/frontend/components/md/attach-common.js +95 -0
- package/src/web/frontend/components/md/attach-modal.jsx +387 -0
- package/src/web/frontend/components/md/attach-picker.jsx +274 -0
- package/src/web/frontend/components/md/composer-launch.js +68 -0
- package/src/web/frontend/components/md/composer-panel.jsx +167 -0
- package/src/web/frontend/components/md/md-panes.jsx +337 -46
- package/src/web/frontend/components/md/sel-menu.jsx +37 -210
- package/src/web/frontend/components/md/task-chain.jsx +2 -5
- package/src/web/frontend/components/md/tool-bar.jsx +75 -40
- package/src/web/frontend/components/repos/desc-modal.jsx +1 -1
- package/src/web/frontend/components/repos/transfer-panel.jsx +4 -0
- package/src/web/frontend/components/sidebar/index.jsx +5 -16
- package/src/web/frontend/components/sidebar/panel.jsx +2 -0
- package/src/web/frontend/components/sidebar/task-children.jsx +11 -1
- package/src/web/frontend/modules/board/board-view.js +31 -13
- package/src/web/frontend/modules/md/attach-mention.js +48 -0
- package/src/web/frontend/modules/md/md-edit-ops.js +24 -0
- package/src/web/frontend/modules/md/md-parse.js +40 -10
- package/src/web/frontend/modules/md/style.css +283 -39
- package/src/web/frontend/modules/md/use-templates.js +3 -1
- package/src/web/frontend/modules/prompts/placeholders.js +0 -13
- package/src/web/frontend/modules/prompts/prompt-editor.jsx +12 -111
- package/src/web/frontend/modules/prompts/style.css +0 -14
- package/src/web/frontend/page/dag/index.jsx +3 -1
- package/src/web/frontend/page/dir/deleted-panel.jsx +63 -0
- package/src/web/frontend/page/dir/index.jsx +137 -4
- package/src/web/frontend/page/dir/landing.jsx +136 -8
- package/src/web/frontend/page/dir/task.jsx +153 -83
- package/src/web/frontend/page/doc/index.jsx +150 -19
- package/src/web/frontend/page/group/index.jsx +39 -2
- package/src/web/frontend/page/overview/index.jsx +11 -5
- package/src/web/frontend/page/refs/index.jsx +122 -0
- package/src/web/frontend/page/refs/style.css +41 -0
- package/src/web/frontend/page/repos/index.jsx +565 -161
- package/src/web/frontend/page/settings/index.jsx +133 -105
- package/src/web/frontend/page/settings/prompt-templates-section.jsx +622 -0
- package/src/web/frontend/page/settings/style.css +161 -12
- package/src/web/frontend/page/settings/task-templates-section.jsx +120 -0
- package/src/web/frontend/page/templates/index.jsx +8 -34
- package/src/web/frontend/panels.jsx +24 -0
- package/src/web/frontend/route-map.js +67 -0
- package/src/web/frontend/style-v2.css +45 -19
- package/src/web/frontend/style.css +443 -15
- package/src/web/frontend/workspace/areas.js +3 -0
- package/src/web/frontend/workspace.js +148 -17
- package/src/web/public/assets/Introduction-BcPrmROW.css +1 -0
- package/src/web/public/assets/Introduction-MAkTZvUX.js +1 -0
- package/src/web/public/assets/{attach-v8BxRJ7p.js → attach-Bw0necIf.js} +1 -1
- package/src/web/public/assets/{cloud-DMotpyNl.js → cloud-CG_hgVn9.js} +3 -3
- package/src/web/public/assets/composer-launch-q1uPzWGo.js +1 -0
- package/src/web/public/assets/composer-panel-S2d6A3fG.js +1 -0
- package/src/web/public/assets/dag-CwY66RrZ.js +1 -0
- package/src/web/public/assets/dir-B_ySdQT1.js +5 -0
- package/src/web/public/assets/group-6sWouRDt.js +1 -0
- package/src/web/public/assets/index-DKncYqtS.js +54 -0
- package/src/web/public/assets/index-DO7b1M3E.css +1 -0
- package/src/web/public/assets/{md-edit-ops-BIXUZ5BM.js → md-edit-ops-ZwnwtEax.js} +10 -10
- package/src/web/public/assets/md-history-BxbOQtPI.js +1 -0
- package/src/web/public/assets/md-panes-Cso2NHbG.js +7 -0
- package/src/web/public/assets/member-picker-BpB9ZpWx.js +1 -0
- package/src/web/public/assets/overview-Bo8ivqRU.js +1 -0
- package/src/web/public/assets/{progress-DRI-n9Gb.js → progress-DPkGjn0P.js} +3 -3
- package/src/web/public/assets/refs-CY4i7PoC.css +1 -0
- package/src/web/public/assets/refs-CskU6rI7.js +1 -0
- package/src/web/public/assets/repos-B_tskNGw.js +9 -0
- package/src/web/public/assets/route-crumb-BZ6ffDRj.js +1 -0
- package/src/web/public/assets/settings-BMTd_p9Y.js +7 -0
- package/src/web/public/assets/settings-qCi-niJC.css +1 -0
- package/src/web/public/assets/task-Cs-9RNQn.js +7 -0
- package/src/web/public/assets/task-status-Bgo2Nfiw.js +1 -0
- package/src/web/public/assets/template-editor-CRxfV218.js +1 -0
- package/src/web/public/assets/templates-Apc3JKXa.js +2 -0
- package/src/web/public/assets/{upload-F3aoeT7X.js → upload-C83Bwy06.js} +1 -1
- package/src/web/public/index.html +4 -3
- package/src/core/json-store.js +0 -219
- package/src/web/frontend/modules/prompts/template-slots.jsx +0 -87
- package/src/web/frontend/page/settings/prompts-section.jsx +0 -531
- package/src/web/public/assets/Introduction-9gBNccF6.js +0 -1
- package/src/web/public/assets/Introduction-B4k08SH9.css +0 -1
- package/src/web/public/assets/dag-B9_B7rnK.js +0 -1
- package/src/web/public/assets/dir-DdMpgTHK.js +0 -3
- package/src/web/public/assets/group-BF2tfUqG.js +0 -1
- package/src/web/public/assets/index-BbAo8n1E.js +0 -50
- package/src/web/public/assets/index-DUxHMjZA.css +0 -1
- package/src/web/public/assets/md-history-DunAB9Pp.js +0 -5
- package/src/web/public/assets/member-picker-CD66NFHl.js +0 -1
- package/src/web/public/assets/overview-_Xza9umy.js +0 -1
- package/src/web/public/assets/repos-BfbPRMJ0.js +0 -10
- package/src/web/public/assets/route-crumb-BHjAXhIY.js +0 -1
- package/src/web/public/assets/settings-CVOnFmxp.js +0 -12
- package/src/web/public/assets/settings-knWtG9Kc.css +0 -1
- package/src/web/public/assets/task-Nw-0PEB4.js +0 -7
- package/src/web/public/assets/template-slots-UVa4FnPn.css +0 -1
- package/src/web/public/assets/template-slots-bXUEg7EO.js +0 -1
- package/src/web/public/assets/templates-cWbR2cCh.js +0 -2
|
@@ -0,0 +1,424 @@
|
|
|
1
|
+
// 打开库并完成「探测 → 建表/导入/升级」的唯一入口。
|
|
2
|
+
//
|
|
3
|
+
// 为什么所有进程都只能走这一条路:迁移逻辑写两套是这类改造最常见的翻车点 ——
|
|
4
|
+
// `nx-kv db migrate` 和「启动时自动迁移」各写一遍,两份最终会给出不同的库。
|
|
5
|
+
// 所以 CLI 子命令、serve、测试夹具全部调这里的同一个 `bootstrap()`。
|
|
6
|
+
//
|
|
7
|
+
// ── 并发(serve 与 CLI 同时首启)──────────────────────────────────────
|
|
8
|
+
//
|
|
9
|
+
// P1: BEGIN IMMEDIATE ── 拿到写锁
|
|
10
|
+
// P2: BEGIN IMMEDIATE ── busy_timeout 等 5s(阻塞在 BEGIN 上,不是阻塞在第一条 INSERT)
|
|
11
|
+
// P1: 校验 → 建表/导入 → 写 meta + user_version → COMMIT
|
|
12
|
+
// P2: 拿到锁 → **重新读** user_version / meta → 已是当前版本 → 空事务 COMMIT
|
|
13
|
+
//
|
|
14
|
+
// 四条要点:
|
|
15
|
+
// 1. 锁必须拿在 `BEGIN IMMEDIATE` 上,**且必须在读版本之前** —— 先读后锁就是
|
|
16
|
+
// TOCTOU:两个进程都读到"没有标志",都去导入(一个成功、一个撞 UNIQUE)。
|
|
17
|
+
// 2. 读版本的动作放在事务内(tx 体的第一行),配合 1 才是双检。
|
|
18
|
+
// 3. 幂等来源:所有动作都是「事务内 + 版本判定」,重复执行到已完成的版本上等于空转。
|
|
19
|
+
// 4. 成功后重命名 legacy 文件(不删),让"再跑一次迁移"物理上不可能。
|
|
20
|
+
//
|
|
21
|
+
// ── 两种拒绝而不是猜的情况 ────────────────────────────────────────────
|
|
22
|
+
//
|
|
23
|
+
// · 库比程序新(user_version > CURRENT):**绝不降级写**。
|
|
24
|
+
// · 有表但没有 meta.store_kind(别人把 SQLite 文件改名成 nxkv.db):
|
|
25
|
+
// **绝不自动建表** —— 那会把别人的库就地改成我们的结构。
|
|
26
|
+
import { existsSync, rmSync, unlinkSync, writeFileSync, renameSync, readFileSync } from 'node:fs';
|
|
27
|
+
import { join } from 'node:path';
|
|
28
|
+
import { attachmentsRootFromEnv, dbPathFromEnv, backupsDirFromEnv, defaultStoreTarget } from '../paths.js';
|
|
29
|
+
import {
|
|
30
|
+
archiveAttachmentManifests,
|
|
31
|
+
syncDocAttachmentIndex,
|
|
32
|
+
syncTaskAttachmentIndex,
|
|
33
|
+
} from '../attachmentdb.js';
|
|
34
|
+
import { badInput } from '../errors.js';
|
|
35
|
+
import { openRaw } from './driver.js';
|
|
36
|
+
import { tx } from './tx.js';
|
|
37
|
+
import {
|
|
38
|
+
CURRENT_SCHEMA_VERSION,
|
|
39
|
+
} from './version.js';
|
|
40
|
+
import {
|
|
41
|
+
backupDatabase,
|
|
42
|
+
countTables,
|
|
43
|
+
fileHasContent,
|
|
44
|
+
getMeta,
|
|
45
|
+
hasMetaTable,
|
|
46
|
+
migrate,
|
|
47
|
+
setMeta,
|
|
48
|
+
storeKindOf,
|
|
49
|
+
userVersion,
|
|
50
|
+
} from './migrator.js';
|
|
51
|
+
import { importLegacy, scanLegacy, ensureSentinelRepo, LEGACY_FILES } from './import-json.js';
|
|
52
|
+
import { seedBuiltinTemplates } from './seed-templates.js';
|
|
53
|
+
import {
|
|
54
|
+
NotNxKvStoreError,
|
|
55
|
+
StoreMigrationError,
|
|
56
|
+
StoreTooNewError,
|
|
57
|
+
isBusyError,
|
|
58
|
+
isReadOnlyError,
|
|
59
|
+
} from './errors.js';
|
|
60
|
+
import { nowMs, stampFileTag } from './time.js';
|
|
61
|
+
|
|
62
|
+
/** `meta.store_kind` 的值:库是 nx-kv 自己建的。 */
|
|
63
|
+
export const STORE_KIND = 'sqlite';
|
|
64
|
+
|
|
65
|
+
/** 当前程序版本(写进 `meta.created_by`,排障时能对上版本)。 */
|
|
66
|
+
export function appVersion() {
|
|
67
|
+
try {
|
|
68
|
+
return JSON.parse(readFileSync(new URL('../../../package.json', import.meta.url), 'utf8')).version;
|
|
69
|
+
} catch {
|
|
70
|
+
return '0.0.0';
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/** 库的当前状态(纯读,不写任何东西)。 */
|
|
75
|
+
export function inspectStore(db) {
|
|
76
|
+
const tables = countTables(db);
|
|
77
|
+
const hasMeta = hasMetaTable(db);
|
|
78
|
+
return {
|
|
79
|
+
path: db.path,
|
|
80
|
+
tables,
|
|
81
|
+
hasMeta,
|
|
82
|
+
storeKind: hasMeta ? storeKindOf(db) : null,
|
|
83
|
+
userVersion: userVersion(db),
|
|
84
|
+
schemaVersion: CURRENT_SCHEMA_VERSION,
|
|
85
|
+
};
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/**
|
|
89
|
+
* 建表 + 必要时导入 + 必要时升级。
|
|
90
|
+
*
|
|
91
|
+
* @param {object} db 连接
|
|
92
|
+
* @param {object} [opts]
|
|
93
|
+
* @param {string} [opts.appDir=APP_DIR] legacy 数据所在目录
|
|
94
|
+
* @param {boolean} [opts.importLegacyData=true] 是否执行 JSON → SQLite 导入
|
|
95
|
+
* @param {boolean} [opts.dryRun=false] 收尾 ROLLBACK(`db migrate --dry-run`)
|
|
96
|
+
* @param {number} [opts.atMs] 时刻兜底
|
|
97
|
+
* @returns {object} { action, createdSchema, upgradedFrom, report, state, imported }
|
|
98
|
+
*/
|
|
99
|
+
export function bootstrap(
|
|
100
|
+
db,
|
|
101
|
+
{ appDir = defaultStoreTarget().appDir, importLegacyData = true, dryRun = false, atMs = nowMs() } = {}
|
|
102
|
+
) {
|
|
103
|
+
const before = inspectStore(db);
|
|
104
|
+
const legacy = scanLegacy(appDir);
|
|
105
|
+
// 迁移上下文:002 的 apply 需要把 manifest.json / docs 树 / 任务正文一起迁走。
|
|
106
|
+
const migrationContext = {
|
|
107
|
+
attachmentsRoot: attachmentsRootFromEnv(),
|
|
108
|
+
docsRoot: process.env.NX_KV_DOCS_DIR || join(appDir, 'docs'),
|
|
109
|
+
atMs,
|
|
110
|
+
};
|
|
111
|
+
const result = {
|
|
112
|
+
action: 'none',
|
|
113
|
+
createdSchema: false,
|
|
114
|
+
upgradedFrom: null,
|
|
115
|
+
backup: null,
|
|
116
|
+
report: null,
|
|
117
|
+
legacyFiles: Object.entries(legacy.files)
|
|
118
|
+
.filter(([, r]) => r && r.ok)
|
|
119
|
+
.map(([kind, r]) => ({ kind, path: r.path })),
|
|
120
|
+
};
|
|
121
|
+
|
|
122
|
+
// ── 只读连接:只探测,不建表、不导入、不升级 ──
|
|
123
|
+
//
|
|
124
|
+
// 理由:诊断类命令(`db status`)不该有副作用;更重要的是**升级必须只发生在一个
|
|
125
|
+
// 地方** —— 拿着只读连接去跑迁移只会得到 "attempt to write a readonly database",
|
|
126
|
+
// 一条完全指不出真因的报错。
|
|
127
|
+
if (db.readOnly) {
|
|
128
|
+
result.action = 'read-only';
|
|
129
|
+
result.state = before;
|
|
130
|
+
return result;
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
// ── 情况 A:库里一张业务表都没有(文件不存在 / 空文件 / 上次中断在建表前)──
|
|
134
|
+
if (before.tables === 0) {
|
|
135
|
+
const out = tx(
|
|
136
|
+
(conn) => {
|
|
137
|
+
// 双检:并发进程可能刚把表建好(锁是在 BEGIN IMMEDIATE 上等的)
|
|
138
|
+
if (countTables(conn) > 0) return { raced: true };
|
|
139
|
+
migrate(conn, { from: 0, context: migrationContext });
|
|
140
|
+
ensureSentinelRepo(conn, atMs); // topics.repo_key 的 FK 目标,无它一条队列都建不出
|
|
141
|
+
setMeta(conn, 'store_kind', STORE_KIND, atMs);
|
|
142
|
+
setMeta(conn, 'schema_version', String(CURRENT_SCHEMA_VERSION), atMs);
|
|
143
|
+
setMeta(conn, 'created_by', 'nx-kv/' + appVersion(), atMs);
|
|
144
|
+
let report = null;
|
|
145
|
+
if (importLegacyData && legacy.any) {
|
|
146
|
+
report = importLegacy(conn, { appDir, atMs });
|
|
147
|
+
}
|
|
148
|
+
// 导入之后立刻把正文引用/文档资源落关系表(002 的 apply 在导入之前跑,
|
|
149
|
+
// 这里补一次,保证「导入的历史任务」也不是只有正文里的 fileId 字符串)。
|
|
150
|
+
syncTaskAttachmentIndex(conn, { atMs });
|
|
151
|
+
syncDocAttachmentIndex(conn, { docsRoot: migrationContext.docsRoot, atMs });
|
|
152
|
+
// 内置模板 seed 放在导入**之后**:legacy templates.json 里用户改过的
|
|
153
|
+
// builtin 行先落库,seed 的 INSERT OR IGNORE 就不会用出厂文本盖掉它。
|
|
154
|
+
seedBuiltinTemplates(conn, atMs);
|
|
155
|
+
return { created: true, report };
|
|
156
|
+
},
|
|
157
|
+
{ db, mode: 'IMMEDIATE', rollback: dryRun }
|
|
158
|
+
);
|
|
159
|
+
result.createdSchema = true;
|
|
160
|
+
if (out && out.raced) {
|
|
161
|
+
result.action = 'raced';
|
|
162
|
+
} else if (out && out.report) {
|
|
163
|
+
result.action = 'imported';
|
|
164
|
+
result.report = out.report;
|
|
165
|
+
} else {
|
|
166
|
+
result.action = 'created';
|
|
167
|
+
}
|
|
168
|
+
return result;
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
// ── 情况 B:有表 → 必须是我们的库 ──
|
|
172
|
+
if (!before.hasMeta || !before.storeKind) {
|
|
173
|
+
throw new NotNxKvStoreError(db.path);
|
|
174
|
+
}
|
|
175
|
+
if (before.storeKind !== STORE_KIND) {
|
|
176
|
+
throw new NotNxKvStoreError(db.path);
|
|
177
|
+
}
|
|
178
|
+
if (before.userVersion > CURRENT_SCHEMA_VERSION) {
|
|
179
|
+
throw new StoreTooNewError(before.userVersion, CURRENT_SCHEMA_VERSION);
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
// ── 情况 C:版本落后 → 先备份(VACUUM INTO,事务外)→ 再逐步升级 ──
|
|
183
|
+
if (before.userVersion < CURRENT_SCHEMA_VERSION) {
|
|
184
|
+
// 升级是"每步一个事务 + 每步提交",没法像导入那样整段 ROLLBACK。
|
|
185
|
+
// 所以演练遇到升级就直接拒绝,而不是假装演练过(静默把库升上去更糟)。
|
|
186
|
+
if (dryRun) {
|
|
187
|
+
throw badInput(
|
|
188
|
+
`--dry-run 不支持 schema 升级(库是 v${before.userVersion},程序是 v${CURRENT_SCHEMA_VERSION})。\n` +
|
|
189
|
+
'升级会逐步提交、无法回滚,请先 `nx-kv db backup` 再直接 `nx-kv db migrate`。'
|
|
190
|
+
);
|
|
191
|
+
}
|
|
192
|
+
result.upgradedFrom = before.userVersion;
|
|
193
|
+
// 升级前备份失败必须中止:没有退路的 schema 变更是不可接受的。
|
|
194
|
+
result.backup = backupDatabase(db, {
|
|
195
|
+
dir: backupsDirFromEnv(),
|
|
196
|
+
from: before.userVersion,
|
|
197
|
+
tag: `nxkv-v${before.userVersion}-${stampFileTag()}`,
|
|
198
|
+
keep: 5,
|
|
199
|
+
});
|
|
200
|
+
const applied = migrate(db, { from: before.userVersion, context: migrationContext });
|
|
201
|
+
result.action = applied.length ? 'upgraded' : 'none';
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
// ── 情况 D:还没有从 JSON 迁过,而 legacy 数据在 → 导入 ──
|
|
205
|
+
const alreadyImported = !!getMeta(db, 'migrated_from_json_at');
|
|
206
|
+
if (importLegacyData && !alreadyImported && legacy.any) {
|
|
207
|
+
const report = tx(
|
|
208
|
+
(conn) => {
|
|
209
|
+
if (!!getMeta(conn, 'migrated_from_json_at')) return null; // 双检
|
|
210
|
+
ensureSentinelRepo(conn, atMs); // `db status` 只建表不导入的库,也要有哨兵
|
|
211
|
+
// 同一个事务里再确认一次:空库导入时不覆盖已有数据
|
|
212
|
+
const taskCount = Number((conn.get('SELECT count(*) AS c FROM tasks') || {}).c || 0);
|
|
213
|
+
if (taskCount > 0) {
|
|
214
|
+
setMeta(conn, 'migrated_from_json_at', String(atMs), atMs);
|
|
215
|
+
return null;
|
|
216
|
+
}
|
|
217
|
+
const out = importLegacy(conn, { appDir, atMs });
|
|
218
|
+
// 导入的数据在本事务里落资源关系;失败则整段回滚,不会留下半套关系。
|
|
219
|
+
syncTaskAttachmentIndex(conn, { atMs });
|
|
220
|
+
syncDocAttachmentIndex(conn, { docsRoot: migrationContext.docsRoot, atMs });
|
|
221
|
+
return out;
|
|
222
|
+
},
|
|
223
|
+
{ db, mode: 'IMMEDIATE', rollback: dryRun }
|
|
224
|
+
);
|
|
225
|
+
if (report) {
|
|
226
|
+
result.action = 'imported';
|
|
227
|
+
result.report = report;
|
|
228
|
+
}
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
// ── 内置模板 seed(幂等;存量库也可能缺新加的 builtin 行)──
|
|
232
|
+
// 只读 / 演练 / 未建表的库跳过(情况 A 已在事务内 seed 过)。
|
|
233
|
+
if (!db.readOnly && !dryRun && before.tables > 0) {
|
|
234
|
+
tx((conn) => seedBuiltinTemplates(conn, atMs), { db, mode: 'IMMEDIATE' });
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
// 旧 manifest 台账在迁移阶段已进库;成功后归档(改名不删,留取证)。
|
|
238
|
+
// 运行时不再读写 manifest,归档失败也不影响 DB 作为唯一真相。
|
|
239
|
+
if (!db.readOnly && !dryRun) {
|
|
240
|
+
const archived = archiveAttachmentManifests(migrationContext.attachmentsRoot, stampFileTag(atMs));
|
|
241
|
+
if (archived.length) result.manifestsArchived = archived;
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
return result;
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
/**
|
|
248
|
+
* 打开库 + bootstrap,失败时把库文件回滚到"迁移前"(本次新建的直接删掉,可重建)。
|
|
249
|
+
*
|
|
250
|
+
* **并发首启的重试**:两个进程同时启动时,先到的那个在把库切到 WAL / 建表,
|
|
251
|
+
* 后到的可能在第一次写时拿到 `attempt to write a readonly database`(瞬时的 WAL
|
|
252
|
+
* 切换窗口,见 errors.isReadOnlyError)或 `database is locked`。这两种都是
|
|
253
|
+
* 「等一等就好」,所以这里整段重来(关连接 → 重开 → 重新探测),而不是直接判失败。
|
|
254
|
+
* 重试用尽仍失败 → 走失败路径(回滚、日志、退出码 2)。
|
|
255
|
+
*
|
|
256
|
+
* @param {object} [opts]
|
|
257
|
+
* @param {string} [opts.path=dbPathFromEnv()] 库路径(`NX_KV_DB`)
|
|
258
|
+
* @param {string} [opts.appDir=APP_DIR] legacy 数据目录(`NX_KV_HOME`)
|
|
259
|
+
* @param {boolean} [opts.importLegacyData=true]
|
|
260
|
+
* @param {boolean} [opts.dryRun=false]
|
|
261
|
+
* @param {boolean} [opts.readOnly=false]
|
|
262
|
+
* @returns {{db: object, result: object, existedBefore: boolean}}
|
|
263
|
+
*/
|
|
264
|
+
export function openAndBootstrap({
|
|
265
|
+
path = dbPathFromEnv(),
|
|
266
|
+
appDir = defaultStoreTarget().appDir,
|
|
267
|
+
importLegacyData = true,
|
|
268
|
+
dryRun = false,
|
|
269
|
+
readOnly = false,
|
|
270
|
+
atMs = nowMs(),
|
|
271
|
+
retries = 6,
|
|
272
|
+
} = {}) {
|
|
273
|
+
let lastErr = null;
|
|
274
|
+
for (let attempt = 0; attempt <= retries; attempt++) {
|
|
275
|
+
try {
|
|
276
|
+
return attemptOpen({ path, appDir, importLegacyData, dryRun, readOnly, atMs });
|
|
277
|
+
} catch (err) {
|
|
278
|
+
lastErr = err;
|
|
279
|
+
// 只重试"另一个进程正好在动这个库"造成的瞬时错误;真实的失败立刻上抛。
|
|
280
|
+
const transient = isBusyError(err) || isReadOnlyError(err);
|
|
281
|
+
if (!transient || attempt >= retries) throw err;
|
|
282
|
+
sleepSync(40 * (attempt + 1));
|
|
283
|
+
}
|
|
284
|
+
}
|
|
285
|
+
throw lastErr;
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
/** 一次完整的「打开 → bootstrap」,失败时清理成"迁移前状态"。 */
|
|
289
|
+
function attemptOpen({ path, appDir, importLegacyData, dryRun, readOnly, atMs }) {
|
|
290
|
+
const existedBefore = fileHasContent(path);
|
|
291
|
+
|
|
292
|
+
// 打开失败(路径不可写 / 只读打开一个不存在的库 / 别人的文件不是 SQLite)
|
|
293
|
+
// 不是"迁移失败":库还没建起来,没什么可回滚,也不该写 migration-failed 日志。
|
|
294
|
+
const db = openRaw(path, { readOnly });
|
|
295
|
+
|
|
296
|
+
try {
|
|
297
|
+
const result = bootstrap(db, { appDir, importLegacyData, dryRun, atMs });
|
|
298
|
+
return { db, result, existedBefore };
|
|
299
|
+
} catch (err) {
|
|
300
|
+
try {
|
|
301
|
+
db.close();
|
|
302
|
+
} catch {
|
|
303
|
+
/* 关不掉就继续清理 */
|
|
304
|
+
}
|
|
305
|
+
// 两种"拒绝"不是迁移失败:库文件不是我们建的/不该动,原样保留。
|
|
306
|
+
const rejection = err instanceof NotNxKvStoreError || err instanceof StoreTooNewError;
|
|
307
|
+
if (rejection) throw err;
|
|
308
|
+
// 迁移中途出错:JSON 一字节不动(我们从没写过它),库文件回滚到迁移前状态。
|
|
309
|
+
//
|
|
310
|
+
// **但不能无条件删**:并发首启时"文件在我打开之前不存在"不等于"库是我建的" ——
|
|
311
|
+
// 先到的进程可能刚建好表并且正在用。所以删之前探一次:库里没有已提交的 schema
|
|
312
|
+
// 才允许删(否则动别人的库 = 数据消失)。
|
|
313
|
+
if (!existedBefore && !hasCommittedSchema(path)) removeDbFiles(path);
|
|
314
|
+
const logPath = writeFailureLog(appDir, err);
|
|
315
|
+
// 统一成 StoreMigrationError:调用方只需认一个类型,退出码 2。
|
|
316
|
+
throw new StoreMigrationError(
|
|
317
|
+
`迁移失败,已回滚(legacy JSON 未改动)。明细见 ${logPath || '(日志写入失败)'}\n` +
|
|
318
|
+
`原因:${String(err.message || err)}`,
|
|
319
|
+
{ logPath, cause: String((err && err.message) || err) }
|
|
320
|
+
);
|
|
321
|
+
}
|
|
322
|
+
}
|
|
323
|
+
|
|
324
|
+
/** 库里有没有**已提交**的 schema(另一个进程的成果)。探不到就当"有"(保守,不删)。 */
|
|
325
|
+
function hasCommittedSchema(path) {
|
|
326
|
+
let probe = null;
|
|
327
|
+
try {
|
|
328
|
+
probe = openRaw(path, { readOnly: true });
|
|
329
|
+
return countTables(probe) > 0 || !!storeKindOf(probe);
|
|
330
|
+
} catch {
|
|
331
|
+
return true;
|
|
332
|
+
} finally {
|
|
333
|
+
if (probe) {
|
|
334
|
+
try {
|
|
335
|
+
probe.close();
|
|
336
|
+
} catch {
|
|
337
|
+
/* ignore */
|
|
338
|
+
}
|
|
339
|
+
}
|
|
340
|
+
}
|
|
341
|
+
}
|
|
342
|
+
|
|
343
|
+
/** 同步小睡(并发重试用)。CLI 进程没有别的事要做,阻塞可接受。 */
|
|
344
|
+
function sleepSync(ms) {
|
|
345
|
+
const buf = new Int32Array(new SharedArrayBuffer(4));
|
|
346
|
+
Atomics.wait(buf, 0, 0, Math.max(0, ms));
|
|
347
|
+
}
|
|
348
|
+
|
|
349
|
+
/** 删掉库文件及其 WAL 附属文件(本次新建的库才允许)。 */
|
|
350
|
+
export function removeDbFiles(path) {
|
|
351
|
+
if (!path || path === ':memory:') return;
|
|
352
|
+
for (const p of [path, path + '-wal', path + '-shm', path + '-journal']) {
|
|
353
|
+
try {
|
|
354
|
+
if (existsSync(p)) unlinkSync(p);
|
|
355
|
+
} catch {
|
|
356
|
+
try {
|
|
357
|
+
rmSync(p, { force: true });
|
|
358
|
+
} catch {
|
|
359
|
+
/* Windows 上偶尔还被句柄占着:留给下次 */
|
|
360
|
+
}
|
|
361
|
+
}
|
|
362
|
+
}
|
|
363
|
+
}
|
|
364
|
+
|
|
365
|
+
/** 写失败明细日志,返回路径(`~/.nx-kv/migration-failed-<时间戳>.log`)。 */
|
|
366
|
+
export function writeFailureLog(appDir, err) {
|
|
367
|
+
const path = join(appDir, `migration-failed-${stampFileTag()}.log`);
|
|
368
|
+
const lines = [
|
|
369
|
+
`nx-kv 迁移失败 ${new Date().toISOString()}`,
|
|
370
|
+
`node ${process.versions.node} platform ${process.platform}`,
|
|
371
|
+
'',
|
|
372
|
+
String((err && err.stack) || err),
|
|
373
|
+
'',
|
|
374
|
+
];
|
|
375
|
+
try {
|
|
376
|
+
writeFileSync(path, lines.join('\n'), 'utf8');
|
|
377
|
+
return path;
|
|
378
|
+
} catch {
|
|
379
|
+
return null;
|
|
380
|
+
}
|
|
381
|
+
}
|
|
382
|
+
|
|
383
|
+
/**
|
|
384
|
+
* 迁移成功后把 legacy JSON **改名**(不删)。
|
|
385
|
+
*
|
|
386
|
+
* 改名而非删除的理由:① 让"再跑一次迁移"物理上不可能;② 用户能自己 diff;
|
|
387
|
+
* ③ 一旦发现漏迁还有据可查 —— 删除则连证据都没了。
|
|
388
|
+
*
|
|
389
|
+
* **例外:`config.json` 不改名。** 它装的是 5 个凭据(token / baseUrl / email /
|
|
390
|
+
* userId / groupId),迁移后**仍被运行时读取**(凭据留文件是 D4 的裁决)。
|
|
391
|
+
* 改名等于把用户登出,而且下一次 `loadConfig()` 会拿默认值静默覆盖 ——
|
|
392
|
+
* 那是"迁移成功、功能全坏"的最坏形状。它的偏好 4 项已经在 `settings` 表里了。
|
|
393
|
+
*
|
|
394
|
+
* @returns {{renamed: Array<{from: string, to: string, missing?: boolean}>}}
|
|
395
|
+
*/
|
|
396
|
+
export function archiveLegacyFiles(appDir, atMs = nowMs()) {
|
|
397
|
+
const tag = stampFileTag(atMs);
|
|
398
|
+
const renamed = [];
|
|
399
|
+
for (const name of Object.values(LEGACY_FILES)) {
|
|
400
|
+
// 凭据文件留在原地(见上面的说明)。
|
|
401
|
+
if (name === LEGACY_FILES.config) continue;
|
|
402
|
+
const from = join(appDir, name);
|
|
403
|
+
if (!fileHasContent(from)) continue;
|
|
404
|
+
const base = name.replace(/\.json$/i, '');
|
|
405
|
+
const to = join(appDir, `${base}.migrated-${tag}.json`);
|
|
406
|
+
try {
|
|
407
|
+
// 目标已存在时绝不覆盖(同一秒内跑两次的极端情况)
|
|
408
|
+
if (existsSync(to)) {
|
|
409
|
+
renamed.push({ from, to, skipped: true });
|
|
410
|
+
continue;
|
|
411
|
+
}
|
|
412
|
+
renameSync(from, to);
|
|
413
|
+
renamed.push({ from, to });
|
|
414
|
+
} catch (err) {
|
|
415
|
+
renamed.push({ from, to, error: String((err && err.message) || err) });
|
|
416
|
+
}
|
|
417
|
+
}
|
|
418
|
+
return { renamed };
|
|
419
|
+
}
|
|
420
|
+
|
|
421
|
+
/** 备份目录(给 CLI 用)。 */
|
|
422
|
+
export function backupsDir() {
|
|
423
|
+
return backupsDirFromEnv();
|
|
424
|
+
}
|
|
@@ -0,0 +1,234 @@
|
|
|
1
|
+
// node:sqlite 的唯一引用点(全项目只此一处)。
|
|
2
|
+
//
|
|
3
|
+
// 为什么收在一处:`node:sqlite` 仍是 experimental,API 有改动史
|
|
4
|
+
// (v26.11 `DatabaseSync` → `Database`;v26.10 `undefined` 绑定行为变化)。
|
|
5
|
+
// 只在这里碰它,升级时改一个文件即可。
|
|
6
|
+
//
|
|
7
|
+
// ── 三个实测坑,全在这个文件里解决 ────────────────────────────────────
|
|
8
|
+
//
|
|
9
|
+
// 1. **每次 import 都往 stderr 打 ExperimentalWarning**,会污染冒烟测试里对
|
|
10
|
+
// stdout+stderr 的文案断言。→ `import './quiet.js'` **必须排在 node:sqlite 之前**
|
|
11
|
+
// (ESM 依赖按 import 声明顺序求值)。
|
|
12
|
+
//
|
|
13
|
+
// 2. **行对象是 null 原型**(`Object.getPrototypeOf(row) === null`)→
|
|
14
|
+
// `assert.deepEqual(row, {a:1})` 失败。→ 出站一律 `{...row}`。
|
|
15
|
+
//
|
|
16
|
+
// 3. **`undefined` 不能绑定**(22.x 抛 `Provided value cannot be bound`;
|
|
17
|
+
// 真正的隐式 null 是 26.10 才有的),`boolean` 同样不能绑定。→ 入站统一
|
|
18
|
+
// `bindValue()`:`undefined → null`、`boolean → 0|1`、`Date → ms`、`bigint → number`。
|
|
19
|
+
//
|
|
20
|
+
// 另一个约束:`PRAGMA journal_mode / foreign_keys / busy_timeout / synchronous`
|
|
21
|
+
// 是**连接级**设置,每个连接都要设(SQLite 的 foreign_keys 默认**关**,漏了它
|
|
22
|
+
// 所有 REFERENCES 都不会生效,而且不报错)。这些在 openRaw 里一次设好。
|
|
23
|
+
import './quiet.js';
|
|
24
|
+
import * as nodeSqlite from 'node:sqlite';
|
|
25
|
+
import { existsSync, mkdirSync } from 'node:fs';
|
|
26
|
+
import { dirname } from 'node:path';
|
|
27
|
+
import { badInput } from '../errors.js';
|
|
28
|
+
import { isBusyError, mapSqliteError } from './errors.js';
|
|
29
|
+
|
|
30
|
+
// v26.11 把 DatabaseSync 改名成 Database;两个都认,只在这里判断。
|
|
31
|
+
const SqliteCtor = nodeSqlite.DatabaseSync ?? nodeSqlite.Database;
|
|
32
|
+
|
|
33
|
+
if (typeof SqliteCtor !== 'function') {
|
|
34
|
+
throw new Error(
|
|
35
|
+
'当前 Node 没有内置 SQLite(node:sqlite)。nx-kv 需要 Node >= 22.13.0,' +
|
|
36
|
+
'请升级 Node 后再运行(`nx-kv version` 可看当前版本)。'
|
|
37
|
+
);
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/** 语句缓存上限:超过就整体清空(简单可靠,避免无界增长)。 */
|
|
41
|
+
const STMT_CACHE_MAX = 256;
|
|
42
|
+
|
|
43
|
+
/**
|
|
44
|
+
* 入站参数归一:把 JS 侧的值转成 SQLite 能绑定的类型。
|
|
45
|
+
*
|
|
46
|
+
* @param {unknown} v
|
|
47
|
+
* @returns {string|number|null|Uint8Array} 可绑定值
|
|
48
|
+
*/
|
|
49
|
+
export function bindValue(v) {
|
|
50
|
+
if (v === undefined || v === null) return null;
|
|
51
|
+
if (typeof v === 'boolean') return v ? 1 : 0;
|
|
52
|
+
if (v instanceof Date) return v.getTime();
|
|
53
|
+
if (typeof v === 'bigint') return Number(v);
|
|
54
|
+
return v;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/** 出站行归一:**null 原型 → 普通对象**,让 deepEqual / JSON.stringify 行为正常。 */
|
|
58
|
+
function plain(row) {
|
|
59
|
+
if (row === undefined || row === null) return null;
|
|
60
|
+
const out = { ...row };
|
|
61
|
+
// bigint 只在 readBigInts 打开时出现;这里统一成 number,避免 `1n !== 1`。
|
|
62
|
+
for (const k of Object.keys(out)) if (typeof out[k] === 'bigint') out[k] = Number(out[k]);
|
|
63
|
+
return out;
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/**
|
|
67
|
+
* 参数列表归一:数组按位置、对象按名字(node:sqlite 默认允许裸名绑 `:name`)。
|
|
68
|
+
* @returns {unknown[]} 直接 spread 给 StatementSync.get/all/run 的参数数组
|
|
69
|
+
*/
|
|
70
|
+
function argsOf(params) {
|
|
71
|
+
if (params === undefined || params === null) return [];
|
|
72
|
+
if (Array.isArray(params)) return params.map(bindValue);
|
|
73
|
+
const out = {};
|
|
74
|
+
for (const [k, v] of Object.entries(params)) {
|
|
75
|
+
// 允许调用方带 : / @ / $ 前缀写键名,统一剥掉(node:sqlite 只认裸名)。
|
|
76
|
+
out[k.replace(/^[:@$]/, '')] = bindValue(v);
|
|
77
|
+
}
|
|
78
|
+
return [out];
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/** 同步小睡(WAL 切换重试用)。 */
|
|
82
|
+
function sleepMsSync(ms) {
|
|
83
|
+
const buf = new Int32Array(new SharedArrayBuffer(4));
|
|
84
|
+
Atomics.wait(buf, 0, 0, Math.max(0, ms));
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/**
|
|
88
|
+
* 把库切到 WAL(**文件级持久设置**,切一次之后每个连接都受益)。
|
|
89
|
+
*
|
|
90
|
+
* 为什么不能简单 `exec('PRAGMA journal_mode = WAL')`:切换需要短暂的排它锁,
|
|
91
|
+
* **两个进程同时首启**时会互相撞 —— 一方拿到锁正在切,另一方会收到
|
|
92
|
+
* `SQLITE_BUSY: database is locked`。而 WAL 是持久属性,另一方切换成功后本连接
|
|
93
|
+
* 本来就无所谓,所以这里的策略是「重试几次,还是忙就算(不当作错误)」。
|
|
94
|
+
*
|
|
95
|
+
* 不这么做的现场症状:两个 `db migrate` 并发时,慢的那个直接报
|
|
96
|
+
* "存储忙,请重试",看上去像迁移失败,其实库好好的。
|
|
97
|
+
*/
|
|
98
|
+
function enableWal(api) {
|
|
99
|
+
for (let i = 0; i < 4; i++) {
|
|
100
|
+
try {
|
|
101
|
+
api.get('PRAGMA journal_mode = WAL');
|
|
102
|
+
return;
|
|
103
|
+
} catch (err) {
|
|
104
|
+
if (!isBusyError(err)) throw mapSqliteError(err);
|
|
105
|
+
sleepMsSync(20 * (i + 1));
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
// 4 次都忙:另一个进程正在切换 / 长期持锁。这不影响本连接的正确性
|
|
109
|
+
// (WAL 一旦由任何人打开就持久生效),也不是迁移失败,所以只是放过。
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
/**
|
|
113
|
+
* 打开一个原始连接。
|
|
114
|
+
*
|
|
115
|
+
* @param {string} dbPath 库文件路径(`:memory:` 合法)
|
|
116
|
+
* @param {object} [opts]
|
|
117
|
+
* @param {boolean} [opts.readOnly=false] 只读连接(`db status` 这类不触发升级的命令用)
|
|
118
|
+
* @param {number} [opts.busyTimeoutMs=5000] 写锁等待上限
|
|
119
|
+
* @returns {object} 驱动对象
|
|
120
|
+
*/
|
|
121
|
+
export function openRaw(dbPath, { readOnly = false, busyTimeoutMs = 5000 } = {}) {
|
|
122
|
+
if (!dbPath) throw new TypeError('openRaw(dbPath) 需要库文件路径');
|
|
123
|
+
if (dbPath !== ':memory:' && !readOnly) mkdirSync(dirname(dbPath), { recursive: true });
|
|
124
|
+
if (readOnly && dbPath !== ':memory:' && !existsSync(dbPath)) {
|
|
125
|
+
// 只读打开**不会**创建文件,SQLite 只会抛 "unable to open database file" ——
|
|
126
|
+
// 那句话指不出真因("库还没建"),所以在驱动层就换成能指路的错误。
|
|
127
|
+
throw badInput(`库文件不存在: ${dbPath}(只读打开不会创建它)`);
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
let raw;
|
|
131
|
+
try {
|
|
132
|
+
raw = new SqliteCtor(dbPath, readOnly ? { readOnly: true } : {});
|
|
133
|
+
} catch (err) {
|
|
134
|
+
throw mapSqliteError(err);
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
const stmts = new Map();
|
|
138
|
+
let closed = false;
|
|
139
|
+
|
|
140
|
+
const api = {
|
|
141
|
+
/** 库文件路径(测试与排障用)。 */
|
|
142
|
+
path: dbPath,
|
|
143
|
+
readOnly,
|
|
144
|
+
/** 底层 DatabaseSync(只在必须绕过封装时用:PRAGMA、VACUUM INTO)。 */
|
|
145
|
+
raw: () => raw,
|
|
146
|
+
/** 连接是否已关闭。 */
|
|
147
|
+
get closed() {
|
|
148
|
+
return closed;
|
|
149
|
+
},
|
|
150
|
+
|
|
151
|
+
/** 执行一段 SQL(可多语句,不能带参数)。DDL / PRAGMA 走它。 */
|
|
152
|
+
exec(sql) {
|
|
153
|
+
try {
|
|
154
|
+
raw.exec(sql);
|
|
155
|
+
} catch (err) {
|
|
156
|
+
throw mapSqliteError(err);
|
|
157
|
+
}
|
|
158
|
+
},
|
|
159
|
+
|
|
160
|
+
/** 预编译(带缓存)。返回 StatementSync 的薄封装。 */
|
|
161
|
+
prepare(sql) {
|
|
162
|
+
let st = stmts.get(sql);
|
|
163
|
+
if (st) return st;
|
|
164
|
+
try {
|
|
165
|
+
st = raw.prepare(sql);
|
|
166
|
+
} catch (err) {
|
|
167
|
+
throw mapSqliteError(err);
|
|
168
|
+
}
|
|
169
|
+
if (stmts.size >= STMT_CACHE_MAX) stmts.clear();
|
|
170
|
+
stmts.set(sql, st);
|
|
171
|
+
return st;
|
|
172
|
+
},
|
|
173
|
+
|
|
174
|
+
/** 取一行;没有行返回 `null`(不是 undefined:`null` 在 JSON 里才看得见)。 */
|
|
175
|
+
get(sql, params) {
|
|
176
|
+
try {
|
|
177
|
+
return plain(api.prepare(sql).get(...argsOf(params)));
|
|
178
|
+
} catch (err) {
|
|
179
|
+
throw mapSqliteError(err);
|
|
180
|
+
}
|
|
181
|
+
},
|
|
182
|
+
|
|
183
|
+
/** 取全部行(每行都是普通对象)。 */
|
|
184
|
+
all(sql, params) {
|
|
185
|
+
try {
|
|
186
|
+
return api.prepare(sql).all(...argsOf(params)).map(plain);
|
|
187
|
+
} catch (err) {
|
|
188
|
+
throw mapSqliteError(err);
|
|
189
|
+
}
|
|
190
|
+
},
|
|
191
|
+
|
|
192
|
+
/** 执行写语句 → `{ changes, lastInsertRowid }`(数字,不是 bigint)。 */
|
|
193
|
+
run(sql, params) {
|
|
194
|
+
try {
|
|
195
|
+
const r = api.prepare(sql).run(...argsOf(params));
|
|
196
|
+
return { changes: Number(r.changes), lastInsertRowid: Number(r.lastInsertRowid) };
|
|
197
|
+
} catch (err) {
|
|
198
|
+
throw mapSqliteError(err);
|
|
199
|
+
}
|
|
200
|
+
},
|
|
201
|
+
|
|
202
|
+
/** 取一个标量(第一列第一行);没有行返回 `null`。 */
|
|
203
|
+
scalar(sql, params) {
|
|
204
|
+
const row = api.get(sql, params);
|
|
205
|
+
if (!row) return null;
|
|
206
|
+
const keys = Object.keys(row);
|
|
207
|
+
return keys.length ? row[keys[0]] : null;
|
|
208
|
+
},
|
|
209
|
+
|
|
210
|
+
/** 关连接(幂等)。**测试删库前必须先关**:Windows 上连接开着会 EBUSY。 */
|
|
211
|
+
close() {
|
|
212
|
+
if (closed) return;
|
|
213
|
+
closed = true;
|
|
214
|
+
stmts.clear();
|
|
215
|
+
try {
|
|
216
|
+
raw.close();
|
|
217
|
+
} catch (err) {
|
|
218
|
+
throw mapSqliteError(err);
|
|
219
|
+
}
|
|
220
|
+
},
|
|
221
|
+
};
|
|
222
|
+
|
|
223
|
+
// ── 连接级 PRAGMA:每个连接都要设,且必须在任何业务语句之前 ──
|
|
224
|
+
//
|
|
225
|
+
// foreign_keys 默认关:漏了它,所有 REFERENCES 静默失效(删仓库不级联、
|
|
226
|
+
// 依赖能指向不存在的任务),而且**不报错**。
|
|
227
|
+
const waitMs = Number.isFinite(Number(busyTimeoutMs)) ? Math.max(0, Number(busyTimeoutMs)) : 5000;
|
|
228
|
+
api.exec('PRAGMA busy_timeout = ' + waitMs);
|
|
229
|
+
api.exec('PRAGMA foreign_keys = ON');
|
|
230
|
+
api.exec('PRAGMA synchronous = NORMAL');
|
|
231
|
+
if (!readOnly) enableWal(api);
|
|
232
|
+
|
|
233
|
+
return api;
|
|
234
|
+
}
|