tempest-db-js 0.5.0 → 0.7.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.
@@ -1,5 +1,8 @@
1
1
  'use strict';
2
2
 
3
+ var module$1 = require('module');
4
+
5
+ var _documentCurrentScript = typeof document !== 'undefined' ? document.currentScript : null;
3
6
  // src/expressions.ts
4
7
  function renderPortableToken(token, dialect) {
5
8
  switch (token) {
@@ -15,6 +18,17 @@ function renderPortableToken(token, dialect) {
15
18
  return "(lower(hex(randomblob(16))))";
16
19
  }
17
20
  }
21
+ module$1.createRequire((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('index.cjs', document.baseURI).href)));
22
+ function toAsyncDriver(driver) {
23
+ return {
24
+ async execute(sql, params) {
25
+ return await driver.execute(sql, params);
26
+ },
27
+ async close() {
28
+ await driver.close();
29
+ }
30
+ };
31
+ }
18
32
 
19
33
  // src/index.ts
20
34
  function isDefaultValue(value) {
@@ -1144,62 +1158,26 @@ function affinityToKind(affinity) {
1144
1158
  }
1145
1159
  function sqliteForeignKeys(driver, table) {
1146
1160
  const rows = driver.execute(`PRAGMA foreign_key_list(${JSON.stringify(table)})`, []).rows;
1147
- const byId = /* @__PURE__ */ new Map();
1148
- for (const r of rows) {
1149
- const list = byId.get(r.id) ?? [];
1150
- list.push(r);
1151
- byId.set(r.id, list);
1152
- }
1153
- const fks = [];
1154
- for (const group of byId.values()) {
1155
- const ordered = [...group].sort((a, b) => a.seq - b.seq);
1156
- const columns = ordered.map((r) => r.from);
1157
- fks.push({
1158
- name: `fk_${table}_${columns.join("_")}`,
1159
- columns,
1160
- refTable: ordered[0]?.table ?? "",
1161
- refColumns: ordered.map((r) => r.to)
1162
- });
1163
- }
1164
- return fks;
1161
+ return sqliteForeignKeysFromPragma(table, rows);
1165
1162
  }
1166
1163
  function sqliteUniques(driver, table) {
1167
1164
  const indexes = driver.execute(`PRAGMA index_list(${JSON.stringify(table)})`, []).rows;
1168
1165
  const uniques = [];
1169
1166
  for (const idx of indexes) {
1170
- if (Number(idx.unique) !== 1 || idx.origin === "pk") continue;
1171
- const cols = driver.execute(`PRAGMA index_info(${JSON.stringify(idx.name)})`, []).rows.sort((a, b) => a.seqno - b.seqno).map((c) => c.name);
1172
- if (cols.length > 0) {
1173
- uniques.push({ name: `uq_${table}_${cols.join("_")}`, columns: cols });
1174
- }
1167
+ if (!isUniqueIndex(idx)) continue;
1168
+ const cols = driver.execute(`PRAGMA index_info(${JSON.stringify(idx.name)})`, []).rows;
1169
+ const unique = sqliteUniqueFromPragma(table, cols);
1170
+ if (unique) uniques.push(unique);
1175
1171
  }
1176
1172
  return uniques;
1177
1173
  }
1178
1174
  function introspectSqlite(driver) {
1179
- const tablesRows = driver.execute(
1180
- "SELECT name FROM sqlite_master WHERE type = 'table' AND name NOT LIKE 'sqlite_%' AND name != 'tempest_db_js_migrations'",
1181
- []
1182
- ).rows;
1175
+ const tablesRows = driver.execute(SQLITE_TABLES_SQL, []).rows;
1183
1176
  const tables = {};
1184
1177
  for (const row of tablesRows) {
1185
1178
  const tableName = String(row.name);
1186
1179
  const info = driver.execute(`PRAGMA table_info(${JSON.stringify(tableName)})`, []).rows;
1187
- const columns = {};
1188
- const primaryKey = [];
1189
- for (const col of info) {
1190
- const isPk = Number(col.pk) > 0;
1191
- const affinity = sqliteAffinity(col.type);
1192
- columns[col.name] = {
1193
- name: col.name,
1194
- type: { kind: affinityToKind(affinity), meta: {} },
1195
- notNull: Number(col.notnull) === 1 || isPk,
1196
- primaryKey: isPk,
1197
- default: null,
1198
- unique: false,
1199
- references: null
1200
- };
1201
- if (isPk) primaryKey.push(col.name);
1202
- }
1180
+ const { columns, primaryKey } = sqliteColumnsFromPragma(info);
1203
1181
  tables[tableName] = {
1204
1182
  name: tableName,
1205
1183
  columns,
@@ -1228,8 +1206,9 @@ function constraintKeys(table) {
1228
1206
  return { fks, uniques };
1229
1207
  }
1230
1208
  function checkDrift(driver, models) {
1231
- const actual = introspectSqlite(driver);
1232
- const expected = reflectSchema(models);
1209
+ return compareSqliteSchemas(introspectSqlite(driver), reflectSchema(models));
1210
+ }
1211
+ function compareSqliteSchemas(actual, expected) {
1233
1212
  const issues = [];
1234
1213
  for (const [tableName, expectedTable] of Object.entries(expected.tables)) {
1235
1214
  const actualTable = actual.tables[tableName];
@@ -1300,6 +1279,90 @@ function checkDrift(driver, models) {
1300
1279
  }
1301
1280
  return issues;
1302
1281
  }
1282
+ function sqliteColumnsFromPragma(info) {
1283
+ const columns = {};
1284
+ const primaryKey = [];
1285
+ for (const col of info) {
1286
+ const isPk = Number(col.pk) > 0;
1287
+ columns[col.name] = {
1288
+ name: col.name,
1289
+ type: { kind: affinityToKind(sqliteAffinity(col.type)), meta: {} },
1290
+ notNull: Number(col.notnull) === 1 || isPk,
1291
+ primaryKey: isPk,
1292
+ default: null,
1293
+ unique: false,
1294
+ references: null
1295
+ };
1296
+ if (isPk) primaryKey.push(col.name);
1297
+ }
1298
+ return { columns, primaryKey };
1299
+ }
1300
+ function sqliteForeignKeysFromPragma(table, rows) {
1301
+ const byId = /* @__PURE__ */ new Map();
1302
+ for (const row of rows) {
1303
+ const group = byId.get(row.id) ?? [];
1304
+ group.push(row);
1305
+ byId.set(row.id, group);
1306
+ }
1307
+ const fks = [];
1308
+ for (const group of byId.values()) {
1309
+ const ordered = [...group].sort((a, b) => a.seq - b.seq);
1310
+ fks.push({
1311
+ name: `fk_${table}_${ordered.map((r) => r.from).join("_")}`,
1312
+ columns: ordered.map((r) => r.from),
1313
+ refTable: ordered[0]?.table ?? "",
1314
+ refColumns: ordered.map((r) => r.to)
1315
+ });
1316
+ }
1317
+ return fks;
1318
+ }
1319
+ function sqliteUniqueFromPragma(table, rows) {
1320
+ const cols = [...rows].sort((a, b) => a.seqno - b.seqno).map((c) => c.name);
1321
+ if (cols.length === 0) return null;
1322
+ return { name: `uq_${table}_${cols.join("_")}`, columns: cols };
1323
+ }
1324
+ function isUniqueIndex(idx) {
1325
+ return Number(idx.unique) === 1 && idx.origin !== "pk";
1326
+ }
1327
+ var SQLITE_TABLES_SQL = "SELECT name FROM sqlite_master WHERE type = 'table' AND name NOT LIKE 'sqlite_%' AND name != 'tempest_db_js_migrations'";
1328
+ async function introspectSqliteAsync(driver) {
1329
+ const tablesRows = (await driver.execute(SQLITE_TABLES_SQL, [])).rows;
1330
+ const tables = {};
1331
+ for (const row of tablesRows) {
1332
+ const tableName = String(row.name);
1333
+ const info = (await driver.execute(`PRAGMA table_info(${JSON.stringify(tableName)})`, [])).rows;
1334
+ const { columns, primaryKey } = sqliteColumnsFromPragma(info);
1335
+ const fkRows = (await driver.execute(`PRAGMA foreign_key_list(${JSON.stringify(tableName)})`, [])).rows;
1336
+ const indexes = (await driver.execute(`PRAGMA index_list(${JSON.stringify(tableName)})`, [])).rows;
1337
+ const uniqueConstraints = [];
1338
+ for (const idx of indexes) {
1339
+ if (!isUniqueIndex(idx)) continue;
1340
+ const cols = (await driver.execute(`PRAGMA index_info(${JSON.stringify(idx.name)})`, [])).rows;
1341
+ const unique = sqliteUniqueFromPragma(tableName, cols);
1342
+ if (unique) uniqueConstraints.push(unique);
1343
+ }
1344
+ tables[tableName] = {
1345
+ name: tableName,
1346
+ columns,
1347
+ primaryKey,
1348
+ uniqueConstraints,
1349
+ foreignKeys: sqliteForeignKeysFromPragma(tableName, fkRows)
1350
+ };
1351
+ }
1352
+ return { tables };
1353
+ }
1354
+ async function checkDriftAsync(driver, dialect, models) {
1355
+ if (dialect === "postgresql") return checkDriftPostgres(driver, models);
1356
+ if (dialect === "sqlite") {
1357
+ return compareSqliteSchemas(
1358
+ await introspectSqliteAsync(driver),
1359
+ reflectSchema(models)
1360
+ );
1361
+ }
1362
+ return [
1363
+ "drift checking is not implemented for MySQL \u2014 its information_schema introspection is still missing"
1364
+ ];
1365
+ }
1303
1366
  function pgTypeToColumnType(dataType, udtName) {
1304
1367
  if (dataType.toLowerCase() === "array") {
1305
1368
  return {
@@ -1740,23 +1803,24 @@ function parseRenameFlags(rest) {
1740
1803
  }
1741
1804
  return out;
1742
1805
  }
1743
- function pending(config, runner) {
1744
- const done = runner.applied();
1806
+ async function pending(config, runner) {
1807
+ const done = await runner.applied();
1745
1808
  return topoOrder(config.migrations).filter((m) => !done.has(m.revision));
1746
1809
  }
1747
- function runMigrationCli(argv, config) {
1810
+ async function runMigrationCli(argv, config) {
1748
1811
  const [command, ...rest] = argv;
1749
- const runner = new MigrationRunner(config.driver, config.dialect);
1812
+ const driver = toAsyncDriver(config.driver);
1813
+ const runner = new AsyncMigrationRunner(driver, config.dialect);
1750
1814
  const appliedAt = config.appliedAt ?? "1970-01-01T00:00:00.000Z";
1751
1815
  switch (command) {
1752
1816
  case "current": {
1753
- const applied = [...runner.applied()].sort();
1817
+ const applied = [...await runner.applied()].sort();
1754
1818
  return ok(applied.length > 0 ? applied : ["(no migrations applied)"]);
1755
1819
  }
1756
1820
  case "heads":
1757
1821
  return ok(heads(config.migrations));
1758
1822
  case "history": {
1759
- const done = runner.applied();
1823
+ const done = await runner.applied();
1760
1824
  return ok(
1761
1825
  topoOrder(config.migrations).map(
1762
1826
  (m) => `${done.has(m.revision) ? "\u2713" : "\xB7"} ${m.revision}${m.label ? ` \u2014 ${m.label}` : ""}`
@@ -1766,7 +1830,7 @@ function runMigrationCli(argv, config) {
1766
1830
  case "upgrade": {
1767
1831
  if (rest.includes("--sql")) {
1768
1832
  const lines = [];
1769
- for (const migration of pending(config, runner)) {
1833
+ for (const migration of await pending(config, runner)) {
1770
1834
  const op = new Op();
1771
1835
  migration.up(op);
1772
1836
  lines.push(`-- ${migration.revision}`);
@@ -1777,19 +1841,19 @@ function runMigrationCli(argv, config) {
1777
1841
  }
1778
1842
  return ok(lines.length > 0 ? lines : ["-- nothing to upgrade"]);
1779
1843
  }
1780
- const ran = runner.upgrade(config.migrations, appliedAt);
1844
+ const ran = await runner.upgrade(config.migrations, appliedAt);
1781
1845
  return ok(ran.length > 0 ? ran.map((r) => `applied ${r}`) : ["nothing to upgrade"]);
1782
1846
  }
1783
1847
  case "downgrade": {
1784
1848
  const steps = rest[0] ? Number(rest[0]) : 1;
1785
- const reverted = runner.downgrade(config.migrations, steps);
1849
+ const reverted = await runner.downgrade(config.migrations, steps);
1786
1850
  return ok(
1787
1851
  reverted.length > 0 ? reverted.map((r) => `reverted ${r}`) : ["nothing to downgrade"]
1788
1852
  );
1789
1853
  }
1790
1854
  case "check": {
1791
1855
  if (!config.models) return fail(["check requires models in the config"]);
1792
- const drift = config.dialect === "sqlite" ? checkDrift(config.driver, config.models) : [];
1856
+ const drift = await checkDriftAsync(driver, config.dialect, config.models);
1793
1857
  const undiffed = diffSchema(
1794
1858
  replaySchema(config.migrations),
1795
1859
  reflectSchema(config.models)
@@ -1836,7 +1900,9 @@ exports.UnknownRevision = UnknownRevision;
1836
1900
  exports.applyOperation = applyOperation;
1837
1901
  exports.applyRenames = applyRenames;
1838
1902
  exports.checkDrift = checkDrift;
1903
+ exports.checkDriftAsync = checkDriftAsync;
1839
1904
  exports.checkDriftPostgres = checkDriftPostgres;
1905
+ exports.compareSqliteSchemas = compareSqliteSchemas;
1840
1906
  exports.defineMigrationConfig = defineMigrationConfig;
1841
1907
  exports.detectRenames = detectRenames;
1842
1908
  exports.diffSchema = diffSchema;
@@ -1845,6 +1911,7 @@ exports.generateMigration = generateMigration;
1845
1911
  exports.heads = heads;
1846
1912
  exports.introspectPostgres = introspectPostgres;
1847
1913
  exports.introspectSqlite = introspectSqlite;
1914
+ exports.introspectSqliteAsync = introspectSqliteAsync;
1848
1915
  exports.invert = invert;
1849
1916
  exports.invertAll = invertAll;
1850
1917
  exports.makeRevisionId = makeRevisionId;