drizzle-kit 0.20.4-bf71f08 → 0.20.4-bfc36f4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (5) hide show
  1. package/bin.cjs +1027 -984
  2. package/package.json +4 -4
  3. package/utils-studio.js +1268 -1267
  4. package/utils-studio.mjs +1317 -1316
  5. package/utils.js +1028 -982
package/utils-studio.js CHANGED
@@ -542,1357 +542,1358 @@ 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) {
868
- }
869
- if (progressCallback) {
870
- progressCallback("columns", columnsCount, "done");
871
- progressCallback("indexes", indexesCount, "done");
872
- progressCallback("fks", foreignKeysCount, "done");
719
+ timerId = setTimeout(timerExpired, remainingWait(time));
873
720
  }
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
- };
721
+ function trailingEdge(time) {
722
+ timerId = void 0;
723
+ if (trailing && lastArgs) {
724
+ return invokeFunc(time);
893
725
  }
726
+ lastArgs = lastThis = void 0;
727
+ return result;
894
728
  }
895
- if (progressCallback) {
896
- progressCallback("enums", Object.keys(enumsToReturn).length, "done");
897
- }
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
- };
912
- };
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"
932
- };
933
- defaultForColumn = (column) => {
934
- if (column.data_type === "serial" || column.data_type === "smallserial" || column.data_type === "bigserial") {
935
- return void 0;
936
- }
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;
942
- }
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}'`;
958
- }
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}`;
729
+ function cancel() {
730
+ if (timerId !== void 0) {
731
+ clearTimeout(timerId);
966
732
  }
733
+ lastInvokeTime = 0;
734
+ lastArgs = lastCallTime = lastThis = timerId = void 0;
967
735
  }
968
- };
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();
1034
- }
1035
- if (c.default) {
1036
- columnBuilder = columnBuilder.default(c.default);
736
+ function flush() {
737
+ return timerId === void 0 ? result : trailingEdge(now());
738
+ }
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);
1037
747
  }
1038
- if (c.primaryKey) {
1039
- columnBuilder = columnBuilder.primaryKey();
748
+ if (maxing) {
749
+ timerId = setTimeout(timerExpired, wait);
750
+ return invokeFunc(lastCallTime);
1040
751
  }
1041
- columns[columnName] = columnBuilder;
1042
- });
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
- });
1055
- } 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
- });
1067
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
1068
775
  });
1069
- return tables;
1070
- };
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;
1071
806
  }
1072
807
  });
1073
808
 
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";
1108
- }
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");
1115
- init_serializer();
1116
- init_outputs();
1117
- init_source();
1118
- dialect2 = new import_sqlite_core.SQLiteSyncDialect();
1119
- fromDatabase2 = async (db, tablesFilter = (table) => true, progressCallback) => {
1120
- 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[^'']*';`
1131
- );
1132
- for (const s of seq) {
1133
- tablesWithSeq.push(s.name);
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
+ });
1134
818
  }
1135
- let columnsCount = 0;
1136
- let tablesCount = /* @__PURE__ */ new Set();
1137
- let indexesCount = 0;
1138
- 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");
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
+ }
1151
826
  }
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);
827
+ function rejected(value) {
828
+ try {
829
+ step(generator["throw"](value));
830
+ } catch (e) {
831
+ reject(e);
1163
832
  }
1164
833
  }
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;
834
+ function step(result) {
835
+ result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected);
1192
836
  }
837
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
838
+ });
839
+ };
840
+ var __importDefault = exports && exports.__importDefault || function(mod) {
841
+ return mod && mod.__esModule ? mod : { "default": mod };
842
+ };
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 = [];
1193
854
  }
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`
1201
- }
1202
- };
1203
- } else if (value.length === 1) {
1204
- result[key].columns[value[0]].primaryKey = true;
1205
- } else {
855
+ requestLayout() {
856
+ this.terminal.requestLayout();
857
+ }
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);
1206
865
  }
1207
866
  }
1208
- if (progressCallback) {
1209
- progressCallback("columns", columnsCount, "done");
1210
- progressCallback("tables", tablesCount.size, "done");
867
+ attach(terminal) {
868
+ this.terminal = terminal;
869
+ this.attachCallbacks.forEach((it) => it(terminal));
1211
870
  }
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`;
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;
1253
898
  }
1254
- for (const idx of Object.keys(fkByTableName)) {
1255
- const value = fkByTableName[idx];
1256
- result[value.tableFrom].foreignKeys[value.name] = value;
899
+ if (key.name === "up") {
900
+ this.selectedIdx -= 1;
901
+ this.selectedIdx = this.selectedIdx < 0 ? this.items.length - 1 : this.selectedIdx;
902
+ return true;
1257
903
  }
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");
904
+ return false;
1301
905
  }
