drizzle-kit 0.20.5-c7dc2fe → 0.20.5-fd4dd75

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