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,4 +1,4 @@
1
- import { renderPortableToken, columnNamesOf, columnsOf } from './chunk-5QQMVTS5.js';
1
+ import { renderPortableToken, columnNamesOf, columnsOf, toAsyncDriver } from './chunk-4AWUP7BM.js';
2
2
 
3
3
  // src/migrations/operations.ts
4
4
  var IrreversibleMigration = class extends Error {
@@ -702,62 +702,26 @@ function affinityToKind(affinity) {
702
702
  }
703
703
  function sqliteForeignKeys(driver, table) {
704
704
  const rows = driver.execute(`PRAGMA foreign_key_list(${JSON.stringify(table)})`, []).rows;
705
- const byId = /* @__PURE__ */ new Map();
706
- for (const r of rows) {
707
- const list = byId.get(r.id) ?? [];
708
- list.push(r);
709
- byId.set(r.id, list);
710
- }
711
- const fks = [];
712
- for (const group of byId.values()) {
713
- const ordered = [...group].sort((a, b) => a.seq - b.seq);
714
- const columns = ordered.map((r) => r.from);
715
- fks.push({
716
- name: `fk_${table}_${columns.join("_")}`,
717
- columns,
718
- refTable: ordered[0]?.table ?? "",
719
- refColumns: ordered.map((r) => r.to)
720
- });
721
- }
722
- return fks;
705
+ return sqliteForeignKeysFromPragma(table, rows);
723
706
  }
724
707
  function sqliteUniques(driver, table) {
725
708
  const indexes = driver.execute(`PRAGMA index_list(${JSON.stringify(table)})`, []).rows;
726
709
  const uniques = [];
727
710
  for (const idx of indexes) {
728
- if (Number(idx.unique) !== 1 || idx.origin === "pk") continue;
729
- const cols = driver.execute(`PRAGMA index_info(${JSON.stringify(idx.name)})`, []).rows.sort((a, b) => a.seqno - b.seqno).map((c) => c.name);
730
- if (cols.length > 0) {
731
- uniques.push({ name: `uq_${table}_${cols.join("_")}`, columns: cols });
732
- }
711
+ if (!isUniqueIndex(idx)) continue;
712
+ const cols = driver.execute(`PRAGMA index_info(${JSON.stringify(idx.name)})`, []).rows;
713
+ const unique = sqliteUniqueFromPragma(table, cols);
714
+ if (unique) uniques.push(unique);
733
715
  }
734
716
  return uniques;
735
717
  }
736
718
  function introspectSqlite(driver) {
737
- const tablesRows = driver.execute(
738
- "SELECT name FROM sqlite_master WHERE type = 'table' AND name NOT LIKE 'sqlite_%' AND name != 'tempest_db_js_migrations'",
739
- []
740
- ).rows;
719
+ const tablesRows = driver.execute(SQLITE_TABLES_SQL, []).rows;
741
720
  const tables = {};
742
721
  for (const row of tablesRows) {
743
722
  const tableName = String(row.name);
744
723
  const info = driver.execute(`PRAGMA table_info(${JSON.stringify(tableName)})`, []).rows;
745
- const columns = {};
746
- const primaryKey = [];
747
- for (const col of info) {
748
- const isPk = Number(col.pk) > 0;
749
- const affinity = sqliteAffinity(col.type);
750
- columns[col.name] = {
751
- name: col.name,
752
- type: { kind: affinityToKind(affinity), meta: {} },
753
- notNull: Number(col.notnull) === 1 || isPk,
754
- primaryKey: isPk,
755
- default: null,
756
- unique: false,
757
- references: null
758
- };
759
- if (isPk) primaryKey.push(col.name);
760
- }
724
+ const { columns, primaryKey } = sqliteColumnsFromPragma(info);
761
725
  tables[tableName] = {
762
726
  name: tableName,
763
727
  columns,
@@ -786,8 +750,9 @@ function constraintKeys(table) {
786
750
  return { fks, uniques };
787
751
  }
788
752
  function checkDrift(driver, models) {
789
- const actual = introspectSqlite(driver);
790
- const expected = reflectSchema(models);
753
+ return compareSqliteSchemas(introspectSqlite(driver), reflectSchema(models));
754
+ }
755
+ function compareSqliteSchemas(actual, expected) {
791
756
  const issues = [];
792
757
  for (const [tableName, expectedTable] of Object.entries(expected.tables)) {
793
758
  const actualTable = actual.tables[tableName];
@@ -858,6 +823,90 @@ function checkDrift(driver, models) {
858
823
  }
859
824
  return issues;
860
825
  }
826
+ function sqliteColumnsFromPragma(info) {
827
+ const columns = {};
828
+ const primaryKey = [];
829
+ for (const col of info) {
830
+ const isPk = Number(col.pk) > 0;
831
+ columns[col.name] = {
832
+ name: col.name,
833
+ type: { kind: affinityToKind(sqliteAffinity(col.type)), meta: {} },
834
+ notNull: Number(col.notnull) === 1 || isPk,
835
+ primaryKey: isPk,
836
+ default: null,
837
+ unique: false,
838
+ references: null
839
+ };
840
+ if (isPk) primaryKey.push(col.name);
841
+ }
842
+ return { columns, primaryKey };
843
+ }
844
+ function sqliteForeignKeysFromPragma(table, rows) {
845
+ const byId = /* @__PURE__ */ new Map();
846
+ for (const row of rows) {
847
+ const group = byId.get(row.id) ?? [];
848
+ group.push(row);
849
+ byId.set(row.id, group);
850
+ }
851
+ const fks = [];
852
+ for (const group of byId.values()) {
853
+ const ordered = [...group].sort((a, b) => a.seq - b.seq);
854
+ fks.push({
855
+ name: `fk_${table}_${ordered.map((r) => r.from).join("_")}`,
856
+ columns: ordered.map((r) => r.from),
857
+ refTable: ordered[0]?.table ?? "",
858
+ refColumns: ordered.map((r) => r.to)
859
+ });
860
+ }
861
+ return fks;
862
+ }
863
+ function sqliteUniqueFromPragma(table, rows) {
864
+ const cols = [...rows].sort((a, b) => a.seqno - b.seqno).map((c) => c.name);
865
+ if (cols.length === 0) return null;
866
+ return { name: `uq_${table}_${cols.join("_")}`, columns: cols };
867
+ }
868
+ function isUniqueIndex(idx) {
869
+ return Number(idx.unique) === 1 && idx.origin !== "pk";
870
+ }
871
+ var SQLITE_TABLES_SQL = "SELECT name FROM sqlite_master WHERE type = 'table' AND name NOT LIKE 'sqlite_%' AND name != 'tempest_db_js_migrations'";
872
+ async function introspectSqliteAsync(driver) {
873
+ const tablesRows = (await driver.execute(SQLITE_TABLES_SQL, [])).rows;
874
+ const tables = {};
875
+ for (const row of tablesRows) {
876
+ const tableName = String(row.name);
877
+ const info = (await driver.execute(`PRAGMA table_info(${JSON.stringify(tableName)})`, [])).rows;
878
+ const { columns, primaryKey } = sqliteColumnsFromPragma(info);
879
+ const fkRows = (await driver.execute(`PRAGMA foreign_key_list(${JSON.stringify(tableName)})`, [])).rows;
880
+ const indexes = (await driver.execute(`PRAGMA index_list(${JSON.stringify(tableName)})`, [])).rows;
881
+ const uniqueConstraints = [];
882
+ for (const idx of indexes) {
883
+ if (!isUniqueIndex(idx)) continue;
884
+ const cols = (await driver.execute(`PRAGMA index_info(${JSON.stringify(idx.name)})`, [])).rows;
885
+ const unique = sqliteUniqueFromPragma(tableName, cols);
886
+ if (unique) uniqueConstraints.push(unique);
887
+ }
888
+ tables[tableName] = {
889
+ name: tableName,
890
+ columns,
891
+ primaryKey,
892
+ uniqueConstraints,
893
+ foreignKeys: sqliteForeignKeysFromPragma(tableName, fkRows)
894
+ };
895
+ }
896
+ return { tables };
897
+ }
898
+ async function checkDriftAsync(driver, dialect, models) {
899
+ if (dialect === "postgresql") return checkDriftPostgres(driver, models);
900
+ if (dialect === "sqlite") {
901
+ return compareSqliteSchemas(
902
+ await introspectSqliteAsync(driver),
903
+ reflectSchema(models)
904
+ );
905
+ }
906
+ return [
907
+ "drift checking is not implemented for MySQL \u2014 its information_schema introspection is still missing"
908
+ ];
909
+ }
861
910
  function pgTypeToColumnType(dataType, udtName) {
862
911
  if (dataType.toLowerCase() === "array") {
863
912
  return {
@@ -1544,23 +1593,24 @@ function parseRenameFlags(rest) {
1544
1593
  }
1545
1594
  return out;
1546
1595
  }
1547
- function pending(config, runner) {
1548
- const done = runner.applied();
1596
+ async function pending(config, runner) {
1597
+ const done = await runner.applied();
1549
1598
  return topoOrder(config.migrations).filter((m) => !done.has(m.revision));
1550
1599
  }
1551
- function runMigrationCli(argv, config) {
1600
+ async function runMigrationCli(argv, config) {
1552
1601
  const [command, ...rest] = argv;
1553
- const runner = new MigrationRunner(config.driver, config.dialect);
1602
+ const driver = toAsyncDriver(config.driver);
1603
+ const runner = new AsyncMigrationRunner(driver, config.dialect);
1554
1604
  const appliedAt = config.appliedAt ?? "1970-01-01T00:00:00.000Z";
1555
1605
  switch (command) {
1556
1606
  case "current": {
1557
- const applied = [...runner.applied()].sort();
1607
+ const applied = [...await runner.applied()].sort();
1558
1608
  return ok(applied.length > 0 ? applied : ["(no migrations applied)"]);
1559
1609
  }
1560
1610
  case "heads":
1561
1611
  return ok(heads(config.migrations));
1562
1612
  case "history": {
1563
- const done = runner.applied();
1613
+ const done = await runner.applied();
1564
1614
  return ok(
1565
1615
  topoOrder(config.migrations).map(
1566
1616
  (m) => `${done.has(m.revision) ? "\u2713" : "\xB7"} ${m.revision}${m.label ? ` \u2014 ${m.label}` : ""}`
@@ -1570,7 +1620,7 @@ function runMigrationCli(argv, config) {
1570
1620
  case "upgrade": {
1571
1621
  if (rest.includes("--sql")) {
1572
1622
  const lines = [];
1573
- for (const migration of pending(config, runner)) {
1623
+ for (const migration of await pending(config, runner)) {
1574
1624
  const op = new Op();
1575
1625
  migration.up(op);
1576
1626
  lines.push(`-- ${migration.revision}`);
@@ -1581,19 +1631,19 @@ function runMigrationCli(argv, config) {
1581
1631
  }
1582
1632
  return ok(lines.length > 0 ? lines : ["-- nothing to upgrade"]);
1583
1633
  }
1584
- const ran = runner.upgrade(config.migrations, appliedAt);
1634
+ const ran = await runner.upgrade(config.migrations, appliedAt);
1585
1635
  return ok(ran.length > 0 ? ran.map((r) => `applied ${r}`) : ["nothing to upgrade"]);
1586
1636
  }
1587
1637
  case "downgrade": {
1588
1638
  const steps = rest[0] ? Number(rest[0]) : 1;
1589
- const reverted = runner.downgrade(config.migrations, steps);
1639
+ const reverted = await runner.downgrade(config.migrations, steps);
1590
1640
  return ok(
1591
1641
  reverted.length > 0 ? reverted.map((r) => `reverted ${r}`) : ["nothing to downgrade"]
1592
1642
  );
1593
1643
  }
1594
1644
  case "check": {
1595
1645
  if (!config.models) return fail(["check requires models in the config"]);
1596
- const drift = config.dialect === "sqlite" ? checkDrift(config.driver, config.models) : [];
1646
+ const drift = await checkDriftAsync(driver, config.dialect, config.models);
1597
1647
  const undiffed = diffSchema(
1598
1648
  replaySchema(config.migrations),
1599
1649
  reflectSchema(config.models)
@@ -1631,6 +1681,6 @@ function runMigrationCli(argv, config) {
1631
1681
  }
1632
1682
  }
1633
1683
 
1634
- export { AsyncMigrationRunner, CyclicMigrationGraph, IrreversibleMigration, MigrationRunner, Op, UnknownRevision, applyOperation, applyRenames, checkDrift, checkDriftPostgres, defineMigrationConfig, detectRenames, diffSchema, emptySchema, generateMigration, heads, introspectPostgres, introspectSqlite, invert, invertAll, makeRevisionId, reflectSchema, reflectTable, renderColumnDef, renderColumnType, renderDefault, renderOperation, replaySchema, runMigrationCli, sqliteAffinity, topoOrder };
1635
- //# sourceMappingURL=chunk-EPMLFNFK.js.map
1636
- //# sourceMappingURL=chunk-EPMLFNFK.js.map
1684
+ export { AsyncMigrationRunner, CyclicMigrationGraph, IrreversibleMigration, MigrationRunner, Op, UnknownRevision, applyOperation, applyRenames, checkDrift, checkDriftAsync, checkDriftPostgres, compareSqliteSchemas, defineMigrationConfig, detectRenames, diffSchema, emptySchema, generateMigration, heads, introspectPostgres, introspectSqlite, introspectSqliteAsync, invert, invertAll, makeRevisionId, reflectSchema, reflectTable, renderColumnDef, renderColumnType, renderDefault, renderOperation, replaySchema, runMigrationCli, sqliteAffinity, topoOrder };
1685
+ //# sourceMappingURL=chunk-SI4CLSF7.js.map
1686
+ //# sourceMappingURL=chunk-SI4CLSF7.js.map