906
+ };
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
+ });
1302
915
  return {
1303
- version: "5",
1304
- dialect: "sqlite",
1305
- tables: result,
1306
- enums: {},
1307
- _meta: {
1308
- tables: {},
1309
- columns: {}
1310
- }
916
+ resolve,
917
+ reject,
918
+ promise
1311
919
  };
1312
920
  };
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();
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);
1334
945
  }
1335
- if (c.default) {
1336
- 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;
1337
953
  }
1338
- if (c.primaryKey) {
1339
- 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;
1340
961
  }
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
1350
- );
1351
- });
1352
- return res;
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);
1353
971
  });
1354
- });
1355
- return tables;
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);
986
+ } else {
987
+ this.stdout.write(sisteransi_1.cursor.show);
988
+ }
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
+ }
1356
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;
1357
1072
  }
1358
1073
  });
1359
1074
 
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;
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());
1382
1081
  }
1383
1082
  });
1384
1083
 
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 };
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();
1443
1091
  }
1444
1092
  });
1445
1093
 
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;
1094
+ // src/cli/validations/outputs.ts
1095
+ var init_outputs = __esm({
1096
+ "src/cli/validations/outputs.ts"() {
1097
+ init_source();
1473
1098
  }
1474
1099
  });
1475
1100
 
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();
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");
1108
+ init_serializer();
1109
+ init_source();
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();
1496
1120
  };
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);
1121
+ fromDatabase = async (db, tablesFilter = (table) => true, schemaFilters, progressCallback) => {
1122
+ const result = {};
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};`
1127
+ );
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);
1547
1140
  }
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);
1141
+ });
1142
+ let columnsCount = 0;
1143
+ let indexesCount = 0;
1144
+ let foreignKeysCount = 0;
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");
1197
+ }
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}';`
1219
+ );
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
1283
+ WHERE contype = 'p'
1284
+ AND connamespace = '${tableSchema}'::regnamespace
1285
+ AND (conrelid::regclass::text = '"${tableName}"' OR conrelid::regclass::text = '${tableName}');`
1286
+ );
1287
+ primaryKeys[`${tableName}_${cprimaryKey.map((pk) => pk.column_name).join("_")}`] = {
1288
+ name: tableCompositePkName[0].primary_key,
1289
+ columns: cprimaryKey.map((c) => c.column_name)
1290
+ };
1291
+ }
1292
+ const defaultValue = defaultForColumn(columnResponse);
1293
+ const isSerial = columnType === "serial";
1294
+ let columnTypeMapped = columnType;
1295
+ if (columnTypeMapped.startsWith("numeric(")) {
1296
+ columnTypeMapped = columnTypeMapped.replace(",", ", ");
1297
+ }
1298
+ if (columnAdditionalDT === "ARRAY") {
1299
+ if (typeof internals.tables[tableName] === "undefined") {
1300
+ internals.tables[tableName] = {
1301
+ columns: {
1302
+ [columnName]: {
1303
+ isArray: true,
1304
+ dimensions: columnDimensions,
1305
+ rawType: columnTypeMapped.substring(
1306
+ 0,
1307
+ columnTypeMapped.length - 2
1308
+ )
1309
+ }
1310
+ }
1311
+ };
1312
+ } else {
1313
+ if (typeof internals.tables[tableName].columns[columnName] === "undefined") {
1314
+ internals.tables[tableName].columns[columnName] = {
1315
+ isArray: true,
1316
+ dimensions: columnDimensions,
1317
+ rawType: columnTypeMapped.substring(
1318
+ 0,
1319
+ columnTypeMapped.length - 2
1320
+ )
1321
+ };
1322
+ }
1323
+ }
1324
+ }
1325
+ if (columnAdditionalDT === "ARRAY") {
1326
+ for (let i = 1; i < Number(columnDimensions); i++) {
1327
+ columnTypeMapped += "[]";
1328
+ }
1329
+ }
1330
+ columnTypeMapped = columnTypeMapped.replace("character varying", "varchar").replace(" without time zone", "").replace("character", "char");
1331
+ columnTypeMapped = trimChar(columnTypeMapped, '"');
1332
+ columnToReturn[columnName] = {
1333
+ name: columnName,
1334
+ type: columnTypeMapped,
1335
+ primaryKey: primaryKey.length === 1 && cprimaryKey.length < 2,
1336
+ // default: isSerial ? undefined : defaultValue,
1337
+ notNull: columnResponse.is_nullable === "NO"
1338
+ };
1339
+ if (!isSerial && typeof defaultValue !== "undefined") {
1340
+ columnToReturn[columnName].default = defaultValue;
1341
+ }
1342
+ }
1343
+ const dbIndexes = await db.query(
1344
+ `SELECT t.relname as table_name, i.relname AS index_name, ix.indisunique AS is_unique, a.attname AS column_name
1345
+ FROM pg_class t
1346
+ JOIN pg_index ix ON t.oid = ix.indrelid
1347
+ JOIN pg_class i ON i.oid = ix.indexrelid
1348
+ JOIN pg_attribute a ON a.attrelid = t.oid AND a.attnum = ANY(ix.indkey)
1349
+ JOIN pg_namespace ns ON ns.oid = t.relnamespace
1350
+ WHERE ns.nspname = '${tableSchema}'
1351
+ AND t.relname = '${tableName}'
1352
+ and ix.indisprimary = false;`
1353
+ );
1354
+ const dbIndexFromConstraint = await db.query(
1355
+ `SELECT
1356
+ idx.indexrelname AS index_name,
1357
+ idx.relname AS table_name,
1358
+ schemaname,
1359
+ CASE WHEN con.conname IS NOT NULL THEN 1 ELSE 0 END AS generated_by_constraint
1360
+ FROM
1361
+ pg_stat_user_indexes idx
1362
+ LEFT JOIN
1363
+ pg_constraint con ON con.conindid = idx.indexrelid
1364
+ WHERE idx.relname = '${tableName}' and schemaname = '${tableSchema}'
1365
+ group by index_name, table_name,schemaname, generated_by_constraint;`
1366
+ );
1367
+ const idxsInConsteraint = dbIndexFromConstraint.filter((it) => it.generated_by_constraint === 1).map((it) => it.index_name);
1368
+ for (const dbIndex of dbIndexes) {
1369
+ const indexName2 = dbIndex.index_name;
1370
+ const indexColumnName = dbIndex.column_name;
1371
+ const indexIsUnique = dbIndex.is_unique;
1372
+ if (idxsInConsteraint.includes(indexName2))
1373
+ continue;
1374
+ if (typeof indexToReturn[indexName2] !== "undefined") {
1375
+ indexToReturn[indexName2].columns.push(indexColumnName);
1376
+ } else {
1377
+ indexToReturn[indexName2] = {
1378
+ name: indexName2,
1379
+ columns: [indexColumnName],
1380
+ isUnique: indexIsUnique
1381
+ };
1382
+ }
1383
+ }
1384
+ indexesCount += Object.keys(indexToReturn).length;
1385
+ if (progressCallback) {
1386
+ progressCallback("indexes", indexesCount, "fetching");
1387
+ }
1388
+ result[tableName] = {
1389
+ name: tableName,
1390
+ schema: tableSchema !== "public" ? tableSchema : "",
1391
+ columns: columnToReturn,
1392
+ indexes: indexToReturn,
1393
+ foreignKeys: foreignKeysToReturn,
1394
+ compositePrimaryKeys: primaryKeys,
1395
+ uniqueConstraints: uniqueConstrains
1396
+ };
1397
+ } catch (e) {
1398
+ rej(e);
1399
+ return;
1566
1400
  }
1567
- }
1568
- if (timerId === void 0) {
1569
- timerId = setTimeout(timerExpired, wait);
1570
- }
1571
- return result;
1401
+ res("");
1402
+ });
1403
+ });
1404
+ if (progressCallback) {
1405
+ progressCallback("tables", tableCount, "done");
1572
1406
  }
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);
1407
+ for await (const _ of all) {
1581
1408
  }
1582
- if (isObject(options)) {
1583
- leading = "leading" in options ? !!options.leading : leading;
1584
- trailing = "trailing" in options ? !!options.trailing : trailing;
1409
+ if (progressCallback) {
1410
+ progressCallback("columns", columnsCount, "done");
1411
+ progressCallback("indexes", indexesCount, "done");
1412
+ progressCallback("fks", foreignKeysCount, "done");
1585
1413
  }
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;
1414
+ const allEnums = await db.query(
1415
+ `select n.nspname as enum_schema,
1416
+ t.typname as enum_name,
1417
+ e.enumlabel as enum_value
1418
+ from pg_type t
1419
+ join pg_enum e on t.oid = e.enumtypid
1420
+ join pg_catalog.pg_namespace n ON n.oid = t.typnamespace;`
1421
+ );
1422
+ const enumsToReturn = {};
1423
+ for (const dbEnum of allEnums) {
1424
+ const enumName = dbEnum.enum_name;
1425
+ const enumValue = dbEnum.enum_value;
1426
+ if (enumsToReturn[enumName] !== void 0 && enumsToReturn[enumName] !== null) {
1427
+ enumsToReturn[enumName].values[enumValue] = enumValue;
1428
+ } else {
1429
+ enumsToReturn[enumName] = {
1430
+ name: enumName,
1431
+ values: { [enumValue]: enumValue }
1432
+ };
1433
+ }
1605
1434
  }
1606
- if (isSymbol(value)) {
1607
- return NAN;
1435
+ if (progressCallback) {
1436
+ progressCallback("enums", Object.keys(enumsToReturn).length, "done");
1608
1437
  }
1609
- if (isObject(value)) {
1610
- var other = typeof value.valueOf == "function" ? value.valueOf() : value;
1611
- value = isObject(other) ? other + "" : other;
1438
+ const schemasObject = Object.fromEntries([...schemas].map((it) => [it, it]));
1439
+ return {
1440
+ version: "5",
1441
+ dialect: "pg",
1442
+ tables: result,
1443
+ enums: enumsToReturn,
1444
+ schemas: schemasObject,
1445
+ _meta: {
1446
+ schemas: {},
1447
+ tables: {},
1448
+ columns: {}
1449
+ },
1450
+ internal: internals
1451
+ };
1452
+ };
1453
+ columnToDefault = {
1454
+ "numeric(": "::numeric",
1455
+ // text: "::text",
1456
+ // "character varying": "::character varying",
1457
+ // "double precision": "::double precision",
1458
+ // "time with time zone": "::time with time zone",
1459
+ "time without time zone": "::time without time zone",
1460
+ // "timestamp with time zone": "::timestamp with time zone",
1461
+ "timestamp without time zone": "::timestamp without time zone",
1462
+ // date: "::date",
1463
+ // interval: "::interval",
1464
+ // character: "::bpchar",
1465
+ // macaddr8: "::macaddr8",
1466
+ // macaddr: "::macaddr",
1467
+ // inet: "::inet",
1468
+ // cidr: "::cidr",
1469
+ // jsonb: "::jsonb",
1470
+ // json: "::json",
1471
+ "character(": "::bpchar"
1472
+ };
1473
+ defaultForColumn = (column) => {
1474
+ if (column.data_type === "serial" || column.data_type === "smallserial" || column.data_type === "bigserial") {
1475
+ return void 0;
1612
1476
  }
1613
- if (typeof value != "string") {
1614
- return value === 0 ? value : +value;
1477
+ const hasDifferentDefaultCast = Object.keys(columnToDefault).find(
1478
+ (it) => column.data_type.startsWith(it)
1479
+ );
1480
+ if (column.column_default === null) {
1481
+ return void 0;
1615
1482
  }
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
- });
1483
+ const columnDefaultAsString = column.column_default.toString();
1484
+ if (columnDefaultAsString.endsWith(
1485
+ hasDifferentDefaultCast ? columnToDefault[hasDifferentDefaultCast] : column.data_type
1486
+ )) {
1487
+ const nonPrefixPart = column.column_default.length - (hasDifferentDefaultCast ? columnToDefault[hasDifferentDefaultCast] : `::${column.data_type}`).length - 1;
1488
+ const rt = column.column_default.toString().substring(1, nonPrefixPart);
1489
+ if (/^-?[\d.]+(?:e-?\d+)?$/.test(rt) && !column.data_type.startsWith("numeric")) {
1490
+ return Number(rt);
1491
+ } else if (column.data_type === "json" || column.data_type === "jsonb") {
1492
+ const jsonWithoutSpaces = JSON.stringify(JSON.parse(rt));
1493
+ return `'${jsonWithoutSpaces}'${hasDifferentDefaultCast ? columnToDefault[hasDifferentDefaultCast] : `::${column.data_type}`}`;
1494
+ } else if (column.data_type === "boolean") {
1495
+ return column.column_default === "true";
1496
+ } else {
1497
+ return `'${rt}'`;
1498
+ }
1499
+ } else {
1500
+ if (/^-?[\d.]+(?:e-?\d+)?$/.test(columnDefaultAsString) && !column.data_type.startsWith("numeric")) {
1501
+ return Number(columnDefaultAsString);
1502
+ } else if (column.data_type === "boolean") {
1503
+ return column.column_default === "true";
1504
+ } else {
1505
+ return `${columnDefaultAsString}`;
1506
+ }
1633
1507
  }
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);
1508
+ };
1509
+ toDrizzle = (schema, schemaName) => {
1510
+ const tables = {};
1511
+ Object.values(schema.tables).forEach((t) => {
1512
+ const columns = {};
1513
+ Object.values(t.columns).forEach((c) => {
1514
+ const columnName = c.name;
1515
+ const type = c.type;
1516
+ let columnBuilder;
1517
+ if (type === "bigint") {
1518
+ columnBuilder = new import_pg_core.PgBigInt53Builder(columnName);
1519
+ } else if (type === "bigserial") {
1520
+ columnBuilder = new import_pg_core.PgBigSerial53Builder(columnName);
1521
+ } else if (type === "boolean") {
1522
+ columnBuilder = new import_pg_core.PgBooleanBuilder(columnName);
1523
+ } else if (type === "cidr") {
1524
+ columnBuilder = new import_pg_core.PgCidrBuilder(columnName);
1525
+ } else if (type === "date") {
1526
+ columnBuilder = new import_pg_core.PgDateBuilder(columnName);
1527
+ } else if (type === "double precision") {
1528
+ columnBuilder = new import_pg_core.PgDoublePrecisionBuilder(columnName);
1529
+ } else if (type === "inet") {
1530
+ columnBuilder = new import_pg_core.PgInetBuilder(columnName);
1531
+ } else if (type === "integer") {
1532
+ columnBuilder = new import_pg_core.PgIntegerBuilder(columnName);
1533
+ } else if (type === "interval" || type.startsWith("interval ")) {
1534
+ columnBuilder = new import_pg_core.PgIntervalBuilder(columnName, {});
1535
+ } else if (type === "json") {
1536
+ columnBuilder = new import_pg_core.PgJsonBuilder(columnName);
1537
+ } else if (type === "jsonb") {
1538
+ columnBuilder = new import_pg_core.PgJsonbBuilder(columnName);
1539
+ } else if (type === "macaddr") {
1540
+ columnBuilder = new import_pg_core.PgMacaddrBuilder(columnName);
1541
+ } else if (type === "macaddr8") {
1542
+ columnBuilder = new import_pg_core.PgMacaddr8Builder(columnName);
1543
+ } else if (type === "numeric" || type.startsWith("numeric(")) {
1544
+ columnBuilder = new import_pg_core.PgNumericBuilder(columnName);
1545
+ } else if (type === "real") {
1546
+ columnBuilder = new import_pg_core.PgRealBuilder(columnName);
1547
+ } else if (type === "serial") {
1548
+ columnBuilder = new import_pg_core.PgSerialBuilder(columnName);
1549
+ } else if (type === "smallint") {
1550
+ columnBuilder = new import_pg_core.PgSmallIntBuilder(columnName);
1551
+ } else if (type === "smallserial") {
1552
+ columnBuilder = new import_pg_core.PgSmallSerialBuilder(columnName);
1553
+ } else if (type === "text") {
1554
+ columnBuilder = new import_pg_core.PgTextBuilder(columnName, {});
1555
+ } else if (type === "time" || type.startsWith("time(") || type === "time with time zone") {
1556
+ columnBuilder = new import_pg_core.PgTimeBuilder(columnName, false, void 0);
1557
+ } else if (type === "timestamp" || type.startsWith("timestamp(") || type === "timestamp with time zone") {
1558
+ columnBuilder = new import_pg_core.PgTimestampBuilder(columnName, false, void 0);
1559
+ } else if (type === "uuid") {
1560
+ columnBuilder = new import_pg_core.PgUUIDBuilder(columnName);
1561
+ } else if (type === "varchar" || type.startsWith("varchar(")) {
1562
+ columnBuilder = new import_pg_core.PgVarcharBuilder(columnName, {});
1563
+ } else if (type === "char" || type.startsWith("char(")) {
1564
+ columnBuilder = new import_pg_core.PgCharBuilder(columnName, {});
1565
+ } else {
1566
+ columnBuilder = (0, import_pg_core.customType)({
1567
+ dataType() {
1568
+ return type;
1569
+ }
1570
+ })(columnName);
1640
1571
  }
1641
- }
1642
- function rejected(value) {
1643
- try {
1644
- step(generator["throw"](value));
1645
- } catch (e) {
1646
- reject(e);
1572
+ if (c.notNull) {
1573
+ columnBuilder = columnBuilder.notNull();
1647
1574
  }
1575
+ if (c.default) {
1576
+ columnBuilder = columnBuilder.default(c.default);
1577
+ }
1578
+ if (c.primaryKey) {
1579
+ columnBuilder = columnBuilder.primaryKey();
1580
+ }
1581
+ columns[columnName] = columnBuilder;
1582
+ });
1583
+ if (schemaName === "public") {
1584
+ tables[t.name] = (0, import_pg_core.pgTable)(t.name, columns, (cb) => {
1585
+ const res = {};
1586
+ Object.values(t.compositePrimaryKeys).forEach((cpk) => {
1587
+ const gh = cpk.columns.map((c) => cb[c]);
1588
+ res[cpk.name] = new import_pg_core.PrimaryKeyBuilder(
1589
+ gh,
1590
+ cpk.name
1591
+ );
1592
+ });
1593
+ return res;
1594
+ });
1595
+ } else {
1596
+ tables[t.name] = (0, import_pg_core.pgSchema)(schemaName).table(t.name, columns, (cb) => {
1597
+ const res = {};
1598
+ Object.values(t.compositePrimaryKeys).forEach((cpk) => {
1599
+ const gh = cpk.columns.map((c) => cb[c]);
1600
+ res[cpk.name] = new import_pg_core.PrimaryKeyBuilder(
1601
+ gh,
1602
+ cpk.name
1603
+ );
1604
+ });
1605
+ return res;
1606
+ });
1648
1607
  }
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
1608
  });
1609
+ return tables;
1654
1610
  };
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
- });
1611
+ }
1612
+ });
1613
+
1614
+ // src/serializer/sqliteSerializer.ts
1615
+ function mapSqlToSqliteType(sqlType) {
1616
+ if ([
1617
+ "int",
1618
+ "integer",
1619
+ "integer auto_increment",
1620
+ "tinyint",
1621
+ "smallint",
1622
+ "mediumint",
1623
+ "bigint",
1624
+ "unsigned big int",
1625
+ "int2",
1626
+ "int8"
1627
+ ].includes(sqlType.toLowerCase())) {
1628
+ return "integer";
1629
+ } else if ([
1630
+ "character",
1631
+ "varchar",
1632
+ "vatying character",
1633
+ "nchar",
1634
+ "native character",
1635
+ "nvarchar",
1636
+ "text",
1637
+ "clob"
1638
+ ].some((it) => it.startsWith(sqlType.toLowerCase()))) {
1639
+ return "text";
1640
+ } else if (sqlType.toLowerCase() === "blob") {
1641
+ return "blob";
1642
+ } else if (["real", "double", "double precision", "float"].includes(
1643
+ sqlType.toLowerCase()
1644
+ )) {
1645
+ return "real";
1646
+ } else {
1647
+ return "numeric";
1648
+ }
1649
+ }
1650
+ var import_drizzle_orm2, import_sqlite_core, dialect2, fromDatabase2, toDrizzle2;
1651
+ var init_sqliteSerializer = __esm({
1652
+ "src/serializer/sqliteSerializer.ts"() {
1653
+ import_drizzle_orm2 = require("drizzle-orm");
1654
+ import_sqlite_core = require("drizzle-orm/sqlite-core");
1655
+ init_serializer();
1656
+ init_outputs();
1657
+ init_source();
1658
+ dialect2 = new import_sqlite_core.SQLiteSyncDialect();
1659
+ fromDatabase2 = async (db, tablesFilter = (table) => true, progressCallback) => {
1660
+ const result = {};
1661
+ const columns = await db.query(
1662
+ `SELECT
1663
+ 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
1664
+ FROM sqlite_master AS m JOIN pragma_table_info(m.name) AS p
1665
+ 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';
1666
+ `
1667
+ );
1668
+ const tablesWithSeq = [];
1669
+ const seq = await db.query(
1670
+ `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[^'']*';`
1671
+ );
1672
+ for (const s of seq) {
1673
+ tablesWithSeq.push(s.name);
1706
1674
  }
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;
1675
+ let columnsCount = 0;
1676
+ let tablesCount = /* @__PURE__ */ new Set();
1677
+ let indexesCount = 0;
1678
+ let foreignKeysCount = 0;
1679
+ const tableToPk = {};
1680
+ for (const column of columns) {
1681
+ if (!tablesFilter(column.tableName))
1682
+ continue;
1683
+ columnsCount += 1;
1684
+ if (progressCallback) {
1685
+ progressCallback("columns", columnsCount, "fetching");
1713
1686
  }
1714
- if (key.name === "up") {
1715
- this.selectedIdx -= 1;
1716
- this.selectedIdx = this.selectedIdx < 0 ? this.items.length - 1 : this.selectedIdx;
1717
- return true;
1687
+ const tableName = column.tableName;
1688
+ tablesCount.add(tableName);
1689
+ if (progressCallback) {
1690
+ progressCallback("tables", tablesCount.size, "fetching");
1718
1691
  }
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;
1692
+ const columnName = column.columnName;
1693
+ const isNotNull = column.notNull === 1;
1694
+ const columnType = column.columnType;
1695
+ const isPrimary = column.pk !== 0;
1696
+ const columnDefault = column.defaultValue;
1697
+ const isAutoincrement = isPrimary && tablesWithSeq.includes(tableName);
1698
+ if (isPrimary) {
1699
+ if (typeof tableToPk[tableName] === "undefined") {
1700
+ tableToPk[tableName] = [columnName];
1701
+ } else {
1702
+ tableToPk[tableName].push(columnName);
1776
1703
  }
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);
1704
+ }
1705
+ const table = result[tableName];
1706
+ const newColumn = {
1707
+ default: columnDefault === null ? void 0 : /^-?[\d.]+(?:e-?\d+)?$/.test(columnDefault) ? Number(columnDefault) : ["CURRENT_TIME", "CURRENT_DATE", "CURRENT_TIMESTAMP"].includes(
1708
+ columnDefault
1709
+ ) ? `(${columnDefault})` : columnDefault === "false" ? false : columnDefault === "true" ? true : columnDefault.startsWith("'") && columnDefault.endsWith("'") ? columnDefault : (
1710
+ // ? columnDefault.substring(1, columnDefault.length - 1)
1711
+ `(${columnDefault})`
1712
+ ),
1713
+ autoincrement: isAutoincrement,
1714
+ name: columnName,
1715
+ type: mapSqlToSqliteType(columnType),
1716
+ primaryKey: false,
1717
+ notNull: isNotNull
1718
+ };
1719
+ if (!table) {
1720
+ result[tableName] = {
1721
+ name: tableName,
1722
+ columns: {
1723
+ [columnName]: newColumn
1724
+ },
1725
+ compositePrimaryKeys: {},
1726
+ indexes: {},
1727
+ foreignKeys: {},
1728
+ uniqueConstraints: {}
1729
+ };
1801
1730
  } else {
1802
- this.stdout.write(sisteransi_1.cursor.show);
1731
+ result[tableName].columns[columnName] = newColumn;
1803
1732
  }
1804
1733
  }
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));
1734
+ for (const [key, value] of Object.entries(tableToPk)) {
1735
+ if (value.length > 1) {
1736
+ value.sort();
1737
+ result[key].compositePrimaryKeys = {
1738
+ [`${key}_${value.join("_")}_pk`]: {
1739
+ columns: value,
1740
+ name: `${key}_${value.join("_")}_pk`
1741
+ }
1742
+ };
1743
+ } else if (value.length === 1) {
1744
+ result[key].columns[value[0]].primaryKey = true;
1745
+ } else {
1746
+ }
1824
1747
  }
