@peerbit/indexer-sqlite3 3.0.0-e6ea5c0 → 3.0.1

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.
Files changed (47) hide show
  1. package/dist/assets/sqlite3/sqlite3.worker.min.js +168 -52
  2. package/dist/index.min.js +277 -53
  3. package/dist/index.min.js.map +3 -3
  4. package/dist/src/engine.d.ts +9 -3
  5. package/dist/src/engine.d.ts.map +1 -1
  6. package/dist/src/engine.js +75 -9
  7. package/dist/src/engine.js.map +1 -1
  8. package/dist/src/index.d.ts +7 -3
  9. package/dist/src/index.d.ts.map +1 -1
  10. package/dist/src/index.js +5 -4
  11. package/dist/src/index.js.map +1 -1
  12. package/dist/src/schema.d.ts +5 -1
  13. package/dist/src/schema.d.ts.map +1 -1
  14. package/dist/src/schema.js +42 -12
  15. package/dist/src/schema.js.map +1 -1
  16. package/dist/src/sqlite3-messages.worker.d.ts +47 -8
  17. package/dist/src/sqlite3-messages.worker.d.ts.map +1 -1
  18. package/dist/src/sqlite3-messages.worker.js +42 -3
  19. package/dist/src/sqlite3-messages.worker.js.map +1 -1
  20. package/dist/src/sqlite3.browser.d.ts +22 -1
  21. package/dist/src/sqlite3.browser.d.ts.map +1 -1
  22. package/dist/src/sqlite3.browser.js +138 -31
  23. package/dist/src/sqlite3.browser.js.map +1 -1
  24. package/dist/src/sqlite3.d.ts +4 -1
  25. package/dist/src/sqlite3.d.ts.map +1 -1
  26. package/dist/src/sqlite3.js +14 -5
  27. package/dist/src/sqlite3.js.map +1 -1
  28. package/dist/src/sqlite3.wasm.d.ts +4 -1
  29. package/dist/src/sqlite3.wasm.d.ts.map +1 -1
  30. package/dist/src/sqlite3.wasm.js +15 -3
  31. package/dist/src/sqlite3.wasm.js.map +1 -1
  32. package/dist/src/sqlite3.worker.js +146 -53
  33. package/dist/src/sqlite3.worker.js.map +1 -1
  34. package/dist/src/utils.d.ts +1 -0
  35. package/dist/src/utils.d.ts.map +1 -1
  36. package/dist/src/utils.js +11 -0
  37. package/dist/src/utils.js.map +1 -1
  38. package/package.json +10 -9
  39. package/src/engine.ts +99 -11
  40. package/src/index.ts +39 -4
  41. package/src/schema.ts +67 -11
  42. package/src/sqlite3-messages.worker.ts +104 -10
  43. package/src/sqlite3.browser.ts +246 -88
  44. package/src/sqlite3.ts +19 -5
  45. package/src/sqlite3.wasm.ts +25 -3
  46. package/src/sqlite3.worker.ts +170 -49
  47. package/src/utils.ts +14 -0
package/dist/index.min.js CHANGED
@@ -20787,20 +20787,39 @@ var isUint8ArrayType = (type) => {
20787
20787
  }
20788
20788
  return false;
20789
20789
  };
