drizzle-kit 0.20.5-e91a5f5 → 0.20.5

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