1825
- detach(terminal) {
1826
- this.detachCallbacks.forEach((it) => it(terminal));
1827
- this.terminal = void 0;
1748
+ if (progressCallback) {
1749
+ progressCallback("columns", columnsCount, "done");
1750
+ progressCallback("tables", tablesCount.size, "done");
1828
1751
  }
1829
- on(type, callback) {
1830
- if (type === "attach") {
1831
- this.attachCallbacks.push(callback);
1832
- } else if (type === "detach") {
1833
- this.detachCallbacks.push(callback);
1752
+ try {
1753
+ const fks = await db.query(
1754
+ `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"
1755
+ FROM sqlite_master m, pragma_foreign_key_list(m.name) as f;`
1756
+ );
1757
+ const fkByTableName = {};
1758
+ for (const fkRow of fks) {
1759
+ foreignKeysCount += 1;
1760
+ if (progressCallback) {
1761
+ progressCallback("fks", foreignKeysCount, "fetching");
1762
+ }
1763
+ const tableName = fkRow.tableFrom;
1764
+ const columnName = fkRow.from;
1765
+ const refTableName = fkRow.tableTo;
1766
+ const refColumnName = fkRow.to;
1767
+ const updateRule = fkRow.onUpdate;
1768
+ const deleteRule = fkRow.onDelete;
1769
+ const sequence = fkRow.seq;
1770
+ const id = fkRow.id;
1771
+ const tableInResult = result[tableName];
1772
+ if (typeof tableInResult === "undefined")
1773
+ continue;
1774
+ if (typeof fkByTableName[`${tableName}_${id}`] !== "undefined") {
1775
+ fkByTableName[`${tableName}_${id}`].columnsFrom.push(columnName);
1776
+ fkByTableName[`${tableName}_${id}`].columnsTo.push(refColumnName);
1777
+ } else {
1778
+ fkByTableName[`${tableName}_${id}`] = {
1779
+ name: "",
1780
+ tableFrom: tableName,
1781
+ tableTo: refTableName,
1782
+ columnsFrom: [columnName],
1783
+ columnsTo: [refColumnName],
1784
+ onDelete: deleteRule == null ? void 0 : deleteRule.toLowerCase(),
1785
+ onUpdate: updateRule == null ? void 0 : updateRule.toLowerCase()
1786
+ };
1787
+ }
1788
+ const columnsFrom = fkByTableName[`${tableName}_${id}`].columnsFrom;
1789
+ const columnsTo = fkByTableName[`${tableName}_${id}`].columnsTo;
1790
+ fkByTableName[`${tableName}_${id}`].name = `${tableName}_${columnsFrom.join(
1791
+ "_"
1792
+ )}_${refTableName}_${columnsTo.join("_")}_fk`;
1834
1793
  }
1794
+ for (const idx of Object.keys(fkByTableName)) {
1795
+ const value = fkByTableName[idx];
1796
+ result[value.tableFrom].foreignKeys[value.name] = value;
1797
+ }
1798
+ } catch (e) {
1835
1799
  }
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);
1800
+ if (progressCallback) {
1801
+ progressCallback("fks", foreignKeysCount, "done");
1844
1802
  }
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}`);
1803
+ const idxs = await db.query(
1804
+ `SELECT
1805
+ m.tbl_name as tableName,
1806
+ il.name as indexName,
1807
+ ii.name as columnName,
1808
+ il.[unique] as isUnique,
1809
+ il.seq as seq
1810
+ FROM sqlite_master AS m,
1811
+ pragma_index_list(m.name) AS il,
1812
+ pragma_index_info(il.name) AS ii
1813
+ WHERE
1814
+ m.type = 'table' and il.name NOT LIKE 'sqlite_autoindex_%';`
1815
+ );
1816
+ for (const idxRow of idxs) {
1817
+ const tableName = idxRow.tableName;
1818
+ const constraintName = idxRow.indexName;
1819
+ const columnName = idxRow.columnName;
1820
+ const isUnique = idxRow.isUnique === 1;
1821
+ const tableInResult = result[tableName];
1822
+ if (typeof tableInResult === "undefined")
1823
+ continue;
1824
+ indexesCount += 1;
1825
+ if (progressCallback) {
1826
+ progressCallback("indexes", indexesCount, "fetching");
1827
+ }
1828
+ if (typeof tableInResult.indexes[constraintName] !== "undefined") {
1829
+ tableInResult.indexes[constraintName].columns.push(columnName);
1830
+ } else {
1831
+ tableInResult.indexes[constraintName] = {
1832
+ name: constraintName,
1833
+ columns: [columnName],
1834
+ isUnique
1835
+ };
1836
+ }
1850
1837
  }
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}`);
1838
+ if (progressCallback) {
1839
+ progressCallback("indexes", indexesCount, "done");
1840
+ progressCallback("enums", 0, "done");
1856
1841
  }