20790
- var insert = async (insertFn, obj, tables, table, fields, handleNestedCallback, parentId = void 0, index) => {
20790
+ var insert = async (insertFn, obj, tables, table, fields, handleNestedCallback, parentId = void 0, index, options) => {
20791
20791
  const bindableValues = [];
20792
20792
  let nestedCallbacks = [];
20793
20793
  handleNestedCallback = table.primary === false ? handleNestedCallback : (fn) => nestedCallbacks.push(fn);
20794
+ const toInsertValue = (item, subTable) => typeof item === "function" && item instanceof Uint8Array === false ? item : subTable.isSimpleValue ? (
20795
+ // eslint-disable-next-line new-cap
20796
+ new subTable.ctor(item)
20797
+ ) : Object.assign(Object.create(subTable.ctor.prototype), item);
20794
20798
  const handleElement = async (item, field2, parentId2, index2) => {
20795
20799
  const subTable = getTableFromValue(table, tables, field2, item);
20796
- await insert(insertFn, typeof item === "function" && item instanceof Uint8Array === false ? item : subTable.isSimpleValue ? (
20797
- // eslint-disable-next-line new-cap
20798
- new subTable.ctor(item)
20799
- ) : Object.assign(Object.create(subTable.ctor.prototype), item), tables, subTable, getSchema(subTable.ctor).fields, handleNestedCallback, parentId2, index2);
20800
+ await insert(insertFn, toInsertValue(item, subTable), tables, subTable, getSchema(subTable.ctor).fields, handleNestedCallback, parentId2, index2, options);
20800
20801
  };
20801
20802
  const handleNested = async (field2, optional, parentId2) => {
20802
20803
  if (Array.isArray(obj[field2.key])) {
20803
20804
  const arr = obj[field2.key];
20805
+ const firstItem = arr.find((item) => item != null);
20806
+ if (parentId2 != null && arr.length > 1 && firstItem != null && options?.insertSimpleVecRows) {
20807
+ const subTable = getTableFromValue(table, tables, field2, firstItem);
20808
+ if (subTable.isSimpleValue) {
20809
+ const rows = [];
20810
+ for (let i = 0; i < arr.length; i++) {
20811
+ const item = arr[i];
20812
+ await insert((values) => {
20813
+ rows.push(values);
20814
+ return void 0;
20815
+ }, toInsertValue(item, subTable), tables, subTable, getSchema(subTable.ctor).fields, handleNestedCallback, parentId2, i, options);
20816
+ }
20817
+ if (rows.length > 0) {
20818
+ await options.insertSimpleVecRows(rows, subTable);
20819
+ }
20820
+ return;
20821
+ }
20822
+ }
20804
20823
  for (let i = 0; i < arr.length; i++) {
20805
20824
  const item = arr[i];
20806
20825
  await handleElement(item, field2, parentId2, i);
@@ -20868,7 +20887,9 @@ var insert = async (insertFn, obj, tables, table, fields, handleNestedCallback,
20868
20887
  (fn) => nestedCallbacks.push(fn),
20869
20888
  void 0,
20870
20889
  // parentId is not defined here, we are inserting a nested object inline
20871
- void 0
20890
+ void 0,
20891
+ // index is not defined here, we are inserting a nested object inline
20892
+ options
20872
20893
  );
20873
20894
  } else {
20874
20895
  nestedFields.push(field2);
@@ -20881,7 +20902,9 @@ var insert = async (insertFn, obj, tables, table, fields, handleNestedCallback,
20881
20902
  const isOptional = nested.type instanceof OptionKind;
20882
20903
  await handleNestedCallback((id) => handleNested(nested, isOptional, id));
20883
20904
  }
20884
- const thisId = await insertFn(bindableValues, table);
20905
+ const thisId = await insertFn(bindableValues, table, {
20906
+ requireId: nestedCallbacks.length > 0
20907
+ });
20885
20908
  if (table.primary === false && nestedCallbacks.length > 0) {
20886
20909
  throw new Error("Unexpected");
20887
20910
  }
@@ -21343,7 +21366,8 @@ var _buildJoin = (table, options) => {
21343
21366
  }
21344
21367
  if (table.columns.length > 0) {
21345
21368
  const usedColumns = removeDuplicatesOrdered(table.columns);
21346
- indexedBy = options?.planner ? ` INDEXED BY ${options.planner.resolveIndex(table.table.name, usedColumns)} ` : "";
21369
+ const usesImplicitPrimaryKeyIndex = table.type === "root" && table.table.primary !== false && usedColumns.length === 1 && usedColumns[0] === table.table.primary;
21370
+ indexedBy = options?.planner && !usesImplicitPrimaryKeyIndex ? ` INDEXED BY ${options.planner.resolveIndex(table.table.name, usedColumns)} ` : "";
21347
21371
  }
21348
21372
  if (table.type !== "root") {
21349
21373
  let nonInlinedParent = table.table.parent && getNonInlinedTable(table.table.parent);
@@ -21893,12 +21917,17 @@ var generatePermutations = (list) => {
21893
21917
  var isFKError = (e) => {
21894
21918
  return e?.code === "SQLITE_CONSTRAINT_FOREIGNKEY" || e?.rc === 787 || e?.message && (e.message.includes("SQLITE_CONSTRAINT_FOREIGNKEY") || e.message.includes("FOREIGN KEY constraint failed"));
21895
21919
  };
21920
+ var isUniqueConstraintError = (e) => {
21921
+ return e?.code === "SQLITE_CONSTRAINT_PRIMARYKEY" || e?.code === "SQLITE_CONSTRAINT_UNIQUE" || e?.rc === 1555 || e?.rc === 2067 || e?.message && (e.message.includes("SQLITE_CONSTRAINT_PRIMARYKEY") || e.message.includes("SQLITE_CONSTRAINT_UNIQUE") || e.message.includes("UNIQUE constraint failed") || e.message.includes("PRIMARY KEY constraint failed"));
21922
+ };
21896
21923
 
21897
21924
  // dist/src/engine.js
21898
21925
  var escapePathToSQLName = (path) => {
21899
21926
  return path.map((x) => x.replace(/[^a-zA-Z0-9]/g, "_"));
21900
21927
  };
21901
21928
  var putStatementKey = (table) => table.name + "_put";
21929
+ var insertKnownIdStatementKey = (table) => table.name + "_insert_known_id";
21930
+ var putStatementBatchNoReturnKey = (table, rows) => table.name + "_put_batch_noreturn_" + rows;
21902
21931
  var replaceStatementKey = (table) => table.name + "_replicate";
21903
21932
  var resolveChildrenStatement = (table) => table.name + "_resolve_children";
21904
21933
  async function safeReset(stmt) {
@@ -21940,7 +21969,20 @@ async function getIgnoreFK(stmt, values) {
21940
21969
  throw e;
21941
21970
  }
21942
21971
  }
21943
- var SQLLiteIndex = class {
21972
+ var createBatchInsertSQL = (table, rows) => {
21973
+ const columns = table.fields.map((field2) => escapeColumnName(field2.name)).join(", ");
21974
+ const rowPlaceholder = `(${table.fields.map(() => "?").join(", ")})`;
21975
+ return `insert into ${table.name} (${columns}) VALUES ${Array.from({
21976
+ length: rows
21977
+ }).map(() => rowPlaceholder).join(", ")};`;
21978
+ };
21979
+ var canUseWithoutRowId = (table) => {
21980
+ if (table.inline || table.primary === false || !table.primaryField) {
21981
+ return false;
21982
+ }
21983
+ return !/^INTEGER\b/i.test(table.primaryField.type);
21984
+ };
21985
+ var SQLiteIndex = class {
21944
21986
  properties;
21945
21987
  // SQLite writes are inherently serialized per connection.
21946
21988
  // We still need an explicit async barrier because our API is async and
@@ -21990,6 +22032,9 @@ var SQLLiteIndex = class {
21990
22032
  exec: this.properties.db.exec.bind(this.properties.db)
21991
22033
  });
21992
22034
  }
22035
+ persisted() {
22036
+ return this.properties.persisted ?? true;
22037
+ }
21993
22038
  get tables() {
21994
22039
  if (this.closed) {
21995
22040
  throw new NotStartedError();
@@ -22053,11 +22098,14 @@ var SQLLiteIndex = class {
22053
22098
  if (table.inline) {
22054
22099
  continue;
22055
22100
  }
22056
- const sqlCreateTable = `create table if not exists ${table.name} (${[...table.fields, ...table.constraints].map((s) => s.definition).join(", ")}) strict`;
22101
+ const tableOptions = canUseWithoutRowId(table) ? " strict, without rowid" : " strict";
22102
+ const sqlCreateTable = `create table if not exists ${table.name} (${[...table.fields, ...table.constraints].map((s) => s.definition).join(", ")})${tableOptions}`;
22057
22103
  this.properties.db.exec(sqlCreateTable);
22058
22104
  let sqlPut = `insert into ${table.name} (${table.fields.map((field2) => escapeColumnName(field2.name)).join(", ")}) VALUES (${table.fields.map((_x) => "?").join(", ")}) RETURNING ${table.primary};`;
22105
+ let sqlInsertKnownId = `insert into ${table.name} (${table.fields.map((field2) => escapeColumnName(field2.name)).join(", ")}) VALUES (${table.fields.map((_x) => "?").join(", ")});`;
22059
22106
  let sqlReplace = `insert or replace into ${table.name} (${table.fields.map((field2) => escapeColumnName(field2.name)).join(", ")}) VALUES (${table.fields.map((_x) => "?").join(", ")});`;
22060
22107
  await this.properties.db.prepare(sqlPut, putStatementKey(table));
22108
+ await this.properties.db.prepare(sqlInsertKnownId, insertKnownIdStatementKey(table));
22061
22109
  await this.properties.db.prepare(sqlReplace, replaceStatementKey(table));
22062
22110
  if (table.parent) {
22063
22111
  await this.properties.db.prepare(selectChildren(table), resolveChildrenStatement(table));
@@ -22145,7 +22193,7 @@ var SQLLiteIndex = class {
22145
22193
  }
22146
22194
  return void 0;
22147
22195
  }
22148
- async put(value, _id) {
22196
+ async put(value, _id, options) {
22149
22197
  return this.withWriteBarrier(async () => {
22150
22198
  const classOfValue = value.constructor;
22151
22199
  return insert(async (values, table) => {
@@ -22153,8 +22201,23 @@ var SQLLiteIndex = class {
22153
22201
  let statement = void 0;
22154
22202
  try {
22155
22203
  if (preId != null) {
22156
- statement = this.properties.db.statements.get(replaceStatementKey(table));
22157
- this.fkMode === "race-tolerant" ? await runIgnoreFK(statement, values) : await statement.run(values);
22204
+ const shouldReplace = options?.replace ?? true;
22205
+ if (!shouldReplace) {
22206
+ statement = this.properties.db.statements.get(insertKnownIdStatementKey(table));
22207
+ try {
22208
+ this.fkMode === "race-tolerant" ? await runIgnoreFK(statement, values) : await statement.run(values);
22209
+ } catch (error2) {
22210
+ if (!isUniqueConstraintError(error2)) {
22211
+ throw error2;
22212
+ }
22213
+ await statement.reset?.();
22214
+ statement = this.properties.db.statements.get(replaceStatementKey(table));
22215
+ this.fkMode === "race-tolerant" ? await runIgnoreFK(statement, values) : await statement.run(values);
22216
+ }
22217
+ } else {
22218
+ statement = this.properties.db.statements.get(replaceStatementKey(table));
22219
+ this.fkMode === "race-tolerant" ? await runIgnoreFK(statement, values) : await statement.run(values);
22220
+ }
22158
22221
  return preId;
22159
22222
  } else {
22160
22223
  statement = this.properties.db.statements.get(putStatementKey(table));
@@ -22169,6 +22232,17 @@ var SQLLiteIndex = class {
22169
22232
  }
22170
22233
  }, value, this.tables, resolveTable(this.scopeString ? [this.scopeString] : [], this.tables, classOfValue, true), getSchema(classOfValue).fields, (_fn) => {
22171
22234
  throw new Error("Unexpected");
22235
+ }, void 0, void 0, {
22236
+ insertSimpleVecRows: async (rows, table) => {
22237
+ if (rows.length === 0) {
22238
+ return;
22239
+ }
22240
+ const key = putStatementBatchNoReturnKey(table, rows.length);
22241
+ const sql = createBatchInsertSQL(table, rows.length);
22242
+ const statement = this.properties.db.statements.get(key) || await this.properties.db.prepare(sql, key);
22243
+ const values = rows.flat();
22244
+ this.fkMode === "race-tolerant" ? await runIgnoreFK(statement, values) : await statement.run(values);
22245
+ }
22172
22246
  });
22173
22247
  });
22174
22248
  }
@@ -22389,10 +22463,11 @@ var SQLiteIndices = class _SQLiteIndices {
22389
22463
  if (existing) {
22390
22464
  return existing.index;
22391
22465
  }
22392
- const index = new SQLLiteIndex({
22466
+ const index = new SQLiteIndex({
22393
22467
  db: this.properties.db,
22394
22468
  schema: properties.schema,
22395
- scope: this._scope
22469
+ scope: this._scope,
22470
+ persisted: await this.persisted()
22396
22471
  });
22397
22472
  await index.init(properties);
22398
22473
  this.indices.push({ schema: properties.schema, index });
@@ -22421,6 +22496,9 @@ var SQLiteIndices = class _SQLiteIndices {
22421
22496
  }
22422
22497
  return scope;
22423
22498
  }
22499
+ persisted() {
22500
+ return this.properties.directory != null;
22501
+ }
22424
22502
  async start() {
22425
22503
  this.closed = false;
22426
22504
  if (!this.properties.parent) {
@@ -22464,12 +22542,44 @@ var SQLiteIndices = class _SQLiteIndices {
22464
22542
  };
22465
22543
 
22466
22544
  // dist/src/sqlite3-messages.worker.js
22467
- var encodeValue = (value) => {
22545
+ var encodeValue = (value, protocol = "legacy") => {
22468
22546
  if (value instanceof Uint8Array) {
22469
- return { type: "uint8array", base64: toBase64(value) };
22547
+ return protocol === "clone" ? { type: "uint8array", encoding: "clone", value } : { type: "uint8array", encoding: "base64", base64: toBase64(value) };
22470
22548
  }
22471
22549
  return { type: "simple", value };
22472
22550
  };
22551
+ var encodeValues = (values, protocol = "legacy") => {
22552
+ if (!values || values.length === 0) {
22553
+ return {
22554
+ values,
22555
+ metrics: {
22556
+ encodeMs: 0,
22557
+ valueCount: 0,
22558
+ blobValueCount: 0,
22559
+ blobBytes: 0
22560
+ }
22561
+ };
22562
+ }
22563
+ let blobBytes = 0;
22564
+ let blobValueCount = 0;
22565
+ const startedAt = performance.now();
22566
+ const encodedValues = values.map((value) => {
22567
+ if (value instanceof Uint8Array) {
22568
+ blobValueCount++;
22569
+ blobBytes += value.byteLength;
22570
+ }
22571
+ return encodeValue(value, protocol);
22572
+ });
22573
+ return {
22574
+ values: encodedValues,
22575
+ metrics: {
22576
+ encodeMs: performance.now() - startedAt,
22577
+ valueCount: values.length,
22578
+ blobValueCount,
22579
+ blobBytes
22580
+ }
22581
+ };
22582
+ };
22473
22583
 
22474
22584
  // dist/src/sqlite3.wasm.js
22475
22585
  init_sqlite_wasm();
@@ -22585,7 +22695,18 @@ var getSqlite3 = async () => {
22585
22695
  }
22586
22696
  return sqlite3Promise;
22587
22697
  };
22588
- var create = async (directory) => {
22698
+ var applyPragmas = (db, pragmas) => {
22699
+ db.exec("PRAGMA journal_mode = WAL");
22700
+ db.exec("PRAGMA foreign_keys = on");
22701
+ db.exec(`PRAGMA synchronous = ${(pragmas?.synchronous ?? "NORMAL").toUpperCase()}`);
22702
+ if (pragmas?.lockingMode) {
22703
+ db.exec(`PRAGMA locking_mode = ${pragmas.lockingMode.toUpperCase()}`);
22704
+ }
22705
+ if (pragmas?.tempStore && pragmas.tempStore !== "DEFAULT") {
22706
+ db.exec(`PRAGMA temp_store = ${pragmas.tempStore.toUpperCase()}`);
22707
+ }
22708
+ };
22709
+ var create = async (directory, options) => {
22589
22710
  let statements = /* @__PURE__ */ new Map();
22590
22711
  const sqlite32 = await getSqlite3();
22591
22712
  let sqliteDb = void 0;
@@ -22680,8 +22801,7 @@ var create = async (directory) => {
22680
22801
  if (!sqliteDb) {
22681
22802
  throw new Error("Failed to open sqlite database");
22682
22803
  }
22683
- sqliteDb.exec("PRAGMA journal_mode = WAL");
22684
- sqliteDb.exec("PRAGMA foreign_keys = on");
22804
+ applyPragmas(sqliteDb, options?.pragmas);
22685
22805
  };
22686
22806
  return {
22687
22807
  close,
@@ -22716,26 +22836,44 @@ var create = async (directory) => {
22716
22836
  };
22717
22837
 
22718
22838
  // dist/src/sqlite3.browser.js
22839
+ var DEFAULT_PROTOCOL = "clone";
22840
+ var EMPTY_ENCODE_METRICS = {
22841
+ encodeMs: 0,
22842
+ valueCount: 0,
22843
+ blobValueCount: 0,
22844
+ blobBytes: 0
22845
+ };
22846
+ var getProtocol = (options) => options?.protocol ?? DEFAULT_PROTOCOL;
22719
22847
  var ProxyStatement = class {
22720
22848
  send;
22721
22849
  databaseId;
22722
22850
  statementId;
22851
+ sql;
22852
+ options;
22723
22853
  id;
22724
- resolvers = {};
22725
- constructor(send, databaseId, statementId) {
22854
+ needsReset = false;
22855
+ constructor(send, databaseId, statementId, sql, options) {
22726
22856
  this.send = send;
22727
22857
  this.databaseId = databaseId;
22728
22858
  this.statementId = statementId;
22859
+ this.sql = sql;
22860
+ this.options = options;
22729
22861
  this.id = statementId;
22730
22862
  }
22731
22863
  async bind(values) {
22864
+ const encoded = encodeValues(values, getProtocol(this.options));
22732
22865
  await this.send({
22733
22866
  type: "bind",
22734
- values: values.map(encodeValue),
22867
+ values: encoded.values ?? [],
22735
22868
  id: v4_default(),
22736
22869
  databaseId: this.databaseId,
22737
22870
  statementId: this.statementId
22871
+ }, {
22872
+ requestType: "bind",
22873
+ sql: this.sql,
22874
+ ...encoded.metrics
22738
22875
  });
22876
+ this.needsReset = true;
22739
22877
  return this;
22740
22878
  }
22741
22879
  async finalize() {
@@ -22744,60 +22882,141 @@ var ProxyStatement = class {
22744
22882
  id: v4_default(),
22745
22883
  databaseId: this.databaseId,
22746
22884
  statementId: this.statementId
22885
+ }, {
22886
+ requestType: "finalize",
22887
+ sql: this.sql,
22888
+ ...EMPTY_ENCODE_METRICS
22747
22889
  });
22890
+ this.needsReset = false;
22748
22891
  }
22749
- get(values) {
22750
- return this.send({
22892
+ async get(values) {
22893
+ const encoded = encodeValues(values, getProtocol(this.options));
22894
+ const result = await this.send({
22751
22895
  type: "get",
22752
- values: values ? values.map(encodeValue) : void 0,
22896
+ values: encoded.values,
22753
22897
  id: v4_default(),
22754
22898
  databaseId: this.databaseId,
22755
22899
  statementId: this.statementId
22900
+ }, {
22901
+ requestType: "get",
22902
+ sql: this.sql,
22903
+ ...encoded.metrics
22756
22904
  });
22905
+ this.needsReset = false;
22906
+ return result;
22757
22907
  }
22758
22908
  async run(values) {
22909
+ const encoded = encodeValues(values, getProtocol(this.options));
22759
22910
  await this.send({
22760
22911
  type: "run-statement",
22761
- values: values.map(encodeValue),
22912
+ values: encoded.values ?? [],
22762
22913
  id: v4_default(),
22763
22914
  databaseId: this.databaseId,
22764
22915
  statementId: this.statementId
22916
+ }, {
22917
+ requestType: "run-statement",
22918
+ sql: this.sql,
22919
+ ...encoded.metrics
22765
22920
  });
22921
+ this.needsReset = false;
22766
22922
  }
22767
22923
  async reset() {
22924
+ if (!this.needsReset) {
22925
+ return this;
22926
+ }
22768
22927
  await this.send({
22769
22928
  type: "reset",
22770
22929
  id: v4_default(),
22771
22930
  databaseId: this.databaseId,
22772
22931
  statementId: this.statementId
22932
+ }, {
22933
+ requestType: "reset",
22934
+ sql: this.sql,
22935
+ ...EMPTY_ENCODE_METRICS
22773
22936
  });
22937
+ this.needsReset = false;
22774
22938
  return this;
22775
22939
  }
22776
22940
  async all(values) {
22777
- let id = v4_default();
22778
- const results = await this.send({
22941
+ const encoded = encodeValues(values, getProtocol(this.options));
22942
+ const result = await this.send({
22779
22943
  type: "all",
22780
- values: values.map(encodeValue),
22781
- id,
22944
+ values: encoded.values ?? [],
22945
+ id: v4_default(),
22782
22946
  databaseId: this.databaseId,
22783
22947
  statementId: this.statementId
22948
+ }, {
22949
+ requestType: "all",
22950
+ sql: this.sql,
22951
+ ...encoded.metrics
22784
22952
  });
22785
- return results;
22953
+ this.needsReset = false;
22954
+ return result;
22786
22955
  }
22787
22956
  };
22788
22957
  var ProxyDatabase = class {
22789
- send;
22958
+ postMessage;
22959
+ options;
22790
22960
  statements = /* @__PURE__ */ new Map();
22791
- resolvers = {};
22792
22961
  databaseId;
22793
- constructor(send) {
22794
- this.send = send;
22962
+ directory;
22963
+ constructor(postMessage, options) {
22964
+ this.postMessage = postMessage;
22965
+ this.options = options;
22966
+ }
22967
+ async send(message, metrics) {
22968
+ const startedAt = performance.now();
22969
+ const protocol = getProtocol(this.options);
22970
+ const shouldProfile = Boolean(this.options?.profile || this.options?.onProfile);
22971
+ const requestType = metrics?.requestType ?? message.type;
22972
+ try {
22973
+ const response = await this.postMessage({
22974
+ ...message,
22975
+ protocol,
22976
+ profile: shouldProfile
22977
+ });
22978
+ this.options?.onProfile?.({
22979
+ requestType,
22980
+ protocol,
22981
+ databaseId: this.databaseId,
22982
+ databaseDirectory: this.directory,
22983
+ sql: metrics?.sql ?? ("sql" in message && typeof message.sql === "string" ? message.sql : void 0),
22984
+ clientEncodeMs: metrics?.encodeMs ?? 0,
22985
+ clientRoundTripMs: performance.now() - startedAt,
22986
+ valueCount: metrics?.valueCount ?? 0,
22987
+ blobValueCount: metrics?.blobValueCount ?? 0,
22988
+ blobBytes: metrics?.blobBytes ?? 0,
22989
+ worker: response.timing
22990
+ });
22991
+ return response.result;
22992
+ } catch (error2) {
22993
+ const responseError = error2;
22994
+ this.options?.onProfile?.({
22995
+ requestType,
22996
+ protocol,
22997
+ databaseId: this.databaseId,
22998
+ databaseDirectory: this.directory,
22999
+ sql: metrics?.sql ?? ("sql" in message && typeof message.sql === "string" ? message.sql : void 0),
23000
+ clientEncodeMs: metrics?.encodeMs ?? 0,
23001
+ clientRoundTripMs: performance.now() - startedAt,
23002
+ valueCount: metrics?.valueCount ?? 0,
23003
+ blobValueCount: metrics?.blobValueCount ?? 0,
23004
+ blobBytes: metrics?.blobBytes ?? 0,
23005
+ worker: responseError?.timing
23006
+ });
23007
+ if (responseError?.type === "error") {
23008
+ throw new Error(responseError.message);
23009
+ }
23010
+ throw error2;
23011
+ }
22795
23012
  }
22796
23013
  async init(directory) {
22797
23014
  this.databaseId = v4_default();
23015
+ this.directory = directory;
22798
23016
  return this.send({
22799
23017
  type: "create",
22800
23018
  directory,
23019
+ pragmas: this.options?.pragmas,
22801
23020
  databaseId: this.databaseId,
22802
23021
  id: v4_default()
22803
23022
  });
@@ -22824,7 +23043,7 @@ var ProxyDatabase = class {
22824
23043
  id: v4_default(),
22825
23044
  databaseId: this.databaseId
22826
23045
  });
22827
- const statement = new ProxyStatement(this.send, this.databaseId, statementId);
23046
+ const statement = new ProxyStatement(this.send.bind(this), this.databaseId, statementId, sql, this.options);
22828
23047
  this.statements.set(statementId, statement);
22829
23048
  if (id != null) {
22830
23049
  this.statements.set(id, statement);
@@ -22861,16 +23080,16 @@ var init = async () => {
22861
23080
  if (initialized) {
22862
23081
  return initialized;
22863
23082
  }
22864
- let worker = new Worker(new URL("/peerbit/sqlite3/sqlite3.worker.min.js", import.meta.url), { type: "module" });
22865
- let resolvers = {};
22866
- let send = (message) => {
23083
+ const worker = new Worker(new URL("/peerbit/sqlite3/sqlite3.worker.min.js", import.meta.url), { type: "module" });
23084
+ const resolvers = {};
23085
+ const postMessage = (message) => {
22867
23086
  const promise = new Promise((resolve, reject) => {
22868
23087
  resolvers[message.id] = { resolve, reject };
22869
23088
  });
22870
23089
  worker.postMessage(message);
22871
23090
  return promise.finally(() => delete resolvers[message.id]);
22872
23091
  };
22873
- let isReady = pDefer();
23092
+ const isReady = pDefer();
22874
23093
  worker.onmessage = async (ev) => {
22875
23094
  const message = ev.data;
22876
23095
  if (message.type === "ready") {
@@ -22878,14 +23097,17 @@ var init = async () => {
22878
23097
  return;
22879
23098
  }
22880
23099
  const resolver = resolvers[message.id];
23100
+ if (!resolver) {
23101
+ return;
23102
+ }
22881
23103
  if (message.type === "error") {
22882
- resolver.reject(new Error(message.message));
22883
- } else if (message.type === "response") {
22884
- resolver.resolve(message.result);
23104
+ resolver.reject(message);
23105
+ } else {
23106
+ resolver.resolve(message);
22885
23107
  }
22886
23108
  };
22887
- const create4 = async (directory) => {
22888
- const db = new ProxyDatabase(send);
23109
+ const create4 = async (directory, options) => {
23110
+ const db = new ProxyDatabase(postMessage, options);
22889
23111
  await isReady.promise;
22890
23112
  await db.init(directory);
22891
23113
  await db.open();
@@ -22899,12 +23121,11 @@ var init = async () => {
22899
23121
  }
22900
23122
  };
22901
23123
  };
22902
- var create2 = (directory) => {
23124
+ var create2 = (directory, options) => {
22903
23125
  if (directory) {
22904
- return init().then((creator) => creator.create(directory));
22905
- } else {
22906
- return create();
23126
+ return init().then((creator) => creator.create(directory, options));
22907
23127
  }
23128
+ return create(directory, options);
22908
23129
  };
22909
23130
 
22910
23131
  // dist/src/index.js
@@ -22913,14 +23134,17 @@ var encodeName = (name) => {
22913
23134
  writer.string(name);
22914
23135
  return toBase58(sha256Sync(writer.finalize()));
22915
23136
  };
22916
- var create3 = async (directory) => {
22917
- const db = await create2(directory);
23137
+ var create3 = async (directory, options) => {
23138
+ const db = await create2(directory, options);
22918
23139
  return new SQLiteIndices({ db, directory });
22919
23140
  };
23141
+ var createDatabase = (directory, options) => create2(directory, options);
22920
23142
  export {
22921
- SQLLiteIndex,
23143
+ SQLiteIndex as SQLLiteIndex,
23144
+ SQLiteIndex,
22922
23145
  SQLiteIndices,
22923
23146
  create3 as create,
23147
+ createDatabase,
22924
23148
  encodeName
22925
23149
  };
22926
23150
  //# sourceMappingURL=index.min.js.map