drizzle-kit 0.20.5-1f065b5 → 0.20.5-440d034

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