1842
+ return {
1843
+ version: "5",
1844
+ dialect: "sqlite",
1845
+ tables: result,
1846
+ enums: {},
1847
+ _meta: {
1848
+ tables: {},
1849
+ columns: {}
1850
+ }
1851
+ };
1857
1852
  };
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;
1853
+ toDrizzle2 = (schema) => {
1854
+ const tables = {};
1855
+ Object.values(schema.tables).forEach((t) => {
1856
+ const columns = {};
1857
+ Object.values(t.columns).forEach((c) => {
1858
+ const columnName = c.name;
1859
+ const type = c.type;
1860
+ let columnBuilder;
1861
+ if (type === "integer") {
1862
+ columnBuilder = new import_sqlite_core.SQLiteIntegerBuilder(columnName);
1863
+ } else if (type === "text") {
1864
+ columnBuilder = new import_sqlite_core.SQLiteTextBuilder(columnName, {});
1865
+ } else if (type === "blob") {
1866
+ columnBuilder = new import_sqlite_core.SQLiteBlobBufferBuilder(columnName);
1867
+ } else if (type === "real") {
1868
+ columnBuilder = new import_sqlite_core.SQLiteRealBuilder(columnName);
1869
+ } else {
1870
+ columnBuilder = new import_sqlite_core.SQLiteNumericBuilder(columnName);
1871
+ }
1872
+ if (c.notNull) {
1873
+ columnBuilder = columnBuilder.notNull();
1874
+ }
1875
+ if (c.default) {
1876
+ columnBuilder = columnBuilder.default(c.default);
1877
+ }
1878
+ if (c.primaryKey) {
1879
+ columnBuilder = columnBuilder.primaryKey();
1880
+ }
1881
+ columns[columnName] = columnBuilder;
1882
+ });
1883
+ tables[t.name] = (0, import_sqlite_core.sqliteTable)(t.name, columns, (cb) => {
1884
+ const res = {};
1885
+ Object.values(t.compositePrimaryKeys).forEach((cpk) => {
1886
+ const gh = cpk.columns.map((c) => cb[c]);
1887
+ res[cpk.name] = new import_sqlite_core.PrimaryKeyBuilder(
1888
+ gh,
1889
+ cpk.name
1890
+ );
1891
+ });
1892
+ return res;
1893
+ });
1879
1894
  });
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());
1895
+ return tables;
1896
+ };
1896
1897
  }
1897
1898
  });
1898
1899