drizzle-kit 0.20.4-bf71f08 → 0.20.4-bfc36f4

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 (5) hide show
  1. package/bin.cjs +1027 -984
  2. package/package.json +4 -4
  3. package/utils-studio.js +1268 -1267
  4. package/utils-studio.mjs +1317 -1316
  5. package/utils.js +1028 -982
package/utils-studio.mjs CHANGED
@@ -9,7 +9,7 @@ var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require
9
9
  }) : x)(function(x) {
10
10
  if (typeof require !== "undefined")
11
11
  return require.apply(this, arguments);
12
- throw new Error('Dynamic require of "' + x + '" is not supported');
12
+ throw Error('Dynamic require of "' + x + '" is not supported');
13
13
  });
14
14
  var __esm = (fn, res) => function __init() {
15
15
  return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
@@ -544,1399 +544,1400 @@ var init_source = __esm({
544
544
  }
545
545
  });
546
546
 
547
- // src/serializer/index.ts
548
- import * as glob from "glob";
549
- var init_serializer = __esm({
550
- "src/serializer/index.ts"() {
551
- init_source();
547
+ // node_modules/.pnpm/hanji@0.0.5/node_modules/hanji/readline.js
548
+ var require_readline = __commonJS({
549
+ "node_modules/.pnpm/hanji@0.0.5/node_modules/hanji/readline.js"(exports) {
550
+ "use strict";
551
+ Object.defineProperty(exports, "__esModule", { value: true });
552
+ exports.prepareReadLine = void 0;
553
+ var prepareReadLine = () => {
554
+ const stdin = process.stdin;
555
+ const stdout = process.stdout;
556
+ const readline = __require("readline");
557
+ const rl = readline.createInterface({
558
+ input: stdin,
559
+ escapeCodeTimeout: 50
560
+ });
561
+ readline.emitKeypressEvents(stdin, rl);
562
+ return {
563
+ stdin,
564
+ stdout,
565
+ closable: rl
566
+ };
567
+ };
568
+ exports.prepareReadLine = prepareReadLine;
552
569
  }
553
570
  });
554
571
 
555
- // src/cli/validations/outputs.ts
556
- var init_outputs = __esm({
557
- "src/cli/validations/outputs.ts"() {
558
- init_source();
572
+ // node_modules/.pnpm/sisteransi@1.0.5/node_modules/sisteransi/src/index.js
573
+ var require_src = __commonJS({
574
+ "node_modules/.pnpm/sisteransi@1.0.5/node_modules/sisteransi/src/index.js"(exports, module) {
575
+ "use strict";
576
+ var ESC = "\x1B";
577
+ var CSI = `${ESC}[`;
578
+ var beep = "\x07";
579
+ var cursor = {
580
+ to(x, y) {
581
+ if (!y)
582
+ return `${CSI}${x + 1}G`;
583
+ return `${CSI}${y + 1};${x + 1}H`;
584
+ },
585
+ move(x, y) {
586
+ let ret = "";
587
+ if (x < 0)
588
+ ret += `${CSI}${-x}D`;
589
+ else if (x > 0)
590
+ ret += `${CSI}${x}C`;
591
+ if (y < 0)
592
+ ret += `${CSI}${-y}A`;
593
+ else if (y > 0)
594
+ ret += `${CSI}${y}B`;
595
+ return ret;
596
+ },
597
+ up: (count = 1) => `${CSI}${count}A`,
598
+ down: (count = 1) => `${CSI}${count}B`,
599
+ forward: (count = 1) => `${CSI}${count}C`,
600
+ backward: (count = 1) => `${CSI}${count}D`,
601
+ nextLine: (count = 1) => `${CSI}E`.repeat(count),
602
+ prevLine: (count = 1) => `${CSI}F`.repeat(count),
603
+ left: `${CSI}G`,
604
+ hide: `${CSI}?25l`,
605
+ show: `${CSI}?25h`,
606
+ save: `${ESC}7`,
607
+ restore: `${ESC}8`
608
+ };
609
+ var scroll = {
610
+ up: (count = 1) => `${CSI}S`.repeat(count),
611
+ down: (count = 1) => `${CSI}T`.repeat(count)
612
+ };
613
+ var erase = {
614
+ screen: `${CSI}2J`,
615
+ up: (count = 1) => `${CSI}1J`.repeat(count),
616
+ down: (count = 1) => `${CSI}J`.repeat(count),
617
+ line: `${CSI}2K`,
618
+ lineEnd: `${CSI}K`,
619
+ lineStart: `${CSI}1K`,
620
+ lines(count) {
621
+ let clear = "";
622
+ for (let i = 0; i < count; i++)
623
+ clear += this.line + (i < count - 1 ? cursor.up() : "");
624
+ if (count)
625
+ clear += cursor.left;
626
+ return clear;
627
+ }
628
+ };
629
+ module.exports = { cursor, scroll, erase, beep };
559
630
  }
560
631
  });
561
632
 
562
- // src/serializer/pgSerializer.ts
563
- import {
564
- customType,
565
- PgBigInt53Builder,
566
- PgBigSerial53Builder,
567
- PgBooleanBuilder,
568
- PgCharBuilder,
569
- PgCidrBuilder,
570
- PgDateBuilder,
571
- PgDialect,
572
- PgDoublePrecisionBuilder,
573
- PgInetBuilder,
574
- PgIntegerBuilder,
575
- PgIntervalBuilder,
576
- PgJsonbBuilder,
577
- PgJsonBuilder,
578
- PgMacaddr8Builder,
579
- PgMacaddrBuilder,
580
- PgNumericBuilder,
581
- PgRealBuilder,
582
- pgSchema,
583
- PgSerialBuilder,
584
- PgSmallIntBuilder,
585
- PgSmallSerialBuilder,
586
- pgTable,
587
- PgTextBuilder,
588
- PgTimeBuilder,
589
- PgTimestampBuilder,
590
- PgUUIDBuilder,
591
- PgVarcharBuilder,
592
- PrimaryKeyBuilder,
593
- uniqueKeyName
594
- } from "drizzle-orm/pg-core";
595
- import { getTableConfig } from "drizzle-orm/pg-core";
596
- import { is, SQL, getTableName } from "drizzle-orm";
597
- var dialect, trimChar, fromDatabase, columnToDefault, defaultForColumn, toDrizzle;
598
- var init_pgSerializer = __esm({
599
- "src/serializer/pgSerializer.ts"() {
600
- init_serializer();
601
- init_source();
602
- init_outputs();
603
- dialect = new PgDialect();
604
- trimChar = (str, char) => {
605
- let start = 0;
606
- let end = str.length;
607
- while (start < end && str[start] === char)
608
- ++start;
609
- while (end > start && str[end - 1] === char)
610
- --end;
611
- return start > 0 || end < str.length ? str.substring(start, end) : str.toString();
633
+ // node_modules/.pnpm/hanji@0.0.5/node_modules/hanji/utils.js
634
+ var require_utils = __commonJS({
635
+ "node_modules/.pnpm/hanji@0.0.5/node_modules/hanji/utils.js"(exports) {
636
+ "use strict";
637
+ Object.defineProperty(exports, "__esModule", { value: true });
638
+ exports.clear = void 0;
639
+ var sisteransi_1 = require_src();
640
+ var strip = (str) => {
641
+ const pattern = [
642
+ "[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]+)*|[a-zA-Z\\d]+(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?\\u0007)",
643
+ "(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PRZcf-ntqry=><~]))"
644
+ ].join("|");
645
+ const RGX = new RegExp(pattern, "g");
646
+ return typeof str === "string" ? str.replace(RGX, "") : str;
612
647
  };
613
- fromDatabase = async (db, tablesFilter = (table) => true, schemaFilters, progressCallback) => {
614
- const result = {};
615
- const internals = { tables: {} };
616
- const where = schemaFilters.map((t) => `table_schema = '${t}'`).join(" or ");
617
- const allTables = await db.query(
618
- `SELECT table_schema, table_name FROM information_schema.tables WHERE ${where};`
619
- );
620
- const schemas = new Set(allTables.map((it) => it.table_schema));
621
- schemas.delete("public");
622
- const allSchemas = await db.query(`select s.nspname as table_schema
623
- from pg_catalog.pg_namespace s
624
- join pg_catalog.pg_user u on u.usesysid = s.nspowner
625
- where nspname not in ('information_schema', 'pg_catalog', 'public')
626
- and nspname not like 'pg_toast%'
627
- and nspname not like 'pg_temp_%'
628
- order by table_schema;`);
629
- allSchemas.forEach((item) => {
630
- if (schemaFilters.includes(item.table_schema)) {
631
- schemas.add(item.table_schema);
648
+ var stringWidth = (str) => [...strip(str)].length;
649
+ var clear = function(prompt, perLine) {
650
+ if (!perLine)
651
+ return sisteransi_1.erase.line + sisteransi_1.cursor.to(0);
652
+ let rows = 0;
653
+ const lines = prompt.split(/\r?\n/);
654
+ for (let line of lines) {
655
+ rows += 1 + Math.floor(Math.max(stringWidth(line) - 1, 0) / perLine);
656
+ }
657
+ return sisteransi_1.erase.lines(rows);
658
+ };
659
+ exports.clear = clear;
660
+ }
661
+ });
662
+
663
+ // node_modules/.pnpm/lodash.throttle@4.1.1/node_modules/lodash.throttle/index.js
664
+ var require_lodash = __commonJS({
665
+ "node_modules/.pnpm/lodash.throttle@4.1.1/node_modules/lodash.throttle/index.js"(exports, module) {
666
+ var FUNC_ERROR_TEXT = "Expected a function";
667
+ var NAN = 0 / 0;
668
+ var symbolTag = "[object Symbol]";
669
+ var reTrim = /^\s+|\s+$/g;
670
+ var reIsBadHex = /^[-+]0x[0-9a-f]+$/i;
671
+ var reIsBinary = /^0b[01]+$/i;
672
+ var reIsOctal = /^0o[0-7]+$/i;
673
+ var freeParseInt = parseInt;
674
+ var freeGlobal = typeof global == "object" && global && global.Object === Object && global;
675
+ var freeSelf = typeof self == "object" && self && self.Object === Object && self;
676
+ var root = freeGlobal || freeSelf || Function("return this")();
677
+ var objectProto = Object.prototype;
678
+ var objectToString = objectProto.toString;
679
+ var nativeMax = Math.max;
680
+ var nativeMin = Math.min;
681
+ var now = function() {
682
+ return root.Date.now();
683
+ };
684
+ function debounce(func, wait, options) {
685
+ var lastArgs, lastThis, maxWait, result, timerId, lastCallTime, lastInvokeTime = 0, leading = false, maxing = false, trailing = true;
686
+ if (typeof func != "function") {
687
+ throw new TypeError(FUNC_ERROR_TEXT);
688
+ }
689
+ wait = toNumber(wait) || 0;
690
+ if (isObject(options)) {
691
+ leading = !!options.leading;
692
+ maxing = "maxWait" in options;
693
+ maxWait = maxing ? nativeMax(toNumber(options.maxWait) || 0, wait) : maxWait;
694
+ trailing = "trailing" in options ? !!options.trailing : trailing;
695
+ }
696
+ function invokeFunc(time) {
697
+ var args = lastArgs, thisArg = lastThis;
698
+ lastArgs = lastThis = void 0;
699
+ lastInvokeTime = time;
700
+ result = func.apply(thisArg, args);
701
+ return result;
702
+ }
703
+ function leadingEdge(time) {
704
+ lastInvokeTime = time;
705
+ timerId = setTimeout(timerExpired, wait);
706
+ return leading ? invokeFunc(time) : result;
707
+ }
708
+ function remainingWait(time) {
709
+ var timeSinceLastCall = time - lastCallTime, timeSinceLastInvoke = time - lastInvokeTime, result2 = wait - timeSinceLastCall;
710
+ return maxing ? nativeMin(result2, maxWait - timeSinceLastInvoke) : result2;
711
+ }
712
+ function shouldInvoke(time) {
713
+ var timeSinceLastCall = time - lastCallTime, timeSinceLastInvoke = time - lastInvokeTime;
714
+ return lastCallTime === void 0 || timeSinceLastCall >= wait || timeSinceLastCall < 0 || maxing && timeSinceLastInvoke >= maxWait;
715
+ }
716
+ function timerExpired() {
717
+ var time = now();
718
+ if (shouldInvoke(time)) {
719
+ return trailingEdge(time);
632
720
  }
633
- });
634
- let columnsCount = 0;
635
- let indexesCount = 0;
636
- let foreignKeysCount = 0;
637
- let tableCount = 0;
638
- const all = allTables.map((row) => {
639
- return new Promise(async (res, rej) => {
640
- const tableName = row.table_name;
641
- if (!tablesFilter(tableName))
642
- return res("");
643
- tableCount += 1;
644
- const tableSchema = row.table_schema;
645
- try {
646
- const columnToReturn = {};
647
- const indexToReturn = {};
648
- const foreignKeysToReturn = {};
649
- const primaryKeys = {};
650
- const uniqueConstrains = {};
651
- const tableResponse = await db.query(
652
- `SELECT a.attrelid::regclass::text, a.attname, is_nullable, a.attndims as array_dimensions
653
- , CASE WHEN a.atttypid = ANY ('{int,int8,int2}'::regtype[])
654
- AND EXISTS (
655
- SELECT FROM pg_attrdef ad
656
- WHERE ad.adrelid = a.attrelid
657
- AND ad.adnum = a.attnum
658
- AND pg_get_expr(ad.adbin, ad.adrelid)
659
- = 'nextval('''
660
- || (pg_get_serial_sequence (a.attrelid::regclass::text
661
- , a.attname))::regclass
662
- || '''::regclass)'
663
- )
664
- THEN CASE a.atttypid
665
- WHEN 'int'::regtype THEN 'serial'
666
- WHEN 'int8'::regtype THEN 'bigserial'
667
- WHEN 'int2'::regtype THEN 'smallserial'
668
- END
669
- ELSE format_type(a.atttypid, a.atttypmod)
670
- END AS data_type, INFORMATION_SCHEMA.COLUMNS.table_name, INFORMATION_SCHEMA.COLUMNS.column_name, INFORMATION_SCHEMA.COLUMNS.column_default, INFORMATION_SCHEMA.COLUMNS.data_type as additional_dt
671
- FROM pg_attribute a
672
- JOIN INFORMATION_SCHEMA.COLUMNS ON INFORMATION_SCHEMA.COLUMNS.column_name = a.attname
673
- WHERE a.attrelid = '"${tableSchema}"."${tableName}"'::regclass and INFORMATION_SCHEMA.COLUMNS.table_name = '${tableName}'
674
- AND a.attnum > 0
675
- AND NOT a.attisdropped
676
- ORDER BY a.attnum;`
677
- );
678
- const tableConstraints = await db.query(
679
- `SELECT c.column_name, c.data_type, constraint_type, constraint_name, constraint_schema
680
- FROM information_schema.table_constraints tc
681
- JOIN information_schema.constraint_column_usage AS ccu USING (constraint_schema, constraint_name)
682
- JOIN information_schema.columns AS c ON c.table_schema = tc.constraint_schema
683
- AND tc.table_name = c.table_name AND ccu.column_name = c.column_name
684
- WHERE tc.table_name = '${tableName}' and constraint_schema = '${tableSchema}';`
685
- );
686
- columnsCount += tableResponse.length;
687
- if (progressCallback) {
688
- progressCallback("columns", columnsCount, "fetching");
689
- }
690
- const tableForeignKeys = await db.query(
691
- `SELECT
692
- tc.table_schema,
693
- tc.constraint_name,
694
- tc.table_name,
695
- kcu.column_name,
696
- ccu.table_schema AS foreign_table_schema,
697
- ccu.table_name AS foreign_table_name,
698
- ccu.column_name AS foreign_column_name,
699
- rc.delete_rule, rc.update_rule
700
- FROM
701
- information_schema.table_constraints AS tc
702
- JOIN information_schema.key_column_usage AS kcu
703
- ON tc.constraint_name = kcu.constraint_name
704
- AND tc.table_schema = kcu.table_schema
705
- JOIN information_schema.constraint_column_usage AS ccu
706
- ON ccu.constraint_name = tc.constraint_name
707
- AND ccu.table_schema = tc.table_schema
708
- JOIN information_schema.referential_constraints AS rc
709
- ON ccu.constraint_name = rc.constraint_name
710
- WHERE tc.constraint_type = 'FOREIGN KEY' AND tc.table_name='${tableName}' and tc.table_schema='${tableSchema}';`
711
- );
712
- foreignKeysCount += tableForeignKeys.length;
713
- if (progressCallback) {
714
- progressCallback("fks", foreignKeysCount, "fetching");
715
- }
716
- for (const fk of tableForeignKeys) {
717
- const columnFrom = fk.column_name;
718
- const tableTo = fk.foreign_table_name;
719
- const columnTo = fk.foreign_column_name;
720
- const foreignKeyName = fk.constraint_name;
721
- const onUpdate = fk.update_rule.toLowerCase();
722
- const onDelete = fk.delete_rule.toLowerCase();
723
- if (typeof foreignKeysToReturn[foreignKeyName] !== "undefined") {
724
- foreignKeysToReturn[foreignKeyName].columnsFrom.push(columnFrom);
725
- foreignKeysToReturn[foreignKeyName].columnsTo.push(columnTo);
726
- } else {
727
- foreignKeysToReturn[foreignKeyName] = {
728
- name: foreignKeyName,
729
- tableFrom: tableName,
730
- tableTo,
731
- columnsFrom: [columnFrom],
732
- columnsTo: [columnTo],
733
- onDelete,
734
- onUpdate
735
- };
736
- }
737
- foreignKeysToReturn[foreignKeyName].columnsFrom = [
738
- ...new Set(foreignKeysToReturn[foreignKeyName].columnsFrom)
739
- ];
740
- foreignKeysToReturn[foreignKeyName].columnsTo = [
741
- ...new Set(foreignKeysToReturn[foreignKeyName].columnsTo)
742
- ];
743
- }
744
- const uniqueConstrainsRows = tableConstraints.filter(
745
- (mapRow) => mapRow.constraint_type === "UNIQUE"
746
- );
747
- for (const unqs of uniqueConstrainsRows) {
748
- const columnName = unqs.column_name;
749
- const constraintName = unqs.constraint_name;
750
- if (typeof uniqueConstrains[constraintName] !== "undefined") {
751
- uniqueConstrains[constraintName].columns.push(columnName);
752
- } else {
753
- uniqueConstrains[constraintName] = {
754
- columns: [columnName],
755
- nullsNotDistinct: false,
756
- name: constraintName
757
- };
758
- }
759
- }
760
- for (const columnResponse of tableResponse) {
761
- const columnName = columnResponse.attname;
762
- const columnAdditionalDT = columnResponse.additional_dt;
763
- const columnDimensions = columnResponse.array_dimensions;
764
- let columnType = columnResponse.data_type;
765
- const primaryKey = tableConstraints.filter(
766
- (mapRow) => columnName === mapRow.column_name && mapRow.constraint_type === "PRIMARY KEY"
767
- );
768
- const cprimaryKey = tableConstraints.filter(
769
- (mapRow) => mapRow.constraint_type === "PRIMARY KEY"
770
- );
771
- if (cprimaryKey.length > 1) {
772
- const tableCompositePkName = await db.query(
773
- `SELECT conname AS primary_key
774
- FROM pg_constraint
775
- WHERE contype = 'p'
776
- AND connamespace = '${tableSchema}'::regnamespace
777
- AND (conrelid::regclass::text = '"${tableName}"' OR conrelid::regclass::text = '${tableName}');`
778
- );
779
- primaryKeys[`${tableName}_${cprimaryKey.map((pk) => pk.column_name).join("_")}`] = {
780
- name: tableCompositePkName[0].primary_key,
781
- columns: cprimaryKey.map((c) => c.column_name)
782
- };
783
- }
784
- const defaultValue = defaultForColumn(columnResponse);
785
- const isSerial = columnType === "serial";
786
- let columnTypeMapped = columnType;
787
- if (columnTypeMapped.startsWith("numeric(")) {
788
- columnTypeMapped = columnTypeMapped.replace(",", ", ");
789
- }
790
- if (columnAdditionalDT === "ARRAY") {
791
- if (typeof internals.tables[tableName] === "undefined") {
792
- internals.tables[tableName] = {
793
- columns: {
794
- [columnName]: {
795
- isArray: true,
796
- dimensions: columnDimensions,
797
- rawType: columnTypeMapped.substring(
798
- 0,
799
- columnTypeMapped.length - 2
800
- )
801
- }
802
- }
803
- };
804
- } else {
805
- if (typeof internals.tables[tableName].columns[columnName] === "undefined") {
806
- internals.tables[tableName].columns[columnName] = {
807
- isArray: true,
808
- dimensions: columnDimensions,
809
- rawType: columnTypeMapped.substring(
810
- 0,
811
- columnTypeMapped.length - 2
812
- )
813
- };
814
- }
815
- }
816
- }
817
- if (columnAdditionalDT === "ARRAY") {
818
- for (let i = 1; i < Number(columnDimensions); i++) {
819
- columnTypeMapped += "[]";
820
- }
821
- }
822
- columnTypeMapped = columnTypeMapped.replace("character varying", "varchar").replace(" without time zone", "").replace("character", "char");
823
- columnTypeMapped = trimChar(columnTypeMapped, '"');
824
- columnToReturn[columnName] = {
825
- name: columnName,
826
- type: columnTypeMapped,
827
- primaryKey: primaryKey.length === 1 && cprimaryKey.length < 2,
828
- // default: isSerial ? undefined : defaultValue,
829
- notNull: columnResponse.is_nullable === "NO"
830
- };
831
- if (!isSerial && typeof defaultValue !== "undefined") {
832
- columnToReturn[columnName].default = defaultValue;
833
- }
834
- }
835
- const dbIndexes = await db.query(
836
- `SELECT t.relname as table_name, i.relname AS index_name, ix.indisunique AS is_unique, a.attname AS column_name
837
- FROM pg_class t
838
- JOIN pg_index ix ON t.oid = ix.indrelid
839
- JOIN pg_class i ON i.oid = ix.indexrelid
840
- JOIN pg_attribute a ON a.attrelid = t.oid AND a.attnum = ANY(ix.indkey)
841
- JOIN pg_namespace ns ON ns.oid = t.relnamespace
842
- WHERE ns.nspname = '${tableSchema}'
843
- AND t.relname = '${tableName}'
844
- and ix.indisprimary = false;`
845
- );
846
- const dbIndexFromConstraint = await db.query(
847
- `SELECT
848
- idx.indexrelname AS index_name,
849
- idx.relname AS table_name,
850
- schemaname,
851
- CASE WHEN con.conname IS NOT NULL THEN 1 ELSE 0 END AS generated_by_constraint
852
- FROM
853
- pg_stat_user_indexes idx
854
- LEFT JOIN
855
- pg_constraint con ON con.conindid = idx.indexrelid
856
- WHERE idx.relname = '${tableName}' and schemaname = '${tableSchema}'
857
- group by index_name, table_name,schemaname, generated_by_constraint;`
858
- );
859
- const idxsInConsteraint = dbIndexFromConstraint.filter((it) => it.generated_by_constraint === 1).map((it) => it.index_name);
860
- for (const dbIndex of dbIndexes) {
861
- const indexName2 = dbIndex.index_name;
862
- const indexColumnName = dbIndex.column_name;
863
- const indexIsUnique = dbIndex.is_unique;
864
- if (idxsInConsteraint.includes(indexName2))
865
- continue;
866
- if (typeof indexToReturn[indexName2] !== "undefined") {
867
- indexToReturn[indexName2].columns.push(indexColumnName);
868
- } else {
869
- indexToReturn[indexName2] = {
870
- name: indexName2,
871
- columns: [indexColumnName],
872
- isUnique: indexIsUnique
873
- };
874
- }
875
- }
876
- indexesCount += Object.keys(indexToReturn).length;
877
- if (progressCallback) {
878
- progressCallback("indexes", indexesCount, "fetching");
879
- }
880
- result[tableName] = {
881
- name: tableName,
882
- schema: tableSchema !== "public" ? tableSchema : "",
883
- columns: columnToReturn,
884
- indexes: indexToReturn,
885
- foreignKeys: foreignKeysToReturn,
886
- compositePrimaryKeys: primaryKeys,
887
- uniqueConstraints: uniqueConstrains
888
- };
889
- } catch (e) {
890
- rej(e);
891
- return;
892
- }
893
- res("");
894
- });
895
- });
896
- if (progressCallback) {
897
- progressCallback("tables", tableCount, "done");
898
- }
899
- for await (const _ of all) {
721
+ timerId = setTimeout(timerExpired, remainingWait(time));
900
722
  }
901
- if (progressCallback) {
902
- progressCallback("columns", columnsCount, "done");
903
- progressCallback("indexes", indexesCount, "done");
904
- progressCallback("fks", foreignKeysCount, "done");
723
+ function trailingEdge(time) {
724
+ timerId = void 0;
725
+ if (trailing && lastArgs) {
726
+ return invokeFunc(time);
727
+ }
728
+ lastArgs = lastThis = void 0;
729
+ return result;
905
730
  }
906
- const allEnums = await db.query(
907
- `select n.nspname as enum_schema,
908
- t.typname as enum_name,
909
- e.enumlabel as enum_value
910
- from pg_type t
911
- join pg_enum e on t.oid = e.enumtypid
912
- join pg_catalog.pg_namespace n ON n.oid = t.typnamespace;`
913
- );
914
- const enumsToReturn = {};
915
- for (const dbEnum of allEnums) {
916
- const enumName = dbEnum.enum_name;
917
- const enumValue = dbEnum.enum_value;
918
- if (enumsToReturn[enumName] !== void 0 && enumsToReturn[enumName] !== null) {
919
- enumsToReturn[enumName].values[enumValue] = enumValue;
920
- } else {
921
- enumsToReturn[enumName] = {
922
- name: enumName,
923
- values: { [enumValue]: enumValue }
924
- };
731
+ function cancel() {
732
+ if (timerId !== void 0) {
733
+ clearTimeout(timerId);
925
734
  }
735
+ lastInvokeTime = 0;
736
+ lastArgs = lastCallTime = lastThis = timerId = void 0;
926
737
  }
927
- if (progressCallback) {
928
- progressCallback("enums", Object.keys(enumsToReturn).length, "done");
738
+ function flush() {
739
+ return timerId === void 0 ? result : trailingEdge(now());
929
740
  }
930
- const schemasObject = Object.fromEntries([...schemas].map((it) => [it, it]));
931
- return {
932
- version: "5",
933
- dialect: "pg",
934
- tables: result,
935
- enums: enumsToReturn,
936
- schemas: schemasObject,
937
- _meta: {
938
- schemas: {},
939
- tables: {},
940
- columns: {}
941
- },
942
- internal: internals
943
- };
741
+ function debounced() {
742
+ var time = now(), isInvoking = shouldInvoke(time);
743
+ lastArgs = arguments;
744
+ lastThis = this;
745
+ lastCallTime = time;
746
+ if (isInvoking) {
747
+ if (timerId === void 0) {
748
+ return leadingEdge(lastCallTime);
749
+ }
750
+ if (maxing) {
751
+ timerId = setTimeout(timerExpired, wait);
752
+ return invokeFunc(lastCallTime);
753
+ }
754
+ }
755
+ if (timerId === void 0) {
756
+ timerId = setTimeout(timerExpired, wait);
757
+ }
758
+ return result;
759
+ }
760
+ debounced.cancel = cancel;
761
+ debounced.flush = flush;
762
+ return debounced;
763
+ }
764
+ function throttle(func, wait, options) {
765
+ var leading = true, trailing = true;
766
+ if (typeof func != "function") {
767
+ throw new TypeError(FUNC_ERROR_TEXT);
768
+ }
769
+ if (isObject(options)) {
770
+ leading = "leading" in options ? !!options.leading : leading;
771
+ trailing = "trailing" in options ? !!options.trailing : trailing;
772
+ }
773
+ return debounce(func, wait, {
774
+ "leading": leading,
775
+ "maxWait": wait,
776
+ "trailing": trailing
777
+ });
778
+ }
779
+ function isObject(value) {
780
+ var type = typeof value;
781
+ return !!value && (type == "object" || type == "function");
782
+ }
783
+ function isObjectLike(value) {
784
+ return !!value && typeof value == "object";
785
+ }
786
+ function isSymbol(value) {
787
+ return typeof value == "symbol" || isObjectLike(value) && objectToString.call(value) == symbolTag;
788
+ }
789
+ function toNumber(value) {
790
+ if (typeof value == "number") {
791
+ return value;
792
+ }
793
+ if (isSymbol(value)) {
794
+ return NAN;
795
+ }
796
+ if (isObject(value)) {
797
+ var other = typeof value.valueOf == "function" ? value.valueOf() : value;
798
+ value = isObject(other) ? other + "" : other;
799
+ }
800
+ if (typeof value != "string") {
801
+ return value === 0 ? value : +value;
802
+ }
803
+ value = value.replace(reTrim, "");
804
+ var isBinary = reIsBinary.test(value);
805
+ return isBinary || reIsOctal.test(value) ? freeParseInt(value.slice(2), isBinary ? 2 : 8) : reIsBadHex.test(value) ? NAN : +value;
806
+ }
807
+ module.exports = throttle;
808
+ }
809
+ });
810
+
811
+ // node_modules/.pnpm/hanji@0.0.5/node_modules/hanji/index.js
812
+ var require_hanji = __commonJS({
813
+ "node_modules/.pnpm/hanji@0.0.5/node_modules/hanji/index.js"(exports) {
814
+ "use strict";
815
+ var __awaiter = exports && exports.__awaiter || function(thisArg, _arguments, P, generator) {
816
+ function adopt(value) {
817
+ return value instanceof P ? value : new P(function(resolve) {
818
+ resolve(value);
819
+ });
820
+ }
821
+ return new (P || (P = Promise))(function(resolve, reject) {
822
+ function fulfilled(value) {
823
+ try {
824
+ step(generator.next(value));
825
+ } catch (e) {
826
+ reject(e);
827
+ }
828
+ }
829
+ function rejected(value) {
830
+ try {
831
+ step(generator["throw"](value));
832
+ } catch (e) {
833
+ reject(e);
834
+ }
835
+ }
836
+ function step(result) {
837
+ result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected);
838
+ }
839
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
840
+ });
944
841
  };
945
- columnToDefault = {
946
- "numeric(": "::numeric",
947
- // text: "::text",
948
- // "character varying": "::character varying",
949
- // "double precision": "::double precision",
950
- // "time with time zone": "::time with time zone",
951
- "time without time zone": "::time without time zone",
952
- // "timestamp with time zone": "::timestamp with time zone",
953
- "timestamp without time zone": "::timestamp without time zone",
954
- // date: "::date",
955
- // interval: "::interval",
956
- // character: "::bpchar",
957
- // macaddr8: "::macaddr8",
958
- // macaddr: "::macaddr",
959
- // inet: "::inet",
960
- // cidr: "::cidr",
961
- // jsonb: "::jsonb",
962
- // json: "::json",
963
- "character(": "::bpchar"
842
+ var __importDefault = exports && exports.__importDefault || function(mod) {
843
+ return mod && mod.__esModule ? mod : { "default": mod };
964
844
  };
965
- defaultForColumn = (column) => {
966
- if (column.data_type === "serial" || column.data_type === "smallserial" || column.data_type === "bigserial") {
967
- return void 0;
845
+ Object.defineProperty(exports, "__esModule", { value: true });
846
+ exports.onTerminate = exports.renderWithTask = exports.render = exports.TaskTerminal = exports.TaskView = exports.Terminal = exports.deferred = exports.SelectState = exports.Prompt = void 0;
847
+ var readline_1 = require_readline();
848
+ var sisteransi_1 = require_src();
849
+ var utils_1 = require_utils();
850
+ var lodash_throttle_1 = __importDefault(require_lodash());
851
+ var Prompt2 = class {
852
+ constructor() {
853
+ this.attachCallbacks = [];
854
+ this.detachCallbacks = [];
855
+ this.inputCallbacks = [];
968
856
  }
969
- const hasDifferentDefaultCast = Object.keys(columnToDefault).find(
970
- (it) => column.data_type.startsWith(it)
971
- );
972
- if (column.column_default === null) {
973
- return void 0;
857
+ requestLayout() {
858
+ this.terminal.requestLayout();
974
859
  }
975
- const columnDefaultAsString = column.column_default.toString();
976
- if (columnDefaultAsString.endsWith(
977
- hasDifferentDefaultCast ? columnToDefault[hasDifferentDefaultCast] : column.data_type
978
- )) {
979
- const nonPrefixPart = column.column_default.length - (hasDifferentDefaultCast ? columnToDefault[hasDifferentDefaultCast] : `::${column.data_type}`).length - 1;
980
- const rt = column.column_default.toString().substring(1, nonPrefixPart);
981
- if (/^-?[\d.]+(?:e-?\d+)?$/.test(rt) && !column.data_type.startsWith("numeric")) {
982
- return Number(rt);
983
- } else if (column.data_type === "json" || column.data_type === "jsonb") {
984
- const jsonWithoutSpaces = JSON.stringify(JSON.parse(rt));
985
- return `'${jsonWithoutSpaces}'${hasDifferentDefaultCast ? columnToDefault[hasDifferentDefaultCast] : `::${column.data_type}`}`;
986
- } else if (column.data_type === "boolean") {
987
- return column.column_default === "true";
988
- } else {
989
- return `'${rt}'`;
990
- }
991
- } else {
992
- if (/^-?[\d.]+(?:e-?\d+)?$/.test(columnDefaultAsString) && !column.data_type.startsWith("numeric")) {
993
- return Number(columnDefaultAsString);
994
- } else if (column.data_type === "boolean") {
995
- return column.column_default === "true";
996
- } else {
997
- return `${columnDefaultAsString}`;
860
+ on(type, callback) {
861
+ if (type === "attach") {
862
+ this.attachCallbacks.push(callback);
863
+ } else if (type === "detach") {
864
+ this.detachCallbacks.push(callback);
865
+ } else if (type === "input") {
866
+ this.inputCallbacks.push(callback);
998
867
  }
999
868
  }
869
+ attach(terminal) {
870
+ this.terminal = terminal;
871
+ this.attachCallbacks.forEach((it) => it(terminal));
872
+ }
873
+ detach(terminal) {
874
+ this.detachCallbacks.forEach((it) => it(terminal));
875
+ this.terminal = void 0;
876
+ }
877
+ input(str, key) {
878
+ this.inputCallbacks.forEach((it) => it(str, key));
879
+ }
1000
880
  };
1001
- toDrizzle = (schema, schemaName) => {
1002
- const tables = {};
1003
- Object.values(schema.tables).forEach((t) => {
1004
- const columns = {};
1005
- Object.values(t.columns).forEach((c) => {
1006
- const columnName = c.name;
1007
- const type = c.type;
1008
- let columnBuilder;
1009
- if (type === "bigint") {
1010
- columnBuilder = new PgBigInt53Builder(columnName);
1011
- } else if (type === "bigserial") {
1012
- columnBuilder = new PgBigSerial53Builder(columnName);
1013
- } else if (type === "boolean") {
1014
- columnBuilder = new PgBooleanBuilder(columnName);
1015
- } else if (type === "cidr") {
1016
- columnBuilder = new PgCidrBuilder(columnName);
1017
- } else if (type === "date") {
1018
- columnBuilder = new PgDateBuilder(columnName);
1019
- } else if (type === "double precision") {
1020
- columnBuilder = new PgDoublePrecisionBuilder(columnName);
1021
- } else if (type === "inet") {
1022
- columnBuilder = new PgInetBuilder(columnName);
1023
- } else if (type === "integer") {
1024
- columnBuilder = new PgIntegerBuilder(columnName);
1025
- } else if (type === "interval" || type.startsWith("interval ")) {
1026
- columnBuilder = new PgIntervalBuilder(columnName, {});
1027
- } else if (type === "json") {
1028
- columnBuilder = new PgJsonBuilder(columnName);
1029
- } else if (type === "jsonb") {
1030
- columnBuilder = new PgJsonbBuilder(columnName);
1031
- } else if (type === "macaddr") {
1032
- columnBuilder = new PgMacaddrBuilder(columnName);
1033
- } else if (type === "macaddr8") {
1034
- columnBuilder = new PgMacaddr8Builder(columnName);
1035
- } else if (type === "numeric" || type.startsWith("numeric(")) {
1036
- columnBuilder = new PgNumericBuilder(columnName);
1037
- } else if (type === "real") {
1038
- columnBuilder = new PgRealBuilder(columnName);
1039
- } else if (type === "serial") {
1040
- columnBuilder = new PgSerialBuilder(columnName);
1041
- } else if (type === "smallint") {
1042
- columnBuilder = new PgSmallIntBuilder(columnName);
1043
- } else if (type === "smallserial") {
1044
- columnBuilder = new PgSmallSerialBuilder(columnName);
1045
- } else if (type === "text") {
1046
- columnBuilder = new PgTextBuilder(columnName, {});
1047
- } else if (type === "time" || type.startsWith("time(") || type === "time with time zone") {
1048
- columnBuilder = new PgTimeBuilder(columnName, false, void 0);
1049
- } else if (type === "timestamp" || type.startsWith("timestamp(") || type === "timestamp with time zone") {
1050
- columnBuilder = new PgTimestampBuilder(columnName, false, void 0);
1051
- } else if (type === "uuid") {
1052
- columnBuilder = new PgUUIDBuilder(columnName);
1053
- } else if (type === "varchar" || type.startsWith("varchar(")) {
1054
- columnBuilder = new PgVarcharBuilder(columnName, {});
1055
- } else if (type === "char" || type.startsWith("char(")) {
1056
- columnBuilder = new PgCharBuilder(columnName, {});
1057
- } else {
1058
- columnBuilder = customType({
1059
- dataType() {
1060
- return type;
1061
- }
1062
- })(columnName);
1063
- }
1064
- if (c.notNull) {
1065
- columnBuilder = columnBuilder.notNull();
881
+ exports.Prompt = Prompt2;
882
+ var SelectState2 = class {
883
+ constructor(items) {
884
+ this.items = items;
885
+ this.selectedIdx = 0;
886
+ }
887
+ bind(prompt) {
888
+ prompt.on("input", (str, key) => {
889
+ const invalidate = this.consume(str, key);
890
+ if (invalidate)
891
+ prompt.requestLayout();
892
+ });
893
+ }
894
+ consume(str, key) {
895
+ if (!key)
896
+ return false;
897
+ if (key.name === "down") {
898
+ this.selectedIdx = (this.selectedIdx + 1) % this.items.length;
899
+ return true;
900
+ }
901
+ if (key.name === "up") {
902
+ this.selectedIdx -= 1;
903
+ this.selectedIdx = this.selectedIdx < 0 ? this.items.length - 1 : this.selectedIdx;
904
+ return true;
905
+ }
906
+ return false;
907
+ }
908
+ };
909
+ exports.SelectState = SelectState2;
910
+ var deferred = () => {
911
+ let resolve;
912
+ let reject;
913
+ const promise = new Promise((res, rej) => {
914
+ resolve = res;
915
+ reject = rej;
916
+ });
917
+ return {
918
+ resolve,
919
+ reject,
920
+ promise
921
+ };
922
+ };
923
+ exports.deferred = deferred;
924
+ var Terminal = class {
925
+ constructor(view, stdin, stdout, closable) {
926
+ this.view = view;
927
+ this.stdin = stdin;
928
+ this.stdout = stdout;
929
+ this.closable = closable;
930
+ this.text = "";
931
+ this.status = "idle";
932
+ if (this.stdin.isTTY)
933
+ this.stdin.setRawMode(true);
934
+ const keypress = (str, key) => {
935
+ if (key.name === "c" && key.ctrl === true) {
936
+ this.requestLayout();
937
+ this.view.detach(this);
938
+ this.tearDown(keypress);
939
+ if (terminateHandler) {
940
+ terminateHandler(this.stdin, this.stdout);
941
+ return;
942
+ }
943
+ this.stdout.write(`
944
+ ^C
945
+ `);
946
+ process.exit(1);
1066
947
  }
1067
- if (c.default) {
1068
- columnBuilder = columnBuilder.default(c.default);
948
+ if (key.name === "escape") {
949
+ this.status = "aborted";
950
+ this.requestLayout();
951
+ this.view.detach(this);
952
+ this.tearDown(keypress);
953
+ this.resolve({ status: "aborted", data: void 0 });
954
+ return;
1069
955
  }
1070
- if (c.primaryKey) {
1071
- columnBuilder = columnBuilder.primaryKey();
956
+ if (key.name === "return") {
957
+ this.status = "submitted";
958
+ this.requestLayout();
959
+ this.view.detach(this);
960
+ this.tearDown(keypress);
961
+ this.resolve({ status: "submitted", data: this.view.result() });
962
+ return;
1072
963
  }
1073
- columns[columnName] = columnBuilder;
964
+ view.input(str, key);
965
+ };
966
+ this.stdin.on("keypress", keypress);
967
+ this.view.attach(this);
968
+ const { resolve, promise } = (0, exports.deferred)();
969
+ this.resolve = resolve;
970
+ this.promise = promise;
971
+ this.renderFunc = (0, lodash_throttle_1.default)((str) => {
972
+ this.stdout.write(str);
1074
973
  });
1075
- if (schemaName === "public") {
1076
- tables[t.name] = pgTable(t.name, columns, (cb) => {
1077
- const res = {};
1078
- Object.values(t.compositePrimaryKeys).forEach((cpk) => {
1079
- const gh = cpk.columns.map((c) => cb[c]);
1080
- res[cpk.name] = new PrimaryKeyBuilder(
1081
- gh,
1082
- cpk.name
1083
- );
1084
- });
1085
- return res;
1086
- });
974
+ }
975
+ tearDown(keypress) {
976
+ this.stdout.write(sisteransi_1.cursor.show);
977
+ this.stdin.removeListener("keypress", keypress);
978
+ if (this.stdin.isTTY)
979
+ this.stdin.setRawMode(false);
980
+ this.closable.close();
981
+ }
982
+ result() {
983
+ return this.promise;
984
+ }
985
+ toggleCursor(state) {
986
+ if (state === "hide") {
987
+ this.stdout.write(sisteransi_1.cursor.hide);
1087
988
  } else {
1088
- tables[t.name] = pgSchema(schemaName).table(t.name, columns, (cb) => {
1089
- const res = {};
1090
- Object.values(t.compositePrimaryKeys).forEach((cpk) => {
1091
- const gh = cpk.columns.map((c) => cb[c]);
1092
- res[cpk.name] = new PrimaryKeyBuilder(
1093
- gh,
1094
- cpk.name
1095
- );
1096
- });
1097
- return res;
1098
- });
989
+ this.stdout.write(sisteransi_1.cursor.show);
1099
990
  }
1100
- });
1101
- return tables;
1102
- };
1103
- }
1104
- });
1105
-
1106
- // src/serializer/sqliteSerializer.ts
1107
- import { getTableName as getTableName2, is as is2, SQL as SQL2 } from "drizzle-orm";
1108
- import {
1109
- getTableConfig as getTableConfig2,
1110
- PrimaryKeyBuilder as PrimaryKeyBuilder2,
1111
- SQLiteBaseInteger,
1112
- SQLiteBlobBufferBuilder,
1113
- SQLiteIntegerBuilder,
1114
- SQLiteNumericBuilder,
1115
- SQLiteRealBuilder,
1116
- SQLiteSyncDialect,
1117
- sqliteTable,
1118
- SQLiteTextBuilder,
1119
- uniqueKeyName as uniqueKeyName2
1120
- } from "drizzle-orm/sqlite-core";
1121
- function mapSqlToSqliteType(sqlType) {
1122
- if ([
1123
- "int",
1124
- "integer",
1125
- "integer auto_increment",
1126
- "tinyint",
1127
- "smallint",
1128
- "mediumint",
1129
- "bigint",
1130
- "unsigned big int",
1131
- "int2",
1132
- "int8"
1133
- ].includes(sqlType.toLowerCase())) {
1134
- return "integer";
1135
- } else if ([
1136
- "character",
1137
- "varchar",
1138
- "vatying character",
1139
- "nchar",
1140
- "native character",
1141
- "nvarchar",
1142
- "text",
1143
- "clob"
1144
- ].some((it) => it.startsWith(sqlType.toLowerCase()))) {
1145
- return "text";
1146
- } else if (sqlType.toLowerCase() === "blob") {
1147
- return "blob";
1148
- } else if (["real", "double", "double precision", "float"].includes(
1149
- sqlType.toLowerCase()
1150
- )) {
1151
- return "real";
1152
- } else {
1153
- return "numeric";
1154
- }
1155
- }
1156
- var dialect2, fromDatabase2, toDrizzle2;
1157
- var init_sqliteSerializer = __esm({
1158
- "src/serializer/sqliteSerializer.ts"() {
1159
- init_serializer();
1160
- init_outputs();
1161
- init_source();
1162
- dialect2 = new SQLiteSyncDialect();
1163
- fromDatabase2 = async (db, tablesFilter = (table) => true, progressCallback) => {
1164
- const result = {};
1165
- const columns = await db.query(
1166
- `SELECT
1167
- m.name as "tableName", p.name as "columnName", p.type as "columnType", p."notnull" as "notNull", p.dflt_value as "defaultValue", p.pk as pk
1168
- FROM sqlite_master AS m JOIN pragma_table_info(m.name) AS p
1169
- WHERE m.type = 'table' and m.tbl_name != 'sqlite_sequence' and m.tbl_name != 'sqlite_stat1' and m.tbl_name != '_litestream_seq' and m.tbl_name != '_litestream_lock' and m.tbl_name != 'libsql_wasm_func_table';
1170
- `
1171
- );
1172
- const tablesWithSeq = [];
1173
- const seq = await db.query(
1174
- `SELECT * FROM sqlite_master WHERE name != 'sqlite_sequence' and name != 'sqlite_stat1' and name != '_litestream_seq' and name != '_litestream_lock' and sql GLOB '*[ *' || CHAR(9) || CHAR(10) || CHAR(13) || ']AUTOINCREMENT[^'']*';`
1175
- );
1176
- for (const s of seq) {
1177
- tablesWithSeq.push(s.name);
1178
991
  }
1179
- let columnsCount = 0;
1180
- let tablesCount = /* @__PURE__ */ new Set();
1181
- let indexesCount = 0;
1182
- let foreignKeysCount = 0;
1183
- const tableToPk = {};
1184
- for (const column of columns) {
1185
- if (!tablesFilter(column.tableName))
1186
- continue;
1187
- columnsCount += 1;
1188
- if (progressCallback) {
1189
- progressCallback("columns", columnsCount, "fetching");
1190
- }
1191
- const tableName = column.tableName;
1192
- tablesCount.add(tableName);
1193
- if (progressCallback) {
1194
- progressCallback("tables", tablesCount.size, "fetching");
1195
- }
1196
- const columnName = column.columnName;
1197
- const isNotNull = column.notNull === 1;
1198
- const columnType = column.columnType;
1199
- const isPrimary = column.pk !== 0;
1200
- const columnDefault = column.defaultValue;
1201
- const isAutoincrement = isPrimary && tablesWithSeq.includes(tableName);
1202
- if (isPrimary) {
1203
- if (typeof tableToPk[tableName] === "undefined") {
1204
- tableToPk[tableName] = [columnName];
1205
- } else {
1206
- tableToPk[tableName].push(columnName);
1207
- }
1208
- }
1209
- const table = result[tableName];
1210
- const newColumn = {
1211
- default: columnDefault === null ? void 0 : /^-?[\d.]+(?:e-?\d+)?$/.test(columnDefault) ? Number(columnDefault) : ["CURRENT_TIME", "CURRENT_DATE", "CURRENT_TIMESTAMP"].includes(
1212
- columnDefault
1213
- ) ? `(${columnDefault})` : columnDefault === "false" ? false : columnDefault === "true" ? true : columnDefault.startsWith("'") && columnDefault.endsWith("'") ? columnDefault : (
1214
- // ? columnDefault.substring(1, columnDefault.length - 1)
1215
- `(${columnDefault})`
1216
- ),
1217
- autoincrement: isAutoincrement,
1218
- name: columnName,
1219
- type: mapSqlToSqliteType(columnType),
1220
- primaryKey: false,
1221
- notNull: isNotNull
1222
- };
1223
- if (!table) {
1224
- result[tableName] = {
1225
- name: tableName,
1226
- columns: {
1227
- [columnName]: newColumn
1228
- },
1229
- compositePrimaryKeys: {},
1230
- indexes: {},
1231
- foreignKeys: {},
1232
- uniqueConstraints: {}
1233
- };
1234
- } else {
1235
- result[tableName].columns[columnName] = newColumn;
1236
- }
992
+ requestLayout() {
993
+ const string = this.view.render(this.status);
994
+ const clearPrefix = this.text ? (0, utils_1.clear)(this.text, this.stdout.columns) : "";
995
+ this.text = string;
996
+ this.renderFunc(`${clearPrefix}${string}`);
1237
997
  }
1238
- for (const [key, value] of Object.entries(tableToPk)) {
1239
- if (value.length > 1) {
1240
- value.sort();
1241
- result[key].compositePrimaryKeys = {
1242
- [`${key}_${value.join("_")}_pk`]: {
1243
- columns: value,
1244
- name: `${key}_${value.join("_")}_pk`
1245
- }
1246
- };
1247
- } else if (value.length === 1) {
1248
- result[key].columns[value[0]].primaryKey = true;
1249
- } else {
1250
- }
998
+ };
999
+ exports.Terminal = Terminal;
1000
+ var TaskView2 = class {
1001
+ constructor() {
1002
+ this.attachCallbacks = [];
1003
+ this.detachCallbacks = [];
1251
1004
  }
1252
- if (progressCallback) {
1253
- progressCallback("columns", columnsCount, "done");
1254
- progressCallback("tables", tablesCount.size, "done");
1005
+ requestLayout() {
1006
+ this.terminal.requestLayout();
1255
1007
  }
1256
- try {
1257
- const fks = await db.query(
1258
- `SELECT m.name as "tableFrom", f.id as "id", f."table" as "tableTo", f."from", f."to", f."on_update" as "onUpdate", f."on_delete" as "onDelete", f.seq as "seq"
1259
- FROM sqlite_master m, pragma_foreign_key_list(m.name) as f;`
1260
- );
1261
- const fkByTableName = {};
1262
- for (const fkRow of fks) {
1263
- foreignKeysCount += 1;
1264
- if (progressCallback) {
1265
- progressCallback("fks", foreignKeysCount, "fetching");
1266
- }
1267
- const tableName = fkRow.tableFrom;
1268
- const columnName = fkRow.from;
1269
- const refTableName = fkRow.tableTo;
1270
- const refColumnName = fkRow.to;
1271
- const updateRule = fkRow.onUpdate;
1272
- const deleteRule = fkRow.onDelete;
1273
- const sequence = fkRow.seq;
1274
- const id = fkRow.id;
1275
- const tableInResult = result[tableName];
1276
- if (typeof tableInResult === "undefined")
1277
- continue;
1278
- if (typeof fkByTableName[`${tableName}_${id}`] !== "undefined") {
1279
- fkByTableName[`${tableName}_${id}`].columnsFrom.push(columnName);
1280
- fkByTableName[`${tableName}_${id}`].columnsTo.push(refColumnName);
1281
- } else {
1282
- fkByTableName[`${tableName}_${id}`] = {
1283
- name: "",
1284
- tableFrom: tableName,
1285
- tableTo: refTableName,
1286
- columnsFrom: [columnName],
1287
- columnsTo: [refColumnName],
1288
- onDelete: deleteRule == null ? void 0 : deleteRule.toLowerCase(),
1289
- onUpdate: updateRule == null ? void 0 : updateRule.toLowerCase()
1290
- };
1291
- }
1292
- const columnsFrom = fkByTableName[`${tableName}_${id}`].columnsFrom;
1293
- const columnsTo = fkByTableName[`${tableName}_${id}`].columnsTo;
1294
- fkByTableName[`${tableName}_${id}`].name = `${tableName}_${columnsFrom.join(
1295
- "_"
1296
- )}_${refTableName}_${columnsTo.join("_")}_fk`;
1297
- }
1298
- for (const idx of Object.keys(fkByTableName)) {
1299
- const value = fkByTableName[idx];
1300
- result[value.tableFrom].foreignKeys[value.name] = value;
1301
- }
1302
- } catch (e) {
1008
+ attach(terminal) {
1009
+ this.terminal = terminal;
1010
+ this.attachCallbacks.forEach((it) => it(terminal));
1303
1011
  }
1304
- if (progressCallback) {
1305
- progressCallback("fks", foreignKeysCount, "done");
1012
+ detach(terminal) {
1013
+ this.detachCallbacks.forEach((it) => it(terminal));
1014
+ this.terminal = void 0;
1306
1015
  }
1307
- const idxs = await db.query(
1308
- `SELECT
1309
- m.tbl_name as tableName,
1310
- il.name as indexName,
1311
- ii.name as columnName,
1312
- il.[unique] as isUnique,
1313
- il.seq as seq
1314
- FROM sqlite_master AS m,
1315
- pragma_index_list(m.name) AS il,
1316
- pragma_index_info(il.name) AS ii
1317
- WHERE
1318
- m.type = 'table' and il.name NOT LIKE 'sqlite_autoindex_%';`
1319
- );
1320
- for (const idxRow of idxs) {
1321
- const tableName = idxRow.tableName;
1322
- const constraintName = idxRow.indexName;
1323
- const columnName = idxRow.columnName;
1324
- const isUnique = idxRow.isUnique === 1;
1325
- const tableInResult = result[tableName];
1326
- if (typeof tableInResult === "undefined")
1327
- continue;
1328
- indexesCount += 1;
1329
- if (progressCallback) {
1330
- progressCallback("indexes", indexesCount, "fetching");
1331
- }
1332
- if (typeof tableInResult.indexes[constraintName] !== "undefined") {
1333
- tableInResult.indexes[constraintName].columns.push(columnName);
1334
- } else {
1335
- tableInResult.indexes[constraintName] = {
1336
- name: constraintName,
1337
- columns: [columnName],
1338
- isUnique
1339
- };
1016
+ on(type, callback) {
1017
+ if (type === "attach") {
1018
+ this.attachCallbacks.push(callback);
1019
+ } else if (type === "detach") {
1020
+ this.detachCallbacks.push(callback);
1340
1021
  }
1341
1022
  }
1342
- if (progressCallback) {
1343
- progressCallback("indexes", indexesCount, "done");
1344
- progressCallback("enums", 0, "done");
1345
- }
1346
- return {
1347
- version: "5",
1348
- dialect: "sqlite",
1349
- tables: result,
1350
- enums: {},
1351
- _meta: {
1352
- tables: {},
1353
- columns: {}
1354
- }
1355
- };
1356
1023
  };
1357
- toDrizzle2 = (schema) => {
1358
- const tables = {};
1359
- Object.values(schema.tables).forEach((t) => {
1360
- const columns = {};
1361
- Object.values(t.columns).forEach((c) => {
1362
- const columnName = c.name;
1363
- const type = c.type;
1364
- let columnBuilder;
1365
- if (type === "integer") {
1366
- columnBuilder = new SQLiteIntegerBuilder(columnName);
1367
- } else if (type === "text") {
1368
- columnBuilder = new SQLiteTextBuilder(columnName, {});
1369
- } else if (type === "blob") {
1370
- columnBuilder = new SQLiteBlobBufferBuilder(columnName);
1371
- } else if (type === "real") {
1372
- columnBuilder = new SQLiteRealBuilder(columnName);
1373
- } else {
1374
- columnBuilder = new SQLiteNumericBuilder(columnName);
1375
- }
1376
- if (c.notNull) {
1377
- columnBuilder = columnBuilder.notNull();
1378
- }
1379
- if (c.default) {
1380
- columnBuilder = columnBuilder.default(c.default);
1381
- }
1382
- if (c.primaryKey) {
1383
- columnBuilder = columnBuilder.primaryKey();
1384
- }
1385
- columns[columnName] = columnBuilder;
1386
- });
1387
- tables[t.name] = sqliteTable(t.name, columns, (cb) => {
1388
- const res = {};
1389
- Object.values(t.compositePrimaryKeys).forEach((cpk) => {
1390
- const gh = cpk.columns.map((c) => cb[c]);
1391
- res[cpk.name] = new PrimaryKeyBuilder2(
1392
- gh,
1393
- cpk.name
1394
- );
1395
- });
1396
- return res;
1397
- });
1398
- });
1399
- return tables;
1024
+ exports.TaskView = TaskView2;
1025
+ var TaskTerminal = class {
1026
+ constructor(view, stdout) {
1027
+ this.view = view;
1028
+ this.stdout = stdout;
1029
+ this.text = "";
1030
+ this.view.attach(this);
1031
+ }
1032
+ requestLayout() {
1033
+ const string = this.view.render("pending");
1034
+ const clearPrefix = this.text ? (0, utils_1.clear)(this.text, this.stdout.columns) : "";
1035
+ this.text = string;
1036
+ this.stdout.write(`${clearPrefix}${string}`);
1037
+ }
1038
+ clear() {
1039
+ const string = this.view.render("done");
1040
+ this.view.detach(this);
1041
+ const clearPrefix = this.text ? (0, utils_1.clear)(this.text, this.stdout.columns) : "";
1042
+ this.stdout.write(`${clearPrefix}${string}`);
1043
+ }
1400
1044
  };
1045
+ exports.TaskTerminal = TaskTerminal;
1046
+ function render2(view) {
1047
+ const { stdin, stdout, closable } = (0, readline_1.prepareReadLine)();
1048
+ if (view instanceof Prompt2) {
1049
+ const terminal = new Terminal(view, stdin, stdout, closable);
1050
+ terminal.requestLayout();
1051
+ return terminal.result();
1052
+ }
1053
+ stdout.write(`${view}
1054
+ `);
1055
+ closable.close();
1056
+ return;
1057
+ }
1058
+ exports.render = render2;
1059
+ function renderWithTask3(view, task) {
1060
+ return __awaiter(this, void 0, void 0, function* () {
1061
+ const terminal = new TaskTerminal(view, process.stdout);
1062
+ terminal.requestLayout();
1063
+ const result = yield task;
1064
+ terminal.clear();
1065
+ return result;
1066
+ });
1067
+ }
1068
+ exports.renderWithTask = renderWithTask3;
1069
+ var terminateHandler;
1070
+ function onTerminate(callback) {
1071
+ terminateHandler = callback;
1072
+ }
1073
+ exports.onTerminate = onTerminate;
1401
1074
  }
1402
1075
  });
1403
1076
 
1404
- // node_modules/.pnpm/hanji@0.0.5/node_modules/hanji/readline.js
1405
- var require_readline = __commonJS({
1406
- "node_modules/.pnpm/hanji@0.0.5/node_modules/hanji/readline.js"(exports) {
1407
- "use strict";
1408
- Object.defineProperty(exports, "__esModule", { value: true });
1409
- exports.prepareReadLine = void 0;
1410
- var prepareReadLine = () => {
1411
- const stdin = process.stdin;
1412
- const stdout = process.stdout;
1413
- const readline = __require("readline");
1414
- const rl = readline.createInterface({
1415
- input: stdin,
1416
- escapeCodeTimeout: 50
1417
- });
1418
- readline.emitKeypressEvents(stdin, rl);
1419
- return {
1420
- stdin,
1421
- stdout,
1422
- closable: rl
1423
- };
1424
- };
1425
- exports.prepareReadLine = prepareReadLine;
1077
+ // src/cli/views.ts
1078
+ var import_hanji;
1079
+ var init_views = __esm({
1080
+ "src/cli/views.ts"() {
1081
+ init_source();
1082
+ import_hanji = __toESM(require_hanji());
1426
1083
  }
1427
1084
  });
1428
1085
 
1429
- // node_modules/.pnpm/sisteransi@1.0.5/node_modules/sisteransi/src/index.js
1430
- var require_src = __commonJS({
1431
- "node_modules/.pnpm/sisteransi@1.0.5/node_modules/sisteransi/src/index.js"(exports, module) {
1432
- "use strict";
1433
- var ESC = "\x1B";
1434
- var CSI = `${ESC}[`;
1435
- var beep = "\x07";
1436
- var cursor = {
1437
- to(x, y) {
1438
- if (!y)
1439
- return `${CSI}${x + 1}G`;
1440
- return `${CSI}${y + 1};${x + 1}H`;
1441
- },
1442
- move(x, y) {
1443
- let ret = "";
1444
- if (x < 0)
1445
- ret += `${CSI}${-x}D`;
1446
- else if (x > 0)
1447
- ret += `${CSI}${x}C`;
1448
- if (y < 0)
1449
- ret += `${CSI}${-y}A`;
1450
- else if (y > 0)
1451
- ret += `${CSI}${y}B`;
1452
- return ret;
1453
- },
1454
- up: (count = 1) => `${CSI}${count}A`,
1455
- down: (count = 1) => `${CSI}${count}B`,
1456
- forward: (count = 1) => `${CSI}${count}C`,
1457
- backward: (count = 1) => `${CSI}${count}D`,
1458
- nextLine: (count = 1) => `${CSI}E`.repeat(count),
1459
- prevLine: (count = 1) => `${CSI}F`.repeat(count),
1460
- left: `${CSI}G`,
1461
- hide: `${CSI}?25l`,
1462
- show: `${CSI}?25h`,
1463
- save: `${ESC}7`,
1464
- restore: `${ESC}8`
1465
- };
1466
- var scroll = {
1467
- up: (count = 1) => `${CSI}S`.repeat(count),
1468
- down: (count = 1) => `${CSI}T`.repeat(count)
1469
- };
1470
- var erase = {
1471
- screen: `${CSI}2J`,
1472
- up: (count = 1) => `${CSI}1J`.repeat(count),
1473
- down: (count = 1) => `${CSI}J`.repeat(count),
1474
- line: `${CSI}2K`,
1475
- lineEnd: `${CSI}K`,
1476
- lineStart: `${CSI}1K`,
1477
- lines(count) {
1478
- let clear = "";
1479
- for (let i = 0; i < count; i++)
1480
- clear += this.line + (i < count - 1 ? cursor.up() : "");
1481
- if (count)
1482
- clear += cursor.left;
1483
- return clear;
1484
- }
1485
- };
1486
- module.exports = { cursor, scroll, erase, beep };
1086
+ // src/serializer/index.ts
1087
+ import * as glob from "glob";
1088
+ var init_serializer = __esm({
1089
+ "src/serializer/index.ts"() {
1090
+ init_source();
1091
+ init_views();
1487
1092
  }
1488
1093
  });
1489
1094
 
1490
- // node_modules/.pnpm/hanji@0.0.5/node_modules/hanji/utils.js
1491
- var require_utils = __commonJS({
1492
- "node_modules/.pnpm/hanji@0.0.5/node_modules/hanji/utils.js"(exports) {
1493
- "use strict";
1494
- Object.defineProperty(exports, "__esModule", { value: true });
1495
- exports.clear = void 0;
1496
- var sisteransi_1 = require_src();
1497
- var strip = (str) => {
1498
- const pattern = [
1499
- "[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]+)*|[a-zA-Z\\d]+(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?\\u0007)",
1500
- "(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PRZcf-ntqry=><~]))"
1501
- ].join("|");
1502
- const RGX = new RegExp(pattern, "g");
1503
- return typeof str === "string" ? str.replace(RGX, "") : str;
1504
- };
1505
- var stringWidth = (str) => [...strip(str)].length;
1506
- var clear = function(prompt, perLine) {
1507
- if (!perLine)
1508
- return sisteransi_1.erase.line + sisteransi_1.cursor.to(0);
1509
- let rows = 0;
1510
- const lines = prompt.split(/\r?\n/);
1511
- for (let line of lines) {
1512
- rows += 1 + Math.floor(Math.max(stringWidth(line) - 1, 0) / perLine);
1513
- }
1514
- return sisteransi_1.erase.lines(rows);
1515
- };
1516
- exports.clear = clear;
1095
+ // src/cli/validations/outputs.ts
1096
+ var init_outputs = __esm({
1097
+ "src/cli/validations/outputs.ts"() {
1098
+ init_source();
1517
1099
  }
1518
1100
  });
1519
1101
 
1520
- // node_modules/.pnpm/lodash.throttle@4.1.1/node_modules/lodash.throttle/index.js
1521
- var require_lodash = __commonJS({
1522
- "node_modules/.pnpm/lodash.throttle@4.1.1/node_modules/lodash.throttle/index.js"(exports, module) {
1523
- var FUNC_ERROR_TEXT = "Expected a function";
1524
- var NAN = 0 / 0;
1525
- var symbolTag = "[object Symbol]";
1526
- var reTrim = /^\s+|\s+$/g;
1527
- var reIsBadHex = /^[-+]0x[0-9a-f]+$/i;
1528
- var reIsBinary = /^0b[01]+$/i;
1529
- var reIsOctal = /^0o[0-7]+$/i;
1530
- var freeParseInt = parseInt;
1531
- var freeGlobal = typeof global == "object" && global && global.Object === Object && global;
1532
- var freeSelf = typeof self == "object" && self && self.Object === Object && self;
1533
- var root = freeGlobal || freeSelf || Function("return this")();
1534
- var objectProto = Object.prototype;
1535
- var objectToString = objectProto.toString;
1536
- var nativeMax = Math.max;
1537
- var nativeMin = Math.min;
1538
- var now = function() {
1539
- return root.Date.now();
1102
+ // src/serializer/pgSerializer.ts
1103
+ import {
1104
+ customType,
1105
+ PgBigInt53Builder,
1106
+ PgBigSerial53Builder,
1107
+ PgBooleanBuilder,
1108
+ PgCharBuilder,
1109
+ PgCidrBuilder,
1110
+ PgDateBuilder,
1111
+ PgDialect,
1112
+ PgDoublePrecisionBuilder,
1113
+ PgInetBuilder,
1114
+ PgIntegerBuilder,
1115
+ PgIntervalBuilder,
1116
+ PgJsonbBuilder,
1117
+ PgJsonBuilder,
1118
+ PgMacaddr8Builder,
1119
+ PgMacaddrBuilder,
1120
+ PgNumericBuilder,
1121
+ PgRealBuilder,
1122
+ pgSchema,
1123
+ PgSerialBuilder,
1124
+ PgSmallIntBuilder,
1125
+ PgSmallSerialBuilder,
1126
+ pgTable,
1127
+ PgTextBuilder,
1128
+ PgTimeBuilder,
1129
+ PgTimestampBuilder,
1130
+ PgUUIDBuilder,
1131
+ PgVarcharBuilder,
1132
+ PrimaryKeyBuilder,
1133
+ uniqueKeyName
1134
+ } from "drizzle-orm/pg-core";
1135
+ import { getTableConfig } from "drizzle-orm/pg-core";
1136
+ import { is, SQL, getTableName } from "drizzle-orm";
1137
+ var dialect, trimChar, fromDatabase, columnToDefault, defaultForColumn, toDrizzle;
1138
+ var init_pgSerializer = __esm({
1139
+ "src/serializer/pgSerializer.ts"() {
1140
+ init_serializer();
1141
+ init_source();
1142
+ init_outputs();
1143
+ dialect = new PgDialect();
1144
+ trimChar = (str, char) => {
1145
+ let start = 0;
1146
+ let end = str.length;
1147
+ while (start < end && str[start] === char)
1148
+ ++start;
1149
+ while (end > start && str[end - 1] === char)
1150
+ --end;
1151
+ return start > 0 || end < str.length ? str.substring(start, end) : str.toString();
1540
1152
  };
1541
- function debounce(func, wait, options) {
1542
- var lastArgs, lastThis, maxWait, result, timerId, lastCallTime, lastInvokeTime = 0, leading = false, maxing = false, trailing = true;
1543
- if (typeof func != "function") {
1544
- throw new TypeError(FUNC_ERROR_TEXT);
1545
- }
1546
- wait = toNumber(wait) || 0;
1547
- if (isObject(options)) {
1548
- leading = !!options.leading;
1549
- maxing = "maxWait" in options;
1550
- maxWait = maxing ? nativeMax(toNumber(options.maxWait) || 0, wait) : maxWait;
1551
- trailing = "trailing" in options ? !!options.trailing : trailing;
1552
- }
1553
- function invokeFunc(time) {
1554
- var args = lastArgs, thisArg = lastThis;
1555
- lastArgs = lastThis = void 0;
1556
- lastInvokeTime = time;
1557
- result = func.apply(thisArg, args);
1558
- return result;
1559
- }
1560
- function leadingEdge(time) {
1561
- lastInvokeTime = time;
1562
- timerId = setTimeout(timerExpired, wait);
1563
- return leading ? invokeFunc(time) : result;
1564
- }
1565
- function remainingWait(time) {
1566
- var timeSinceLastCall = time - lastCallTime, timeSinceLastInvoke = time - lastInvokeTime, result2 = wait - timeSinceLastCall;
1567
- return maxing ? nativeMin(result2, maxWait - timeSinceLastInvoke) : result2;
1568
- }
1569
- function shouldInvoke(time) {
1570
- var timeSinceLastCall = time - lastCallTime, timeSinceLastInvoke = time - lastInvokeTime;
1571
- return lastCallTime === void 0 || timeSinceLastCall >= wait || timeSinceLastCall < 0 || maxing && timeSinceLastInvoke >= maxWait;
1572
- }
1573
- function timerExpired() {
1574
- var time = now();
1575
- if (shouldInvoke(time)) {
1576
- return trailingEdge(time);
1577
- }
1578
- timerId = setTimeout(timerExpired, remainingWait(time));
1579
- }
1580
- function trailingEdge(time) {
1581
- timerId = void 0;
1582
- if (trailing && lastArgs) {
1583
- return invokeFunc(time);
1584
- }
1585
- lastArgs = lastThis = void 0;
1586
- return result;
1587
- }
1588
- function cancel() {
1589
- if (timerId !== void 0) {
1590
- clearTimeout(timerId);
1591
- }
1592
- lastInvokeTime = 0;
1593
- lastArgs = lastCallTime = lastThis = timerId = void 0;
1594
- }
1595
- function flush() {
1596
- return timerId === void 0 ? result : trailingEdge(now());
1597
- }
1598
- function debounced() {
1599
- var time = now(), isInvoking = shouldInvoke(time);
1600
- lastArgs = arguments;
1601
- lastThis = this;
1602
- lastCallTime = time;
1603
- if (isInvoking) {
1604
- if (timerId === void 0) {
1605
- return leadingEdge(lastCallTime);
1606
- }
1607
- if (maxing) {
1608
- timerId = setTimeout(timerExpired, wait);
1609
- return invokeFunc(lastCallTime);
1610
- }
1611
- }
1612
- if (timerId === void 0) {
1613
- timerId = setTimeout(timerExpired, wait);
1153
+ fromDatabase = async (db, tablesFilter = (table) => true, schemaFilters, progressCallback) => {
1154
+ const result = {};
1155
+ const internals = { tables: {} };
1156
+ const where = schemaFilters.map((t) => `table_schema = '${t}'`).join(" or ");
1157
+ const allTables = await db.query(
1158
+ `SELECT table_schema, table_name FROM information_schema.tables WHERE ${where};`
1159
+ );
1160
+ const schemas = new Set(allTables.map((it) => it.table_schema));
1161
+ schemas.delete("public");
1162
+ const allSchemas = await db.query(`select s.nspname as table_schema
1163
+ from pg_catalog.pg_namespace s
1164
+ join pg_catalog.pg_user u on u.usesysid = s.nspowner
1165
+ where nspname not in ('information_schema', 'pg_catalog', 'public')
1166
+ and nspname not like 'pg_toast%'
1167
+ and nspname not like 'pg_temp_%'
1168
+ order by table_schema;`);
1169
+ allSchemas.forEach((item) => {
1170
+ if (schemaFilters.includes(item.table_schema)) {
1171
+ schemas.add(item.table_schema);
1614
1172
  }
1615
- return result;
1616
- }
1617
- debounced.cancel = cancel;
1618
- debounced.flush = flush;
1619
- return debounced;
1620
- }
1621
- function throttle(func, wait, options) {
1622
- var leading = true, trailing = true;
1623
- if (typeof func != "function") {
1624
- throw new TypeError(FUNC_ERROR_TEXT);
1173
+ });
1174
+ let columnsCount = 0;
1175
+ let indexesCount = 0;
1176
+ let foreignKeysCount = 0;
1177
+ let tableCount = 0;
1178
+ const all = allTables.map((row) => {
1179
+ return new Promise(async (res, rej) => {
1180
+ const tableName = row.table_name;
1181
+ if (!tablesFilter(tableName))
1182
+ return res("");
1183
+ tableCount += 1;
1184
+ const tableSchema = row.table_schema;
1185
+ try {
1186
+ const columnToReturn = {};
1187
+ const indexToReturn = {};
1188
+ const foreignKeysToReturn = {};
1189
+ const primaryKeys = {};
1190
+ const uniqueConstrains = {};
1191
+ const tableResponse = await db.query(
1192
+ `SELECT a.attrelid::regclass::text, a.attname, is_nullable, a.attndims as array_dimensions
1193
+ , CASE WHEN a.atttypid = ANY ('{int,int8,int2}'::regtype[])
1194
+ AND EXISTS (
1195
+ SELECT FROM pg_attrdef ad
1196
+ WHERE ad.adrelid = a.attrelid
1197
+ AND ad.adnum = a.attnum
1198
+ AND pg_get_expr(ad.adbin, ad.adrelid)
1199
+ = 'nextval('''
1200
+ || (pg_get_serial_sequence (a.attrelid::regclass::text
1201
+ , a.attname))::regclass
1202
+ || '''::regclass)'
1203
+ )
1204
+ THEN CASE a.atttypid
1205
+ WHEN 'int'::regtype THEN 'serial'
1206
+ WHEN 'int8'::regtype THEN 'bigserial'
1207
+ WHEN 'int2'::regtype THEN 'smallserial'
1208
+ END
1209
+ ELSE format_type(a.atttypid, a.atttypmod)
1210
+ END AS data_type, INFORMATION_SCHEMA.COLUMNS.table_name, INFORMATION_SCHEMA.COLUMNS.column_name, INFORMATION_SCHEMA.COLUMNS.column_default, INFORMATION_SCHEMA.COLUMNS.data_type as additional_dt
1211
+ FROM pg_attribute a
1212
+ JOIN INFORMATION_SCHEMA.COLUMNS ON INFORMATION_SCHEMA.COLUMNS.column_name = a.attname
1213
+ WHERE a.attrelid = '"${tableSchema}"."${tableName}"'::regclass and INFORMATION_SCHEMA.COLUMNS.table_name = '${tableName}'
1214
+ AND a.attnum > 0
1215
+ AND NOT a.attisdropped
1216
+ ORDER BY a.attnum;`
1217
+ );
1218
+ const tableConstraints = await db.query(
1219
+ `SELECT c.column_name, c.data_type, constraint_type, constraint_name, constraint_schema
1220
+ FROM information_schema.table_constraints tc
1221
+ JOIN information_schema.constraint_column_usage AS ccu USING (constraint_schema, constraint_name)
1222
+ JOIN information_schema.columns AS c ON c.table_schema = tc.constraint_schema
1223
+ AND tc.table_name = c.table_name AND ccu.column_name = c.column_name
1224
+ WHERE tc.table_name = '${tableName}' and constraint_schema = '${tableSchema}';`
1225
+ );
1226
+ columnsCount += tableResponse.length;
1227
+ if (progressCallback) {
1228
+ progressCallback("columns", columnsCount, "fetching");
1229
+ }
1230
+ const tableForeignKeys = await db.query(
1231
+ `SELECT
1232
+ tc.table_schema,
1233
+ tc.constraint_name,
1234
+ tc.table_name,
1235
+ kcu.column_name,
1236
+ ccu.table_schema AS foreign_table_schema,
1237
+ ccu.table_name AS foreign_table_name,
1238
+ ccu.column_name AS foreign_column_name,
1239
+ rc.delete_rule, rc.update_rule
1240
+ FROM
1241
+ information_schema.table_constraints AS tc
1242
+ JOIN information_schema.key_column_usage AS kcu
1243
+ ON tc.constraint_name = kcu.constraint_name
1244
+ AND tc.table_schema = kcu.table_schema
1245
+ JOIN information_schema.constraint_column_usage AS ccu
1246
+ ON ccu.constraint_name = tc.constraint_name
1247
+ AND ccu.table_schema = tc.table_schema
1248
+ JOIN information_schema.referential_constraints AS rc
1249
+ ON ccu.constraint_name = rc.constraint_name
1250
+ WHERE tc.constraint_type = 'FOREIGN KEY' AND tc.table_name='${tableName}' and tc.table_schema='${tableSchema}';`
1251
+ );
1252
+ foreignKeysCount += tableForeignKeys.length;
1253
+ if (progressCallback) {
1254
+ progressCallback("fks", foreignKeysCount, "fetching");
1255
+ }
1256
+ for (const fk of tableForeignKeys) {
1257
+ const columnFrom = fk.column_name;
1258
+ const tableTo = fk.foreign_table_name;
1259
+ const columnTo = fk.foreign_column_name;
1260
+ const foreignKeyName = fk.constraint_name;
1261
+ const onUpdate = fk.update_rule.toLowerCase();
1262
+ const onDelete = fk.delete_rule.toLowerCase();
1263
+ if (typeof foreignKeysToReturn[foreignKeyName] !== "undefined") {
1264
+ foreignKeysToReturn[foreignKeyName].columnsFrom.push(columnFrom);
1265
+ foreignKeysToReturn[foreignKeyName].columnsTo.push(columnTo);
1266
+ } else {
1267
+ foreignKeysToReturn[foreignKeyName] = {
1268
+ name: foreignKeyName,
1269
+ tableFrom: tableName,
1270
+ tableTo,
1271
+ columnsFrom: [columnFrom],
1272
+ columnsTo: [columnTo],
1273
+ onDelete,
1274
+ onUpdate
1275
+ };
1276
+ }
1277
+ foreignKeysToReturn[foreignKeyName].columnsFrom = [
1278
+ ...new Set(foreignKeysToReturn[foreignKeyName].columnsFrom)
1279
+ ];
1280
+ foreignKeysToReturn[foreignKeyName].columnsTo = [
1281
+ ...new Set(foreignKeysToReturn[foreignKeyName].columnsTo)
1282
+ ];
1283
+ }
1284
+ const uniqueConstrainsRows = tableConstraints.filter(
1285
+ (mapRow) => mapRow.constraint_type === "UNIQUE"
1286
+ );
1287
+ for (const unqs of uniqueConstrainsRows) {
1288
+ const columnName = unqs.column_name;
1289
+ const constraintName = unqs.constraint_name;
1290
+ if (typeof uniqueConstrains[constraintName] !== "undefined") {
1291
+ uniqueConstrains[constraintName].columns.push(columnName);
1292
+ } else {
1293
+ uniqueConstrains[constraintName] = {
1294
+ columns: [columnName],
1295
+ nullsNotDistinct: false,
1296
+ name: constraintName
1297
+ };
1298
+ }
1299
+ }
1300
+ for (const columnResponse of tableResponse) {
1301
+ const columnName = columnResponse.attname;
1302
+ const columnAdditionalDT = columnResponse.additional_dt;
1303
+ const columnDimensions = columnResponse.array_dimensions;
1304
+ let columnType = columnResponse.data_type;
1305
+ const primaryKey = tableConstraints.filter(
1306
+ (mapRow) => columnName === mapRow.column_name && mapRow.constraint_type === "PRIMARY KEY"
1307
+ );
1308
+ const cprimaryKey = tableConstraints.filter(
1309
+ (mapRow) => mapRow.constraint_type === "PRIMARY KEY"
1310
+ );
1311
+ if (cprimaryKey.length > 1) {
1312
+ const tableCompositePkName = await db.query(
1313
+ `SELECT conname AS primary_key
1314
+ FROM pg_constraint
1315
+ WHERE contype = 'p'
1316
+ AND connamespace = '${tableSchema}'::regnamespace
1317
+ AND (conrelid::regclass::text = '"${tableName}"' OR conrelid::regclass::text = '${tableName}');`
1318
+ );
1319
+ primaryKeys[`${tableName}_${cprimaryKey.map((pk) => pk.column_name).join("_")}`] = {
1320
+ name: tableCompositePkName[0].primary_key,
1321
+ columns: cprimaryKey.map((c) => c.column_name)
1322
+ };
1323
+ }
1324
+ const defaultValue = defaultForColumn(columnResponse);
1325
+ const isSerial = columnType === "serial";
1326
+ let columnTypeMapped = columnType;
1327
+ if (columnTypeMapped.startsWith("numeric(")) {
1328
+ columnTypeMapped = columnTypeMapped.replace(",", ", ");
1329
+ }
1330
+ if (columnAdditionalDT === "ARRAY") {
1331
+ if (typeof internals.tables[tableName] === "undefined") {
1332
+ internals.tables[tableName] = {
1333
+ columns: {
1334
+ [columnName]: {
1335
+ isArray: true,
1336
+ dimensions: columnDimensions,
1337
+ rawType: columnTypeMapped.substring(
1338
+ 0,
1339
+ columnTypeMapped.length - 2
1340
+ )
1341
+ }
1342
+ }
1343
+ };
1344
+ } else {
1345
+ if (typeof internals.tables[tableName].columns[columnName] === "undefined") {
1346
+ internals.tables[tableName].columns[columnName] = {
1347
+ isArray: true,
1348
+ dimensions: columnDimensions,
1349
+ rawType: columnTypeMapped.substring(
1350
+ 0,
1351
+ columnTypeMapped.length - 2
1352
+ )
1353
+ };
1354
+ }
1355
+ }
1356
+ }
1357
+ if (columnAdditionalDT === "ARRAY") {
1358
+ for (let i = 1; i < Number(columnDimensions); i++) {
1359
+ columnTypeMapped += "[]";
1360
+ }
1361
+ }
1362
+ columnTypeMapped = columnTypeMapped.replace("character varying", "varchar").replace(" without time zone", "").replace("character", "char");
1363
+ columnTypeMapped = trimChar(columnTypeMapped, '"');
1364
+ columnToReturn[columnName] = {
1365
+ name: columnName,
1366
+ type: columnTypeMapped,
1367
+ primaryKey: primaryKey.length === 1 && cprimaryKey.length < 2,
1368
+ // default: isSerial ? undefined : defaultValue,
1369
+ notNull: columnResponse.is_nullable === "NO"
1370
+ };
1371
+ if (!isSerial && typeof defaultValue !== "undefined") {
1372
+ columnToReturn[columnName].default = defaultValue;
1373
+ }
1374
+ }
1375
+ const dbIndexes = await db.query(
1376
+ `SELECT t.relname as table_name, i.relname AS index_name, ix.indisunique AS is_unique, a.attname AS column_name
1377
+ FROM pg_class t
1378
+ JOIN pg_index ix ON t.oid = ix.indrelid
1379
+ JOIN pg_class i ON i.oid = ix.indexrelid
1380
+ JOIN pg_attribute a ON a.attrelid = t.oid AND a.attnum = ANY(ix.indkey)
1381
+ JOIN pg_namespace ns ON ns.oid = t.relnamespace
1382
+ WHERE ns.nspname = '${tableSchema}'
1383
+ AND t.relname = '${tableName}'
1384
+ and ix.indisprimary = false;`
1385
+ );
1386
+ const dbIndexFromConstraint = await db.query(
1387
+ `SELECT
1388
+ idx.indexrelname AS index_name,
1389
+ idx.relname AS table_name,
1390
+ schemaname,
1391
+ CASE WHEN con.conname IS NOT NULL THEN 1 ELSE 0 END AS generated_by_constraint
1392
+ FROM
1393
+ pg_stat_user_indexes idx
1394
+ LEFT JOIN
1395
+ pg_constraint con ON con.conindid = idx.indexrelid
1396
+ WHERE idx.relname = '${tableName}' and schemaname = '${tableSchema}'
1397
+ group by index_name, table_name,schemaname, generated_by_constraint;`
1398
+ );
1399
+ const idxsInConsteraint = dbIndexFromConstraint.filter((it) => it.generated_by_constraint === 1).map((it) => it.index_name);
1400
+ for (const dbIndex of dbIndexes) {
1401
+ const indexName2 = dbIndex.index_name;
1402
+ const indexColumnName = dbIndex.column_name;
1403
+ const indexIsUnique = dbIndex.is_unique;
1404
+ if (idxsInConsteraint.includes(indexName2))
1405
+ continue;
1406
+ if (typeof indexToReturn[indexName2] !== "undefined") {
1407
+ indexToReturn[indexName2].columns.push(indexColumnName);
1408
+ } else {
1409
+ indexToReturn[indexName2] = {
1410
+ name: indexName2,
1411
+ columns: [indexColumnName],
1412
+ isUnique: indexIsUnique
1413
+ };
1414
+ }
1415
+ }
1416
+ indexesCount += Object.keys(indexToReturn).length;
1417
+ if (progressCallback) {
1418
+ progressCallback("indexes", indexesCount, "fetching");
1419
+ }
1420
+ result[tableName] = {
1421
+ name: tableName,
1422
+ schema: tableSchema !== "public" ? tableSchema : "",
1423
+ columns: columnToReturn,
1424
+ indexes: indexToReturn,
1425
+ foreignKeys: foreignKeysToReturn,
1426
+ compositePrimaryKeys: primaryKeys,
1427
+ uniqueConstraints: uniqueConstrains
1428
+ };
1429
+ } catch (e) {
1430
+ rej(e);
1431
+ return;
1432
+ }
1433
+ res("");
1434
+ });
1435
+ });
1436
+ if (progressCallback) {
1437
+ progressCallback("tables", tableCount, "done");
1625
1438
  }
1626
- if (isObject(options)) {
1627
- leading = "leading" in options ? !!options.leading : leading;
1628
- trailing = "trailing" in options ? !!options.trailing : trailing;
1439
+ for await (const _ of all) {
1629
1440
  }
1630
- return debounce(func, wait, {
1631
- "leading": leading,
1632
- "maxWait": wait,
1633
- "trailing": trailing
1634
- });
1635
- }
1636
- function isObject(value) {
1637
- var type = typeof value;
1638
- return !!value && (type == "object" || type == "function");
1639
- }
1640
- function isObjectLike(value) {
1641
- return !!value && typeof value == "object";
1642
- }
1643
- function isSymbol(value) {
1644
- return typeof value == "symbol" || isObjectLike(value) && objectToString.call(value) == symbolTag;
1645
- }
1646
- function toNumber(value) {
1647
- if (typeof value == "number") {
1648
- return value;
1441
+ if (progressCallback) {
1442
+ progressCallback("columns", columnsCount, "done");
1443
+ progressCallback("indexes", indexesCount, "done");
1444
+ progressCallback("fks", foreignKeysCount, "done");
1649
1445
  }
1650
- if (isSymbol(value)) {
1651
- return NAN;
1446
+ const allEnums = await db.query(
1447
+ `select n.nspname as enum_schema,
1448
+ t.typname as enum_name,
1449
+ e.enumlabel as enum_value
1450
+ from pg_type t
1451
+ join pg_enum e on t.oid = e.enumtypid
1452
+ join pg_catalog.pg_namespace n ON n.oid = t.typnamespace;`
1453
+ );
1454
+ const enumsToReturn = {};
1455
+ for (const dbEnum of allEnums) {
1456
+ const enumName = dbEnum.enum_name;
1457
+ const enumValue = dbEnum.enum_value;
1458
+ if (enumsToReturn[enumName] !== void 0 && enumsToReturn[enumName] !== null) {
1459
+ enumsToReturn[enumName].values[enumValue] = enumValue;
1460
+ } else {
1461
+ enumsToReturn[enumName] = {
1462
+ name: enumName,
1463
+ values: { [enumValue]: enumValue }
1464
+ };
1465
+ }
1652
1466
  }
1653
- if (isObject(value)) {
1654
- var other = typeof value.valueOf == "function" ? value.valueOf() : value;
1655
- value = isObject(other) ? other + "" : other;
1467
+ if (progressCallback) {
1468
+ progressCallback("enums", Object.keys(enumsToReturn).length, "done");
1656
1469
  }
1657
- if (typeof value != "string") {
1658
- return value === 0 ? value : +value;
1470
+ const schemasObject = Object.fromEntries([...schemas].map((it) => [it, it]));
1471
+ return {
1472
+ version: "5",
1473
+ dialect: "pg",
1474
+ tables: result,
1475
+ enums: enumsToReturn,
1476
+ schemas: schemasObject,
1477
+ _meta: {
1478
+ schemas: {},
1479
+ tables: {},
1480
+ columns: {}
1481
+ },
1482
+ internal: internals
1483
+ };
1484
+ };
1485
+ columnToDefault = {
1486
+ "numeric(": "::numeric",
1487
+ // text: "::text",
1488
+ // "character varying": "::character varying",
1489
+ // "double precision": "::double precision",
1490
+ // "time with time zone": "::time with time zone",
1491
+ "time without time zone": "::time without time zone",
1492
+ // "timestamp with time zone": "::timestamp with time zone",
1493
+ "timestamp without time zone": "::timestamp without time zone",
1494
+ // date: "::date",
1495
+ // interval: "::interval",
1496
+ // character: "::bpchar",
1497
+ // macaddr8: "::macaddr8",
1498
+ // macaddr: "::macaddr",
1499
+ // inet: "::inet",
1500
+ // cidr: "::cidr",
1501
+ // jsonb: "::jsonb",
1502
+ // json: "::json",
1503
+ "character(": "::bpchar"
1504
+ };
1505
+ defaultForColumn = (column) => {
1506
+ if (column.data_type === "serial" || column.data_type === "smallserial" || column.data_type === "bigserial") {
1507
+ return void 0;
1659
1508
  }
1660
- value = value.replace(reTrim, "");
1661
- var isBinary = reIsBinary.test(value);
1662
- return isBinary || reIsOctal.test(value) ? freeParseInt(value.slice(2), isBinary ? 2 : 8) : reIsBadHex.test(value) ? NAN : +value;
1663
- }
1664
- module.exports = throttle;
1665
- }
1666
- });
1667
-
1668
- // node_modules/.pnpm/hanji@0.0.5/node_modules/hanji/index.js
1669
- var require_hanji = __commonJS({
1670
- "node_modules/.pnpm/hanji@0.0.5/node_modules/hanji/index.js"(exports) {
1671
- "use strict";
1672
- var __awaiter = exports && exports.__awaiter || function(thisArg, _arguments, P, generator) {
1673
- function adopt(value) {
1674
- return value instanceof P ? value : new P(function(resolve) {
1675
- resolve(value);
1676
- });
1509
+ const hasDifferentDefaultCast = Object.keys(columnToDefault).find(
1510
+ (it) => column.data_type.startsWith(it)
1511
+ );
1512
+ if (column.column_default === null) {
1513
+ return void 0;
1677
1514
  }
1678
- return new (P || (P = Promise))(function(resolve, reject) {
1679
- function fulfilled(value) {
1680
- try {
1681
- step(generator.next(value));
1682
- } catch (e) {
1683
- reject(e);
1684
- }
1515
+ const columnDefaultAsString = column.column_default.toString();
1516
+ if (columnDefaultAsString.endsWith(
1517
+ hasDifferentDefaultCast ? columnToDefault[hasDifferentDefaultCast] : column.data_type
1518
+ )) {
1519
+ const nonPrefixPart = column.column_default.length - (hasDifferentDefaultCast ? columnToDefault[hasDifferentDefaultCast] : `::${column.data_type}`).length - 1;
1520
+ const rt = column.column_default.toString().substring(1, nonPrefixPart);
1521
+ if (/^-?[\d.]+(?:e-?\d+)?$/.test(rt) && !column.data_type.startsWith("numeric")) {
1522
+ return Number(rt);
1523
+ } else if (column.data_type === "json" || column.data_type === "jsonb") {
1524
+ const jsonWithoutSpaces = JSON.stringify(JSON.parse(rt));
1525
+ return `'${jsonWithoutSpaces}'${hasDifferentDefaultCast ? columnToDefault[hasDifferentDefaultCast] : `::${column.data_type}`}`;
1526
+ } else if (column.data_type === "boolean") {
1527
+ return column.column_default === "true";
1528
+ } else {
1529
+ return `'${rt}'`;
1685
1530
  }
1686
- function rejected(value) {
1687
- try {
1688
- step(generator["throw"](value));
1689
- } catch (e) {
1690
- reject(e);
1691
- }
1531
+ } else {
1532
+ if (/^-?[\d.]+(?:e-?\d+)?$/.test(columnDefaultAsString) && !column.data_type.startsWith("numeric")) {
1533
+ return Number(columnDefaultAsString);
1534
+ } else if (column.data_type === "boolean") {
1535
+ return column.column_default === "true";
1536
+ } else {
1537
+ return `${columnDefaultAsString}`;
1692
1538
  }
1693
- function step(result) {
1694
- result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected);
1539
+ }
1540
+ };
1541
+ toDrizzle = (schema, schemaName) => {
1542
+ const tables = {};
1543
+ Object.values(schema.tables).forEach((t) => {
1544
+ const columns = {};
1545
+ Object.values(t.columns).forEach((c) => {
1546
+ const columnName = c.name;
1547
+ const type = c.type;
1548
+ let columnBuilder;
1549
+ if (type === "bigint") {
1550
+ columnBuilder = new PgBigInt53Builder(columnName);
1551
+ } else if (type === "bigserial") {
1552
+ columnBuilder = new PgBigSerial53Builder(columnName);
1553
+ } else if (type === "boolean") {
1554
+ columnBuilder = new PgBooleanBuilder(columnName);
1555
+ } else if (type === "cidr") {
1556
+ columnBuilder = new PgCidrBuilder(columnName);
1557
+ } else if (type === "date") {
1558
+ columnBuilder = new PgDateBuilder(columnName);
1559
+ } else if (type === "double precision") {
1560
+ columnBuilder = new PgDoublePrecisionBuilder(columnName);
1561
+ } else if (type === "inet") {
1562
+ columnBuilder = new PgInetBuilder(columnName);
1563
+ } else if (type === "integer") {
1564
+ columnBuilder = new PgIntegerBuilder(columnName);
1565
+ } else if (type === "interval" || type.startsWith("interval ")) {
1566
+ columnBuilder = new PgIntervalBuilder(columnName, {});
1567
+ } else if (type === "json") {
1568
+ columnBuilder = new PgJsonBuilder(columnName);
1569
+ } else if (type === "jsonb") {
1570
+ columnBuilder = new PgJsonbBuilder(columnName);
1571
+ } else if (type === "macaddr") {
1572
+ columnBuilder = new PgMacaddrBuilder(columnName);
1573
+ } else if (type === "macaddr8") {
1574
+ columnBuilder = new PgMacaddr8Builder(columnName);
1575
+ } else if (type === "numeric" || type.startsWith("numeric(")) {
1576
+ columnBuilder = new PgNumericBuilder(columnName);
1577
+ } else if (type === "real") {
1578
+ columnBuilder = new PgRealBuilder(columnName);
1579
+ } else if (type === "serial") {
1580
+ columnBuilder = new PgSerialBuilder(columnName);
1581
+ } else if (type === "smallint") {
1582
+ columnBuilder = new PgSmallIntBuilder(columnName);
1583
+ } else if (type === "smallserial") {
1584
+ columnBuilder = new PgSmallSerialBuilder(columnName);
1585
+ } else if (type === "text") {
1586
+ columnBuilder = new PgTextBuilder(columnName, {});
1587
+ } else if (type === "time" || type.startsWith("time(") || type === "time with time zone") {
1588
+ columnBuilder = new PgTimeBuilder(columnName, false, void 0);
1589
+ } else if (type === "timestamp" || type.startsWith("timestamp(") || type === "timestamp with time zone") {
1590
+ columnBuilder = new PgTimestampBuilder(columnName, false, void 0);
1591
+ } else if (type === "uuid") {
1592
+ columnBuilder = new PgUUIDBuilder(columnName);
1593
+ } else if (type === "varchar" || type.startsWith("varchar(")) {
1594
+ columnBuilder = new PgVarcharBuilder(columnName, {});
1595
+ } else if (type === "char" || type.startsWith("char(")) {
1596
+ columnBuilder = new PgCharBuilder(columnName, {});
1597
+ } else {
1598
+ columnBuilder = customType({
1599
+ dataType() {
1600
+ return type;
1601
+ }
1602
+ })(columnName);
1603
+ }
1604
+ if (c.notNull) {
1605
+ columnBuilder = columnBuilder.notNull();
1606
+ }
1607
+ if (c.default) {
1608
+ columnBuilder = columnBuilder.default(c.default);
1609
+ }
1610
+ if (c.primaryKey) {
1611
+ columnBuilder = columnBuilder.primaryKey();
1612
+ }
1613
+ columns[columnName] = columnBuilder;
1614
+ });
1615
+ if (schemaName === "public") {
1616
+ tables[t.name] = pgTable(t.name, columns, (cb) => {
1617
+ const res = {};
1618
+ Object.values(t.compositePrimaryKeys).forEach((cpk) => {
1619
+ const gh = cpk.columns.map((c) => cb[c]);
1620
+ res[cpk.name] = new PrimaryKeyBuilder(
1621
+ gh,
1622
+ cpk.name
1623
+ );
1624
+ });
1625
+ return res;
1626
+ });
1627
+ } else {
1628
+ tables[t.name] = pgSchema(schemaName).table(t.name, columns, (cb) => {
1629
+ const res = {};
1630
+ Object.values(t.compositePrimaryKeys).forEach((cpk) => {
1631
+ const gh = cpk.columns.map((c) => cb[c]);
1632
+ res[cpk.name] = new PrimaryKeyBuilder(
1633
+ gh,
1634
+ cpk.name
1635
+ );
1636
+ });
1637
+ return res;
1638
+ });
1695
1639
  }
1696
- step((generator = generator.apply(thisArg, _arguments || [])).next());
1697
1640
  });
1641
+ return tables;
1698
1642
  };
1699
- var __importDefault = exports && exports.__importDefault || function(mod) {
1700
- return mod && mod.__esModule ? mod : { "default": mod };
1701
- };
1702
- Object.defineProperty(exports, "__esModule", { value: true });
1703
- exports.onTerminate = exports.renderWithTask = exports.render = exports.TaskTerminal = exports.TaskView = exports.Terminal = exports.deferred = exports.SelectState = exports.Prompt = void 0;
1704
- var readline_1 = require_readline();
1705
- var sisteransi_1 = require_src();
1706
- var utils_1 = require_utils();
1707
- var lodash_throttle_1 = __importDefault(require_lodash());
1708
- var Prompt2 = class {
1709
- constructor() {
1710
- this.attachCallbacks = [];
1711
- this.detachCallbacks = [];
1712
- this.inputCallbacks = [];
1713
- }
1714
- requestLayout() {
1715
- this.terminal.requestLayout();
1716
- }
1717
- on(type, callback) {
1718
- if (type === "attach") {
1719
- this.attachCallbacks.push(callback);
1720
- } else if (type === "detach") {
1721
- this.detachCallbacks.push(callback);
1722
- } else if (type === "input") {
1723
- this.inputCallbacks.push(callback);
1724
- }
1725
- }
1726
- attach(terminal) {
1727
- this.terminal = terminal;
1728
- this.attachCallbacks.forEach((it) => it(terminal));
1729
- }
1730
- detach(terminal) {
1731
- this.detachCallbacks.forEach((it) => it(terminal));
1732
- this.terminal = void 0;
1733
- }
1734
- input(str, key) {
1735
- this.inputCallbacks.forEach((it) => it(str, key));
1736
- }
1737
- };
1738
- exports.Prompt = Prompt2;
1739
- var SelectState2 = class {
1740
- constructor(items) {
1741
- this.items = items;
1742
- this.selectedIdx = 0;
1743
- }
1744
- bind(prompt) {
1745
- prompt.on("input", (str, key) => {
1746
- const invalidate = this.consume(str, key);
1747
- if (invalidate)
1748
- prompt.requestLayout();
1749
- });
1643
+ }
1644
+ });
1645
+
1646
+ // src/serializer/sqliteSerializer.ts
1647
+ import { getTableName as getTableName2, is as is2, SQL as SQL2 } from "drizzle-orm";
1648
+ import {
1649
+ getTableConfig as getTableConfig2,
1650
+ PrimaryKeyBuilder as PrimaryKeyBuilder2,
1651
+ SQLiteBaseInteger,
1652
+ SQLiteBlobBufferBuilder,
1653
+ SQLiteIntegerBuilder,
1654
+ SQLiteNumericBuilder,
1655
+ SQLiteRealBuilder,
1656
+ SQLiteSyncDialect,
1657
+ sqliteTable,
1658
+ SQLiteTextBuilder,
1659
+ uniqueKeyName as uniqueKeyName2
1660
+ } from "drizzle-orm/sqlite-core";
1661
+ function mapSqlToSqliteType(sqlType) {
1662
+ if ([
1663
+ "int",
1664
+ "integer",
1665
+ "integer auto_increment",
1666
+ "tinyint",
1667
+ "smallint",
1668
+ "mediumint",
1669
+ "bigint",
1670
+ "unsigned big int",
1671
+ "int2",
1672
+ "int8"
1673
+ ].includes(sqlType.toLowerCase())) {
1674
+ return "integer";
1675
+ } else if ([
1676
+ "character",
1677
+ "varchar",
1678
+ "vatying character",
1679
+ "nchar",
1680
+ "native character",
1681
+ "nvarchar",
1682
+ "text",
1683
+ "clob"
1684
+ ].some((it) => it.startsWith(sqlType.toLowerCase()))) {
1685
+ return "text";
1686
+ } else if (sqlType.toLowerCase() === "blob") {
1687
+ return "blob";
1688
+ } else if (["real", "double", "double precision", "float"].includes(
1689
+ sqlType.toLowerCase()
1690
+ )) {
1691
+ return "real";
1692
+ } else {
1693
+ return "numeric";
1694
+ }
1695
+ }
1696
+ var dialect2, fromDatabase2, toDrizzle2;
1697
+ var init_sqliteSerializer = __esm({
1698
+ "src/serializer/sqliteSerializer.ts"() {
1699
+ init_serializer();
1700
+ init_outputs();
1701
+ init_source();
1702
+ dialect2 = new SQLiteSyncDialect();
1703
+ fromDatabase2 = async (db, tablesFilter = (table) => true, progressCallback) => {
1704
+ const result = {};
1705
+ const columns = await db.query(
1706
+ `SELECT
1707
+ m.name as "tableName", p.name as "columnName", p.type as "columnType", p."notnull" as "notNull", p.dflt_value as "defaultValue", p.pk as pk
1708
+ FROM sqlite_master AS m JOIN pragma_table_info(m.name) AS p
1709
+ WHERE m.type = 'table' and m.tbl_name != 'sqlite_sequence' and m.tbl_name != 'sqlite_stat1' and m.tbl_name != '_litestream_seq' and m.tbl_name != '_litestream_lock' and m.tbl_name != 'libsql_wasm_func_table';
1710
+ `
1711
+ );
1712
+ const tablesWithSeq = [];
1713
+ const seq = await db.query(
1714
+ `SELECT * FROM sqlite_master WHERE name != 'sqlite_sequence' and name != 'sqlite_stat1' and name != '_litestream_seq' and name != '_litestream_lock' and sql GLOB '*[ *' || CHAR(9) || CHAR(10) || CHAR(13) || ']AUTOINCREMENT[^'']*';`
1715
+ );
1716
+ for (const s of seq) {
1717
+ tablesWithSeq.push(s.name);
1750
1718
  }
1751
- consume(str, key) {
1752
- if (!key)
1753
- return false;
1754
- if (key.name === "down") {
1755
- this.selectedIdx = (this.selectedIdx + 1) % this.items.length;
1756
- return true;
1719
+ let columnsCount = 0;
1720
+ let tablesCount = /* @__PURE__ */ new Set();
1721
+ let indexesCount = 0;
1722
+ let foreignKeysCount = 0;
1723
+ const tableToPk = {};
1724
+ for (const column of columns) {
1725
+ if (!tablesFilter(column.tableName))
1726
+ continue;
1727
+ columnsCount += 1;
1728
+ if (progressCallback) {
1729
+ progressCallback("columns", columnsCount, "fetching");
1757
1730
  }
1758
- if (key.name === "up") {
1759
- this.selectedIdx -= 1;
1760
- this.selectedIdx = this.selectedIdx < 0 ? this.items.length - 1 : this.selectedIdx;
1761
- return true;
1731
+ const tableName = column.tableName;
1732
+ tablesCount.add(tableName);
1733
+ if (progressCallback) {
1734
+ progressCallback("tables", tablesCount.size, "fetching");
1762
1735
  }
1763
- return false;
1764
- }
1765
- };
1766
- exports.SelectState = SelectState2;
1767
- var deferred = () => {
1768
- let resolve;
1769
- let reject;
1770
- const promise = new Promise((res, rej) => {
1771
- resolve = res;
1772
- reject = rej;
1773
- });
1774
- return {
1775
- resolve,
1776
- reject,
1777
- promise
1778
- };
1779
- };
1780
- exports.deferred = deferred;
1781
- var Terminal = class {
1782
- constructor(view, stdin, stdout, closable) {
1783
- this.view = view;
1784
- this.stdin = stdin;
1785
- this.stdout = stdout;
1786
- this.closable = closable;
1787
- this.text = "";
1788
- this.status = "idle";
1789
- if (this.stdin.isTTY)
1790
- this.stdin.setRawMode(true);
1791
- const keypress = (str, key) => {
1792
- if (key.name === "c" && key.ctrl === true) {
1793
- this.requestLayout();
1794
- this.view.detach(this);
1795
- this.tearDown(keypress);
1796
- if (terminateHandler) {
1797
- terminateHandler(this.stdin, this.stdout);
1798
- return;
1799
- }
1800
- this.stdout.write(`
1801
- ^C
1802
- `);
1803
- process.exit(1);
1804
- }
1805
- if (key.name === "escape") {
1806
- this.status = "aborted";
1807
- this.requestLayout();
1808
- this.view.detach(this);
1809
- this.tearDown(keypress);
1810
- this.resolve({ status: "aborted", data: void 0 });
1811
- return;
1812
- }
1813
- if (key.name === "return") {
1814
- this.status = "submitted";
1815
- this.requestLayout();
1816
- this.view.detach(this);
1817
- this.tearDown(keypress);
1818
- this.resolve({ status: "submitted", data: this.view.result() });
1819
- return;
1736
+ const columnName = column.columnName;
1737
+ const isNotNull = column.notNull === 1;
1738
+ const columnType = column.columnType;
1739
+ const isPrimary = column.pk !== 0;
1740
+ const columnDefault = column.defaultValue;
1741
+ const isAutoincrement = isPrimary && tablesWithSeq.includes(tableName);
1742
+ if (isPrimary) {
1743
+ if (typeof tableToPk[tableName] === "undefined") {
1744
+ tableToPk[tableName] = [columnName];
1745
+ } else {
1746
+ tableToPk[tableName].push(columnName);
1820
1747
  }
1821
- view.input(str, key);
1822
- };
1823
- this.stdin.on("keypress", keypress);
1824
- this.view.attach(this);
1825
- const { resolve, promise } = (0, exports.deferred)();
1826
- this.resolve = resolve;
1827
- this.promise = promise;
1828
- this.renderFunc = (0, lodash_throttle_1.default)((str) => {
1829
- this.stdout.write(str);
1830
- });
1831
- }
1832
- tearDown(keypress) {
1833
- this.stdout.write(sisteransi_1.cursor.show);
1834
- this.stdin.removeListener("keypress", keypress);
1835
- if (this.stdin.isTTY)
1836
- this.stdin.setRawMode(false);
1837
- this.closable.close();
1838
- }
1839
- result() {
1840
- return this.promise;
1841
- }
1842
- toggleCursor(state) {
1843
- if (state === "hide") {
1844
- this.stdout.write(sisteransi_1.cursor.hide);
1748
+ }
1749
+ const table = result[tableName];
1750
+ const newColumn = {
1751
+ default: columnDefault === null ? void 0 : /^-?[\d.]+(?:e-?\d+)?$/.test(columnDefault) ? Number(columnDefault) : ["CURRENT_TIME", "CURRENT_DATE", "CURRENT_TIMESTAMP"].includes(
1752
+ columnDefault
1753
+ ) ? `(${columnDefault})` : columnDefault === "false" ? false : columnDefault === "true" ? true : columnDefault.startsWith("'") && columnDefault.endsWith("'") ? columnDefault : (
1754
+ // ? columnDefault.substring(1, columnDefault.length - 1)
1755
+ `(${columnDefault})`
1756
+ ),
1757
+ autoincrement: isAutoincrement,
1758
+ name: columnName,
1759
+ type: mapSqlToSqliteType(columnType),
1760
+ primaryKey: false,
1761
+ notNull: isNotNull
1762
+ };
1763
+ if (!table) {
1764
+ result[tableName] = {
1765
+ name: tableName,
1766
+ columns: {
1767
+ [columnName]: newColumn
1768
+ },
1769
+ compositePrimaryKeys: {},
1770
+ indexes: {},
1771
+ foreignKeys: {},
1772
+ uniqueConstraints: {}
1773
+ };
1845
1774
  } else {
1846
- this.stdout.write(sisteransi_1.cursor.show);
1775
+ result[tableName].columns[columnName] = newColumn;
1847
1776
  }
1848
1777
  }
1849
- requestLayout() {
1850
- const string = this.view.render(this.status);
1851
- const clearPrefix = this.text ? (0, utils_1.clear)(this.text, this.stdout.columns) : "";
1852
- this.text = string;
1853
- this.renderFunc(`${clearPrefix}${string}`);
1854
- }
1855
- };
1856
- exports.Terminal = Terminal;
1857
- var TaskView2 = class {
1858
- constructor() {
1859
- this.attachCallbacks = [];
1860
- this.detachCallbacks = [];
1861
- }
1862
- requestLayout() {
1863
- this.terminal.requestLayout();
1864
- }
1865
- attach(terminal) {
1866
- this.terminal = terminal;
1867
- this.attachCallbacks.forEach((it) => it(terminal));
1778
+ for (const [key, value] of Object.entries(tableToPk)) {
1779
+ if (value.length > 1) {
1780
+ value.sort();
1781
+ result[key].compositePrimaryKeys = {
1782
+ [`${key}_${value.join("_")}_pk`]: {
1783
+ columns: value,
1784
+ name: `${key}_${value.join("_")}_pk`
1785
+ }
1786
+ };
1787
+ } else if (value.length === 1) {
1788
+ result[key].columns[value[0]].primaryKey = true;
1789
+ } else {
1790
+ }
1868
1791
  }
1869
- detach(terminal) {
1870
- this.detachCallbacks.forEach((it) => it(terminal));
1871
- this.terminal = void 0;
1792
+ if (progressCallback) {
1793
+ progressCallback("columns", columnsCount, "done");
1794
+ progressCallback("tables", tablesCount.size, "done");
1872
1795
  }
1873
- on(type, callback) {
1874
- if (type === "attach") {
1875
- this.attachCallbacks.push(callback);
1876
- } else if (type === "detach") {
1877
- this.detachCallbacks.push(callback);
1796
+ try {
1797
+ const fks = await db.query(
1798
+ `SELECT m.name as "tableFrom", f.id as "id", f."table" as "tableTo", f."from", f."to", f."on_update" as "onUpdate", f."on_delete" as "onDelete", f.seq as "seq"
1799
+ FROM sqlite_master m, pragma_foreign_key_list(m.name) as f;`
1800
+ );
1801
+ const fkByTableName = {};
1802
+ for (const fkRow of fks) {
1803
+ foreignKeysCount += 1;
1804
+ if (progressCallback) {
1805
+ progressCallback("fks", foreignKeysCount, "fetching");
1806
+ }
1807
+ const tableName = fkRow.tableFrom;
1808
+ const columnName = fkRow.from;
1809
+ const refTableName = fkRow.tableTo;
1810
+ const refColumnName = fkRow.to;
1811
+ const updateRule = fkRow.onUpdate;
1812
+ const deleteRule = fkRow.onDelete;
1813
+ const sequence = fkRow.seq;
1814
+ const id = fkRow.id;
1815
+ const tableInResult = result[tableName];
1816
+ if (typeof tableInResult === "undefined")
1817
+ continue;
1818
+ if (typeof fkByTableName[`${tableName}_${id}`] !== "undefined") {
1819
+ fkByTableName[`${tableName}_${id}`].columnsFrom.push(columnName);
1820
+ fkByTableName[`${tableName}_${id}`].columnsTo.push(refColumnName);
1821
+ } else {
1822
+ fkByTableName[`${tableName}_${id}`] = {
1823
+ name: "",
1824
+ tableFrom: tableName,
1825
+ tableTo: refTableName,
1826
+ columnsFrom: [columnName],
1827
+ columnsTo: [refColumnName],
1828
+ onDelete: deleteRule == null ? void 0 : deleteRule.toLowerCase(),
1829
+ onUpdate: updateRule == null ? void 0 : updateRule.toLowerCase()
1830
+ };
1831
+ }
1832
+ const columnsFrom = fkByTableName[`${tableName}_${id}`].columnsFrom;
1833
+ const columnsTo = fkByTableName[`${tableName}_${id}`].columnsTo;
1834
+ fkByTableName[`${tableName}_${id}`].name = `${tableName}_${columnsFrom.join(
1835
+ "_"
1836
+ )}_${refTableName}_${columnsTo.join("_")}_fk`;
1878
1837
  }
1838
+ for (const idx of Object.keys(fkByTableName)) {
1839
+ const value = fkByTableName[idx];
1840
+ result[value.tableFrom].foreignKeys[value.name] = value;
1841
+ }
1842
+ } catch (e) {
1879
1843
  }
1880
- };
1881
- exports.TaskView = TaskView2;
1882
- var TaskTerminal = class {
1883
- constructor(view, stdout) {
1884
- this.view = view;
1885
- this.stdout = stdout;
1886
- this.text = "";
1887
- this.view.attach(this);
1844
+ if (progressCallback) {
1845
+ progressCallback("fks", foreignKeysCount, "done");
1888
1846
  }
1889
- requestLayout() {
1890
- const string = this.view.render("pending");
1891
- const clearPrefix = this.text ? (0, utils_1.clear)(this.text, this.stdout.columns) : "";
1892
- this.text = string;
1893
- this.stdout.write(`${clearPrefix}${string}`);
1847
+ const idxs = await db.query(
1848
+ `SELECT
1849
+ m.tbl_name as tableName,
1850
+ il.name as indexName,
1851
+ ii.name as columnName,
1852
+ il.[unique] as isUnique,
1853
+ il.seq as seq
1854
+ FROM sqlite_master AS m,
1855
+ pragma_index_list(m.name) AS il,
1856
+ pragma_index_info(il.name) AS ii
1857
+ WHERE
1858
+ m.type = 'table' and il.name NOT LIKE 'sqlite_autoindex_%';`
1859
+ );
1860
+ for (const idxRow of idxs) {
1861
+ const tableName = idxRow.tableName;
1862
+ const constraintName = idxRow.indexName;
1863
+ const columnName = idxRow.columnName;
1864
+ const isUnique = idxRow.isUnique === 1;
1865
+ const tableInResult = result[tableName];
1866
+ if (typeof tableInResult === "undefined")
1867
+ continue;
1868
+ indexesCount += 1;
1869
+ if (progressCallback) {
1870
+ progressCallback("indexes", indexesCount, "fetching");
1871
+ }
1872
+ if (typeof tableInResult.indexes[constraintName] !== "undefined") {
1873
+ tableInResult.indexes[constraintName].columns.push(columnName);
1874
+ } else {
1875
+ tableInResult.indexes[constraintName] = {
1876
+ name: constraintName,
1877
+ columns: [columnName],
1878
+ isUnique
1879
+ };
1880
+ }
1894
1881
  }
1895
- clear() {
1896
- const string = this.view.render("done");
1897
- this.view.detach(this);
1898
- const clearPrefix = this.text ? (0, utils_1.clear)(this.text, this.stdout.columns) : "";
1899
- this.stdout.write(`${clearPrefix}${string}`);
1882
+ if (progressCallback) {
1883
+ progressCallback("indexes", indexesCount, "done");
1884
+ progressCallback("enums", 0, "done");
1900
1885
  }
1886
+ return {
1887
+ version: "5",
1888
+ dialect: "sqlite",
1889
+ tables: result,
1890
+ enums: {},
1891
+ _meta: {
1892
+ tables: {},
1893
+ columns: {}
1894
+ }
1895
+ };
1901
1896
  };
1902
- exports.TaskTerminal = TaskTerminal;
1903
- function render2(view) {
1904
- const { stdin, stdout, closable } = (0, readline_1.prepareReadLine)();
1905
- if (view instanceof Prompt2) {
1906
- const terminal = new Terminal(view, stdin, stdout, closable);
1907
- terminal.requestLayout();
1908
- return terminal.result();
1909
- }
1910
- stdout.write(`${view}
1911
- `);
1912
- closable.close();
1913
- return;
1914
- }
1915
- exports.render = render2;
1916
- function renderWithTask3(view, task) {
1917
- return __awaiter(this, void 0, void 0, function* () {
1918
- const terminal = new TaskTerminal(view, process.stdout);
1919
- terminal.requestLayout();
1920
- const result = yield task;
1921
- terminal.clear();
1922
- return result;
1897
+ toDrizzle2 = (schema) => {
1898
+ const tables = {};
1899
+ Object.values(schema.tables).forEach((t) => {
1900
+ const columns = {};
1901
+ Object.values(t.columns).forEach((c) => {
1902
+ const columnName = c.name;
1903
+ const type = c.type;
1904
+ let columnBuilder;
1905
+ if (type === "integer") {
1906
+ columnBuilder = new SQLiteIntegerBuilder(columnName);
1907
+ } else if (type === "text") {
1908
+ columnBuilder = new SQLiteTextBuilder(columnName, {});
1909
+ } else if (type === "blob") {
1910
+ columnBuilder = new SQLiteBlobBufferBuilder(columnName);
1911
+ } else if (type === "real") {
1912
+ columnBuilder = new SQLiteRealBuilder(columnName);
1913
+ } else {
1914
+ columnBuilder = new SQLiteNumericBuilder(columnName);
1915
+ }
1916
+ if (c.notNull) {
1917
+ columnBuilder = columnBuilder.notNull();
1918
+ }
1919
+ if (c.default) {
1920
+ columnBuilder = columnBuilder.default(c.default);
1921
+ }
1922
+ if (c.primaryKey) {
1923
+ columnBuilder = columnBuilder.primaryKey();
1924
+ }
1925
+ columns[columnName] = columnBuilder;
1926
+ });
1927
+ tables[t.name] = sqliteTable(t.name, columns, (cb) => {
1928
+ const res = {};
1929
+ Object.values(t.compositePrimaryKeys).forEach((cpk) => {
1930
+ const gh = cpk.columns.map((c) => cb[c]);
1931
+ res[cpk.name] = new PrimaryKeyBuilder2(
1932
+ gh,
1933
+ cpk.name
1934
+ );
1935
+ });
1936
+ return res;
1937
+ });
1923
1938
  });
1924
- }
1925
- exports.renderWithTask = renderWithTask3;
1926
- var terminateHandler;
1927
- function onTerminate(callback) {
1928
- terminateHandler = callback;
1929
- }
1930
- exports.onTerminate = onTerminate;
1931
- }
1932
- });
1933
-
1934
- // src/cli/views.ts
1935
- var import_hanji;
1936
- var init_views = __esm({
1937
- "src/cli/views.ts"() {
1938
- init_source();
1939
- import_hanji = __toESM(require_hanji());
1939
+ return tables;
1940
+ };
1940
1941
  }
1941
1942
  });
1942
1943