@bungres/kit 0.7.0 → 1.0.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.
Files changed (3) hide show
  1. package/dist/cli.js +259 -88
  2. package/dist/index.js +252 -81
  3. package/package.json +2 -2
package/dist/cli.js CHANGED
@@ -56,12 +56,12 @@ var require_src = __commonJS((exports, module) => {
56
56
  ret += `${CSI2}${y}B`;
57
57
  return ret;
58
58
  },
59
- up: (count2 = 1) => `${CSI2}${count2}A`,
60
- down: (count2 = 1) => `${CSI2}${count2}B`,
61
- forward: (count2 = 1) => `${CSI2}${count2}C`,
62
- backward: (count2 = 1) => `${CSI2}${count2}D`,
63
- nextLine: (count2 = 1) => `${CSI2}E`.repeat(count2),
64
- prevLine: (count2 = 1) => `${CSI2}F`.repeat(count2),
59
+ up: (count = 1) => `${CSI2}${count}A`,
60
+ down: (count = 1) => `${CSI2}${count}B`,
61
+ forward: (count = 1) => `${CSI2}${count}C`,
62
+ backward: (count = 1) => `${CSI2}${count}D`,
63
+ nextLine: (count = 1) => `${CSI2}E`.repeat(count),
64
+ prevLine: (count = 1) => `${CSI2}F`.repeat(count),
65
65
  left: `${CSI2}G`,
66
66
  hide: `${CSI2}?25l`,
67
67
  show: `${CSI2}?25h`,
@@ -69,21 +69,21 @@ var require_src = __commonJS((exports, module) => {
69
69
  restore: `${ESC2}8`
70
70
  };
71
71
  var scroll = {
72
- up: (count2 = 1) => `${CSI2}S`.repeat(count2),
73
- down: (count2 = 1) => `${CSI2}T`.repeat(count2)
72
+ up: (count = 1) => `${CSI2}S`.repeat(count),
73
+ down: (count = 1) => `${CSI2}T`.repeat(count)
74
74
  };
75
75
  var erase = {
76
76
  screen: `${CSI2}2J`,
77
- up: (count2 = 1) => `${CSI2}1J`.repeat(count2),
78
- down: (count2 = 1) => `${CSI2}J`.repeat(count2),
77
+ up: (count = 1) => `${CSI2}1J`.repeat(count),
78
+ down: (count = 1) => `${CSI2}J`.repeat(count),
79
79
  line: `${CSI2}2K`,
80
80
  lineEnd: `${CSI2}K`,
81
81
  lineStart: `${CSI2}1K`,
82
- lines(count2) {
82
+ lines(count) {
83
83
  let clear = "";
84
- for (let i = 0;i < count2; i++)
85
- clear += this.line + (i < count2 - 1 ? cursor.up() : "");
86
- if (count2)
84
+ for (let i = 0;i < count; i++)
85
+ clear += this.line + (i < count - 1 ? cursor.up() : "");
86
+ if (count)
87
87
  clear += cursor.left;
88
88
  return clear;
89
89
  }
@@ -98,16 +98,16 @@ var require_picocolors = __commonJS((exports, module) => {
98
98
  var env = p2.env || {};
99
99
  var isColorSupported = !(!!env.NO_COLOR || argv.includes("--no-color")) && (!!env.FORCE_COLOR || argv.includes("--color") || p2.platform === "win32" || (p2.stdout || {}).isTTY && env.TERM !== "dumb" || !!env.CI);
100
100
  var formatter = (open, close, replace = open) => (input2) => {
101
- let string = "" + input2, index2 = string.indexOf(close, open.length);
102
- return ~index2 ? open + replaceClose(string, close, replace, index2) + close : open + string + close;
101
+ let string = "" + input2, index = string.indexOf(close, open.length);
102
+ return ~index ? open + replaceClose(string, close, replace, index) + close : open + string + close;
103
103
  };
104
- var replaceClose = (string, close, replace, index2) => {
104
+ var replaceClose = (string, close, replace, index) => {
105
105
  let result2 = "", cursor3 = 0;
106
106
  do {
107
- result2 += string.substring(cursor3, index2) + replace;
108
- cursor3 = index2 + close.length;
109
- index2 = string.indexOf(close, cursor3);
110
- } while (~index2);
107
+ result2 += string.substring(cursor3, index) + replace;
108
+ cursor3 = index + close.length;
109
+ index = string.indexOf(close, cursor3);
110
+ } while (~index);
111
111
  return result2 + string.substring(cursor3);
112
112
  };
113
113
  var createColors = (enabled = isColorSupported) => {
@@ -164,7 +164,7 @@ var require_picocolors = __commonJS((exports, module) => {
164
164
  // src/schema-loader.ts
165
165
  import { resolve, join } from "path";
166
166
 
167
- // ../bungres-orm/src/schema/table.ts
167
+ // ../bungres-orm/dist/index.js
168
168
  var TableConfigSymbol = Symbol.for("BungresTableConfig");
169
169
  function getTableConfig(table) {
170
170
  return table[TableConfigSymbol];
@@ -234,7 +234,6 @@ var table = createTableFactory("snake");
234
234
  var snakeCase = { table: createTableFactory("snake") };
235
235
  var camelCase = { table: createTableFactory("camel") };
236
236
  var noCasing = { table: createTableFactory("none") };
237
- // ../bungres-orm/src/schema/columns.ts
238
237
  function buildColumn(dataType, nameOrOpts, opts) {
239
238
  let name = "";
240
239
  let options = opts;
@@ -263,6 +262,13 @@ function buildColumn(dataType, nameOrOpts, opts) {
263
262
  return Object.assign(config2, {
264
263
  as(alias) {
265
264
  return Object.assign({}, this, { alias });
265
+ },
266
+ array() {
267
+ return Object.assign({}, this, { dataType: `${this.dataType}[]` });
268
+ },
269
+ generatedAlwaysAs(expr) {
270
+ const sqlStr = typeof expr === "string" ? expr : expr.sql;
271
+ return Object.assign({}, this, { generatedAs: sqlStr });
266
272
  }
267
273
  });
268
274
  }
@@ -292,7 +298,6 @@ var textArray = col("text[]");
292
298
  var integerArray = col("integer[]");
293
299
  var varcharArray = col("varchar[]");
294
300
  var uuidArray = col("uuid[]");
295
- // ../bungres-orm/src/core/sql.ts
296
301
  function sql(strings, ...values) {
297
302
  let query = "";
298
303
  const params = [];
@@ -335,7 +340,6 @@ function colName(c) {
335
340
  return c.sql;
336
341
  return c.tableName ? `${c.tableName}."${c.name}"` : `"${c.name}"`;
337
342
  }
338
- // ../bungres-orm/src/core/conditions.ts
339
343
  function isColumnConfig(val) {
340
344
  return val !== null && typeof val === "object" && "name" in val && "dataType" in val;
341
345
  }
@@ -489,14 +493,13 @@ function parseOrderByObject(tableConfig, orderByObj) {
489
493
  }
490
494
  return parts;
491
495
  }
492
-
493
- // ../bungres-orm/src/builders/delete.ts
494
496
  class DeleteBuilder {
495
497
  _table;
496
498
  _executor;
497
499
  _where = [];
498
500
  _returning;
499
501
  _comment;
502
+ _with = [];
500
503
  constructor(table2, executor) {
501
504
  this._table = table2;
502
505
  this._executor = executor;
@@ -515,6 +518,10 @@ class DeleteBuilder {
515
518
  }
516
519
  return this;
517
520
  }
521
+ with(...ctes) {
522
+ this._with.push(...ctes);
523
+ return this;
524
+ }
518
525
  returning(...columns) {
519
526
  this._returning = columns.length > 0 ? columns : ["*"];
520
527
  return this;
@@ -524,8 +531,20 @@ class DeleteBuilder {
524
531
  return this;
525
532
  }
526
533
  toSQL() {
527
- let query = `DELETE FROM ${getTableConfig(this._table).qualifiedName}`;
534
+ const tConfig = getTableConfig(this._table);
528
535
  const params = [];
536
+ let prefix = "";
537
+ if (this._with.length > 0) {
538
+ const cteStrs = [];
539
+ for (const cte of this._with) {
540
+ const chunk = cte.query.toSQL();
541
+ const offset = params.length;
542
+ params.push(...chunk.params);
543
+ cteStrs.push(`"${cte.alias}" AS (${chunk.sql.replace(/\$(\d+)/g, (_, n) => `$${parseInt(n) + offset}`)})`);
544
+ }
545
+ prefix = `WITH ${cteStrs.join(", ")} `;
546
+ }
547
+ let query = `DELETE FROM ${tConfig.qualifiedName}`;
529
548
  if (this._where.length > 0) {
530
549
  const combined = sqlJoin(this._where, " AND ");
531
550
  query += " WHERE " + combined.sql;
@@ -537,17 +556,19 @@ class DeleteBuilder {
537
556
  if (this._comment) {
538
557
  query += ` /* ${this._comment.replace(/\*\//g, "")} */`;
539
558
  }
540
- return { sql: query, params };
559
+ return { sql: prefix + query, params };
541
560
  }
542
561
  }
543
- // ../bungres-orm/src/builders/insert.ts
562
+
544
563
  class InsertBuilder {
545
564
  _table;
546
565
  _executor;
547
566
  _values = [];
548
567
  _onConflict;
568
+ _onConflictUpdateConfig;
549
569
  _returning;
550
570
  _comment;
571
+ _with = [];
551
572
  constructor(table2, executor) {
552
573
  this._table = table2;
553
574
  this._executor = executor;
@@ -574,6 +595,14 @@ class InsertBuilder {
574
595
  this._onConflict = clause;
575
596
  return this;
576
597
  }
598
+ onConflictDoUpdate(config2) {
599
+ this._onConflictUpdateConfig = config2;
600
+ return this;
601
+ }
602
+ with(...ctes) {
603
+ this._with.push(...ctes);
604
+ return this;
605
+ }
577
606
  returning(...columns) {
578
607
  this._returning = columns.length > 0 ? columns : ["*"];
579
608
  return this;
@@ -599,6 +628,17 @@ class InsertBuilder {
599
628
  }
600
629
  const columnsStr = keys.map((k) => `"${tConfig.columns[k]?.name ?? k}"`).join(", ");
601
630
  const params = [];
631
+ let prefix = "";
632
+ if (this._with.length > 0) {
633
+ const cteStrs = [];
634
+ for (const cte of this._with) {
635
+ const chunk = cte.query.toSQL();
636
+ const offset = params.length;
637
+ params.push(...chunk.params);
638
+ cteStrs.push(`"${cte.alias}" AS (${chunk.sql.replace(/\$(\d+)/g, (_, n) => `$${parseInt(n) + offset}`)})`);
639
+ }
640
+ prefix = `WITH ${cteStrs.join(", ")} `;
641
+ }
602
642
  const valuesStrs = this._values.map((v) => {
603
643
  const vals = keys.map((k) => {
604
644
  const val = v[k];
@@ -642,6 +682,52 @@ class InsertBuilder {
642
682
  query += " " + this._onConflict.sql.replace(/\$(\d+)/g, (_, n) => `$${parseInt(n) + offset}`);
643
683
  params.push(...this._onConflict.params);
644
684
  }
685
+ } else if (this._onConflictUpdateConfig) {
686
+ const config2 = this._onConflictUpdateConfig;
687
+ const targets = Array.isArray(config2.target) ? config2.target : [config2.target];
688
+ const targetStrs = [];
689
+ for (const t of targets) {
690
+ if (typeof t === "string") {
691
+ targetStrs.push(`"${tConfig.columns[t]?.name ?? t}"`);
692
+ } else {
693
+ const offset = params.length;
694
+ targetStrs.push(t.sql.replace(/\$(\d+)/g, (_, n) => `$${parseInt(n) + offset}`));
695
+ params.push(...t.params);
696
+ }
697
+ }
698
+ const setEntries = Object.entries(config2.set);
699
+ if (setEntries.length === 0)
700
+ throw new Error("InsertBuilder: onConflictDoUpdate requires 'set' fields");
701
+ const setClauses = setEntries.map(([key, value]) => {
702
+ const dbCol = tConfig.columns[key]?.name ?? key;
703
+ if (value && typeof value === "object" && "sql" in value && "params" in value) {
704
+ const chunk = value;
705
+ const offset = params.length;
706
+ params.push(...chunk.params);
707
+ return `"${dbCol}" = ${chunk.sql.replace(/\$(\d+)/g, (_, n) => `$${parseInt(n) + offset}`)}`;
708
+ }
709
+ if (value && typeof value === "object" && !(value instanceof Date)) {
710
+ const colType = tConfig.columns[key]?.dataType;
711
+ if (colType === "json" || colType === "jsonb") {
712
+ params.push(value);
713
+ } else if (Array.isArray(value)) {
714
+ const pgArray = "{" + value.map((item) => {
715
+ if (item === null || item === undefined)
716
+ return "NULL";
717
+ if (typeof item === "string")
718
+ return '"' + item.replace(/"/g, "\\\"") + '"';
719
+ return typeof item === "object" ? '"' + JSON.stringify(item).replace(/"/g, "\\\"") + '"' : String(item);
720
+ }).join(",") + "}";
721
+ params.push(pgArray);
722
+ } else {
723
+ params.push(JSON.stringify(value));
724
+ }
725
+ return `"${dbCol}" = $${params.length}`;
726
+ }
727
+ params.push(value);
728
+ return `"${dbCol}" = $${params.length}`;
729
+ });
730
+ query += ` ON CONFLICT (${targetStrs.join(", ")}) DO UPDATE SET ${setClauses.join(", ")}`;
645
731
  }
646
732
  if (this._returning) {
647
733
  query += " RETURNING " + (this._returning[0] === "*" ? Object.keys(tConfig.columns).map((c) => `"${tConfig.columns[c].name}" AS "${c}"`).join(", ") : this._returning.map((c) => `"${tConfig.columns[c]?.name ?? c}" AS "${c}"`).join(", "));
@@ -649,10 +735,10 @@ class InsertBuilder {
649
735
  if (this._comment) {
650
736
  query += ` /* ${this._comment.replace(/\*\//g, "")} */`;
651
737
  }
652
- return { sql: query, params };
738
+ return { sql: prefix + query, params };
653
739
  }
654
740
  }
655
- // ../bungres-orm/src/builders/select.ts
741
+
656
742
  class SelectBuilder {
657
743
  _table;
658
744
  _executor;
@@ -665,6 +751,8 @@ class SelectBuilder {
665
751
  _select;
666
752
  _selection;
667
753
  _joins = [];
754
+ _with = [];
755
+ _setOperations = [];
668
756
  _comment;
669
757
  constructor(table2, executor, selection) {
670
758
  this._table = table2;
@@ -675,12 +763,35 @@ class SelectBuilder {
675
763
  return this._executor.execute(this).then(onfulfilled, onrejected);
676
764
  }
677
765
  async single() {
766
+ if (this._limit === undefined) {
767
+ this.limit(1);
768
+ }
678
769
  return this._executor.executeSingle(this);
679
770
  }
680
771
  select(...columns) {
681
772
  this._select = columns;
682
773
  return this;
683
774
  }
775
+ with(...ctes) {
776
+ this._with.push(...ctes);
777
+ return this;
778
+ }
779
+ union(other) {
780
+ this._setOperations.push({ type: "UNION", builder: other });
781
+ return this;
782
+ }
783
+ unionAll(other) {
784
+ this._setOperations.push({ type: "UNION ALL", builder: other });
785
+ return this;
786
+ }
787
+ intersect(other) {
788
+ this._setOperations.push({ type: "INTERSECT", builder: other });
789
+ return this;
790
+ }
791
+ except(other) {
792
+ this._setOperations.push({ type: "EXCEPT", builder: other });
793
+ return this;
794
+ }
684
795
  comment(tag) {
685
796
  this._comment = tag;
686
797
  return this;
@@ -783,7 +894,23 @@ class SelectBuilder {
783
894
  }).join(", ");
784
895
  } else {
785
896
  const qName = getTableConfig(this._table).qualifiedName;
786
- cols = Object.keys(getTableConfig(this._table).columns).map((c) => `${qName}."${getTableConfig(this._table).columns[c].name}" AS "${c}"`).join(", ");
897
+ const colsKeys = Object.keys(getTableConfig(this._table).columns);
898
+ if (colsKeys.length === 0) {
899
+ cols = "*";
900
+ } else {
901
+ cols = colsKeys.map((c) => `${qName}."${getTableConfig(this._table).columns[c].name}" AS "${c}"`).join(", ");
902
+ }
903
+ }
904
+ let prefix = "";
905
+ if (this._with.length > 0) {
906
+ const cteStrs = [];
907
+ for (const cte of this._with) {
908
+ const chunk = cte.query.toSQL();
909
+ const offset = params.length;
910
+ params.push(...chunk.params);
911
+ cteStrs.push(`"${cte.alias}" AS (${chunk.sql.replace(/\$(\d+)/g, (_, n) => `$${parseInt(n) + offset}`)})`);
912
+ }
913
+ prefix = `WITH ${cteStrs.join(", ")} `;
787
914
  }
788
915
  let query = `SELECT ${cols} FROM ${getTableConfig(this._table).qualifiedName}`;
789
916
  if (this._joins.length > 0) {
@@ -843,10 +970,18 @@ class SelectBuilder {
843
970
  params.push(this._offset);
844
971
  query += ` OFFSET $${params.length}`;
845
972
  }
973
+ if (this._setOperations.length > 0) {
974
+ for (const op of this._setOperations) {
975
+ const chunk = op.builder.toSQL();
976
+ const offset = params.length;
977
+ params.push(...chunk.params);
978
+ query += ` ${op.type} ${chunk.sql.replace(/\$(\d+)/g, (_, n) => `$${parseInt(n) + offset}`)}`;
979
+ }
980
+ }
846
981
  if (this._comment) {
847
982
  query += ` /* ${this._comment.replace(/\*\//g, "")} */`;
848
983
  }
849
- return { sql: query, params };
984
+ return { sql: prefix + query, params };
850
985
  }
851
986
  }
852
987
 
@@ -861,7 +996,7 @@ class SelectBuilderIntermediate {
861
996
  return new SelectBuilder(table2, this._executor, this._selection);
862
997
  }
863
998
  }
864
- // ../bungres-orm/src/builders/update.ts
999
+
865
1000
  class UpdateBuilder {
866
1001
  _table;
867
1002
  _executor;
@@ -869,6 +1004,7 @@ class UpdateBuilder {
869
1004
  _where = [];
870
1005
  _returning;
871
1006
  _comment;
1007
+ _with = [];
872
1008
  constructor(table2, executor) {
873
1009
  this._table = table2;
874
1010
  this._executor = executor;
@@ -891,6 +1027,10 @@ class UpdateBuilder {
891
1027
  }
892
1028
  return this;
893
1029
  }
1030
+ with(...ctes) {
1031
+ this._with.push(...ctes);
1032
+ return this;
1033
+ }
894
1034
  returning(...columns) {
895
1035
  this._returning = columns.length > 0 ? columns : ["*"];
896
1036
  return this;
@@ -905,6 +1045,17 @@ class UpdateBuilder {
905
1045
  throw new Error("UpdateBuilder: no fields to set");
906
1046
  }
907
1047
  const params = [];
1048
+ let prefix = "";
1049
+ if (this._with.length > 0) {
1050
+ const cteStrs = [];
1051
+ for (const cte of this._with) {
1052
+ const chunk = cte.query.toSQL();
1053
+ const offset = params.length;
1054
+ params.push(...chunk.params);
1055
+ cteStrs.push(`"${cte.alias}" AS (${chunk.sql.replace(/\$(\d+)/g, (_, n) => `$${parseInt(n) + offset}`)})`);
1056
+ }
1057
+ prefix = `WITH ${cteStrs.join(", ")} `;
1058
+ }
908
1059
  const setClauses = entries.map(([key, value]) => {
909
1060
  const dbCol = getTableConfig(this._table).columns[key]?.name ?? key;
910
1061
  if (value && typeof value === "object" && "sql" in value && "params" in value) {
@@ -947,10 +1098,9 @@ class UpdateBuilder {
947
1098
  if (this._comment) {
948
1099
  query += ` /* ${this._comment.replace(/\*\//g, "")} */`;
949
1100
  }
950
- return { sql: query, params };
1101
+ return { sql: prefix + query, params };
951
1102
  }
952
1103
  }
953
- // ../bungres-orm/src/builders/relational.ts
954
1104
  function getPkColumn(tableConfig) {
955
1105
  if (tableConfig.primaryKeys?.length > 0)
956
1106
  return tableConfig.primaryKeys[0];
@@ -1208,8 +1358,6 @@ class RelationalQueryBuilder {
1208
1358
  return { sql: sql2, params };
1209
1359
  }
1210
1360
  }
1211
-
1212
- // ../bungres-orm/src/core/db.ts
1213
1361
  function parseDBName(url) {
1214
1362
  try {
1215
1363
  return new URL(url).pathname.slice(1);
@@ -1318,6 +1466,7 @@ class BungresDB {
1318
1466
 
1319
1467
  class BungresTransaction {
1320
1468
  _sql;
1469
+ _savepointCounter = 0;
1321
1470
  constructor(sql2) {
1322
1471
  this._sql = sql2;
1323
1472
  }
@@ -1352,6 +1501,19 @@ class BungresTransaction {
1352
1501
  const result2 = await this._sql.unsafe(query, params);
1353
1502
  return Array.from(result2);
1354
1503
  }
1504
+ async transaction(fn) {
1505
+ this._savepointCounter++;
1506
+ const spName = `sp_${this._savepointCounter}`;
1507
+ await this._sql.unsafe(`SAVEPOINT ${spName}`);
1508
+ try {
1509
+ const result2 = await fn(this);
1510
+ await this._sql.unsafe(`RELEASE SAVEPOINT ${spName}`);
1511
+ return result2;
1512
+ } catch (e) {
1513
+ await this._sql.unsafe(`ROLLBACK TO SAVEPOINT ${spName}`);
1514
+ throw e;
1515
+ }
1516
+ }
1355
1517
  }
1356
1518
  function bungres(config2) {
1357
1519
  const db2 = new BungresDB(config2);
@@ -1375,7 +1537,6 @@ function bungres(config2) {
1375
1537
  }
1376
1538
  return db2;
1377
1539
  }
1378
- // ../bungres-orm/src/ddl.ts
1379
1540
  function generateCreateTable(config2, ifNotExists = true) {
1380
1541
  const tableName = config2.schema ? `"${config2.schema}"."${config2.name}"` : `"${config2.name}"`;
1381
1542
  const exists = ifNotExists ? " IF NOT EXISTS" : "";
@@ -1385,8 +1546,8 @@ function generateCreateTable(config2, ifNotExists = true) {
1385
1546
  columnDefs.push(`PRIMARY KEY (${pkCols})`);
1386
1547
  }
1387
1548
  if (config2.checks) {
1388
- for (const check of config2.checks) {
1389
- columnDefs.push(`CHECK (${check})`);
1549
+ for (const check2 of config2.checks) {
1550
+ columnDefs.push(`CHECK (${check2})`);
1390
1551
  }
1391
1552
  }
1392
1553
  let sql2 = `CREATE TABLE${exists} ${tableName} (
@@ -1424,7 +1585,9 @@ function buildColumnDDL(key, col2, tableName) {
1424
1585
  if (col2.unique && !col2.primaryKey) {
1425
1586
  parts.push("UNIQUE");
1426
1587
  }
1427
- if (col2.defaultFn) {
1588
+ if (col2.generatedAs) {
1589
+ parts.push(`GENERATED ALWAYS AS (${col2.generatedAs}) STORED`);
1590
+ } else if (col2.defaultFn) {
1428
1591
  parts.push(`DEFAULT ${col2.defaultFn}`);
1429
1592
  } else if (col2.defaultValue !== undefined) {
1430
1593
  parts.push(`DEFAULT ${formatDefaultValue(col2.defaultValue, col2.dataType)}`);
@@ -1445,6 +1608,13 @@ function buildColumnDDL(key, col2, tableName) {
1445
1608
  return parts.join(" ");
1446
1609
  }
1447
1610
  function buildType(col2) {
1611
+ if (col2.enumConfig) {
1612
+ return `"${col2.enumConfig.enumName}"`;
1613
+ }
1614
+ if (col2.dataType.endsWith("[]")) {
1615
+ const baseType = buildType({ ...col2, dataType: col2.dataType.slice(0, -2) });
1616
+ return `${baseType}[]`;
1617
+ }
1448
1618
  switch (col2.dataType) {
1449
1619
  case "varchar":
1450
1620
  return col2.length ? `VARCHAR(${col2.length})` : "VARCHAR";
@@ -1479,12 +1649,12 @@ function formatDefaultValue(value, dataType) {
1479
1649
  }
1480
1650
  function buildIndex(table2, idx) {
1481
1651
  const tableName = table2.schema ? `"${table2.schema}"."${table2.name}"` : `"${table2.name}"`;
1482
- const unique = idx.unique ? "UNIQUE " : "";
1652
+ const unique2 = idx.unique ? "UNIQUE " : "";
1483
1653
  const using = idx.using ? ` USING ${idx.using.toUpperCase()}` : "";
1484
1654
  const cols = idx.columns.map((c) => `"${c}"`).join(", ");
1485
1655
  const where = idx.where ? ` WHERE ${idx.where}` : "";
1486
1656
  const idxName = idx.name ?? `idx_${table2.name}_${idx.columns.join("_")}`;
1487
- return `CREATE ${unique}INDEX IF NOT EXISTS "${idxName}" ON ${tableName}${using} (${cols})${where};`;
1657
+ return `CREATE ${unique2}INDEX IF NOT EXISTS "${idxName}" ON ${tableName}${using} (${cols})${where};`;
1488
1658
  }
1489
1659
  function generateAddColumn(tableName, schema, key, col2) {
1490
1660
  const tbl = schema ? `"${schema}"."${tableName}"` : `"${tableName}"`;
@@ -1494,6 +1664,7 @@ function generateDropColumn(tableName, schema, columnName) {
1494
1664
  const tbl = schema ? `"${schema}"."${tableName}"` : `"${tableName}"`;
1495
1665
  return `ALTER TABLE ${tbl} DROP COLUMN IF EXISTS "${columnName}";`;
1496
1666
  }
1667
+
1497
1668
  // src/schema-loader.ts
1498
1669
  async function loadSchemas(patterns, cwd = process.cwd()) {
1499
1670
  const globs = Array.isArray(patterns) ? patterns : [patterns];
@@ -1575,7 +1746,7 @@ var getStringTruncatedWidth = (input2, truncationOptions = {}, widthOptions = {}
1575
1746
  [CJKT_WIDE_RE, WIDE_WIDTH]
1576
1747
  ];
1577
1748
  let indexPrev = 0;
1578
- let index2 = 0;
1749
+ let index = 0;
1579
1750
  let length = input2.length;
1580
1751
  let lengthExtra = 0;
1581
1752
  let truncationEnabled = false;
@@ -1587,8 +1758,8 @@ var getStringTruncatedWidth = (input2, truncationOptions = {}, widthOptions = {}
1587
1758
  let widthExtra = 0;
1588
1759
  outer:
1589
1760
  while (true) {
1590
- if (unmatchedEnd > unmatchedStart || index2 >= length && index2 > indexPrev) {
1591
- const unmatched = input2.slice(unmatchedStart, unmatchedEnd) || input2.slice(indexPrev, index2);
1761
+ if (unmatchedEnd > unmatchedStart || index >= length && index > indexPrev) {
1762
+ const unmatched = input2.slice(unmatchedStart, unmatchedEnd) || input2.slice(indexPrev, index);
1592
1763
  lengthExtra = 0;
1593
1764
  for (const char of unmatched.replaceAll(MODIFIER_RE, "")) {
1594
1765
  const codePoint = char.codePointAt(0) || 0;
@@ -1611,17 +1782,17 @@ var getStringTruncatedWidth = (input2, truncationOptions = {}, widthOptions = {}
1611
1782
  }
1612
1783
  unmatchedStart = unmatchedEnd = 0;
1613
1784
  }
1614
- if (index2 >= length) {
1785
+ if (index >= length) {
1615
1786
  break outer;
1616
1787
  }
1617
1788
  for (let i = 0, l = PARSE_BLOCKS.length;i < l; i++) {
1618
1789
  const [BLOCK_RE, BLOCK_WIDTH] = PARSE_BLOCKS[i];
1619
- BLOCK_RE.lastIndex = index2;
1790
+ BLOCK_RE.lastIndex = index;
1620
1791
  if (BLOCK_RE.test(input2)) {
1621
- lengthExtra = BLOCK_RE === CJKT_WIDE_RE ? getCodePointsLength(input2.slice(index2, BLOCK_RE.lastIndex)) : BLOCK_RE === EMOJI_RE ? 1 : BLOCK_RE.lastIndex - index2;
1792
+ lengthExtra = BLOCK_RE === CJKT_WIDE_RE ? getCodePointsLength(input2.slice(index, BLOCK_RE.lastIndex)) : BLOCK_RE === EMOJI_RE ? 1 : BLOCK_RE.lastIndex - index;
1622
1793
  widthExtra = lengthExtra * BLOCK_WIDTH;
1623
1794
  if (width + widthExtra > truncationLimit) {
1624
- truncationIndex = Math.min(truncationIndex, index2 + Math.floor((truncationLimit - width) / BLOCK_WIDTH));
1795
+ truncationIndex = Math.min(truncationIndex, index + Math.floor((truncationLimit - width) / BLOCK_WIDTH));
1625
1796
  }
1626
1797
  if (width + widthExtra > LIMIT) {
1627
1798
  truncationEnabled = true;
@@ -1629,12 +1800,12 @@ var getStringTruncatedWidth = (input2, truncationOptions = {}, widthOptions = {}
1629
1800
  }
1630
1801
  width += widthExtra;
1631
1802
  unmatchedStart = indexPrev;
1632
- unmatchedEnd = index2;
1633
- index2 = indexPrev = BLOCK_RE.lastIndex;
1803
+ unmatchedEnd = index;
1804
+ index = indexPrev = BLOCK_RE.lastIndex;
1634
1805
  continue outer;
1635
1806
  }
1636
1807
  }
1637
- index2 += 1;
1808
+ index += 1;
1638
1809
  }
1639
1810
  return {
1640
1811
  width: truncationEnabled ? truncationLimit : width,
@@ -1693,7 +1864,7 @@ var getClosingCode = (openingCode) => {
1693
1864
  };
1694
1865
  var wrapAnsiCode = (code2) => `${ESC}${ANSI_CSI}${code2}${ANSI_SGR_TERMINATOR}`;
1695
1866
  var wrapAnsiHyperlink = (url) => `${ESC}${ANSI_ESCAPE_LINK}${url}${ANSI_ESCAPE_BELL}`;
1696
- var wrapWord = (rows, word, columns2) => {
1867
+ var wrapWord = (rows, word, columns) => {
1697
1868
  const characters = word[Symbol.iterator]();
1698
1869
  let isInsideEscape = false;
1699
1870
  let isInsideLinkEscape = false;
@@ -1705,7 +1876,7 @@ var wrapWord = (rows, word, columns2) => {
1705
1876
  while (!currentCharacter.done) {
1706
1877
  const character = currentCharacter.value;
1707
1878
  const characterLength = dist_default2(character);
1708
- if (visible + characterLength <= columns2) {
1879
+ if (visible + characterLength <= columns) {
1709
1880
  rows[rows.length - 1] += character;
1710
1881
  } else {
1711
1882
  rows.push(character);
@@ -1726,7 +1897,7 @@ var wrapWord = (rows, word, columns2) => {
1726
1897
  }
1727
1898
  } else {
1728
1899
  visible += characterLength;
1729
- if (visible === columns2 && !nextCharacter.done) {
1900
+ if (visible === columns && !nextCharacter.done) {
1730
1901
  rows.push("");
1731
1902
  visible = 0;
1732
1903
  }
@@ -1754,7 +1925,7 @@ var stringVisibleTrimSpacesRight = (string) => {
1754
1925
  }
1755
1926
  return words.slice(0, last).join(" ") + words.slice(last).join("");
1756
1927
  };
1757
- var exec = (string, columns2, options = {}) => {
1928
+ var exec = (string, columns, options = {}) => {
1758
1929
  if (options.trim !== false && string.trim() === "") {
1759
1930
  return "";
1760
1931
  }
@@ -1764,8 +1935,8 @@ var exec = (string, columns2, options = {}) => {
1764
1935
  const words = string.split(" ");
1765
1936
  let rows = [""];
1766
1937
  let rowLength = 0;
1767
- for (let index2 = 0;index2 < words.length; index2++) {
1768
- const word = words[index2];
1938
+ for (let index = 0;index < words.length; index++) {
1939
+ const word = words[index];
1769
1940
  if (options.trim !== false) {
1770
1941
  const row = rows.at(-1) ?? "";
1771
1942
  const trimmed = row.trimStart();
@@ -1774,8 +1945,8 @@ var exec = (string, columns2, options = {}) => {
1774
1945
  rowLength = dist_default2(trimmed);
1775
1946
  }
1776
1947
  }
1777
- if (index2 !== 0) {
1778
- if (rowLength >= columns2 && (options.wordWrap === false || options.trim === false)) {
1948
+ if (index !== 0) {
1949
+ if (rowLength >= columns && (options.wordWrap === false || options.trim === false)) {
1779
1950
  rows.push("");
1780
1951
  rowLength = 0;
1781
1952
  }
@@ -1785,28 +1956,28 @@ var exec = (string, columns2, options = {}) => {
1785
1956
  }
1786
1957
  }
1787
1958
  const wordLength = dist_default2(word);
1788
- if (options.hard && wordLength > columns2) {
1789
- const remainingColumns = columns2 - rowLength;
1790
- const breaksStartingThisLine = 1 + Math.floor((wordLength - remainingColumns - 1) / columns2);
1791
- const breaksStartingNextLine = Math.floor((wordLength - 1) / columns2);
1959
+ if (options.hard && wordLength > columns) {
1960
+ const remainingColumns = columns - rowLength;
1961
+ const breaksStartingThisLine = 1 + Math.floor((wordLength - remainingColumns - 1) / columns);
1962
+ const breaksStartingNextLine = Math.floor((wordLength - 1) / columns);
1792
1963
  if (breaksStartingNextLine < breaksStartingThisLine) {
1793
1964
  rows.push("");
1794
1965
  }
1795
- wrapWord(rows, word, columns2);
1966
+ wrapWord(rows, word, columns);
1796
1967
  rowLength = dist_default2(rows.at(-1) ?? "");
1797
1968
  continue;
1798
1969
  }
1799
- if (rowLength + wordLength > columns2 && rowLength && wordLength) {
1800
- if (options.wordWrap === false && rowLength < columns2) {
1801
- wrapWord(rows, word, columns2);
1970
+ if (rowLength + wordLength > columns && rowLength && wordLength) {
1971
+ if (options.wordWrap === false && rowLength < columns) {
1972
+ wrapWord(rows, word, columns);
1802
1973
  rowLength = dist_default2(rows.at(-1) ?? "");
1803
1974
  continue;
1804
1975
  }
1805
1976
  rows.push("");
1806
1977
  rowLength = 0;
1807
1978
  }
1808
- if (rowLength + wordLength > columns2 && options.wordWrap === false) {
1809
- wrapWord(rows, word, columns2);
1979
+ if (rowLength + wordLength > columns && options.wordWrap === false) {
1980
+ wrapWord(rows, word, columns);
1810
1981
  rowLength = dist_default2(rows.at(-1) ?? "");
1811
1982
  continue;
1812
1983
  }
@@ -1863,8 +2034,8 @@ var exec = (string, columns2, options = {}) => {
1863
2034
  return returnValue;
1864
2035
  };
1865
2036
  var CRLF_OR_LF = /\r?\n/;
1866
- function wrapAnsi(string, columns2, options) {
1867
- return String(string).normalize().split(CRLF_OR_LF).map((line2) => exec(line2, columns2, options)).join(`
2037
+ function wrapAnsi(string, columns, options) {
2038
+ return String(string).normalize().split(CRLF_OR_LF).map((line2) => exec(line2, columns, options)).join(`
1868
2039
  `);
1869
2040
  }
1870
2041
 
@@ -3144,11 +3315,11 @@ function diffSchemas(prev, next) {
3144
3315
  const idxName = idx.name ?? `idx_${tableName}_${idx.columns.join("_")}`;
3145
3316
  if (!prevIdxNames.has(idxName)) {
3146
3317
  const tbl = nextConfig.schema ? `"${nextConfig.schema}"."${tableName}"` : `"${tableName}"`;
3147
- const unique2 = idx.unique ? "UNIQUE " : "";
3318
+ const unique = idx.unique ? "UNIQUE " : "";
3148
3319
  const using = idx.using ? ` USING ${idx.using.toUpperCase()}` : "";
3149
3320
  const cols = idx.columns.map((c2) => `"${c2}"`).join(", ");
3150
3321
  const where = idx.where ? ` WHERE ${idx.where}` : "";
3151
- statements.push(`CREATE ${unique2}INDEX IF NOT EXISTS "${idxName}" ON ${tbl}${using} (${cols})${where};`);
3322
+ statements.push(`CREATE ${unique}INDEX IF NOT EXISTS "${idxName}" ON ${tbl}${using} (${cols})${where};`);
3152
3323
  summary.push(`CREATE INDEX ${idxName} ON ${tableName}`);
3153
3324
  }
3154
3325
  }
@@ -3470,7 +3641,7 @@ export const db = bungres({ url, schema });
3470
3641
  // src/commands/pull.ts
3471
3642
  import { resolve as resolve4, join as join5 } from "path";
3472
3643
  async function introspectDb(sql2, dbSchema) {
3473
- const columns2 = await sql2.unsafe(`SELECT
3644
+ const columns = await sql2.unsafe(`SELECT
3474
3645
  c.table_name,
3475
3646
  c.column_name,
3476
3647
  c.data_type,
@@ -3504,7 +3675,7 @@ async function introspectDb(sql2, dbSchema) {
3504
3675
  const indexes = await sql2.unsafe(`SELECT tablename, indexname, indexdef
3505
3676
  FROM pg_indexes
3506
3677
  WHERE schemaname = $1`, [dbSchema]);
3507
- return groupByTable(columns2, constraints, indexes);
3678
+ return groupByTable(columns, constraints, indexes);
3508
3679
  }
3509
3680
  async function runPull(config2) {
3510
3681
  console.log("@bungres/kit pull: introspecting database...");
@@ -3527,9 +3698,9 @@ async function runPull(config2) {
3527
3698
  await sql2.end();
3528
3699
  }
3529
3700
  }
3530
- function groupByTable(columns2, constraints, indexes) {
3701
+ function groupByTable(columns, constraints, indexes) {
3531
3702
  const map = new Map;
3532
- for (const col2 of columns2) {
3703
+ for (const col2 of columns) {
3533
3704
  if (!map.has(col2.table_name)) {
3534
3705
  map.set(col2.table_name, {
3535
3706
  tableName: col2.table_name,
@@ -4306,7 +4477,7 @@ async function runStudio(config2) {
4306
4477
  fk.columns.forEach((col2) => fkColumns.add(col2));
4307
4478
  });
4308
4479
  }
4309
- const columns2 = Object.entries(s.config.columns).map(([key, col2]) => {
4480
+ const columns = Object.entries(s.config.columns).map(([key, col2]) => {
4310
4481
  const fk = col2.references ? {
4311
4482
  table: col2.references.table,
4312
4483
  column: col2.references.column
@@ -4321,7 +4492,7 @@ async function runStudio(config2) {
4321
4492
  return {
4322
4493
  name: s.config.name,
4323
4494
  exportName: s.exportName,
4324
- columns: columns2,
4495
+ columns,
4325
4496
  foreignKeys: s.config.foreignKeys || []
4326
4497
  };
4327
4498
  });
@@ -4444,12 +4615,12 @@ async function runStudio(config2) {
4444
4615
  </div>
4445
4616
  `, { headers: { "Content-Type": "text/html" } });
4446
4617
  }
4447
- const columns2 = Object.keys(data[0] || {});
4618
+ const columns = Object.keys(data[0] || {});
4448
4619
  let html = '<div class="flex flex-col h-full w-full bg-background">';
4449
4620
  html += '<div class="flex-1 overflow-auto">';
4450
4621
  html += '<table class="text-left border-collapse text-sm whitespace-nowrap">';
4451
4622
  html += "<thead><tr>";
4452
- columns2.forEach((col2) => {
4623
+ columns.forEach((col2) => {
4453
4624
  const colConfig = schema.config.columns ? schema.config.columns[col2] : null;
4454
4625
  let typeLabel = colConfig ? colConfig.dataType : "unknown";
4455
4626
  let indexLabel = "";
@@ -4481,7 +4652,7 @@ async function runStudio(config2) {
4481
4652
  html += "</tr></thead><tbody>";
4482
4653
  data.forEach((row) => {
4483
4654
  html += '<tr class="hover:bg-muted/50 transition-colors">';
4484
- columns2.forEach((col2) => {
4655
+ columns.forEach((col2) => {
4485
4656
  html += `<td class="border-b border-r border-border px-4 py-2 max-w-[300px] overflow-hidden text-ellipsis">${formatValue(row[col2])}</td>`;
4486
4657
  });
4487
4658
  html += "</tr>";
@@ -4684,7 +4855,7 @@ async function ensureDatabase2(dbUrl) {
4684
4855
  // package.json
4685
4856
  var package_default = {
4686
4857
  name: "@bungres/kit",
4687
- version: "0.7.0",
4858
+ version: "1.0.0",
4688
4859
  description: "CLI toolkit for @bungres/orm \u2014 migrate, push, generate, pull",
4689
4860
  license: "MIT",
4690
4861
  engines: {
@@ -4734,7 +4905,7 @@ var package_default = {
4734
4905
  test: "bun test"
4735
4906
  },
4736
4907
  dependencies: {
4737
- "@bungres/orm": "^0.6.0",
4908
+ "@bungres/orm": "^1.0.0",
4738
4909
  "@clack/prompts": "^1.7.0",
4739
4910
  picocolors: "^1.1.1"
4740
4911
  },