sensemaking 0.19.1 → 0.20.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/dist/cjs/chunk/extract.d.cts +1 -0
- package/dist/cjs/chunk/extract.d.ts +1 -0
- package/dist/cjs/chunk/extract.js +23 -5
- package/dist/cjs/chunk/extract.js.map +1 -1
- package/dist/cjs/chunk/index.d.cts +1 -1
- package/dist/cjs/chunk/index.d.ts +1 -1
- package/dist/cjs/chunk/index.js +3 -0
- package/dist/cjs/chunk/index.js.map +1 -1
- package/dist/cjs/index.d.cts +1 -1
- package/dist/cjs/index.d.ts +1 -1
- package/dist/cjs/index.js +3 -0
- package/dist/cjs/index.js.map +1 -1
- package/dist/cjs/scan/pool.d.cts +15 -0
- package/dist/cjs/scan/pool.d.ts +15 -0
- package/dist/cjs/scan/pool.js +263 -0
- package/dist/cjs/scan/pool.js.map +1 -0
- package/dist/cjs/scan/reparse.d.cts +2 -0
- package/dist/cjs/scan/reparse.d.ts +2 -0
- package/dist/cjs/scan/reparse.js +15 -76
- package/dist/cjs/scan/reparse.js.map +1 -1
- package/dist/cjs/store/builder.d.cts +11 -0
- package/dist/cjs/store/builder.d.ts +11 -0
- package/dist/cjs/store/builder.js +27 -0
- package/dist/cjs/store/builder.js.map +1 -0
- package/dist/cjs/store/duckdb/fieldStats.js +87 -10
- package/dist/cjs/store/duckdb/fieldStats.js.map +1 -1
- package/dist/cjs/store/duckdb/lexical.d.cts +1 -0
- package/dist/cjs/store/duckdb/lexical.d.ts +1 -0
- package/dist/cjs/store/duckdb/lexical.js +21 -5
- package/dist/cjs/store/duckdb/lexical.js.map +1 -1
- package/dist/cjs/store/duckdb/open.d.cts +9 -8
- package/dist/cjs/store/duckdb/open.d.ts +9 -8
- package/dist/cjs/store/duckdb/open.js +69 -120
- package/dist/cjs/store/duckdb/open.js.map +1 -1
- package/dist/cjs/store/duckdb/reconcile.d.cts +2 -6
- package/dist/cjs/store/duckdb/reconcile.d.ts +2 -6
- package/dist/cjs/store/duckdb/reconcile.js +45 -581
- package/dist/cjs/store/duckdb/reconcile.js.map +1 -1
- package/dist/cjs/store/duckdb/store.d.cts +1 -2
- package/dist/cjs/store/duckdb/store.d.ts +1 -2
- package/dist/cjs/store/duckdb/store.js +3 -26
- package/dist/cjs/store/duckdb/store.js.map +1 -1
- package/dist/cjs/store/index.d.cts +9 -3
- package/dist/cjs/store/index.d.ts +9 -3
- package/dist/cjs/store/index.js +40 -7
- package/dist/cjs/store/index.js.map +1 -1
- package/dist/cjs/store/open.d.cts +15 -0
- package/dist/cjs/store/open.d.ts +15 -0
- package/dist/cjs/store/open.js +516 -0
- package/dist/cjs/store/open.js.map +1 -0
- package/dist/cjs/store/reconcile.d.cts +7 -0
- package/dist/cjs/store/reconcile.d.ts +7 -0
- package/dist/cjs/store/reconcile.js +752 -0
- package/dist/cjs/store/reconcile.js.map +1 -0
- package/dist/cjs/store/shared.d.cts +1 -0
- package/dist/cjs/store/shared.d.ts +1 -0
- package/dist/cjs/store/shared.js +37 -0
- package/dist/cjs/store/shared.js.map +1 -1
- package/dist/cjs/store/signature.d.cts +3 -0
- package/dist/cjs/store/signature.d.ts +3 -0
- package/dist/cjs/store/signature.js +162 -0
- package/dist/cjs/store/signature.js.map +1 -0
- package/dist/cjs/store/sqlite/open.d.cts +9 -9
- package/dist/cjs/store/sqlite/open.d.ts +9 -9
- package/dist/cjs/store/sqlite/open.js +188 -198
- package/dist/cjs/store/sqlite/open.js.map +1 -1
- package/dist/cjs/store/sqlite/reconcile.d.cts +5 -10
- package/dist/cjs/store/sqlite/reconcile.d.ts +5 -10
- package/dist/cjs/store/sqlite/reconcile.js +48 -850
- package/dist/cjs/store/sqlite/reconcile.js.map +1 -1
- package/dist/cjs/store/sqlite/store.d.cts +1 -1
- package/dist/cjs/store/sqlite/store.d.ts +1 -1
- package/dist/cjs/store/sqlite/store.js +3 -13
- package/dist/cjs/store/sqlite/store.js.map +1 -1
- package/dist/cjs/store/turso/open.d.cts +6 -11
- package/dist/cjs/store/turso/open.d.ts +6 -11
- package/dist/cjs/store/turso/open.js +78 -169
- package/dist/cjs/store/turso/open.js.map +1 -1
- package/dist/cjs/store/turso/reconcile.d.cts +5 -6
- package/dist/cjs/store/turso/reconcile.d.ts +5 -6
- package/dist/cjs/store/turso/reconcile.js +169 -729
- package/dist/cjs/store/turso/reconcile.js.map +1 -1
- package/dist/cjs/store/turso/store.d.cts +1 -2
- package/dist/cjs/store/turso/store.d.ts +1 -2
- package/dist/cjs/store/turso/store.js +1 -12
- package/dist/cjs/store/turso/store.js.map +1 -1
- package/dist/cjs/store/types.d.cts +28 -6
- package/dist/cjs/store/types.d.ts +28 -6
- package/dist/cjs/store/types.js +14 -0
- package/dist/cjs/store/types.js.map +1 -1
- package/dist/cjs/text/strip.js +3 -6
- package/dist/cjs/text/strip.js.map +1 -1
- package/dist/cjs/watch.js +28 -16
- package/dist/cjs/watch.js.map +1 -1
- package/dist/esm/chunk/extract.d.ts +1 -0
- package/dist/esm/chunk/extract.js +10 -2
- package/dist/esm/chunk/extract.js.map +1 -1
- package/dist/esm/chunk/index.d.ts +1 -1
- package/dist/esm/chunk/index.js +1 -1
- package/dist/esm/chunk/index.js.map +1 -1
- package/dist/esm/index.d.ts +1 -1
- package/dist/esm/index.js +1 -1
- package/dist/esm/index.js.map +1 -1
- package/dist/esm/scan/pool.d.ts +15 -0
- package/dist/esm/scan/pool.js +77 -0
- package/dist/esm/scan/pool.js.map +1 -0
- package/dist/esm/scan/reparse.d.ts +2 -0
- package/dist/esm/scan/reparse.js +11 -58
- package/dist/esm/scan/reparse.js.map +1 -1
- package/dist/esm/store/builder.d.ts +11 -0
- package/dist/esm/store/builder.js +14 -0
- package/dist/esm/store/builder.js.map +1 -0
- package/dist/esm/store/duckdb/fieldStats.js +32 -19
- package/dist/esm/store/duckdb/fieldStats.js.map +1 -1
- package/dist/esm/store/duckdb/lexical.d.ts +1 -0
- package/dist/esm/store/duckdb/lexical.js +22 -9
- package/dist/esm/store/duckdb/lexical.js.map +1 -1
- package/dist/esm/store/duckdb/open.d.ts +9 -8
- package/dist/esm/store/duckdb/open.js +32 -57
- package/dist/esm/store/duckdb/open.js.map +1 -1
- package/dist/esm/store/duckdb/reconcile.d.ts +2 -6
- package/dist/esm/store/duckdb/reconcile.js +24 -117
- package/dist/esm/store/duckdb/reconcile.js.map +1 -1
- package/dist/esm/store/duckdb/store.d.ts +1 -2
- package/dist/esm/store/duckdb/store.js +4 -11
- package/dist/esm/store/duckdb/store.js.map +1 -1
- package/dist/esm/store/index.d.ts +9 -3
- package/dist/esm/store/index.js +23 -7
- package/dist/esm/store/index.js.map +1 -1
- package/dist/esm/store/open.d.ts +15 -0
- package/dist/esm/store/open.js +137 -0
- package/dist/esm/store/open.js.map +1 -0
- package/dist/esm/store/reconcile.d.ts +7 -0
- package/dist/esm/store/reconcile.js +132 -0
- package/dist/esm/store/reconcile.js.map +1 -0
- package/dist/esm/store/shared.d.ts +1 -0
- package/dist/esm/store/shared.js +9 -0
- package/dist/esm/store/shared.js.map +1 -1
- package/dist/esm/store/signature.d.ts +3 -0
- package/dist/esm/store/signature.js +35 -0
- package/dist/esm/store/signature.js.map +1 -0
- package/dist/esm/store/sqlite/open.d.ts +9 -9
- package/dist/esm/store/sqlite/open.js +81 -111
- package/dist/esm/store/sqlite/open.js.map +1 -1
- package/dist/esm/store/sqlite/reconcile.d.ts +5 -10
- package/dist/esm/store/sqlite/reconcile.js +31 -201
- package/dist/esm/store/sqlite/reconcile.js.map +1 -1
- package/dist/esm/store/sqlite/store.d.ts +1 -1
- package/dist/esm/store/sqlite/store.js +4 -7
- package/dist/esm/store/sqlite/store.js.map +1 -1
- package/dist/esm/store/turso/open.d.ts +6 -11
- package/dist/esm/store/turso/open.js +30 -77
- package/dist/esm/store/turso/open.js.map +1 -1
- package/dist/esm/store/turso/reconcile.d.ts +5 -6
- package/dist/esm/store/turso/reconcile.js +42 -146
- package/dist/esm/store/turso/reconcile.js.map +1 -1
- package/dist/esm/store/turso/store.d.ts +1 -2
- package/dist/esm/store/turso/store.js +2 -6
- package/dist/esm/store/turso/store.js.map +1 -1
- package/dist/esm/store/types.d.ts +28 -6
- package/dist/esm/store/types.js +12 -1
- package/dist/esm/store/types.js.map +1 -1
- package/dist/esm/text/strip.js +3 -4
- package/dist/esm/text/strip.js.map +1 -1
- package/dist/esm/watch.js +5 -3
- package/dist/esm/watch.js.map +1 -1
- package/package.json +2 -2
|
@@ -1,23 +1,21 @@
|
|
|
1
1
|
// The Node floor (>=22.20) is explained here and nowhere else: 22.20 is the first release with
|
|
2
2
|
// both FTS5 and row-returning INSERT ... RETURNING. Raise it only for a load-bearing capability.
|
|
3
|
-
import { mkdirSync } from 'node:fs';
|
|
4
|
-
import { join } from 'node:path';
|
|
5
3
|
import { DatabaseSync } from 'node:sqlite';
|
|
6
|
-
import { contentTokenize, featureSignature
|
|
7
|
-
import { rekeyChunkText } from '../../embed/handoff.js';
|
|
4
|
+
import { contentTokenize, featureSignature } from '../../config/index.js';
|
|
8
5
|
import { SenseError } from '../../errors.js';
|
|
9
6
|
import { activeFeatures, FEATURES } from '../../features/index.js';
|
|
10
|
-
import {
|
|
7
|
+
import { listFiles, parseFile } from '../../scan/index.js';
|
|
8
|
+
import { openWithDialect } from '../open.js';
|
|
11
9
|
import { getMeta, setMeta } from '../shared.js';
|
|
12
10
|
import { BEGIN_WRITE, withTransaction } from '../transaction.js';
|
|
13
11
|
import { createConnection } from './connection.js';
|
|
14
|
-
import {
|
|
12
|
+
import { contentRow, INSERT_CONTENT_SQL, sqliteDialect } from './reconcile.js';
|
|
15
13
|
import { registerFunctions } from './sql-functions.js';
|
|
16
14
|
import { createStore } from './store.js';
|
|
17
15
|
export const DB_FILENAME = 'cache.db';
|
|
18
16
|
// Cache shape version, independent of the config's own `version`. Bumping it rebuilds
|
|
19
17
|
// existing trees on first query.
|
|
20
|
-
export const SCHEMA_VERSION = '
|
|
18
|
+
export const SCHEMA_VERSION = '19';
|
|
21
19
|
// unicode61 splits on spaces, so a language written without them indexes a whole run as one
|
|
22
20
|
// token and word search finds nothing; `content.tokenize` is how such a tree picks trigram.
|
|
23
21
|
const DEFAULT_TOKENIZE = 'porter unicode61';
|
|
@@ -51,7 +49,7 @@ async function createContentTable(conn, tokenize) {
|
|
|
51
49
|
}
|
|
52
50
|
// Content is a separate table (not a column on frontmatter) so `SELECT * FROM frontmatter`
|
|
53
51
|
// can't dump file text into context. Features add their own tables after the core ones.
|
|
54
|
-
async function
|
|
52
|
+
async function ensureSchemaTables(conn, cfg, tokenize) {
|
|
55
53
|
await conn.exec(`CREATE TABLE IF NOT EXISTS frontmatter ("path" TEXT PRIMARY KEY, "_mtime" REAL, "_ctime" REAL, "_size" INTEGER, "_parse_error" TEXT)`);
|
|
56
54
|
// IF NOT EXISTS is safe against a tokenizer change: open() compares the table's own DDL
|
|
57
55
|
// against the resolved tokenizer before this runs, so a stale table is already gone by now.
|
|
@@ -78,18 +76,9 @@ function setJournalWal(db) {
|
|
|
78
76
|
}
|
|
79
77
|
}
|
|
80
78
|
}
|
|
81
|
-
async function connect(cfg) {
|
|
82
|
-
const stateDir = join(cfg.baseDir, STATE_DIR);
|
|
83
|
-
mkdirSync(stateDir, {
|
|
84
|
-
recursive: true
|
|
85
|
-
});
|
|
86
|
-
const dbPath = join(stateDir, DB_FILENAME);
|
|
79
|
+
async function connect(dbPath, cfg) {
|
|
87
80
|
const db = new DatabaseSync(dbPath);
|
|
88
|
-
// A throw below must release this handle, or on Windows the leaked WAL db is undeletable and
|
|
89
|
-
// scratch cleanup fails with EPERM/EBUSY. `closed` keeps the catch from double-closing.
|
|
90
|
-
let closed = false;
|
|
91
81
|
try {
|
|
92
|
-
var _ref;
|
|
93
82
|
// Before journal_mode, not after: converting a fresh database to WAL takes a brief exclusive
|
|
94
83
|
// lock, and with no timeout set yet a second process opening the same tree fails in 1ms.
|
|
95
84
|
db.exec('PRAGMA busy_timeout = 30000');
|
|
@@ -98,107 +87,88 @@ async function connect(cfg) {
|
|
|
98
87
|
setJournalWal(db);
|
|
99
88
|
registerFunctions(db, contentTokenize(cfg) === undefined);
|
|
100
89
|
const conn = createConnection(db);
|
|
101
|
-
db.exec('CREATE TABLE IF NOT EXISTS meta (key TEXT PRIMARY KEY, value TEXT)');
|
|
102
90
|
// Before the rebuild branch below, never after: that branch deletes the cache, so a typo'd
|
|
103
91
|
// tokenizer validated later would cost a full re-index (and re-embed) to reach its own error.
|
|
104
92
|
const tokenize = resolveTokenize(db, cfg);
|
|
105
|
-
// Schema-version or feature-set mismatch: reconcile only reparses changed files, so an
|
|
106
|
-
// old cache can't be patched incrementally -- rebuild instead (cheap: nothing expensive lives here).
|
|
107
|
-
const version = await getMeta(conn, 'schema_version');
|
|
108
|
-
const features = await getMeta(conn, 'features');
|
|
109
|
-
const wantFeatures = featureSignature(cfg, FEATURES);
|
|
110
|
-
let tokenizeOnlyRebuild = false;
|
|
111
|
-
if (version !== null && version !== SCHEMA_VERSION || features !== null && features !== wantFeatures) {
|
|
112
|
-
// Indexing derives from presets, so a config edit rebuilding the cache must say so and
|
|
113
|
-
// name what changed -- silent rebuilds make derived indexing look like a hang or a bug.
|
|
114
|
-
if (version !== null && version !== SCHEMA_VERSION) {
|
|
115
|
-
console.error('sense: cache format changed (new sensemaking version); rebuilding the index');
|
|
116
|
-
closed = true;
|
|
117
|
-
db.close();
|
|
118
|
-
clearCache(cfg);
|
|
119
|
-
return connect(cfg);
|
|
120
|
-
}
|
|
121
|
-
const changedKeys = changedSignatureKeys(features !== null && features !== void 0 ? features : '', wantFeatures);
|
|
122
|
-
// Only the tokenizer moved, and frontmatter, links, sections and embeddings are file-derived
|
|
123
|
-
// and tokenizer-independent. Any other signature change takes the full clear/reopen below.
|
|
124
|
-
if (changedKeys.size === 1 && changedKeys.has('tokenize')) {
|
|
125
|
-
console.error('sense: config change (content tokenizer) rebuilds the text index; vectors, links, and sections are kept');
|
|
126
|
-
// One transaction, so a crash before COMMIT rolls back to the old tokenizer's table rather
|
|
127
|
-
// than to no table. IF EXISTS makes a retry after such a crash a no-op, not a raw error.
|
|
128
|
-
await withTransaction(conn, async ()=>{
|
|
129
|
-
await conn.exec('DROP TABLE IF EXISTS content');
|
|
130
|
-
await createContentTable(conn, tokenize);
|
|
131
|
-
}, BEGIN_WRITE);
|
|
132
|
-
tokenizeOnlyRebuild = true;
|
|
133
|
-
} else if (changedKeys.size === 1 && changedKeys.has('embed') && embedIdentityAdopted(features !== null && features !== void 0 ? features : '', wantFeatures)) {
|
|
134
|
-
// First sight of a resolved weight identity: the model itself hasn't changed, so
|
|
135
|
-
// adopt it into meta with no rebuild and no re-embed, mirroring the tokenize precedent.
|
|
136
|
-
console.error("sense: recorded the embedding model's resolved identity; vectors are unaffected");
|
|
137
|
-
await setMeta(conn, 'features', wantFeatures);
|
|
138
|
-
} else {
|
|
139
|
-
const changed = signatureDiff(features !== null && features !== void 0 ? features : '', wantFeatures);
|
|
140
|
-
console.error(`sense: config change (${changed}) rebuilds the index`);
|
|
141
|
-
closed = true;
|
|
142
|
-
db.close();
|
|
143
|
-
clearCache(cfg);
|
|
144
|
-
return connect(cfg);
|
|
145
|
-
}
|
|
146
|
-
}
|
|
147
|
-
// Meta can lie after a crash between table creation and the signature write; the table's own
|
|
148
|
-
// DDL cannot, so a mismatch here rebuilds whatever meta says.
|
|
149
|
-
const stored = storedTokenize(db);
|
|
150
|
-
if (stored !== null && stored !== tokenize) {
|
|
151
|
-
console.error('sense: cache was built with a different content tokenizer; rebuilding the index');
|
|
152
|
-
closed = true;
|
|
153
|
-
db.close();
|
|
154
|
-
clearCache(cfg);
|
|
155
|
-
return connect(cfg);
|
|
156
|
-
}
|
|
157
|
-
// One writer at a time: the feature hooks check a column then add it, so two cold opens racing
|
|
158
|
-
// here both see it missing and the second ALTER fails with a duplicate column.
|
|
159
|
-
await withTransaction(conn, ()=>ensureSchema(conn, cfg, tokenize), BEGIN_WRITE);
|
|
160
|
-
let rebuildWarnings = [];
|
|
161
|
-
if (tokenizeOnlyRebuild) {
|
|
162
|
-
rebuildWarnings = await rebuildContentTable(conn, cfg, cfg.baseDir);
|
|
163
|
-
await setMeta(conn, 'features', wantFeatures);
|
|
164
|
-
}
|
|
165
|
-
// 3x the largest reconcile this cache has recorded, floored at 30s and capped at 10min.
|
|
166
|
-
// Installed before reconcile() -- that call is the one that races a watcher's transaction.
|
|
167
|
-
const recordedMaxMs = Number((_ref = await getMeta(conn, 'reconcile_max_ms')) !== null && _ref !== void 0 ? _ref : '0');
|
|
168
|
-
db.exec(`PRAGMA busy_timeout = ${Math.min(Math.max(30000, 3 * recordedMaxMs), 600000)}`);
|
|
169
|
-
const { parsed, warnings } = await reconcile(conn, cfg, cfg.baseDir);
|
|
170
93
|
return {
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
warnings: [
|
|
177
|
-
...rebuildWarnings,
|
|
178
|
-
...warnings
|
|
179
|
-
]
|
|
94
|
+
handle: {
|
|
95
|
+
db,
|
|
96
|
+
tokenize
|
|
97
|
+
},
|
|
98
|
+
conn
|
|
180
99
|
};
|
|
181
100
|
} catch (err) {
|
|
182
|
-
|
|
101
|
+
// A throw here must release this handle, or on Windows the leaked WAL db is undeletable and
|
|
102
|
+
// scratch cleanup fails with EPERM/EBUSY.
|
|
103
|
+
db.close();
|
|
183
104
|
throw err;
|
|
184
105
|
}
|
|
185
106
|
}
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
};
|
|
107
|
+
async function close(handle) {
|
|
108
|
+
handle.db.close();
|
|
109
|
+
}
|
|
110
|
+
// Only the tokenizer moved, and frontmatter, links, sections and embeddings are file-derived
|
|
111
|
+
// and tokenizer-independent. Any other signature change takes the full clear/reopen in open.ts.
|
|
112
|
+
async function partialRebuild(handle, conn, _cfg, changedKeys) {
|
|
113
|
+
if (!(changedKeys.size === 1 && changedKeys.has('tokenize'))) return false;
|
|
114
|
+
console.error('sense: config change (content tokenizer) rebuilds the text index; vectors, links, and sections are kept');
|
|
115
|
+
// One transaction, so a crash before COMMIT rolls back to the old tokenizer's table rather
|
|
116
|
+
// than to no table. IF EXISTS makes a retry after such a crash a no-op, not a raw error.
|
|
117
|
+
await withTransaction(conn, async ()=>{
|
|
118
|
+
await conn.exec('DROP TABLE IF EXISTS content');
|
|
119
|
+
await createContentTable(conn, handle.tokenize);
|
|
120
|
+
}, BEGIN_WRITE);
|
|
121
|
+
return true;
|
|
200
122
|
}
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
123
|
+
// Tokenize-only rebuild: only `content` is repopulated (the other tables are tokenizer-independent)
|
|
124
|
+
// and no feature extractors run. Warnings come from the reparse, since mtimes stay untouched and reconcile would never reparse them.
|
|
125
|
+
async function postSchemaRebuild(_handle, conn, cfg, baseDir, wantFeatures) {
|
|
126
|
+
const stmt = await conn.prepare('SELECT "path" FROM frontmatter');
|
|
127
|
+
const known = new Set((await stmt.all()).map((r)=>r.path));
|
|
128
|
+
const files = listFiles(cfg, baseDir).filter((f)=>known.has(f.relPath));
|
|
129
|
+
const segmenting = contentTokenize(cfg) === undefined;
|
|
130
|
+
const warnings = [];
|
|
131
|
+
const rows = [];
|
|
132
|
+
for (const file of files){
|
|
133
|
+
const { doc, warnings: fileWarnings } = parseFile(file);
|
|
134
|
+
warnings.push(...fileWarnings);
|
|
135
|
+
rows.push(contentRow(doc, segmenting));
|
|
136
|
+
}
|
|
137
|
+
await withTransaction(conn, async ()=>{
|
|
138
|
+
if (rows.length > 0) await conn.runBatch(INSERT_CONTENT_SQL, rows);
|
|
139
|
+
}, BEGIN_WRITE);
|
|
140
|
+
await setMeta(conn, 'features', wantFeatures);
|
|
141
|
+
return warnings;
|
|
142
|
+
}
|
|
143
|
+
// Meta can lie after a crash between table creation and the signature write; the table's own
|
|
144
|
+
// DDL cannot, so a mismatch here rebuilds whatever meta says.
|
|
145
|
+
function extraRebuildReason(handle) {
|
|
146
|
+
const stored = storedTokenize(handle.db);
|
|
147
|
+
if (stored !== null && stored !== handle.tokenize) return 'cache was built with a different content tokenizer';
|
|
148
|
+
return null;
|
|
149
|
+
}
|
|
150
|
+
async function ensureSchema(handle, conn, cfg) {
|
|
151
|
+
// One writer at a time: the feature hooks check a column then add it, so two cold opens racing
|
|
152
|
+
// here both see it missing and the second ALTER fails with a duplicate column.
|
|
153
|
+
await withTransaction(conn, ()=>ensureSchemaTables(conn, cfg, handle.tokenize), BEGIN_WRITE);
|
|
154
|
+
}
|
|
155
|
+
async function setDerivedBusyTimeout(handle, _conn, ms) {
|
|
156
|
+
handle.db.exec(`PRAGMA busy_timeout = ${ms}`);
|
|
157
|
+
}
|
|
158
|
+
// This store's dialect (types.ts's OpenDialect) for the shared orchestration in store/open.ts.
|
|
159
|
+
export const sqliteOpenDialect = {
|
|
160
|
+
filename: DB_FILENAME,
|
|
161
|
+
schemaVersion: SCHEMA_VERSION,
|
|
162
|
+
reconcileDialect: sqliteDialect,
|
|
163
|
+
connect,
|
|
164
|
+
close,
|
|
165
|
+
partialRebuild,
|
|
166
|
+
postSchemaRebuild,
|
|
167
|
+
extraRebuildReason,
|
|
168
|
+
ensureSchema,
|
|
169
|
+
setDerivedBusyTimeout,
|
|
170
|
+
createStore: (handle, conn, cfg)=>createStore(handle.db, conn, cfg)
|
|
171
|
+
};
|
|
172
|
+
export async function openSqlite(cfg) {
|
|
173
|
+
return openWithDialect(cfg, sqliteOpenDialect);
|
|
204
174
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["/Users/kevin/Dev/OpenSource/ai/sensemaking/src/store/sqlite/open.ts"],"sourcesContent":["// The Node floor (>=22.20) is explained here and nowhere else: 22.20 is the first release with\n// both FTS5 and row-returning INSERT ... RETURNING. Raise it only for a load-bearing capability.\nimport { mkdirSync } from 'node:fs';\nimport { join } from 'node:path';\nimport { DatabaseSync } from 'node:sqlite';\nimport type { Config, ResolvedConfig } from '../../config/index.ts';\nimport { contentTokenize, featureSignature, STATE_DIR } from '../../config/index.ts';\nimport { rekeyChunkText } from '../../embed/handoff.ts';\nimport { SenseError } from '../../errors.ts';\nimport { activeFeatures, FEATURES } from '../../features/index.ts';\nimport { clearCache } from '../cache.ts';\nimport { getMeta, setMeta } from '../shared.ts';\nimport { BEGIN_WRITE, withTransaction } from '../transaction.ts';\nimport type { Connection, Store } from '../types.ts';\nimport { createConnection } from './connection.ts';\nimport { changedSignatureKeys, embedIdentityAdopted, rebuildContentTable, reconcile, signatureDiff } from './reconcile.ts';\nimport { registerFunctions } from './sql-functions.ts';\nimport { createStore } from './store.ts';\n\nexport const DB_FILENAME = 'cache.db';\n// Cache shape version, independent of the config's own `version`. Bumping it rebuilds\n// existing trees on first query.\nexport const SCHEMA_VERSION = '18';\n\ninterface ConnectResult {\n db: DatabaseSync;\n conn: Connection;\n cfg: ResolvedConfig;\n dbPath: string;\n parsed: number;\n warnings: string[];\n}\n\nexport interface OpenResult {\n store: Store;\n cfg: ResolvedConfig;\n dbPath: string;\n parsed: number;\n warnings: string[];\n}\n\n// unicode61 splits on spaces, so a language written without them indexes a whole run as one\n// token and word search finds nothing; `content.tokenize` is how such a tree picks trigram.\nconst DEFAULT_TOKENIZE = 'porter unicode61';\n\n// FTS5 takes its tokenizer as a DDL string literal where nothing can bind, so the configured\n// value is concatenated; probing a throwaway table first is both the safety and the validation.\nfunction resolveTokenize(db: DatabaseSync, cfg: Config): string {\n const configured = contentTokenize(cfg);\n if (configured === undefined) return DEFAULT_TOKENIZE;\n const literal = configured.replace(/'/g, \"''\");\n try {\n db.exec('DROP TABLE IF EXISTS temp.sense_tokenize_probe');\n db.exec(`CREATE VIRTUAL TABLE temp.sense_tokenize_probe USING fts5(x, tokenize = '${literal}')`);\n db.exec('DROP TABLE IF EXISTS temp.sense_tokenize_probe');\n } catch (err) {\n throw new SenseError('CONFIG_INVALID', `content.tokenize \"${configured}\" is not a tokenizer this SQLite accepts (${(err as Error).message}); the built-in choices are unicode61, ascii, porter, and trigram, each with their own options`);\n }\n return literal;\n}\n\n// The tokenizer the content table was actually built with, from its own DDL -- the one\n// record that cannot desynchronize from the table. NULL when the table does not exist yet.\nfunction storedTokenize(db: DatabaseSync): string | null {\n const row = db.prepare(`SELECT sql FROM sqlite_master WHERE name = 'content'`).get() as { sql: string } | undefined;\n if (!row) return null;\n const m = row.sql.match(/tokenize = '((?:[^']|'')*)'/);\n return m ? m[1] : null;\n}\n\n// The `_seg` sidecars are appended after path, never inserted: bm25() and snippet(content, 2)\n// are documented against the first three columns. Each holds its field's exploded unspaced runs.\nasync function createContentTable(conn: Connection, tokenize: string): Promise<void> {\n await conn.exec(`CREATE VIRTUAL TABLE IF NOT EXISTS content USING fts5(title, summary, text, path UNINDEXED, title_seg, summary_seg, text_seg, tokenize = '${tokenize}')`);\n}\n\n// Content is a separate table (not a column on frontmatter) so `SELECT * FROM frontmatter`\n// can't dump file text into context. Features add their own tables after the core ones.\nasync function ensureSchema(conn: Connection, cfg: Config, tokenize: string): Promise<void> {\n await conn.exec(`CREATE TABLE IF NOT EXISTS frontmatter (\"path\" TEXT PRIMARY KEY, \"_mtime\" REAL, \"_ctime\" REAL, \"_size\" INTEGER, \"_parse_error\" TEXT)`);\n // IF NOT EXISTS is safe against a tokenizer change: open() compares the table's own DDL\n // against the resolved tokenizer before this runs, so a stale table is already gone by now.\n await createContentTable(conn, tokenize);\n // Coverage, not ownership: a path can appear under several presets. path leads the PK so the\n // per-doc delete is an index hit -- keyed the other way, cold builds went quadratic.\n await conn.exec(`CREATE TABLE IF NOT EXISTS preset_files (\"path\" TEXT, preset TEXT, PRIMARY KEY (\"path\", preset))`);\n await conn.exec('CREATE INDEX IF NOT EXISTS preset_files_preset ON preset_files(preset)');\n for (const feature of activeFeatures(cfg)) await feature.schema(conn);\n if ((await getMeta(conn, 'schema_version')) === null) await setMeta(conn, 'schema_version', SCHEMA_VERSION);\n if ((await getMeta(conn, 'features')) === null) await setMeta(conn, 'features', featureSignature(cfg, FEATURES));\n}\n\n// Two processes opening the same fresh tree both try to convert it, and the loser gets SQLITE_BUSY\n// with no busy handler behind it. Bounded because a lock held past this is a real problem, not a race.\nfunction setJournalWal(db: DatabaseSync): void {\n const deadline = Date.now() + 5000;\n for (;;) {\n try {\n db.exec('PRAGMA journal_mode = WAL');\n return;\n } catch (err) {\n if (Date.now() >= deadline || !/database is locked|busy/i.test((err as Error).message)) throw err;\n Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 20);\n }\n }\n}\n\nasync function connect(cfg: ResolvedConfig): Promise<ConnectResult> {\n const stateDir = join(cfg.baseDir, STATE_DIR);\n mkdirSync(stateDir, { recursive: true });\n const dbPath = join(stateDir, DB_FILENAME);\n\n const db = new DatabaseSync(dbPath);\n // A throw below must release this handle, or on Windows the leaked WAL db is undeletable and\n // scratch cleanup fails with EPERM/EBUSY. `closed` keeps the catch from double-closing.\n let closed = false;\n try {\n // Before journal_mode, not after: converting a fresh database to WAL takes a brief exclusive\n // lock, and with no timeout set yet a second process opening the same tree fails in 1ms.\n db.exec('PRAGMA busy_timeout = 30000');\n // busy_timeout does not cover the WAL conversion itself: SQLite does not invoke the busy\n // handler for it, so a concurrent cold open needs its own bounded wait.\n setJournalWal(db);\n registerFunctions(db, contentTokenize(cfg) === undefined);\n const conn = createConnection(db);\n\n db.exec('CREATE TABLE IF NOT EXISTS meta (key TEXT PRIMARY KEY, value TEXT)');\n\n // Before the rebuild branch below, never after: that branch deletes the cache, so a typo'd\n // tokenizer validated later would cost a full re-index (and re-embed) to reach its own error.\n const tokenize = resolveTokenize(db, cfg);\n\n // Schema-version or feature-set mismatch: reconcile only reparses changed files, so an\n // old cache can't be patched incrementally -- rebuild instead (cheap: nothing expensive lives here).\n const version = await getMeta(conn, 'schema_version');\n const features = await getMeta(conn, 'features');\n const wantFeatures = featureSignature(cfg, FEATURES);\n let tokenizeOnlyRebuild = false;\n if ((version !== null && version !== SCHEMA_VERSION) || (features !== null && features !== wantFeatures)) {\n // Indexing derives from presets, so a config edit rebuilding the cache must say so and\n // name what changed -- silent rebuilds make derived indexing look like a hang or a bug.\n if (version !== null && version !== SCHEMA_VERSION) {\n console.error('sense: cache format changed (new sensemaking version); rebuilding the index');\n closed = true;\n db.close();\n clearCache(cfg);\n return connect(cfg);\n }\n const changedKeys = changedSignatureKeys(features ?? '', wantFeatures);\n // Only the tokenizer moved, and frontmatter, links, sections and embeddings are file-derived\n // and tokenizer-independent. Any other signature change takes the full clear/reopen below.\n if (changedKeys.size === 1 && changedKeys.has('tokenize')) {\n console.error('sense: config change (content tokenizer) rebuilds the text index; vectors, links, and sections are kept');\n // One transaction, so a crash before COMMIT rolls back to the old tokenizer's table rather\n // than to no table. IF EXISTS makes a retry after such a crash a no-op, not a raw error.\n await withTransaction(\n conn,\n async () => {\n await conn.exec('DROP TABLE IF EXISTS content');\n await createContentTable(conn, tokenize);\n },\n BEGIN_WRITE\n );\n tokenizeOnlyRebuild = true;\n } else if (changedKeys.size === 1 && changedKeys.has('embed') && embedIdentityAdopted(features ?? '', wantFeatures)) {\n // First sight of a resolved weight identity: the model itself hasn't changed, so\n // adopt it into meta with no rebuild and no re-embed, mirroring the tokenize precedent.\n console.error(\"sense: recorded the embedding model's resolved identity; vectors are unaffected\");\n await setMeta(conn, 'features', wantFeatures);\n } else {\n const changed = signatureDiff(features ?? '', wantFeatures);\n console.error(`sense: config change (${changed}) rebuilds the index`);\n closed = true;\n db.close();\n clearCache(cfg);\n return connect(cfg);\n }\n }\n\n // Meta can lie after a crash between table creation and the signature write; the table's own\n // DDL cannot, so a mismatch here rebuilds whatever meta says.\n const stored = storedTokenize(db);\n if (stored !== null && stored !== tokenize) {\n console.error('sense: cache was built with a different content tokenizer; rebuilding the index');\n closed = true;\n db.close();\n clearCache(cfg);\n return connect(cfg);\n }\n\n // One writer at a time: the feature hooks check a column then add it, so two cold opens racing\n // here both see it missing and the second ALTER fails with a duplicate column.\n await withTransaction(conn, () => ensureSchema(conn, cfg, tokenize), BEGIN_WRITE);\n\n let rebuildWarnings: string[] = [];\n if (tokenizeOnlyRebuild) {\n rebuildWarnings = await rebuildContentTable(conn, cfg, cfg.baseDir);\n await setMeta(conn, 'features', wantFeatures);\n }\n\n // 3x the largest reconcile this cache has recorded, floored at 30s and capped at 10min.\n // Installed before reconcile() -- that call is the one that races a watcher's transaction.\n const recordedMaxMs = Number((await getMeta(conn, 'reconcile_max_ms')) ?? '0');\n db.exec(`PRAGMA busy_timeout = ${Math.min(Math.max(30000, 3 * recordedMaxMs), 600_000)}`);\n\n const { parsed, warnings } = await reconcile(conn, cfg, cfg.baseDir);\n\n return { db, conn, cfg, dbPath, parsed, warnings: [...rebuildWarnings, ...warnings] };\n } catch (err) {\n if (!closed) db.close();\n throw err;\n }\n}\n\n// The sqlite store's open: connects synchronously (see connect() above), then wraps the\n// resulting connection in the async Store interface.\nexport async function openSqlite(cfg: ResolvedConfig): Promise<OpenResult> {\n const { db, conn, cfg: resolvedCfg, dbPath, parsed, warnings } = await connect(cfg);\n const store = createStore(db, conn, resolvedCfg, resolvedCfg.baseDir);\n // reconcile ran before this object existed, so its chunk text is keyed by the connection.\n rekeyChunkText(conn, store);\n return { store: store, cfg: resolvedCfg, dbPath, parsed, warnings };\n}\n\nexport async function docCount(store: Store): Promise<number> {\n const stmt = await store.prepare('SELECT COUNT(*) AS n FROM frontmatter');\n return ((await stmt.get()) as { n: number }).n;\n}\n"],"names":["mkdirSync","join","DatabaseSync","contentTokenize","featureSignature","STATE_DIR","rekeyChunkText","SenseError","activeFeatures","FEATURES","clearCache","getMeta","setMeta","BEGIN_WRITE","withTransaction","createConnection","changedSignatureKeys","embedIdentityAdopted","rebuildContentTable","reconcile","signatureDiff","registerFunctions","createStore","DB_FILENAME","SCHEMA_VERSION","DEFAULT_TOKENIZE","resolveTokenize","db","cfg","configured","undefined","literal","replace","exec","err","message","storedTokenize","row","prepare","get","m","sql","match","createContentTable","conn","tokenize","ensureSchema","feature","schema","setJournalWal","deadline","Date","now","test","Atomics","wait","Int32Array","SharedArrayBuffer","connect","stateDir","baseDir","recursive","dbPath","closed","version","features","wantFeatures","tokenizeOnlyRebuild","console","error","close","changedKeys","size","has","changed","stored","rebuildWarnings","recordedMaxMs","Number","Math","min","max","parsed","warnings","openSqlite","resolvedCfg","store","docCount","stmt","n"],"mappings":"AAAA,+FAA+F;AAC/F,iGAAiG;AACjG,SAASA,SAAS,QAAQ,UAAU;AACpC,SAASC,IAAI,QAAQ,YAAY;AACjC,SAASC,YAAY,QAAQ,cAAc;AAE3C,SAASC,eAAe,EAAEC,gBAAgB,EAAEC,SAAS,QAAQ,wBAAwB;AACrF,SAASC,cAAc,QAAQ,yBAAyB;AACxD,SAASC,UAAU,QAAQ,kBAAkB;AAC7C,SAASC,cAAc,EAAEC,QAAQ,QAAQ,0BAA0B;AACnE,SAASC,UAAU,QAAQ,cAAc;AACzC,SAASC,OAAO,EAAEC,OAAO,QAAQ,eAAe;AAChD,SAASC,WAAW,EAAEC,eAAe,QAAQ,oBAAoB;AAEjE,SAASC,gBAAgB,QAAQ,kBAAkB;AACnD,SAASC,oBAAoB,EAAEC,oBAAoB,EAAEC,mBAAmB,EAAEC,SAAS,EAAEC,aAAa,QAAQ,iBAAiB;AAC3H,SAASC,iBAAiB,QAAQ,qBAAqB;AACvD,SAASC,WAAW,QAAQ,aAAa;AAEzC,OAAO,MAAMC,cAAc,WAAW;AACtC,sFAAsF;AACtF,iCAAiC;AACjC,OAAO,MAAMC,iBAAiB,KAAK;AAmBnC,4FAA4F;AAC5F,4FAA4F;AAC5F,MAAMC,mBAAmB;AAEzB,6FAA6F;AAC7F,gGAAgG;AAChG,SAASC,gBAAgBC,EAAgB,EAAEC,GAAW;IACpD,MAAMC,aAAa1B,gBAAgByB;IACnC,IAAIC,eAAeC,WAAW,OAAOL;IACrC,MAAMM,UAAUF,WAAWG,OAAO,CAAC,M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,CAAA,MAAMkD,KAAKjD,GAAG,EAAC,EAAqBkD,CAAC;AAChD"}
|
|
1
|
+
{"version":3,"sources":["/Users/kevin/Dev/OpenSource/ai/sensemaking/src/store/sqlite/open.ts"],"sourcesContent":["// The Node floor (>=22.20) is explained here and nowhere else: 22.20 is the first release with\n// both FTS5 and row-returning INSERT ... RETURNING. Raise it only for a load-bearing capability.\nimport { DatabaseSync } from 'node:sqlite';\nimport type { Config, ResolvedConfig } from '../../config/index.ts';\nimport { contentTokenize, featureSignature } from '../../config/index.ts';\nimport { SenseError } from '../../errors.ts';\nimport { activeFeatures, FEATURES } from '../../features/index.ts';\nimport { listFiles, parseFile } from '../../scan/index.ts';\nimport type { OpenResult } from '../open.ts';\nimport { openWithDialect } from '../open.ts';\nimport { getMeta, setMeta } from '../shared.ts';\nimport { BEGIN_WRITE, withTransaction } from '../transaction.ts';\nimport type { Connection, OpenDialect } from '../types.ts';\nimport { createConnection } from './connection.ts';\nimport { contentRow, INSERT_CONTENT_SQL, sqliteDialect } from './reconcile.ts';\nimport { registerFunctions } from './sql-functions.ts';\nimport { createStore } from './store.ts';\n\nexport const DB_FILENAME = 'cache.db';\n// Cache shape version, independent of the config's own `version`. Bumping it rebuilds\n// existing trees on first query.\nexport const SCHEMA_VERSION = '19';\n\nexport type { OpenResult };\n\n// unicode61 splits on spaces, so a language written without them indexes a whole run as one\n// token and word search finds nothing; `content.tokenize` is how such a tree picks trigram.\nconst DEFAULT_TOKENIZE = 'porter unicode61';\n\n// The connection plus this store's own extra state (types.ts's OpenDialect<Handle>): the\n// resolved tokenizer, threaded through connect, the tokenize-only rebuild, and ensureSchema.\ninterface SqliteHandle {\n db: DatabaseSync;\n tokenize: string;\n}\n\n// FTS5 takes its tokenizer as a DDL string literal where nothing can bind, so the configured\n// value is concatenated; probing a throwaway table first is both the safety and the validation.\nfunction resolveTokenize(db: DatabaseSync, cfg: Config): string {\n const configured = contentTokenize(cfg);\n if (configured === undefined) return DEFAULT_TOKENIZE;\n const literal = configured.replace(/'/g, \"''\");\n try {\n db.exec('DROP TABLE IF EXISTS temp.sense_tokenize_probe');\n db.exec(`CREATE VIRTUAL TABLE temp.sense_tokenize_probe USING fts5(x, tokenize = '${literal}')`);\n db.exec('DROP TABLE IF EXISTS temp.sense_tokenize_probe');\n } catch (err) {\n throw new SenseError('CONFIG_INVALID', `content.tokenize \"${configured}\" is not a tokenizer this SQLite accepts (${(err as Error).message}); the built-in choices are unicode61, ascii, porter, and trigram, each with their own options`);\n }\n return literal;\n}\n\n// The tokenizer the content table was actually built with, from its own DDL -- the one\n// record that cannot desynchronize from the table. NULL when the table does not exist yet.\nfunction storedTokenize(db: DatabaseSync): string | null {\n const row = db.prepare(`SELECT sql FROM sqlite_master WHERE name = 'content'`).get() as { sql: string } | undefined;\n if (!row) return null;\n const m = row.sql.match(/tokenize = '((?:[^']|'')*)'/);\n return m ? m[1] : null;\n}\n\n// The `_seg` sidecars are appended after path, never inserted: bm25() and snippet(content, 2)\n// are documented against the first three columns. Each holds its field's exploded unspaced runs.\nasync function createContentTable(conn: Connection, tokenize: string): Promise<void> {\n await conn.exec(`CREATE VIRTUAL TABLE IF NOT EXISTS content USING fts5(title, summary, text, path UNINDEXED, title_seg, summary_seg, text_seg, tokenize = '${tokenize}')`);\n}\n\n// Content is a separate table (not a column on frontmatter) so `SELECT * FROM frontmatter`\n// can't dump file text into context. Features add their own tables after the core ones.\nasync function ensureSchemaTables(conn: Connection, cfg: Config, tokenize: string): Promise<void> {\n await conn.exec(`CREATE TABLE IF NOT EXISTS frontmatter (\"path\" TEXT PRIMARY KEY, \"_mtime\" REAL, \"_ctime\" REAL, \"_size\" INTEGER, \"_parse_error\" TEXT)`);\n // IF NOT EXISTS is safe against a tokenizer change: open() compares the table's own DDL\n // against the resolved tokenizer before this runs, so a stale table is already gone by now.\n await createContentTable(conn, tokenize);\n // Coverage, not ownership: a path can appear under several presets. path leads the PK so the\n // per-doc delete is an index hit -- keyed the other way, cold builds went quadratic.\n await conn.exec(`CREATE TABLE IF NOT EXISTS preset_files (\"path\" TEXT, preset TEXT, PRIMARY KEY (\"path\", preset))`);\n await conn.exec('CREATE INDEX IF NOT EXISTS preset_files_preset ON preset_files(preset)');\n for (const feature of activeFeatures(cfg)) await feature.schema(conn);\n if ((await getMeta(conn, 'schema_version')) === null) await setMeta(conn, 'schema_version', SCHEMA_VERSION);\n if ((await getMeta(conn, 'features')) === null) await setMeta(conn, 'features', featureSignature(cfg, FEATURES));\n}\n\n// Two processes opening the same fresh tree both try to convert it, and the loser gets SQLITE_BUSY\n// with no busy handler behind it. Bounded because a lock held past this is a real problem, not a race.\nfunction setJournalWal(db: DatabaseSync): void {\n const deadline = Date.now() + 5000;\n for (;;) {\n try {\n db.exec('PRAGMA journal_mode = WAL');\n return;\n } catch (err) {\n if (Date.now() >= deadline || !/database is locked|busy/i.test((err as Error).message)) throw err;\n Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 20);\n }\n }\n}\n\nasync function connect(dbPath: string, cfg: ResolvedConfig): Promise<{ handle: SqliteHandle; conn: Connection }> {\n const db = new DatabaseSync(dbPath);\n try {\n // Before journal_mode, not after: converting a fresh database to WAL takes a brief exclusive\n // lock, and with no timeout set yet a second process opening the same tree fails in 1ms.\n db.exec('PRAGMA busy_timeout = 30000');\n // busy_timeout does not cover the WAL conversion itself: SQLite does not invoke the busy\n // handler for it, so a concurrent cold open needs its own bounded wait.\n setJournalWal(db);\n registerFunctions(db, contentTokenize(cfg) === undefined);\n const conn = createConnection(db);\n // Before the rebuild branch below, never after: that branch deletes the cache, so a typo'd\n // tokenizer validated later would cost a full re-index (and re-embed) to reach its own error.\n const tokenize = resolveTokenize(db, cfg);\n return { handle: { db, tokenize }, conn };\n } catch (err) {\n // A throw here must release this handle, or on Windows the leaked WAL db is undeletable and\n // scratch cleanup fails with EPERM/EBUSY.\n db.close();\n throw err;\n }\n}\n\nasync function close(handle: SqliteHandle): Promise<void> {\n handle.db.close();\n}\n\n// Only the tokenizer moved, and frontmatter, links, sections and embeddings are file-derived\n// and tokenizer-independent. Any other signature change takes the full clear/reopen in open.ts.\nasync function partialRebuild(handle: SqliteHandle, conn: Connection, _cfg: Config, changedKeys: Set<string>): Promise<boolean> {\n if (!(changedKeys.size === 1 && changedKeys.has('tokenize'))) return false;\n console.error('sense: config change (content tokenizer) rebuilds the text index; vectors, links, and sections are kept');\n // One transaction, so a crash before COMMIT rolls back to the old tokenizer's table rather\n // than to no table. IF EXISTS makes a retry after such a crash a no-op, not a raw error.\n await withTransaction(\n conn,\n async () => {\n await conn.exec('DROP TABLE IF EXISTS content');\n await createContentTable(conn, handle.tokenize);\n },\n BEGIN_WRITE\n );\n return true;\n}\n\n// Tokenize-only rebuild: only `content` is repopulated (the other tables are tokenizer-independent)\n// and no feature extractors run. Warnings come from the reparse, since mtimes stay untouched and reconcile would never reparse them.\nasync function postSchemaRebuild(_handle: SqliteHandle, conn: Connection, cfg: Config, baseDir: string, wantFeatures: string): Promise<string[]> {\n const stmt = await conn.prepare('SELECT \"path\" FROM frontmatter');\n const known = new Set(((await stmt.all()) as Array<{ path: string }>).map((r) => r.path));\n const files = listFiles(cfg, baseDir).filter((f) => known.has(f.relPath));\n const segmenting = contentTokenize(cfg) === undefined;\n const warnings: string[] = [];\n const rows: unknown[][] = [];\n for (const file of files) {\n const { doc, warnings: fileWarnings } = parseFile(file);\n warnings.push(...fileWarnings);\n rows.push(contentRow(doc, segmenting));\n }\n await withTransaction(\n conn,\n async () => {\n if (rows.length > 0) await conn.runBatch(INSERT_CONTENT_SQL, rows);\n },\n BEGIN_WRITE\n );\n await setMeta(conn, 'features', wantFeatures);\n return warnings;\n}\n\n// Meta can lie after a crash between table creation and the signature write; the table's own\n// DDL cannot, so a mismatch here rebuilds whatever meta says.\nfunction extraRebuildReason(handle: SqliteHandle): string | null {\n const stored = storedTokenize(handle.db);\n if (stored !== null && stored !== handle.tokenize) return 'cache was built with a different content tokenizer';\n return null;\n}\n\nasync function ensureSchema(handle: SqliteHandle, conn: Connection, cfg: Config): Promise<void> {\n // One writer at a time: the feature hooks check a column then add it, so two cold opens racing\n // here both see it missing and the second ALTER fails with a duplicate column.\n await withTransaction(conn, () => ensureSchemaTables(conn, cfg, handle.tokenize), BEGIN_WRITE);\n}\n\nasync function setDerivedBusyTimeout(handle: SqliteHandle, _conn: Connection, ms: number): Promise<void> {\n handle.db.exec(`PRAGMA busy_timeout = ${ms}`);\n}\n\n// This store's dialect (types.ts's OpenDialect) for the shared orchestration in store/open.ts.\nexport const sqliteOpenDialect: OpenDialect<SqliteHandle> = {\n filename: DB_FILENAME,\n schemaVersion: SCHEMA_VERSION,\n reconcileDialect: sqliteDialect,\n connect,\n close,\n partialRebuild,\n postSchemaRebuild,\n extraRebuildReason,\n ensureSchema,\n setDerivedBusyTimeout,\n createStore: (handle, conn, cfg) => createStore(handle.db, conn, cfg),\n};\n\nexport async function openSqlite(cfg: ResolvedConfig): Promise<OpenResult> {\n return openWithDialect(cfg, sqliteOpenDialect);\n}\n"],"names":["DatabaseSync","contentTokenize","featureSignature","SenseError","activeFeatures","FEATURES","listFiles","parseFile","openWithDialect","getMeta","setMeta","BEGIN_WRITE","withTransaction","createConnection","contentRow","INSERT_CONTENT_SQL","sqliteDialect","registerFunctions","createStore","DB_FILENAME","SCHEMA_VERSION","DEFAULT_TOKENIZE","resolveTokenize","db","cfg","configured","undefined","literal","replace","exec","err","message","storedTokenize","row","prepare","get","m","sql","match","createContentTable","conn","tokenize","ensureSchemaTables","feature","schema","setJournalWal","deadline","Date","now","test","Atomics","wait","Int32Array","SharedArrayBuffer","connect","dbPath","handle","close","partialRebuild","_cfg","changedKeys","size","has","console","error","postSchemaRebuild","_handle","baseDir","wantFeatures","stmt","known","Set","all","map","r","path","files","filter","f","relPath","segmenting","warnings","rows","file","doc","fileWarnings","push","length","runBatch","extraRebuildReason","stored","ensureSchema","setDerivedBusyTimeout","_conn","ms","sqliteOpenDialect","filename","schemaVersion","reconcileDialect","openSqlite"],"mappings":"AAA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Ae7E;IACf8E,kBAAkBlF;IAClBsC;IACAG;IACAC;IACAO;IACAwB;IACAE;IACAC;IACA1E,aAAa,CAACsC,QAAQhB,MAAMhB,MAAQN,YAAYsC,OAAOjC,EAAE,EAAEiB,MAAMhB;AACnE,EAAE;AAEF,OAAO,eAAe2E,WAAW3E,GAAmB;IAClD,OAAOhB,gBAAgBgB,KAAKuE;AAC9B"}
|
|
@@ -1,10 +1,5 @@
|
|
|
1
|
-
import type {
|
|
2
|
-
import type {
|
|
3
|
-
export declare
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
}>;
|
|
7
|
-
export declare function changedSignatureKeys(before: string, after: string): Set<string>;
|
|
8
|
-
export declare function embedIdentityAdopted(before: string, after: string): boolean;
|
|
9
|
-
export declare function signatureDiff(before: string, after: string): string;
|
|
10
|
-
export declare function rebuildContentTable(conn: Connection, cfg: Config, baseDir: string): Promise<string[]>;
|
|
1
|
+
import type { ParsedDoc } from '../../scan/index.js';
|
|
2
|
+
import type { ReconcileDialect } from '../types.js';
|
|
3
|
+
export declare const INSERT_CONTENT_SQL = "INSERT INTO content (rowid, title, summary, text, \"path\", title_seg, summary_seg, text_seg) VALUES ((SELECT rowid FROM frontmatter WHERE \"path\" = ?), ?, ?, ?, ?, ?, ?, ?)";
|
|
4
|
+
export declare function contentRow(doc: ParsedDoc, segmenting: boolean): unknown[];
|
|
5
|
+
export declare const sqliteDialect: ReconcileDialect;
|
|
@@ -1,29 +1,18 @@
|
|
|
1
1
|
import { contentTokenize } from '../../config/index.js';
|
|
2
2
|
import { SenseError } from '../../errors.js';
|
|
3
|
-
import { activeFeatures } from '../../features/index.js';
|
|
4
|
-
import { progress } from '../../output/progress.js';
|
|
5
|
-
import { listFiles, parseFile, RESERVED_COLUMNS } from '../../scan/index.js';
|
|
6
|
-
import { reparseFiles } from '../../scan/reparse.js';
|
|
7
3
|
import { segmentField } from '../../text/segment.js';
|
|
8
|
-
import {
|
|
9
|
-
import { BEGIN_WRITE
|
|
10
|
-
//
|
|
11
|
-
//
|
|
12
|
-
const CORE_FRONTMATTER_COLUMNS = new Set([
|
|
13
|
-
'path',
|
|
14
|
-
'_mtime',
|
|
15
|
-
'_ctime',
|
|
16
|
-
'_size',
|
|
17
|
-
'_parse_error'
|
|
18
|
-
]);
|
|
4
|
+
import { recordReconcileDuration } from '../shared.js';
|
|
5
|
+
import { BEGIN_WRITE } from '../transaction.js';
|
|
6
|
+
// This store's dialect (types.ts's ReconcileDialect) for the shared orchestration in
|
|
7
|
+
// store/reconcile.ts. content is FTS5-virtual with "_seg" sidecars for lexical.ts.
|
|
19
8
|
// SQLite's compile-time SQLITE_MAX_COLUMN, default 2000 (https://www.sqlite.org/limits.html).
|
|
20
9
|
const MAX_FRONTMATTER_COLUMNS = 2000;
|
|
21
|
-
// Shared by
|
|
22
|
-
// literal instead of two copies drifting apart.
|
|
23
|
-
const INSERT_CONTENT_SQL = `INSERT INTO content (rowid, title, summary, text, "path", title_seg, summary_seg, text_seg) VALUES ((SELECT rowid FROM frontmatter WHERE "path" = ?), ?, ?, ?, ?, ?, ?, ?)`;
|
|
10
|
+
// Shared by reconcileContent() and the tokenize-only rebuild in open.ts, so both prepare the
|
|
11
|
+
// same literal instead of two copies drifting apart.
|
|
12
|
+
export const INSERT_CONTENT_SQL = `INSERT INTO content (rowid, title, summary, text, "path", title_seg, summary_seg, text_seg) VALUES ((SELECT rowid FROM frontmatter WHERE "path" = ?), ?, ?, ?, ?, ?, ?, ?)`;
|
|
24
13
|
// A single content row's param tuple, matching INSERT_CONTENT_SQL's placeholder order.
|
|
25
14
|
// Assumes the frontmatter row for doc.relPath already exists (rowid subquery).
|
|
26
|
-
function contentRow(doc, segmenting) {
|
|
15
|
+
export function contentRow(doc, segmenting) {
|
|
27
16
|
return [
|
|
28
17
|
doc.relPath,
|
|
29
18
|
doc.search.title,
|
|
@@ -35,188 +24,29 @@ function contentRow(doc, segmenting) {
|
|
|
35
24
|
segmenting ? segmentField(doc.search.text) : ''
|
|
36
25
|
];
|
|
37
26
|
}
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
const existing = new Map(existingRows.map((r)=>[
|
|
44
|
-
r.path,
|
|
45
|
-
r
|
|
27
|
+
async function reconcileContent(conn, touched, docs, _delta, cfg) {
|
|
28
|
+
// FTS5 has no upsert, so delete-before-insert, coupled to the frontmatter rowid (indexed via
|
|
29
|
+
// its PRIMARY KEY) rather than the UNINDEXED `path` column, which a per-row DELETE would scan to find.
|
|
30
|
+
if (touched.length > 0) await conn.runBatch('DELETE FROM content WHERE rowid = (SELECT rowid FROM frontmatter WHERE "path" = ?)', touched.map((p)=>[
|
|
31
|
+
p
|
|
46
32
|
]));
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
if (vanished.length === 0 && toReparse.length === 0) return {
|
|
53
|
-
parsed: 0,
|
|
54
|
-
warnings: []
|
|
55
|
-
};
|
|
56
|
-
const features = activeFeatures(cfg);
|
|
57
|
-
const seenColumns = await getColumns(conn);
|
|
58
|
-
// Bulk reparses (a sync, a cold build) are the long silences a query can hit; short
|
|
59
|
-
// reconciles stay silent (progress() has a threshold).
|
|
60
|
-
const report = progress('reparsing files', toReparse.length);
|
|
61
|
-
const { docs: parsedDocs, warnings, newColumns } = await reparseFiles(toReparse, features, cfg, seenColumns, report.tick);
|
|
62
|
-
report.finish();
|
|
63
|
-
for (const col of newColumns)seenColumns.add(col);
|
|
64
|
-
const allColumns = [
|
|
65
|
-
...seenColumns
|
|
66
|
-
];
|
|
67
|
-
// Fence before ALTERing: SQLite's own failure past this point is a raw
|
|
68
|
-
// "too many columns on sqlite_altertab_frontmatter" with no indication of the boundary or the levers.
|
|
69
|
-
if (allColumns.length > MAX_FRONTMATTER_COLUMNS) {
|
|
70
|
-
throw new SenseError('COLUMN_LIMIT', `frontmatter would need ${allColumns.length} columns, crossing SQLite's compile-time SQLITE_MAX_COLUMN limit (default ${MAX_FRONTMATTER_COLUMNS}; see https://www.sqlite.org/limits.html). Narrow the presets' include globs so fewer/other files are indexed, or fix whatever is generating unbounded frontmatter keys.`);
|
|
33
|
+
if (docs.length > 0) {
|
|
34
|
+
// A non-default tokenizer means the tree has chosen its own scheme; a phrase query over
|
|
35
|
+
// grapheme runs would be nonsense against trigram, so the sidecars stay empty.
|
|
36
|
+
const segmenting = contentTokenize(cfg) === undefined;
|
|
37
|
+
await conn.runBatch(INSERT_CONTENT_SQL, docs.map((doc)=>contentRow(doc, segmenting)));
|
|
71
38
|
}
|
|
72
|
-
// Columns the frontmatter upsert actually writes: core + parsed frontmatter keys, never a
|
|
73
|
-
// feature-owned reserved column (see CORE_FRONTMATTER_COLUMNS above).
|
|
74
|
-
const writableColumns = allColumns.filter((c)=>CORE_FRONTMATTER_COLUMNS.has(c) || !RESERVED_COLUMNS.has(c));
|
|
75
|
-
// ON CONFLICT UPDATE (not OR REPLACE) keeps the row's rowid stable across reparses --
|
|
76
|
-
// content rows are coupled to that rowid below.
|
|
77
|
-
const insertSql = `INSERT INTO frontmatter (${writableColumns.map(quoteIdent).join(', ')}) VALUES (${writableColumns.map(()=>'?').join(', ')}) ON CONFLICT("path") DO UPDATE SET ${writableColumns.filter((c)=>c !== 'path').map((c)=>`${quoteIdent(c)} = excluded.${quoteIdent(c)}`).join(', ')}`;
|
|
78
|
-
const added = toReparse.filter((f)=>!existing.has(f.relPath)).map((f)=>f.relPath);
|
|
79
|
-
const delta = {
|
|
80
|
-
files,
|
|
81
|
-
reparsed: parsedDocs.map((d)=>d.relPath),
|
|
82
|
-
added,
|
|
83
|
-
vanished
|
|
84
|
-
};
|
|
85
|
-
const addedSet = new Set(added);
|
|
86
|
-
const reparsedExisting = parsedDocs.map((d)=>d.relPath).filter((p)=>!addedSet.has(p));
|
|
87
|
-
const txStart = Date.now();
|
|
88
|
-
await withTransaction(conn, async ()=>{
|
|
89
|
-
var _feature_remove, _feature_afterReconcile;
|
|
90
|
-
// Re-read inside the write transaction: newColumns came from a read taken before it opened, so a
|
|
91
|
-
// concurrent reconcile may have added some of them since. ALTER has no IF NOT EXISTS.
|
|
92
|
-
const present = await getColumns(conn);
|
|
93
|
-
for (const col of newColumns)if (!present.has(col)) await conn.exec(`ALTER TABLE frontmatter ADD COLUMN ${quoteIdent(col)}`);
|
|
94
|
-
// content's rowid lookup depends on its coupled frontmatter row, so the content
|
|
95
|
-
// deletes/inserts run while every path still has one -- the vanished frontmatter delete comes last.
|
|
96
|
-
if (vanished.length > 0) {
|
|
97
|
-
await conn.runBatch('DELETE FROM content WHERE rowid = (SELECT rowid FROM frontmatter WHERE "path" = ?)', vanished.map((p)=>[
|
|
98
|
-
p
|
|
99
|
-
]));
|
|
100
|
-
}
|
|
101
|
-
if (reparsedExisting.length > 0) {
|
|
102
|
-
// FTS5 has no upsert, so delete-before-insert, coupled to the frontmatter rowid (indexed via
|
|
103
|
-
// its PRIMARY KEY) rather than the UNINDEXED `path` column, which a per-row DELETE would scan to find.
|
|
104
|
-
await conn.runBatch('DELETE FROM content WHERE rowid = (SELECT rowid FROM frontmatter WHERE "path" = ?)', reparsedExisting.map((p)=>[
|
|
105
|
-
p
|
|
106
|
-
]));
|
|
107
|
-
}
|
|
108
|
-
if (parsedDocs.length > 0) {
|
|
109
|
-
const rows = parsedDocs.map((doc)=>writableColumns.map((col)=>{
|
|
110
|
-
var _doc_data_col;
|
|
111
|
-
if (col === 'path') return doc.relPath;
|
|
112
|
-
if (col === '_mtime') return doc.mtimeMs;
|
|
113
|
-
if (col === '_ctime') return doc.ctimeMs;
|
|
114
|
-
if (col === '_size') return doc.size;
|
|
115
|
-
// Written per parse, unlike _rank, which a feature pass owns and the upsert skips.
|
|
116
|
-
if (col === '_parse_error') return doc.parseError;
|
|
117
|
-
return (_doc_data_col = doc.data[col]) !== null && _doc_data_col !== void 0 ? _doc_data_col : null;
|
|
118
|
-
}));
|
|
119
|
-
await conn.runBatch(insertSql, rows);
|
|
120
|
-
// A non-default tokenizer means the tree has chosen its own scheme; a phrase query over
|
|
121
|
-
// grapheme runs would be nonsense against trigram, so the sidecars stay empty.
|
|
122
|
-
const segmenting = contentTokenize(cfg) === undefined;
|
|
123
|
-
await conn.runBatch(INSERT_CONTENT_SQL, parsedDocs.map((doc)=>contentRow(doc, segmenting)));
|
|
124
|
-
}
|
|
125
|
-
if (vanished.length > 0) await conn.runBatch('DELETE FROM frontmatter WHERE "path" = ?', vanished.map((p)=>[
|
|
126
|
-
p
|
|
127
|
-
]));
|
|
128
|
-
// A preset edit forces a full rebuild, so an unchanged doc's coverage is already correct;
|
|
129
|
-
// new docs have nothing to clear, which keeps cold builds linear.
|
|
130
|
-
const presetTouched = [
|
|
131
|
-
...vanished,
|
|
132
|
-
...reparsedExisting
|
|
133
|
-
];
|
|
134
|
-
if (presetTouched.length > 0) await conn.runBatch('DELETE FROM preset_files WHERE "path" = ?', presetTouched.map((p)=>[
|
|
135
|
-
p
|
|
136
|
-
]));
|
|
137
|
-
const presetRows = [];
|
|
138
|
-
for (const doc of parsedDocs)for (const presetName of doc.presets)presetRows.push([
|
|
139
|
-
doc.relPath,
|
|
140
|
-
presetName
|
|
141
|
-
]);
|
|
142
|
-
if (presetRows.length > 0) await conn.runBatch('INSERT INTO preset_files ("path", preset) VALUES (?, ?)', presetRows);
|
|
143
|
-
const removedPaths = [
|
|
144
|
-
...vanished,
|
|
145
|
-
...reparsedExisting
|
|
146
|
-
];
|
|
147
|
-
if (removedPaths.length > 0) for (const feature of features)await ((_feature_remove = feature.remove) === null || _feature_remove === void 0 ? void 0 : _feature_remove.call(feature, conn, removedPaths, delta));
|
|
148
|
-
for (const feature of features){
|
|
149
|
-
var _feature_store;
|
|
150
|
-
const docsForFeature = parsedDocs.map((doc)=>({
|
|
151
|
-
path: doc.relPath,
|
|
152
|
-
extracted: doc.extracted[feature.name]
|
|
153
|
-
}));
|
|
154
|
-
await ((_feature_store = feature.store) === null || _feature_store === void 0 ? void 0 : _feature_store.call(feature, conn, docsForFeature, delta));
|
|
155
|
-
}
|
|
156
|
-
for (const feature of features)await ((_feature_afterReconcile = feature.afterReconcile) === null || _feature_afterReconcile === void 0 ? void 0 : _feature_afterReconcile.call(feature, conn, delta));
|
|
157
|
-
}, BEGIN_WRITE);
|
|
158
|
-
// Reconcile's own write-transaction duration, for open()'s derived busy_timeout (F):
|
|
159
|
-
// keep the observed max so a big watcher reconcile's lock hold is what the next open bounds its wait against.
|
|
160
|
-
const durationMs = Date.now() - txStart;
|
|
161
|
-
const prevRaw = await getMeta(conn, 'reconcile_max_ms');
|
|
162
|
-
// -1, not 0, so a genuinely 0ms first reconcile (sub-millisecond, common on a tiny tree)
|
|
163
|
-
// still gets recorded instead of losing to the "nothing recorded yet" default.
|
|
164
|
-
const prevMax = prevRaw === null ? -1 : Number(prevRaw);
|
|
165
|
-
if (durationMs > prevMax) await setMeta(conn, 'reconcile_max_ms', String(durationMs));
|
|
166
|
-
return {
|
|
167
|
-
parsed: parsedDocs.length,
|
|
168
|
-
warnings
|
|
169
|
-
};
|
|
170
|
-
}
|
|
171
|
-
// Segment keys that moved between two feature signatures (see config.featureSignature's
|
|
172
|
-
// format: global features, embed provider, tokenize, then one segment per preset).
|
|
173
|
-
export function changedSignatureKeys(before, after) {
|
|
174
|
-
const keyOf = (part)=>part.startsWith('preset:') ? part.split(':').slice(0, 2).join(':') : part.split(':')[0];
|
|
175
|
-
const parse = (sig)=>new Map(sig.split('|').map((part)=>[
|
|
176
|
-
keyOf(part),
|
|
177
|
-
part
|
|
178
|
-
]));
|
|
179
|
-
const a = parse(before);
|
|
180
|
-
const b = parse(after);
|
|
181
|
-
const changed = new Set();
|
|
182
|
-
for (const [key, val] of b)if (a.get(key) !== val) changed.add(key);
|
|
183
|
-
for (const key of a.keys())if (!b.has(key)) changed.add(key);
|
|
184
|
-
return changed;
|
|
185
|
-
}
|
|
186
|
-
// Whether the embed segment only gained its resolved weight identity: same provider and
|
|
187
|
-
// model, no identity recorded before, one now -- adopted into meta without a rebuild.
|
|
188
|
-
export function embedIdentityAdopted(before, after) {
|
|
189
|
-
const embedPart = (sig)=>sig.split('|').find((p)=>p.startsWith('embed:'));
|
|
190
|
-
const b = embedPart(before);
|
|
191
|
-
const a = embedPart(after);
|
|
192
|
-
if (b === undefined || a === undefined) return false;
|
|
193
|
-
const at = a.indexOf('@');
|
|
194
|
-
return b.indexOf('@') === -1 && at !== -1 && a.slice(0, at) === b;
|
|
195
|
-
}
|
|
196
|
-
// Names what moved, for the rebuild notice.
|
|
197
|
-
export function signatureDiff(before, after) {
|
|
198
|
-
const changed = changedSignatureKeys(before, after);
|
|
199
|
-
const label = (key)=>key === 'embed' ? 'embed settings' : key === 'tokenize' ? 'content tokenizer' : key.startsWith('preset:') ? `preset "${key.slice(7)}"` : 'features';
|
|
200
|
-
return changed.size === 0 ? 'features' : [
|
|
201
|
-
...changed
|
|
202
|
-
].map(label).join(', ');
|
|
203
|
-
}
|
|
204
|
-
// Tokenize-only rebuild: only `content` is repopulated (the other tables are tokenizer-independent)
|
|
205
|
-
// and no feature extractors run. Returns per-file warnings, since mtimes stay untouched and reconcile would never reparse them.
|
|
206
|
-
export async function rebuildContentTable(conn, cfg, baseDir) {
|
|
207
|
-
const stmt = await conn.prepare('SELECT "path" FROM frontmatter');
|
|
208
|
-
const known = new Set((await stmt.all()).map((r)=>r.path));
|
|
209
|
-
const files = listFiles(cfg, baseDir).filter((f)=>known.has(f.relPath));
|
|
210
|
-
const segmenting = contentTokenize(cfg) === undefined;
|
|
211
|
-
const warnings = [];
|
|
212
|
-
const rows = [];
|
|
213
|
-
for (const file of files){
|
|
214
|
-
const { doc, warnings: fileWarnings } = parseFile(file);
|
|
215
|
-
warnings.push(...fileWarnings);
|
|
216
|
-
rows.push(contentRow(doc, segmenting));
|
|
217
|
-
}
|
|
218
|
-
await withTransaction(conn, async ()=>{
|
|
219
|
-
if (rows.length > 0) await conn.runBatch(INSERT_CONTENT_SQL, rows);
|
|
220
|
-
}, BEGIN_WRITE);
|
|
221
|
-
return warnings;
|
|
222
39
|
}
|
|
40
|
+
export const sqliteDialect = {
|
|
41
|
+
beginMode: ()=>BEGIN_WRITE,
|
|
42
|
+
checkColumnLimit (count) {
|
|
43
|
+
// Fence before ALTERing: SQLite's own failure past this point is a raw
|
|
44
|
+
// "too many columns on sqlite_altertab_frontmatter" with no indication of the boundary or the levers.
|
|
45
|
+
if (count > MAX_FRONTMATTER_COLUMNS) {
|
|
46
|
+
throw new SenseError('COLUMN_LIMIT', `frontmatter would need ${count} columns, crossing SQLite's compile-time SQLITE_MAX_COLUMN limit (default ${MAX_FRONTMATTER_COLUMNS}; see https://www.sqlite.org/limits.html). Narrow the presets' include globs so fewer/other files are indexed, or fix whatever is generating unbounded frontmatter keys.`);
|
|
47
|
+
}
|
|
48
|
+
},
|
|
49
|
+
columnTypeSuffix: ()=>'',
|
|
50
|
+
reconcileContent,
|
|
51
|
+
recordDuration: recordReconcileDuration
|
|
52
|
+
};
|