qubu 0.6.0 → 0.6.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (65) hide show
  1. package/README.md +112 -0
  2. package/dist/codegen.d.mts +1 -1
  3. package/dist/codegen.mjs +1 -1
  4. package/dist/{column-r1Y4ivwt.mjs → column-BzN8KFJa.mjs} +39 -2
  5. package/dist/{column-Da37jYSD.mjs → column-CFvSbil0.mjs} +1 -1
  6. package/dist/{complete-types-CY0KbzNw.d.mts → complete-types-CNMWBWap.d.mts} +1 -1
  7. package/dist/{constraints-YGyNPQ_z.mjs → constraints-DM_tarXc.mjs} +2 -2
  8. package/dist/core.d.mts +1 -1
  9. package/dist/core.mjs +2 -3
  10. package/dist/diagnostics-I9vVtXkc.mjs +40 -0
  11. package/dist/diff.d.mts +2 -2
  12. package/dist/expressions-BCjc08zw.mjs +129 -0
  13. package/dist/{index-B2rZf3-2.d.mts → index-CGui70hi.d.mts} +2 -2
  14. package/dist/index.d.mts +2 -2
  15. package/dist/index.mjs +58 -15
  16. package/dist/introspection/mysql.d.mts +26 -0
  17. package/dist/introspection/mysql.mjs +1145 -0
  18. package/dist/introspection/postgres.d.mts +40 -0
  19. package/dist/introspection/postgres.mjs +1554 -0
  20. package/dist/introspection/sqlite.d.mts +15 -0
  21. package/dist/introspection/sqlite.mjs +986 -0
  22. package/dist/introspection.d.mts +3 -78
  23. package/dist/introspection.mjs +5 -3683
  24. package/dist/mysql.d.mts +1 -1
  25. package/dist/mysql.mjs +2 -2
  26. package/dist/{on-conflict-DZQ85f1t.mjs → on-conflict-CnaY5qso.mjs} +76 -4
  27. package/dist/postgres-Dey7QXPL.mjs +69 -0
  28. package/dist/postgres.d.mts +3 -3
  29. package/dist/postgres.mjs +3 -52
  30. package/dist/registry-oWDiqD7i.mjs +127 -0
  31. package/dist/{relational-CxnLCqZQ.mjs → relational-DSAJ-l58.mjs} +1 -2
  32. package/dist/schema.d.mts +1 -1
  33. package/dist/schema.mjs +7 -6
  34. package/dist/{serialize-BN07IK0v.mjs → serialize-CE-gw5_s.mjs} +3 -3
  35. package/dist/{serialize-CEIIlWhC.d.mts → serialize-OvXCLzjm.d.mts} +1 -1
  36. package/dist/snapshot/mysql.d.mts +2 -2
  37. package/dist/snapshot/mysql.mjs +28 -28
  38. package/dist/snapshot/postgres.d.mts +4 -4
  39. package/dist/snapshot/postgres.mjs +21 -21
  40. package/dist/snapshot/sqlite.d.mts +4 -4
  41. package/dist/snapshot/sqlite.mjs +27 -27
  42. package/dist/{snapshot-Xam8-q0j.mjs → snapshot-DgsOhf_8.mjs} +4 -42
  43. package/dist/snapshot.d.mts +4 -4
  44. package/dist/snapshot.mjs +1 -1
  45. package/dist/{source-SqrKWjFJ.mjs → source-BDuUXmAk.mjs} +2 -2
  46. package/dist/sqlite.d.mts +1 -1
  47. package/dist/sqlite.mjs +6 -6
  48. package/dist/{table-BwflqeAj.mjs → table-C1QGNe4P.mjs} +3 -3
  49. package/dist/{types-CTCqtFlS.d.mts → types-BEn0N_al.d.mts} +1 -1
  50. package/dist/{types-BIJsj2fJ.mjs → types-BLNRatG_.mjs} +2 -4
  51. package/dist/{types-C0VkiwpR.d.mts → types-DUe6eeI0.d.mts} +57 -28
  52. package/docs/guides/compose-queries.md +22 -0
  53. package/docs/guides/drizzle.md +11 -11
  54. package/docs/guides/mutations.md +89 -0
  55. package/docs/guides/valtio-sync.md +113 -0
  56. package/docs/migrations/index.md +50 -12
  57. package/docs/migrations/operations.md +20 -6
  58. package/docs/reference/supported-surface.md +17 -6
  59. package/docs/schema/code-generation.md +3 -2
  60. package/docs/schema/introspection.md +3 -2
  61. package/docs/sql-semantic-types.md +8 -0
  62. package/package.json +13 -1
  63. package/dist/registry-BRcUuazJ.mjs +0 -256
  64. package/dist/standard-DfcZEVOj.mjs +0 -12
  65. package/dist/value-D14I_XgL.mjs +0 -29
@@ -1,5 +1,6 @@
1
1
  import { a as toSnapshotJsonValue } from "./canonical-DMvR9yBe.mjs";
2
- import { a as hasIntrospectionErrors, i as createIntrospectionDiagnostic, n as introspectedPhysicalIdentityPolicy, r as IntrospectionError, t as mapCatalogToSnapshot } from "./snapshot-Xam8-q0j.mjs";
2
+ import { n as createIntrospectionDiagnostic, r as hasIntrospectionErrors, t as IntrospectionError } from "./diagnostics-I9vVtXkc.mjs";
3
+ import { n as introspectedPhysicalIdentityPolicy, t as mapCatalogToSnapshot } from "./snapshot-DgsOhf_8.mjs";
3
4
  import { n as assertCompleteSchemaSnapshot } from "./complete-DP7pliuY.mjs";
4
5
  import "./snapshot.mjs";
5
6
  //#region src/introspection/catalog.ts
@@ -186,7 +187,7 @@ function mapTable(table, dialect, tables, diagnostics) {
186
187
  const columns = table.columns.map((column) => mapColumn(column, dialect)).sort(compareId);
187
188
  const columnIds = new Map(table.columns.map((column) => [column.physicalName, column.id]));
188
189
  const constraints = table.constraints.map((constraint) => mapConstraint(constraint, dialect, columnIds, tables, diagnostics)).filter((value) => value !== void 0).sort(compareId);
189
- const indexes = table.indexes.map((index) => mapIndex$1(index, dialect, columnIds)).sort(compareId);
190
+ const indexes = table.indexes.map((index) => mapIndex(index, dialect, columnIds)).sort(compareId);
190
191
  return {
191
192
  kind: "table",
192
193
  id: table.id,
@@ -298,7 +299,7 @@ function mapConstraint(constraint, dialect, columns, tables, diagnostics) {
298
299
  ...constraint.validated === void 0 ? {} : { validated: constraint.validated }
299
300
  };
300
301
  }
301
- function mapIndex$1(index, dialect, columns) {
302
+ function mapIndex(index, dialect, columns) {
302
303
  return {
303
304
  kind: "index",
304
305
  id: index.id,
@@ -669,3683 +670,4 @@ function isCatalogSqlExpression(value) {
669
670
  return typeof value === "object" && value !== null && !Array.isArray(value) && value.kind === "sql" && typeof value.text === "string";
670
671
  }
671
672
  //#endregion
672
- //#region src/introspection/mysql.ts
673
- const mysqlServerQuery = `SELECT VERSION() AS version, @@version_comment AS version_comment`;
674
- const mysqlTablesQuery = `
675
- SELECT TABLE_NAME AS table_name, TABLE_TYPE AS table_type,
676
- ENGINE AS engine, TABLE_COLLATION AS table_collation,
677
- CREATE_OPTIONS AS create_options, TABLE_COMMENT AS table_comment
678
- FROM INFORMATION_SCHEMA.TABLES
679
- WHERE TABLE_SCHEMA = ?
680
- ORDER BY TABLE_NAME
681
- `;
682
- const mysqlColumnsQuery = `
683
- SELECT TABLE_NAME AS table_name, COLUMN_NAME AS column_name,
684
- ORDINAL_POSITION AS ordinal_position, COLUMN_TYPE AS column_type,
685
- DATA_TYPE AS data_type,
686
- IS_NULLABLE AS is_nullable, COLUMN_DEFAULT AS column_default,
687
- EXTRA AS extra, GENERATION_EXPRESSION AS generation_expression,
688
- CHARACTER_SET_NAME AS character_set_name,
689
- COLLATION_NAME AS collation_name, COLUMN_COMMENT AS column_comment
690
- FROM INFORMATION_SCHEMA.COLUMNS
691
- WHERE TABLE_SCHEMA = ?
692
- ORDER BY TABLE_NAME, ORDINAL_POSITION
693
- `;
694
- const mysqlKeyUsageQuery = `
695
- SELECT kcu.TABLE_NAME AS table_name, kcu.CONSTRAINT_NAME AS constraint_name,
696
- tc.CONSTRAINT_TYPE AS constraint_type, tc.ENFORCED AS enforced,
697
- kcu.COLUMN_NAME AS column_name, kcu.ORDINAL_POSITION AS ordinal_position,
698
- kcu.REFERENCED_TABLE_NAME AS referenced_table_name,
699
- kcu.REFERENCED_COLUMN_NAME AS referenced_column_name,
700
- rc.UPDATE_RULE AS update_rule, rc.DELETE_RULE AS delete_rule,
701
- rc.MATCH_OPTION AS match_option
702
- FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE kcu
703
- JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS tc
704
- ON tc.CONSTRAINT_SCHEMA = kcu.CONSTRAINT_SCHEMA
705
- AND tc.TABLE_NAME = kcu.TABLE_NAME
706
- AND tc.CONSTRAINT_NAME = kcu.CONSTRAINT_NAME
707
- LEFT JOIN INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS rc
708
- ON rc.CONSTRAINT_SCHEMA = kcu.CONSTRAINT_SCHEMA
709
- AND rc.TABLE_NAME = kcu.TABLE_NAME
710
- AND rc.CONSTRAINT_NAME = kcu.CONSTRAINT_NAME
711
- WHERE kcu.CONSTRAINT_SCHEMA = ?
712
- ORDER BY kcu.TABLE_NAME, kcu.CONSTRAINT_NAME, kcu.ORDINAL_POSITION
713
- `;
714
- const mysqlChecksQuery = `
715
- SELECT tc.TABLE_NAME AS table_name, tc.CONSTRAINT_NAME AS constraint_name,
716
- tc.ENFORCED AS enforced, cc.CHECK_CLAUSE AS check_clause
717
- FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS tc
718
- JOIN INFORMATION_SCHEMA.CHECK_CONSTRAINTS cc
719
- ON cc.CONSTRAINT_SCHEMA = tc.CONSTRAINT_SCHEMA
720
- AND cc.CONSTRAINT_NAME = tc.CONSTRAINT_NAME
721
- WHERE tc.CONSTRAINT_SCHEMA = ? AND tc.CONSTRAINT_TYPE = 'CHECK'
722
- ORDER BY tc.TABLE_NAME, tc.CONSTRAINT_NAME
723
- `;
724
- const mysqlStatisticsQuery = `
725
- SELECT TABLE_NAME AS table_name, INDEX_NAME AS index_name,
726
- NON_UNIQUE AS non_unique, SEQ_IN_INDEX AS seq_in_index,
727
- COLUMN_NAME AS column_name, COLLATION AS collation,
728
- INDEX_TYPE AS index_type, EXPRESSION AS expression,
729
- SUB_PART AS sub_part, IS_VISIBLE AS is_visible,
730
- COMMENT AS comment, INDEX_COMMENT AS index_comment
731
- FROM INFORMATION_SCHEMA.STATISTICS
732
- WHERE TABLE_SCHEMA = ?
733
- ORDER BY TABLE_NAME, INDEX_NAME, SEQ_IN_INDEX
734
- `;
735
- /** View definitions and execution properties for the selected database. */
736
- const mysqlViewsQuery = `
737
- SELECT TABLE_NAME AS table_name, VIEW_DEFINITION AS view_definition,
738
- CHECK_OPTION AS check_option, IS_UPDATABLE AS is_updatable,
739
- SECURITY_TYPE AS security_type, DEFINER AS definer
740
- FROM INFORMATION_SCHEMA.VIEWS
741
- WHERE TABLE_SCHEMA = ?
742
- ORDER BY TABLE_NAME
743
- `;
744
- /** Stored function and procedure declarations for the selected database. */
745
- const mysqlRoutinesQuery = `
746
- SELECT ROUTINE_NAME AS routine_name, ROUTINE_TYPE AS routine_type,
747
- DATA_TYPE AS data_type, DTD_IDENTIFIER AS dtd_identifier,
748
- ROUTINE_BODY AS routine_body,
749
- ROUTINE_DEFINITION AS routine_definition,
750
- EXTERNAL_LANGUAGE AS external_language,
751
- SQL_DATA_ACCESS AS sql_data_access,
752
- IS_DETERMINISTIC AS is_deterministic,
753
- SECURITY_TYPE AS security_type, SQL_MODE AS sql_mode,
754
- ROUTINE_COMMENT AS routine_comment
755
- FROM INFORMATION_SCHEMA.ROUTINES
756
- WHERE ROUTINE_SCHEMA = ?
757
- ORDER BY ROUTINE_NAME, ROUTINE_TYPE
758
- `;
759
- /** Parameter rows, including the ordinal zero return row for functions. */
760
- const mysqlRoutineParametersQuery = `
761
- SELECT SPECIFIC_NAME AS routine_name, ORDINAL_POSITION AS ordinal_position,
762
- PARAMETER_MODE AS parameter_mode, PARAMETER_NAME AS parameter_name,
763
- DATA_TYPE AS data_type, DTD_IDENTIFIER AS dtd_identifier
764
- FROM INFORMATION_SCHEMA.PARAMETERS
765
- WHERE SPECIFIC_SCHEMA = ?
766
- ORDER BY SPECIFIC_NAME, ORDINAL_POSITION
767
- `;
768
- /** Trigger bodies and their table/event metadata. */
769
- const mysqlTriggersQuery = `
770
- SELECT TRIGGER_NAME AS trigger_name, EVENT_MANIPULATION AS event_manipulation,
771
- EVENT_OBJECT_TABLE AS table_name, ACTION_CONDITION AS action_condition,
772
- ACTION_STATEMENT AS action_statement,
773
- ACTION_ORIENTATION AS action_orientation,
774
- ACTION_TIMING AS action_timing, ACTION_ORDER AS action_order,
775
- DEFINER AS definer, SQL_MODE AS sql_mode
776
- FROM INFORMATION_SCHEMA.TRIGGERS
777
- WHERE TRIGGER_SCHEMA = ?
778
- ORDER BY TRIGGER_NAME, ACTION_ORDER
779
- `;
780
- /** Partition and subpartition declarations for tables in the selected database. */
781
- const mysqlPartitionsQuery = `
782
- SELECT TABLE_NAME AS table_name, PARTITION_NAME AS partition_name,
783
- SUBPARTITION_NAME AS subpartition_name,
784
- PARTITION_ORDINAL_POSITION AS partition_ordinal_position,
785
- SUBPARTITION_ORDINAL_POSITION AS subpartition_ordinal_position,
786
- PARTITION_METHOD AS partition_method,
787
- SUBPARTITION_METHOD AS subpartition_method,
788
- PARTITION_EXPRESSION AS partition_expression,
789
- SUBPARTITION_EXPRESSION AS subpartition_expression,
790
- PARTITION_DESCRIPTION AS partition_description,
791
- PARTITION_COMMENT AS partition_comment,
792
- TABLESPACE_NAME AS tablespace_name
793
- FROM INFORMATION_SCHEMA.PARTITIONS
794
- WHERE TABLE_SCHEMA = ? AND PARTITION_NAME IS NOT NULL
795
- ORDER BY TABLE_NAME, PARTITION_ORDINAL_POSITION, SUBPARTITION_ORDINAL_POSITION
796
- `;
797
- /** Collations used by tables or columns in the selected database. */
798
- const mysqlCollationsQuery = `
799
- SELECT c.COLLATION_NAME AS collation_name,
800
- c.CHARACTER_SET_NAME AS character_set_name,
801
- c.ID AS collation_id, c.IS_DEFAULT AS is_default,
802
- c.IS_COMPILED AS is_compiled, c.SORTLEN AS sort_length,
803
- c.PAD_ATTRIBUTE AS pad_attribute
804
- FROM INFORMATION_SCHEMA.COLLATIONS c
805
- JOIN (
806
- SELECT DISTINCT TABLE_COLLATION AS collation_name
807
- FROM INFORMATION_SCHEMA.TABLES
808
- WHERE TABLE_SCHEMA = ? AND TABLE_COLLATION IS NOT NULL
809
- UNION
810
- SELECT DISTINCT COLLATION_NAME AS collation_name
811
- FROM INFORMATION_SCHEMA.COLUMNS
812
- WHERE TABLE_SCHEMA = ? AND COLLATION_NAME IS NOT NULL
813
- ) used ON used.collation_name = c.COLLATION_NAME
814
- ORDER BY c.COLLATION_NAME
815
- `;
816
- /** Scheduled events are retained as opaque MySQL objects, not migration input. */
817
- const mysqlEventsQuery = `
818
- SELECT EVENT_NAME AS event_name, EVENT_TYPE AS event_type,
819
- STATUS AS status, EVENT_DEFINITION AS event_definition,
820
- EVENT_BODY AS event_body, EXECUTE_AT AS execute_at,
821
- INTERVAL_VALUE AS interval_value, INTERVAL_FIELD AS interval_field,
822
- EVENT_COMMENT AS event_comment, DEFINER AS definer
823
- FROM INFORMATION_SCHEMA.EVENTS
824
- WHERE EVENT_SCHEMA = ?
825
- ORDER BY EVENT_NAME
826
- `;
827
- /** Read one MySQL database into the normalized catalog contract. */
828
- async function readMysqlCatalog(connection, options) {
829
- const diagnostics = [];
830
- if (connection.dialect !== "mysql") {
831
- diagnostics.push(createIntrospectionDiagnostic({
832
- severity: "error",
833
- code: "dialect-mismatch",
834
- message: "MySQL catalog reading requires a MySQL CatalogConnection",
835
- path: ["connection", "dialect"]
836
- }));
837
- return emptyCatalog$2(options.namespace, diagnostics);
838
- }
839
- const server = serverInfo$2((await query$2(connection, mysqlServerQuery, [], options, diagnostics, "server"))[0], diagnostics);
840
- const tableRows = await query$2(connection, mysqlTablesQuery, [options.namespace], options, diagnostics, "tables");
841
- const tables = tableRows.filter((row) => text$2(row.table_type) === "BASE TABLE").map((row) => table$1(row, options.namespace));
842
- const deferredObjects = [];
843
- const opaqueObjects = [];
844
- const views = [];
845
- const comments = [];
846
- const tableByName = new Map(tables.map((item) => [item.physicalName, item]));
847
- const viewRows = await query$2(connection, mysqlViewsQuery, [options.namespace], options, diagnostics, "views");
848
- const viewRowsByName = new Map(viewRows.map((row) => [text$2(row.table_name) ?? "", row]));
849
- for (const row of tableRows.filter((currentRow) => text$2(currentRow.table_type) !== "BASE TABLE")) {
850
- const kind = text$2(row.table_type)?.toUpperCase();
851
- if (kind === "VIEW" || kind === "SYSTEM VIEW") {
852
- const mapped = viewObject$1(row, viewRowsByName.get(text$2(row.table_name) ?? ""), options.namespace, diagnostics);
853
- if (mapped.kind === "deferred-object") deferredObjects.push(mapped);
854
- else views.push(mapped);
855
- } else {
856
- const mapped = deferred$1(row, options.namespace);
857
- deferredObjects.push(mapped);
858
- diagnostics.push(createIntrospectionDiagnostic({
859
- severity: "warning",
860
- code: "unmodeled-object",
861
- message: `MySQL object ${mapped.physicalName} (${kind ?? "unknown"}) is retained as a deferred record`,
862
- path: ["deferredObjects", mapped.physicalName],
863
- physicalReference: mapped.reference,
864
- remediation: "Inspect the deferred record before using it as migration input."
865
- }));
866
- }
867
- }
868
- const relationByName = /* @__PURE__ */ new Map();
869
- for (const currentTable of tables) relationByName.set(currentTable.physicalName, {
870
- kind: "table",
871
- id: currentTable.id
872
- });
873
- for (const view of views) relationByName.set(view.physicalName, {
874
- kind: "view",
875
- id: view.id
876
- });
877
- const columnRows = await query$2(connection, mysqlColumnsQuery, [options.namespace], options, diagnostics, "columns");
878
- for (const currentTable of tables) currentTable.columns = columnRows.filter((row) => text$2(row.table_name) === currentTable.physicalName).map((row) => column$2(row, currentTable, options.namespace));
879
- for (const view of views) view.columns = columnRows.filter((row) => text$2(row.table_name) === view.physicalName).map((row) => column$2(row, view, options.namespace));
880
- const keyRows = await query$2(connection, mysqlKeyUsageQuery, [options.namespace], options, diagnostics, "constraints");
881
- for (const currentTable of tables) currentTable.constraints = constraints(currentTable, keyRows.filter((row) => text$2(row.table_name) === currentTable.physicalName), tableByName, options.namespace, diagnostics);
882
- const checkRows = await query$2(connection, mysqlChecksQuery, [options.namespace], options, diagnostics, "checks");
883
- const constraintsByTable = /* @__PURE__ */ new Map();
884
- for (const currentTable of tables) constraintsByTable.set(currentTable.physicalName, [...currentTable.constraints]);
885
- for (const row of checkRows) {
886
- const currentTable = tableByName.get(text$2(row.table_name) ?? "");
887
- if (!currentTable) continue;
888
- const physicalName = text$2(row.constraint_name) ?? `check_${currentTable.physicalName}`;
889
- const check = {
890
- kind: "check",
891
- id: stableId$2(physicalName),
892
- identitySource: "physical-name",
893
- physicalName,
894
- expression: sql$2(text$2(row.check_clause) ?? "true", options.namespace, currentTable, physicalName),
895
- dialect: text$2(row.enforced)?.toUpperCase() === "NO" ? {
896
- dialect: "mysql",
897
- version: 1,
898
- data: { enforced: false }
899
- } : void 0
900
- };
901
- constraintsByTable.get(currentTable.physicalName)?.push(check);
902
- }
903
- for (const currentTable of tables) currentTable.constraints = constraintsByTable.get(currentTable.physicalName) ?? [];
904
- const statRows = await query$2(connection, mysqlStatisticsQuery, [options.namespace], options, diagnostics, "statistics");
905
- const grouped = /* @__PURE__ */ new Map();
906
- for (const row of statRows) {
907
- const key = `${text$2(row.table_name) ?? ""}\u0000${text$2(row.index_name) ?? ""}`;
908
- const group = grouped.get(key) ?? [];
909
- group.push(row);
910
- grouped.set(key, group);
911
- }
912
- for (const rows of grouped.values()) {
913
- const currentTable = tableByName.get(text$2(rows[0].table_name) ?? "");
914
- if (!currentTable) continue;
915
- const mappedIndex = mapIndex(rows, currentTable, options.namespace, diagnostics);
916
- if (mappedIndex) currentTable.indexes = [...currentTable.indexes, mappedIndex];
917
- }
918
- const routineRows = await query$2(connection, mysqlRoutinesQuery, [options.namespace], options, diagnostics, "routines");
919
- const routineParameterRows = await query$2(connection, mysqlRoutineParametersQuery, [options.namespace], options, diagnostics, "routine-parameters");
920
- const routineParameters = /* @__PURE__ */ new Map();
921
- for (const row of routineParameterRows) {
922
- const name = text$2(row.routine_name) ?? "unknown";
923
- const group = routineParameters.get(name) ?? [];
924
- group.push(row);
925
- routineParameters.set(name, group);
926
- }
927
- const routines = routineRows.map((row) => {
928
- const routine = routineObject(row, routineParameters.get(text$2(row.routine_name) ?? "") ?? [], options.namespace);
929
- if (routine.comment) comments.push(routine.comment);
930
- relationByName.set(routine.physicalName, {
931
- kind: "routine",
932
- id: routine.id
933
- });
934
- return routine;
935
- });
936
- const triggerRows = await query$2(connection, mysqlTriggersQuery, [options.namespace], options, diagnostics, "triggers");
937
- const triggers = [];
938
- for (const rows of groupRows(triggerRows, (row) => text$2(row.trigger_name) ?? "unknown")) {
939
- const mapped = triggerObject$1(rows, relationByName, options.namespace, diagnostics);
940
- if (mapped.kind === "trigger") triggers.push(mapped);
941
- else deferredObjects.push(mapped);
942
- }
943
- const partitionRows = await query$2(connection, mysqlPartitionsQuery, [options.namespace], options, diagnostics, "partitions");
944
- const partitions = [];
945
- for (const row of partitionRows) {
946
- const mapped = partitionObject$1(row, tableByName, options.namespace, diagnostics);
947
- if (mapped.kind === "partition") {
948
- partitions.push(mapped);
949
- if (mapped.comment) comments.push(mapped.comment);
950
- } else deferredObjects.push(mapped);
951
- }
952
- const collationRows = await query$2(connection, mysqlCollationsQuery, [options.namespace, options.namespace], options, diagnostics, "collations");
953
- const usedCollations = new Set([...tableRows.map((row) => text$2(row.table_collation)), ...columnRows.map((row) => text$2(row.collation_name))].filter((value) => value !== void 0));
954
- const collations = collationRows.filter((row) => {
955
- const name = text$2(row.collation_name);
956
- return name !== void 0 && usedCollations.has(name);
957
- }).map((row) => collationObject$1(row, options.namespace));
958
- const eventRows = await query$2(connection, mysqlEventsQuery, [options.namespace], options, diagnostics, "events");
959
- for (const row of eventRows) {
960
- const event = opaqueEvent(row, options.namespace);
961
- opaqueObjects.push(event);
962
- diagnostics.push(createIntrospectionDiagnostic({
963
- severity: "warning",
964
- code: "unmodeled-object",
965
- message: `MySQL event ${event.physicalName} is retained as opaque data`,
966
- path: ["opaqueObjects", event.physicalName],
967
- physicalReference: event.reference,
968
- remediation: "Inspect the event definition before treating it as migration input."
969
- }));
970
- const eventComment = text$2(row.event_comment);
971
- if (eventComment !== void 0 && eventComment !== "") comments.push(objectComment({
972
- kind: "opaque-object",
973
- id: event.id
974
- }, eventComment, event.reference, options.namespace));
975
- }
976
- for (const currentTable of tables) {
977
- const tableComment = text$2(tableRows.find((row) => text$2(row.table_name) === currentTable.physicalName)?.table_comment);
978
- if (tableComment !== void 0 && tableComment !== "") comments.push(objectComment({
979
- kind: "table",
980
- id: currentTable.id
981
- }, tableComment, currentTable.reference, options.namespace));
982
- for (const currentColumn of currentTable.columns) {
983
- const columnComment = text$2(columnRows.find((row) => text$2(row.table_name) === currentTable.physicalName && text$2(row.column_name) === currentColumn.physicalName)?.column_comment);
984
- if (columnComment !== void 0 && columnComment !== "") comments.push(objectComment({
985
- kind: "column",
986
- id: currentColumn.id
987
- }, columnComment, currentColumn.reference, options.namespace));
988
- }
989
- }
990
- for (const view of views) {
991
- const viewComment = text$2(tableRows.find((row) => text$2(row.table_name) === view.physicalName)?.table_comment);
992
- if (viewComment !== void 0 && viewComment !== "") comments.push(objectComment({
993
- kind: view.kind,
994
- id: view.id
995
- }, viewComment, view.reference, options.namespace));
996
- for (const currentColumn of view.columns) {
997
- const columnComment = text$2(columnRows.find((row) => text$2(row.table_name) === view.physicalName && text$2(row.column_name) === currentColumn.physicalName)?.column_comment);
998
- if (columnComment !== void 0 && columnComment !== "") comments.push(objectComment({
999
- kind: "column",
1000
- id: currentColumn.id
1001
- }, columnComment, currentColumn.reference, options.namespace));
1002
- }
1003
- }
1004
- const capabilities = {
1005
- generatedColumns: server.capabilities.generatedColumns,
1006
- identityMetadata: server.capabilities.identityMetadata,
1007
- checkConstraints: server.capabilities.checkConstraints,
1008
- checkConstraintEnforcement: server.capabilities.checkConstraintEnforcement,
1009
- expressionDecompilation: server.capabilities.expressionDecompilation,
1010
- indexExpressions: server.capabilities.indexExpressions,
1011
- indexPredicates: server.capabilities.indexPredicates,
1012
- indexIncludedColumns: server.capabilities.indexIncludedColumns,
1013
- namespaces: server.capabilities.namespaces,
1014
- visibility: server.capabilities.visibility
1015
- };
1016
- const serverCapabilities = {
1017
- ...server.capabilities,
1018
- views: true,
1019
- materializedViews: false,
1020
- sequences: false,
1021
- enums: false,
1022
- domains: false,
1023
- collations: true,
1024
- routines: true,
1025
- triggers: true,
1026
- partitions: true,
1027
- policies: false,
1028
- extensions: false,
1029
- comments: true,
1030
- ownership: false,
1031
- scheduledEvents: true,
1032
- tableEngines: true,
1033
- generatedColumnModes: true,
1034
- selectedNamespace: options.namespace,
1035
- productFamily: server.product === "mariadb" ? "mariadb" : "mysql8"
1036
- };
1037
- const namespace = {
1038
- kind: "mysql-database",
1039
- name: options.namespace,
1040
- reference: reference$2("namespace", options.namespace, options.namespace, "INFORMATION_SCHEMA.SCHEMATA", "SCHEMA_NAME"),
1041
- dialect: mysqlExtension({
1042
- selectedNamespace: options.namespace,
1043
- views: true,
1044
- materializedViews: false,
1045
- sequences: false,
1046
- routines: true,
1047
- triggers: true,
1048
- partitions: true,
1049
- collations: true,
1050
- comments: true,
1051
- ownership: false,
1052
- policies: false,
1053
- extensions: false
1054
- })
1055
- };
1056
- return Object.freeze({
1057
- dialect: "mysql",
1058
- server: {
1059
- ...server,
1060
- capabilities: serverCapabilities
1061
- },
1062
- namespace,
1063
- tables: Object.freeze(tables),
1064
- views: Object.freeze(views),
1065
- collations: Object.freeze(collations),
1066
- routines: Object.freeze(routines),
1067
- triggers: Object.freeze(triggers),
1068
- partitions: Object.freeze(partitions),
1069
- deferredObjects: Object.freeze(deferredObjects),
1070
- opaqueObjects: Object.freeze(opaqueObjects),
1071
- comments: Object.freeze(comments),
1072
- ownership: Object.freeze([]),
1073
- capabilities,
1074
- diagnostics: Object.freeze(diagnostics)
1075
- });
1076
- }
1077
- async function query$2(connection, textValue, parameters, options, diagnostics, operation) {
1078
- try {
1079
- return await connection.query({
1080
- text: textValue,
1081
- parameters
1082
- }, { signal: options.signal });
1083
- } catch {
1084
- diagnostics.push(createIntrospectionDiagnostic({
1085
- severity: "error",
1086
- code: "query-failed",
1087
- message: `MySQL catalog query failed while reading ${operation}`,
1088
- path: [operation],
1089
- remediation: "Check Information Schema permissions and the selected database."
1090
- }));
1091
- return [];
1092
- }
1093
- }
1094
- function serverInfo$2(row, diagnostics) {
1095
- const rawVersion = text$2(row?.version) ?? "unknown";
1096
- const comment = text$2(row?.version_comment) ?? "";
1097
- const mariadb = /mariadb/i.test(rawVersion) || /mariadb/i.test(comment);
1098
- const parts = rawVersion.match(/(\d+)\.(\d+)(?:\.(\d+))?/);
1099
- const major = parts ? Number(parts[1]) : void 0;
1100
- const minor = parts ? Number(parts[2]) : void 0;
1101
- if (mariadb) diagnostics.push(createIntrospectionDiagnostic({
1102
- severity: "error",
1103
- code: "unsupported-product",
1104
- message: "MariaDB requires a dedicated catalog adapter and is not treated as MySQL",
1105
- path: ["server", "product"]
1106
- }));
1107
- const supported = !mariadb && major === 8 && ((minor ?? 0) > 0 || (minor ?? 0) === 0 && Number(parts?.[3] ?? 0) >= 16);
1108
- if (!supported && !mariadb) diagnostics.push(createIntrospectionDiagnostic({
1109
- severity: "error",
1110
- code: "unsupported-server",
1111
- message: "MySQL introspection requires MySQL 8.0 or newer",
1112
- path: ["server", "version"]
1113
- }));
1114
- return {
1115
- product: mariadb ? "mariadb" : "mysql",
1116
- rawVersion,
1117
- parsedVersion: major === void 0 ? void 0 : {
1118
- major,
1119
- minor,
1120
- patch: parts?.[3] ? Number(parts[3]) : void 0
1121
- },
1122
- capabilities: {
1123
- generatedColumns: supported,
1124
- identityMetadata: supported,
1125
- checkConstraints: supported,
1126
- checkConstraintEnforcement: supported ? "enforced" : "unknown",
1127
- expressionDecompilation: false,
1128
- indexExpressions: supported,
1129
- indexPredicates: false,
1130
- indexIncludedColumns: false,
1131
- namespaces: true,
1132
- visibility: "complete",
1133
- mysql8: supported
1134
- }
1135
- };
1136
- }
1137
- function table$1(row, namespace) {
1138
- const physicalName = text$2(row.table_name) ?? "unnamed_table";
1139
- return {
1140
- kind: "table",
1141
- id: stableId$2(physicalName),
1142
- identitySource: "physical-name",
1143
- physicalName,
1144
- reference: reference$2("table", physicalName, namespace, "INFORMATION_SCHEMA.TABLES", "TABLE_NAME"),
1145
- columns: [],
1146
- constraints: [],
1147
- indexes: [],
1148
- dialect: mysqlExtension({
1149
- ...text$2(row.engine) === void 0 ? {} : { engine: text$2(row.engine) },
1150
- ...text$2(row.table_collation) === void 0 ? {} : { collation: text$2(row.table_collation) },
1151
- ...text$2(row.create_options) === void 0 ? {} : { createOptions: text$2(row.create_options) }
1152
- })
1153
- };
1154
- }
1155
- function deferred$1(row, namespace) {
1156
- const physicalName = text$2(row.table_name) ?? "unnamed_object";
1157
- return {
1158
- kind: "deferred-object",
1159
- id: stableId$2(`deferred:${text$2(row.table_type) ?? "other"}:${physicalName}`),
1160
- identitySource: "physical-name",
1161
- objectKind: text$2(row.table_type)?.toUpperCase() === "VIEW" || text$2(row.table_type)?.toUpperCase() === "SYSTEM VIEW" ? "view" : "other",
1162
- physicalName,
1163
- reference: reference$2("deferred-object", physicalName, namespace, "INFORMATION_SCHEMA.TABLES", "TABLE_NAME"),
1164
- dialect: mysqlExtension({
1165
- ...text$2(row.table_type) === void 0 ? {} : { tableType: text$2(row.table_type) },
1166
- ...text$2(row.engine) === void 0 ? {} : { engine: text$2(row.engine) }
1167
- })
1168
- };
1169
- }
1170
- function column$2(row, table, namespace) {
1171
- const physicalName = text$2(row.column_name) ?? "unnamed_column";
1172
- const extra = text$2(row.extra) ?? "";
1173
- const generationExpression = text$2(row.generation_expression);
1174
- const generated = generationExpression !== void 0 && (/GENERATED/i.test(extra) || generationExpression !== "") ? {
1175
- kind: "generated",
1176
- mode: /VIRTUAL/i.test(extra) ? "virtual" : /STORED/i.test(extra) ? "stored" : "unknown",
1177
- expression: sql$2(generationExpression, namespace, table, physicalName)
1178
- } : void 0;
1179
- const identity = /auto_increment/i.test(extra) ? {
1180
- kind: "identity",
1181
- generation: "by-default",
1182
- options: {},
1183
- dialect: {
1184
- dialect: "mysql",
1185
- version: 1,
1186
- data: { autoIncrement: true }
1187
- }
1188
- } : void 0;
1189
- const onUpdateMatch = extra.match(/on update\s+(.+)$/i);
1190
- const defaultText = text$2(row.column_default);
1191
- const defaultValue = literal(defaultText, text$2(row.data_type));
1192
- return {
1193
- kind: "column",
1194
- id: stableId$2(physicalName),
1195
- identitySource: "physical-name",
1196
- physicalName,
1197
- ordinalPosition: number$2(row.ordinal_position) ?? 0,
1198
- nullable: text$2(row.is_nullable)?.toUpperCase() !== "NO",
1199
- storage: { nativeType: text$2(row.column_type) ?? "unknown" },
1200
- default: defaultValue !== void 0 ? {
1201
- kind: "literal",
1202
- value: defaultValue
1203
- } : defaultText !== void 0 ? {
1204
- kind: "expression",
1205
- expression: sql$2(defaultText, namespace, table, physicalName)
1206
- } : void 0,
1207
- generated,
1208
- identity,
1209
- onUpdate: onUpdateMatch?.[1] ? sql$2(onUpdateMatch[1], namespace, table, physicalName) : void 0,
1210
- dialect: mysqlExtension({
1211
- ...text$2(row.data_type) === void 0 ? {} : { dataType: text$2(row.data_type) },
1212
- ...text$2(row.character_set_name) === void 0 ? {} : { characterSet: text$2(row.character_set_name) },
1213
- ...text$2(row.collation_name) === void 0 ? {} : { collation: text$2(row.collation_name) },
1214
- ...extra === "" ? {} : { extra }
1215
- }),
1216
- reference: reference$2("column", physicalName, namespace, "INFORMATION_SCHEMA.COLUMNS", "COLUMN_NAME")
1217
- };
1218
- }
1219
- function constraints(table, rows, tableByName, namespace, diagnostics) {
1220
- const grouped = /* @__PURE__ */ new Map();
1221
- for (const row of rows) {
1222
- const key = text$2(row.constraint_name) ?? "unknown";
1223
- const group = grouped.get(key) ?? [];
1224
- group.push(row);
1225
- grouped.set(key, group);
1226
- }
1227
- const result = [];
1228
- for (const [physicalName, group] of grouped) {
1229
- const first = group[0];
1230
- const columns = group.sort((left, right) => (number$2(left.ordinal_position) ?? 0) - (number$2(right.ordinal_position) ?? 0)).map((row) => text$2(row.column_name) ?? "unknown");
1231
- const common = {
1232
- id: stableId$2(physicalName),
1233
- identitySource: "physical-name",
1234
- physicalName,
1235
- reference: reference$2("constraint", physicalName, namespace, "INFORMATION_SCHEMA.TABLE_CONSTRAINTS", "CONSTRAINT_NAME")
1236
- };
1237
- const type = text$2(first.constraint_type);
1238
- if (type === "PRIMARY KEY") {
1239
- result.push({
1240
- kind: "primary-key",
1241
- ...common,
1242
- columns
1243
- });
1244
- continue;
1245
- }
1246
- if (type === "UNIQUE") {
1247
- result.push({
1248
- kind: "unique",
1249
- ...common,
1250
- columns,
1251
- nulls: "distinct"
1252
- });
1253
- continue;
1254
- }
1255
- if (type !== "FOREIGN KEY") continue;
1256
- const targetTableName = text$2(first.referenced_table_name) ?? "unknown";
1257
- if (!tableByName.has(targetTableName)) diagnostics.push(createIntrospectionDiagnostic({
1258
- severity: "error",
1259
- code: "unresolved-reference",
1260
- message: `MySQL foreign key target ${targetTableName} was not found`,
1261
- path: [
1262
- table.id,
1263
- "constraints",
1264
- physicalName
1265
- ]
1266
- }));
1267
- result.push({
1268
- kind: "foreign-key",
1269
- ...common,
1270
- columns,
1271
- target: {
1272
- table: targetTableName,
1273
- columns: group.map((row) => text$2(row.referenced_column_name) ?? "unknown")
1274
- },
1275
- onUpdate: action$1(first.update_rule),
1276
- onDelete: action$1(first.delete_rule),
1277
- match: match$1(first.match_option),
1278
- dialect: text$2(first.enforced)?.toUpperCase() === "NO" ? {
1279
- dialect: "mysql",
1280
- version: 1,
1281
- data: { enforced: false }
1282
- } : void 0
1283
- });
1284
- }
1285
- return result;
1286
- }
1287
- function mapIndex(rows, table, namespace, diagnostics) {
1288
- const first = rows[0];
1289
- const physicalName = text$2(first.index_name);
1290
- if (!physicalName) return;
1291
- const terms = [];
1292
- for (const row of rows) {
1293
- const expression = text$2(row.expression);
1294
- const columnName = text$2(row.column_name);
1295
- if (!expression && !columnName) {
1296
- diagnostics.push(createIntrospectionDiagnostic({
1297
- severity: "error",
1298
- code: "unsupported-feature",
1299
- message: `MySQL index ${physicalName} has an unrepresented term`,
1300
- path: [
1301
- table.id,
1302
- "indexes",
1303
- physicalName
1304
- ]
1305
- }));
1306
- continue;
1307
- }
1308
- terms.push(expression ? {
1309
- kind: "expression",
1310
- expression: sql$2(expression, namespace, table, physicalName),
1311
- position: number$2(row.seq_in_index) ?? 0
1312
- } : {
1313
- kind: "column",
1314
- column: columnName,
1315
- position: number$2(row.seq_in_index) ?? 0,
1316
- direction: text$2(row.collation) === "D" ? "DESC" : "ASC",
1317
- prefixLength: row.sub_part === null || row.sub_part === void 0 ? void 0 : {
1318
- kind: "literal",
1319
- value: number$2(row.sub_part) ?? text$2(row.sub_part) ?? ""
1320
- }
1321
- });
1322
- if (row.sub_part !== null && row.sub_part !== void 0) diagnostics.push(createIntrospectionDiagnostic({
1323
- severity: "warning",
1324
- code: "lossy-mapping",
1325
- message: `MySQL index prefix length for ${physicalName} is retained only in catalog rows`,
1326
- path: [
1327
- table.id,
1328
- "indexes",
1329
- physicalName
1330
- ]
1331
- }));
1332
- }
1333
- return {
1334
- kind: "index",
1335
- id: stableId$2(physicalName),
1336
- identitySource: "physical-name",
1337
- physicalName,
1338
- unique: number$2(first.non_unique) === 0,
1339
- terms,
1340
- method: text$2(first.index_type),
1341
- dialect: mysqlExtension({
1342
- ...text$2(first.index_type) === void 0 ? {} : { indexType: text$2(first.index_type) },
1343
- ...text$2(first.is_visible) === void 0 ? {} : { visible: text$2(first.is_visible).toUpperCase() !== "NO" },
1344
- ...text$2(first.comment) === void 0 ? {} : { comment: text$2(first.comment) },
1345
- ...text$2(first.index_comment) === void 0 ? {} : { indexComment: text$2(first.index_comment) }
1346
- }),
1347
- reference: reference$2("index", physicalName, namespace, "INFORMATION_SCHEMA.STATISTICS", "INDEX_NAME")
1348
- };
1349
- }
1350
- function viewObject$1(tableRow, viewRow, namespace, diagnostics) {
1351
- const physicalName = text$2(tableRow.table_name) ?? "unnamed_view";
1352
- const physicalReference = reference$2("view", physicalName, namespace, "INFORMATION_SCHEMA.VIEWS", "TABLE_NAME");
1353
- const definition = text$2(viewRow?.view_definition);
1354
- if (definition === void 0 || definition.trim() === "") {
1355
- diagnostics.push(createIntrospectionDiagnostic({
1356
- severity: "error",
1357
- code: "expression-parse-failed",
1358
- message: `MySQL view ${physicalName} has no recoverable definition`,
1359
- path: [
1360
- "views",
1361
- physicalName,
1362
- "definition"
1363
- ],
1364
- physicalReference,
1365
- remediation: "Grant the metadata privilege needed to read INFORMATION_SCHEMA.VIEWS.VIEW_DEFINITION."
1366
- }));
1367
- return {
1368
- kind: "deferred-object",
1369
- id: stableId$2(`view:${physicalName}`),
1370
- identitySource: "physical-name",
1371
- objectKind: "view",
1372
- physicalName,
1373
- reference: physicalReference,
1374
- dialect: mysqlExtension({
1375
- reason: "definition-unavailable",
1376
- ...text$2(viewRow?.definer) === void 0 ? {} : { definer: text$2(viewRow?.definer) }
1377
- })
1378
- };
1379
- }
1380
- const checkOption = normalizeCheckOption(viewRow?.check_option);
1381
- const securityType = text$2(viewRow?.security_type)?.toUpperCase();
1382
- return {
1383
- kind: "view",
1384
- id: stableId$2(physicalName),
1385
- identitySource: "physical-name",
1386
- physicalName,
1387
- columns: [],
1388
- definition: sql$2(definition, namespace, {
1389
- kind: "view",
1390
- physicalName,
1391
- reference: physicalReference
1392
- }, physicalName),
1393
- ...checkOption === void 0 ? {} : { checkOption },
1394
- ...securityType === "INVOKER" ? { securityInvoker: true } : {},
1395
- reference: physicalReference,
1396
- provenance: {
1397
- kind: "catalog",
1398
- dialect: "mysql",
1399
- reference: physicalReference
1400
- },
1401
- dialect: mysqlExtension({
1402
- ...text$2(viewRow?.is_updatable) === void 0 ? {} : { isUpdatable: text$2(viewRow?.is_updatable) },
1403
- ...securityType === void 0 ? {} : { securityType },
1404
- ...text$2(viewRow?.definer) === void 0 ? {} : { definer: text$2(viewRow?.definer) }
1405
- })
1406
- };
1407
- }
1408
- function routineObject(row, parameterRows, namespace) {
1409
- const physicalName = text$2(row.routine_name) ?? "unnamed_routine";
1410
- const physicalReference = reference$2("routine", physicalName, namespace, "INFORMATION_SCHEMA.ROUTINES", "ROUTINE_NAME");
1411
- const parameters = parameterRows.filter((row) => (number$2(row.ordinal_position) ?? 0) > 0).sort((left, right) => (number$2(left.ordinal_position) ?? 0) - (number$2(right.ordinal_position) ?? 0)).map(routineParameter);
1412
- const definition = text$2(row.routine_definition);
1413
- const returnType = text$2(row.data_type);
1414
- const routine = {
1415
- kind: "routine",
1416
- id: stableId$2(physicalName),
1417
- identitySource: "physical-name",
1418
- physicalName,
1419
- routineKind: text$2(row.routine_type)?.toUpperCase() === "FUNCTION" ? "function" : text$2(row.routine_type)?.toUpperCase() === "PROCEDURE" ? "procedure" : "unknown",
1420
- parameters,
1421
- ...returnType === void 0 || returnType.toUpperCase() === "VOID" ? {} : { returnType: storage$1(row.data_type, row.dtd_identifier) },
1422
- ...text$2(row.external_language) === void 0 && text$2(row.routine_body) === void 0 ? {} : { language: text$2(row.external_language) ?? text$2(row.routine_body) ?? "unknown" },
1423
- ...definition === void 0 ? {} : { body: sql$2(definition, namespace, {
1424
- kind: "routine",
1425
- physicalName,
1426
- reference: physicalReference
1427
- }, physicalName) },
1428
- volatility: "unknown",
1429
- ...text$2(row.security_type) === void 0 ? {} : { security: routineSecurity(row.security_type) },
1430
- reference: physicalReference,
1431
- provenance: {
1432
- kind: "catalog",
1433
- dialect: "mysql",
1434
- reference: physicalReference
1435
- },
1436
- dialect: mysqlExtension({
1437
- ...text$2(row.is_deterministic) === void 0 ? {} : { deterministic: text$2(row.is_deterministic).toUpperCase() === "YES" },
1438
- ...text$2(row.sql_data_access) === void 0 ? {} : { sqlDataAccess: text$2(row.sql_data_access) },
1439
- ...text$2(row.sql_mode) === void 0 ? {} : { sqlMode: text$2(row.sql_mode) }
1440
- })
1441
- };
1442
- const commentText = text$2(row.routine_comment);
1443
- if (commentText === void 0 || commentText === "") return routine;
1444
- return {
1445
- ...routine,
1446
- comment: objectComment({
1447
- kind: "routine",
1448
- id: routine.id
1449
- }, commentText, physicalReference, namespace)
1450
- };
1451
- }
1452
- function routineParameter(row) {
1453
- const parameterName = text$2(row.parameter_name);
1454
- return {
1455
- ...parameterName === void 0 ? {} : { name: parameterName },
1456
- ...routineParameterMode$1(row.parameter_mode) === void 0 ? {} : { mode: routineParameterMode$1(row.parameter_mode) },
1457
- storage: storage$1(row.data_type, row.dtd_identifier),
1458
- ordinalPosition: number$2(row.ordinal_position) ?? 0
1459
- };
1460
- }
1461
- function triggerObject$1(rows, relations, namespace, diagnostics) {
1462
- const first = rows[0];
1463
- const physicalName = text$2(first.trigger_name) ?? "unnamed_trigger";
1464
- const physicalReference = reference$2("trigger", physicalName, namespace, "INFORMATION_SCHEMA.TRIGGERS", "TRIGGER_NAME");
1465
- const tableName = text$2(first.table_name);
1466
- const target = tableName === void 0 ? void 0 : relations.get(tableName);
1467
- const body = text$2(first.action_statement);
1468
- if (target === void 0 || body === void 0 || body.trim() === "") {
1469
- if (target === void 0) diagnostics.push(createIntrospectionDiagnostic({
1470
- severity: "error",
1471
- code: "unresolved-reference",
1472
- message: `MySQL trigger ${physicalName} target ${tableName ?? "unknown"} was not found`,
1473
- path: [
1474
- "triggers",
1475
- physicalName,
1476
- "table"
1477
- ],
1478
- physicalReference
1479
- }));
1480
- if (body === void 0 || body.trim() === "") diagnostics.push(createIntrospectionDiagnostic({
1481
- severity: "error",
1482
- code: "expression-parse-failed",
1483
- message: `MySQL trigger ${physicalName} has no recoverable body`,
1484
- path: [
1485
- "triggers",
1486
- physicalName,
1487
- "body"
1488
- ],
1489
- physicalReference
1490
- }));
1491
- return {
1492
- kind: "deferred-object",
1493
- id: stableId$2(`trigger:${physicalName}`),
1494
- identitySource: "physical-name",
1495
- objectKind: "trigger",
1496
- physicalName,
1497
- reference: physicalReference,
1498
- dialect: mysqlExtension({
1499
- ...tableName === void 0 ? {} : { tableName },
1500
- ...body === void 0 ? {} : { actionStatement: body }
1501
- })
1502
- };
1503
- }
1504
- const timing = triggerTiming$1(first.action_timing);
1505
- const events = [...new Set(rows.map((row) => triggerEvent(row.event_manipulation)).filter((value) => value !== void 0))];
1506
- return {
1507
- kind: "trigger",
1508
- id: stableId$2(physicalName),
1509
- identitySource: "physical-name",
1510
- physicalName,
1511
- table: target,
1512
- timing,
1513
- events,
1514
- orientation: triggerOrientation(first.action_orientation),
1515
- ...text$2(first.action_condition) === void 0 ? {} : { condition: sql$2(text$2(first.action_condition), namespace, {
1516
- kind: "trigger",
1517
- physicalName,
1518
- reference: physicalReference
1519
- }, physicalName) },
1520
- body: sql$2(body, namespace, {
1521
- kind: "trigger",
1522
- physicalName,
1523
- reference: physicalReference
1524
- }, physicalName),
1525
- reference: physicalReference,
1526
- provenance: {
1527
- kind: "catalog",
1528
- dialect: "mysql",
1529
- reference: physicalReference
1530
- },
1531
- dialect: mysqlExtension({
1532
- ...text$2(first.definer) === void 0 ? {} : { definer: text$2(first.definer) },
1533
- ...text$2(first.sql_mode) === void 0 ? {} : { sqlMode: text$2(first.sql_mode) },
1534
- ...number$2(first.action_order) === void 0 ? {} : { actionOrder: number$2(first.action_order) }
1535
- })
1536
- };
1537
- }
1538
- function partitionObject$1(row, tables, namespace, diagnostics) {
1539
- const tableName = text$2(row.table_name) ?? "unknown";
1540
- const partitionName = text$2(row.partition_name);
1541
- const subpartitionName = text$2(row.subpartition_name);
1542
- const physicalName = partitionName === void 0 ? tableName : subpartitionName === void 0 ? partitionName : `${partitionName}/${subpartitionName}`;
1543
- const physicalReference = reference$2("partition", physicalName, namespace, "INFORMATION_SCHEMA.PARTITIONS", "PARTITION_NAME");
1544
- const parent = tables.get(tableName);
1545
- if (parent === void 0) {
1546
- diagnostics.push(createIntrospectionDiagnostic({
1547
- severity: "error",
1548
- code: "unresolved-reference",
1549
- message: `MySQL partition ${physicalName} parent table ${tableName} was not found`,
1550
- path: [
1551
- "partitions",
1552
- physicalName,
1553
- "parent"
1554
- ],
1555
- physicalReference
1556
- }));
1557
- return {
1558
- kind: "deferred-object",
1559
- id: stableId$2(`partition:${tableName}:${physicalName}`),
1560
- identitySource: "physical-name",
1561
- objectKind: "partition",
1562
- physicalName,
1563
- reference: physicalReference,
1564
- dialect: mysqlExtension({ tableName })
1565
- };
1566
- }
1567
- const method = text$2(row.subpartition_method) ?? text$2(row.partition_method) ?? "UNKNOWN";
1568
- const strategy = partitionStrategy$1(method);
1569
- if (strategy === "unknown") diagnostics.push(createIntrospectionDiagnostic({
1570
- severity: "warning",
1571
- code: "unsupported-feature",
1572
- message: `MySQL partition method ${method} is retained with an unknown normalized strategy`,
1573
- path: [
1574
- "partitions",
1575
- physicalName,
1576
- "strategy"
1577
- ],
1578
- physicalReference
1579
- }));
1580
- const boundText = text$2(row.partition_description) ?? text$2(row.subpartition_expression) ?? text$2(row.partition_expression);
1581
- const expression = text$2(row.partition_expression);
1582
- const partition = {
1583
- kind: "partition",
1584
- id: stableId$2(`partition:${tableName}:${physicalName}`),
1585
- identitySource: "physical-name",
1586
- physicalName,
1587
- parent: {
1588
- kind: "table",
1589
- id: parent.id
1590
- },
1591
- strategy,
1592
- ...expression === void 0 ? {} : { keyColumns: partitionKeyColumns$1(expression) },
1593
- ...boundText === void 0 ? {} : { bound: sql$2(boundText, namespace, parent, physicalName) },
1594
- reference: physicalReference,
1595
- dialect: mysqlExtension({
1596
- ...text$2(row.partition_method) === void 0 ? {} : { partitionMethod: text$2(row.partition_method) },
1597
- ...text$2(row.subpartition_method) === void 0 ? {} : { subpartitionMethod: text$2(row.subpartition_method) },
1598
- ...text$2(row.subpartition_name) === void 0 ? {} : { subpartitionName: text$2(row.subpartition_name) },
1599
- ...text$2(row.tablespace_name) === void 0 ? {} : { tablespace: text$2(row.tablespace_name) }
1600
- })
1601
- };
1602
- const commentText = text$2(row.partition_comment);
1603
- if (commentText === void 0 || commentText === "") return partition;
1604
- return {
1605
- ...partition,
1606
- comment: objectComment({
1607
- kind: "partition",
1608
- id: partition.id
1609
- }, commentText, physicalReference, namespace)
1610
- };
1611
- }
1612
- function collationObject$1(row, namespace) {
1613
- const physicalName = text$2(row.collation_name) ?? "unknown_collation";
1614
- return {
1615
- kind: "collation",
1616
- id: stableId$2(physicalName),
1617
- identitySource: "physical-name",
1618
- physicalName,
1619
- reference: reference$2("collation", physicalName, namespace, "INFORMATION_SCHEMA.COLLATIONS", "COLLATION_NAME"),
1620
- dialect: mysqlExtension({
1621
- ...text$2(row.character_set_name) === void 0 ? {} : { characterSet: text$2(row.character_set_name) },
1622
- ...number$2(row.collation_id) === void 0 ? {} : { id: number$2(row.collation_id) },
1623
- ...text$2(row.is_default) === void 0 ? {} : { isDefault: text$2(row.is_default) === "Yes" },
1624
- ...text$2(row.is_compiled) === void 0 ? {} : { isCompiled: text$2(row.is_compiled) === "Yes" },
1625
- ...number$2(row.sort_length) === void 0 ? {} : { sortLength: number$2(row.sort_length) },
1626
- ...text$2(row.pad_attribute) === void 0 ? {} : { padAttribute: text$2(row.pad_attribute) }
1627
- })
1628
- };
1629
- }
1630
- function opaqueEvent(row, namespace) {
1631
- const physicalName = text$2(row.event_name) ?? "unnamed_event";
1632
- const physicalReference = reference$2("opaque-object", physicalName, namespace, "INFORMATION_SCHEMA.EVENTS", "EVENT_NAME");
1633
- const definition = text$2(row.event_definition) ?? text$2(row.event_body);
1634
- return {
1635
- kind: "opaque-object",
1636
- id: stableId$2(`event:${physicalName}`),
1637
- identitySource: "physical-name",
1638
- objectKind: "event",
1639
- physicalName,
1640
- data: {
1641
- ...text$2(row.event_type) === void 0 ? {} : { eventType: text$2(row.event_type) },
1642
- ...text$2(row.status) === void 0 ? {} : { status: text$2(row.status) },
1643
- ...text$2(row.execute_at) === void 0 ? {} : { executeAt: text$2(row.execute_at) },
1644
- ...text$2(row.interval_value) === void 0 ? {} : { intervalValue: text$2(row.interval_value) },
1645
- ...text$2(row.interval_field) === void 0 ? {} : { intervalField: text$2(row.interval_field) },
1646
- ...text$2(row.definer) === void 0 ? {} : { definer: text$2(row.definer) }
1647
- },
1648
- ...definition === void 0 ? {} : { sql: sql$2(definition, namespace, {
1649
- kind: "opaque-object",
1650
- physicalName,
1651
- reference: physicalReference
1652
- }, physicalName) },
1653
- reference: physicalReference,
1654
- provenance: {
1655
- kind: "catalog",
1656
- dialect: "mysql",
1657
- reference: physicalReference
1658
- },
1659
- dialect: mysqlExtension({ objectKind: "event" })
1660
- };
1661
- }
1662
- function objectComment(object, comment, physicalReference, namespace) {
1663
- return {
1664
- kind: "comment",
1665
- id: stableId$2(`${object.kind}_${object.id}_comment`),
1666
- object,
1667
- text: comment,
1668
- reference: physicalReference,
1669
- provenance: {
1670
- kind: "catalog",
1671
- dialect: "mysql",
1672
- reference: physicalReference,
1673
- path: ["namespace", namespace]
1674
- }
1675
- };
1676
- }
1677
- function groupRows(rows, keyOf) {
1678
- const groups = /* @__PURE__ */ new Map();
1679
- for (const row of rows) {
1680
- const key = keyOf(row);
1681
- const group = groups.get(key) ?? [];
1682
- group.push(row);
1683
- groups.set(key, group);
1684
- }
1685
- return [...groups.entries()].sort(([left], [right]) => left.localeCompare(right)).map(([, group]) => group);
1686
- }
1687
- function mysqlExtension(data) {
1688
- return {
1689
- dialect: "mysql",
1690
- version: 1,
1691
- data
1692
- };
1693
- }
1694
- function storage$1(dataType, declaration) {
1695
- return { nativeType: text$2(declaration) ?? text$2(dataType) ?? "unknown" };
1696
- }
1697
- function normalizeCheckOption(value) {
1698
- const normalized = text$2(value)?.toLowerCase();
1699
- return normalized === "none" || normalized === void 0 ? normalized === void 0 ? void 0 : "none" : normalized === "local" ? "local" : normalized === "cascaded" ? "cascaded" : void 0;
1700
- }
1701
- function routineSecurity(value) {
1702
- return text$2(value)?.toLowerCase() === "invoker" ? "invoker" : text$2(value)?.toLowerCase() === "definer" ? "definer" : "unknown";
1703
- }
1704
- function routineParameterMode$1(value) {
1705
- const normalized = text$2(value)?.toLowerCase();
1706
- return normalized === "in" ? "in" : normalized === "out" ? "out" : normalized === "inout" ? "inout" : void 0;
1707
- }
1708
- function triggerTiming$1(value) {
1709
- const normalized = text$2(value)?.toLowerCase();
1710
- return normalized === "before" ? "before" : normalized === "after" ? "after" : "unknown";
1711
- }
1712
- function triggerEvent(value) {
1713
- const normalized = text$2(value)?.toLowerCase();
1714
- return normalized === "insert" || normalized === "update" || normalized === "delete" ? normalized : void 0;
1715
- }
1716
- function triggerOrientation(value) {
1717
- const normalized = text$2(value)?.toLowerCase();
1718
- return normalized === "row" ? "row" : normalized === "statement" ? "statement" : void 0;
1719
- }
1720
- function partitionStrategy$1(value) {
1721
- const normalized = value.toLowerCase();
1722
- return normalized === "range" ? "range" : normalized === "list" ? "list" : normalized === "hash" ? "hash" : "unknown";
1723
- }
1724
- function partitionKeyColumns$1(expression) {
1725
- return expression.split(",").map((value) => value.trim()).filter((value) => /^[A-Za-z_][A-Za-z0-9_$]*$/.test(value));
1726
- }
1727
- function sql$2(textValue, namespace, table, name) {
1728
- return {
1729
- kind: "sql",
1730
- dialect: "mysql",
1731
- text: textValue,
1732
- provenance: {
1733
- kind: "catalog",
1734
- dialect: "mysql",
1735
- reference: table.reference ?? reference$2(table.kind, name, namespace, "INFORMATION_SCHEMA", "TABLE_NAME", table.physicalName)
1736
- }
1737
- };
1738
- }
1739
- function reference$2(kind, name, namespace, relation, key, value = name) {
1740
- return {
1741
- kind,
1742
- name,
1743
- namespace,
1744
- catalog: {
1745
- relation,
1746
- key,
1747
- value
1748
- }
1749
- };
1750
- }
1751
- function literal(value, dataType) {
1752
- if (value === void 0) return;
1753
- if (value.toUpperCase() === "NULL") return null;
1754
- if (value.toUpperCase() === "TRUE") return true;
1755
- if (value.toUpperCase() === "FALSE") return false;
1756
- if (/^-?(?:\d+\.?\d*|\.\d+)$/.test(value)) return Number(value);
1757
- if (/^'(?:''|[^'])*'$/.test(value)) return value.slice(1, -1).replace(/''/g, "'");
1758
- if (value === "" || /^(?:char|varchar|text|tinytext|mediumtext|longtext|enum|set)$/i.test(dataType ?? "")) return value;
1759
- }
1760
- function emptyCatalog$2(namespace, diagnostics) {
1761
- return {
1762
- dialect: "mysql",
1763
- server: {
1764
- product: "mysql",
1765
- rawVersion: "unknown",
1766
- capabilities: {
1767
- generatedColumns: false,
1768
- identityMetadata: false,
1769
- checkConstraints: false,
1770
- checkConstraintEnforcement: "unknown",
1771
- expressionDecompilation: false,
1772
- indexExpressions: false,
1773
- indexPredicates: false,
1774
- indexIncludedColumns: false,
1775
- namespaces: true,
1776
- visibility: "unknown"
1777
- }
1778
- },
1779
- namespace: {
1780
- kind: "mysql-database",
1781
- name: namespace
1782
- },
1783
- tables: [],
1784
- deferredObjects: [],
1785
- diagnostics
1786
- };
1787
- }
1788
- function stableId$2(value) {
1789
- if (value && !/[.\\\u0000-\u001f\u007f]/.test(value)) return value;
1790
- let hash = 2166136261;
1791
- for (const character of value) {
1792
- hash ^= character.charCodeAt(0);
1793
- hash = Math.imul(hash, 16777619);
1794
- }
1795
- return `introspected_${(hash >>> 0).toString(16)}`;
1796
- }
1797
- function text$2(value) {
1798
- return value === null || value === void 0 ? void 0 : String(value);
1799
- }
1800
- function number$2(value) {
1801
- if (typeof value === "number" && Number.isFinite(value)) return value;
1802
- if (typeof value === "string" && value.trim() !== "") {
1803
- const result = Number(value);
1804
- return Number.isFinite(result) ? result : void 0;
1805
- }
1806
- }
1807
- function action$1(value) {
1808
- const normalized = text$2(value)?.toLowerCase();
1809
- return normalized === "cascade" ? "cascade" : normalized === "restrict" ? "restrict" : normalized === "set null" ? "set-null" : normalized === "set default" ? "set-default" : "no-action";
1810
- }
1811
- function match$1(value) {
1812
- return text$2(value)?.toLowerCase() === "full" ? "full" : "simple";
1813
- }
1814
- //#endregion
1815
- //#region src/introspection/postgres.ts
1816
- /** Fixed server metadata query used by the PostgreSQL catalog reader. */
1817
- const postgresServerQuery = `
1818
- SELECT
1819
- current_setting('server_version_num') AS server_version_num,
1820
- current_setting('server_version') AS server_version
1821
- `;
1822
- /** Read one PostgreSQL schema into the normalized catalog contract. */
1823
- async function readPostgresCatalog(connection, options) {
1824
- const diagnostics = [];
1825
- if (connection.dialect !== "postgresql") {
1826
- diagnostics.push(createIntrospectionDiagnostic({
1827
- severity: "error",
1828
- code: "dialect-mismatch",
1829
- message: `PostgreSQL catalog reader received a ${connection.dialect} connection`,
1830
- path: ["connection", "dialect"],
1831
- remediation: "Use a PostgreSQL CatalogConnection with this reader."
1832
- }));
1833
- return emptyCatalog$1(options.namespace, diagnostics);
1834
- }
1835
- const server = serverInfo$1((await query$1(connection, postgresServerQuery, [], options, diagnostics, "server"))[0], diagnostics);
1836
- const relationObjects = (await query$1(connection, postgresRelationsQuery, [options.namespace], options, diagnostics, "relations")).filter((row) => {
1837
- const kind = text$1(row.relkind);
1838
- return kind !== "i" && kind !== "I";
1839
- });
1840
- const tables = relationObjects.filter((row) => row.relkind === "r" || row.relkind === "p").map((row) => relationTable(row));
1841
- const tableByOid = new Map(tables.map((table) => [table.reference?.catalog?.value, table]));
1842
- const viewRows = await query$1(connection, postgresViewsQuery, [options.namespace], options, diagnostics, "views");
1843
- const views = [];
1844
- for (const row of viewRows) {
1845
- const view = viewObject(row, options.namespace, diagnostics);
1846
- if (view.kind === "deferred-object") continue;
1847
- views.push(view);
1848
- }
1849
- const relationReferences = /* @__PURE__ */ new Map();
1850
- for (const table of tables) relationReferences.set(table.reference?.catalog?.value, {
1851
- kind: "table",
1852
- id: table.id
1853
- });
1854
- for (const view of views) relationReferences.set(view.reference?.catalog?.value, {
1855
- kind: view.kind,
1856
- id: view.id
1857
- });
1858
- const columnRows = await query$1(connection, postgresColumnsQuery, [options.namespace], options, diagnostics, "columns");
1859
- const identityRows = await query$1(connection, postgresIdentitiesQuery, [options.namespace], options, diagnostics, "identities");
1860
- const identityOptionsByColumn = /* @__PURE__ */ new Map();
1861
- for (const row of identityRows) identityOptionsByColumn.set(columnKey(row.table_oid, row.ordinal_position), identityOptions(row));
1862
- const columnsByTable = groupBy(columnRows, (row) => row.table_oid);
1863
- for (const table of tables) table.columns = (columnsByTable.get(table.reference?.catalog?.value) ?? []).sort(compareOrdinal).map((row) => column$1(row, table, options.namespace, identityOptionsByColumn.get(columnKey(row.table_oid, row.ordinal_position))));
1864
- for (const view of views) view.columns = (columnsByTable.get(view.reference?.catalog?.value) ?? []).sort(compareOrdinal).map((row) => column$1(row, view, options.namespace));
1865
- const indexRows = await query$1(connection, postgresIndexesQuery, [options.namespace], options, diagnostics, "indexes");
1866
- const indexReferences = /* @__PURE__ */ new Map();
1867
- for (const row of indexRows) {
1868
- const indexOid = text$1(row.index_oid);
1869
- const physicalName = text$1(row.physical_name);
1870
- if (indexOid && physicalName) indexReferences.set(`pg_class:${indexOid}`, {
1871
- kind: "index",
1872
- id: stableId$1(physicalName),
1873
- physicalName,
1874
- reference: reference$1("index", physicalName, options.namespace, "pg_class", "oid", row.index_oid)
1875
- });
1876
- }
1877
- const constraintsByTable = groupBy(await query$1(connection, postgresConstraintsQuery, [options.namespace], options, diagnostics, "constraints"), (row) => row.table_oid);
1878
- for (const table of tables) {
1879
- const rows = constraintsByTable.get(table.reference?.catalog?.value) ?? [];
1880
- const columnsByNumber = new Map(table.columns.map((column) => [column.ordinalPosition, column.physicalName]));
1881
- table.constraints = rows.map((row) => constraint(row, table, columnsByNumber, tableByOid, options.namespace, diagnostics, indexReferences)).filter((value) => value !== void 0);
1882
- }
1883
- const indexesByTable = groupBy(indexRows, (row) => row.table_oid);
1884
- for (const table of tables) table.indexes = mapIndexes(indexesByTable.get(table.reference?.catalog?.value) ?? [], table, new Map(table.columns.map((column) => [column.ordinalPosition, column.physicalName])), options.namespace);
1885
- const sequences = (await query$1(connection, postgresSequencesQuery, [options.namespace], options, diagnostics, "sequences")).map((row) => sequenceObject(row, options.namespace, tableByOid, diagnostics));
1886
- const enums = mapEnums(await query$1(connection, postgresEnumsQuery, [options.namespace], options, diagnostics, "enums"), options.namespace);
1887
- const domains = mapDomains(await query$1(connection, postgresDomainsQuery, [options.namespace], options, diagnostics, "domains"), await query$1(connection, postgresDomainConstraintsQuery, [options.namespace], options, diagnostics, "domain-constraints"), options.namespace);
1888
- const collations = (await query$1(connection, postgresCollationsQuery, [options.namespace], options, diagnostics, "collations")).map((row) => collationObject(row, options.namespace));
1889
- const triggerRows = await query$1(connection, postgresTriggersQuery, [options.namespace], options, diagnostics, "triggers");
1890
- const triggers = [];
1891
- const triggerDeferredObjects = [];
1892
- for (const row of triggerRows) {
1893
- const value = triggerObject(row, options.namespace, relationReferences, diagnostics);
1894
- if (value.kind === "deferred-object") triggerDeferredObjects.push(value);
1895
- else triggers.push(value);
1896
- }
1897
- const routines = mapRoutines(await query$1(connection, postgresRoutinesQuery, [options.namespace], options, diagnostics, "routines"), await query$1(connection, postgresRoutineParametersQuery, [options.namespace], options, diagnostics, "routine-parameters"), options.namespace, diagnostics);
1898
- const partitions = (await query$1(connection, postgresPartitionsQuery, [options.namespace], options, diagnostics, "partitions")).map((row) => partitionObject(row, options.namespace, tableByOid, diagnostics)).filter((value) => value !== void 0);
1899
- const policies = (await query$1(connection, postgresPoliciesQuery, [options.namespace], options, diagnostics, "policies")).map((row) => policyObject(row, options.namespace, tableByOid, diagnostics)).filter((value) => value !== void 0);
1900
- const extensionObjects = (await query$1(connection, postgresExtensionsQuery, [options.namespace], options, diagnostics, "extensions")).map((row) => extensionObject(row, options.namespace));
1901
- const typedRelationOids = new Set([...views, ...sequences].map((object) => object.reference?.catalog?.value));
1902
- const deferredObjects = relationObjects.filter((row) => {
1903
- const relkind = text$1(row.relkind);
1904
- return relkind === "f" || (relkind === "v" || relkind === "m" || relkind === "S") && !typedRelationOids.has(row.oid === void 0 ? void 0 : text$1(row.oid));
1905
- }).map((row) => deferredObject(row, text$1(row.relkind) === "f" ? "foreign-table" : text$1(row.relkind) === "v" ? "view" : text$1(row.relkind) === "m" ? "materialized-view" : "sequence"));
1906
- deferredObjects.push(...triggerDeferredObjects);
1907
- const opaqueObjects = relationObjects.filter((row) => {
1908
- const kind = text$1(row.relkind);
1909
- return kind !== "r" && kind !== "p" && kind !== "v" && kind !== "m" && kind !== "S" && kind !== "f";
1910
- }).map((row) => opaqueRelationObject(row, options.namespace, diagnostics));
1911
- const metadata = mapMetadataRows(await query$1(connection, postgresMetadataQuery, [options.namespace], options, diagnostics, "comments-and-ownership"), options.namespace, tables, views, sequences, enums, domains, collations, routines, triggers, policies, extensionObjects, deferredObjects, opaqueObjects, indexReferences, relationReferences, diagnostics);
1912
- opaqueObjects.push(...metadata.opaqueObjects);
1913
- return Object.freeze({
1914
- dialect: "postgresql",
1915
- server,
1916
- namespace: {
1917
- kind: "postgres-schema",
1918
- name: options.namespace,
1919
- reference: reference$1("namespace", options.namespace, options.namespace, "pg_namespace", "nspname")
1920
- },
1921
- tables: Object.freeze(tables),
1922
- views: Object.freeze(views),
1923
- sequences: Object.freeze(sequences),
1924
- enums: Object.freeze(enums),
1925
- domains: Object.freeze(domains),
1926
- collations: Object.freeze(collations),
1927
- triggers: Object.freeze(triggers),
1928
- routines: Object.freeze(routines),
1929
- partitions: Object.freeze(partitions),
1930
- policies: Object.freeze(policies),
1931
- extensionObjects: Object.freeze(extensionObjects),
1932
- deferredObjects: Object.freeze(deferredObjects),
1933
- opaqueObjects: Object.freeze(opaqueObjects),
1934
- comments: Object.freeze(metadata.comments),
1935
- ownership: Object.freeze(metadata.ownership),
1936
- capabilities: server.capabilities,
1937
- diagnostics: Object.freeze(diagnostics)
1938
- });
1939
- }
1940
- const postgresRelationsQuery = `
1941
- SELECT c.oid::text AS oid, n.nspname AS namespace, c.relname,
1942
- c.relkind, c.relispartition
1943
- FROM pg_class c
1944
- JOIN pg_namespace n ON n.oid = c.relnamespace
1945
- WHERE n.nspname = $1
1946
- AND c.relkind NOT IN ('i', 'I')
1947
- ORDER BY c.relname
1948
- `;
1949
- /** Fixed view and materialized-view definitions from PostgreSQL's decompiler. */
1950
- const postgresViewsQuery = `
1951
- SELECT c.oid::text AS oid, n.nspname AS namespace, c.relname AS physical_name,
1952
- c.relkind, pg_get_viewdef(c.oid, true) AS definition,
1953
- v.check_option, c.reloptions
1954
- FROM pg_catalog.pg_class c
1955
- JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace
1956
- LEFT JOIN information_schema.views v
1957
- ON v.table_schema = n.nspname AND v.table_name = c.relname
1958
- WHERE n.nspname = $1 AND c.relkind IN ('v', 'm')
1959
- ORDER BY c.oid
1960
- `;
1961
- const postgresColumnsQuery = `
1962
- SELECT a.attrelid::text AS table_oid, a.attnum::int AS ordinal_position,
1963
- a.attname AS physical_name, NOT a.attnotnull AS nullable,
1964
- format_type(a.atttypid, a.atttypmod) AS native_type,
1965
- a.attidentity, a.attgenerated,
1966
- pg_get_expr(ad.adbin, ad.adrelid) AS default_expression
1967
- FROM pg_attribute a
1968
- JOIN pg_class c ON c.oid = a.attrelid
1969
- JOIN pg_namespace n ON n.oid = c.relnamespace
1970
- LEFT JOIN pg_attrdef ad ON ad.adrelid = a.attrelid AND ad.adnum = a.attnum
1971
- WHERE n.nspname = $1
1972
- AND c.relkind IN ('r', 'p', 'v', 'm')
1973
- AND a.attnum > 0
1974
- AND NOT a.attisdropped
1975
- ORDER BY a.attrelid, a.attnum
1976
- `;
1977
- const postgresConstraintsQuery = `
1978
- SELECT con.oid::text AS oid, con.conrelid::text AS table_oid,
1979
- con.conname AS physical_name, con.contype,
1980
- con.conkey, con.confrelid::text AS target_table_oid, con.confkey,
1981
- con.confupdtype, con.confdeltype, con.confmatchtype,
1982
- con.condeferrable, con.condeferred, con.convalidated,
1983
- con.conindid::text AS backing_index_oid,
1984
- i.indnullsnotdistinct,
1985
- pg_get_constraintdef(con.oid, true) AS definition
1986
- FROM pg_constraint con
1987
- JOIN pg_class c ON c.oid = con.conrelid
1988
- JOIN pg_namespace n ON n.oid = c.relnamespace
1989
- LEFT JOIN pg_index i ON i.indexrelid = con.conindid
1990
- WHERE n.nspname = $1
1991
- AND con.contype IN ('p', 'u', 'f', 'c', 'x')
1992
- ORDER BY con.conrelid, con.oid
1993
- `;
1994
- const postgresIndexesQuery = `
1995
- SELECT i.indexrelid::text AS index_oid, i.indrelid::text AS table_oid,
1996
- c.relname AS physical_name, i.indisunique, i.indnkeyatts::int,
1997
- i.indnatts::int, am.amname AS method,
1998
- pg_get_expr(i.indpred, i.indrelid, true) AS predicate,
1999
- s.position::int,
2000
- (i.indkey[s.position])::int AS attnum,
2001
- (i.indoption[s.position])::int AS indoption,
2002
- opc.opcname AS operator_class,
2003
- pg_get_indexdef(i.indexrelid, s.position, true) AS term_definition
2004
- FROM pg_index i
2005
- JOIN pg_class c ON c.oid = i.indexrelid
2006
- JOIN pg_class t ON t.oid = i.indrelid
2007
- JOIN pg_namespace n ON n.oid = t.relnamespace
2008
- JOIN pg_am am ON am.oid = c.relam
2009
- CROSS JOIN LATERAL generate_series(1, i.indnatts) AS s(position)
2010
- LEFT JOIN pg_opclass opc ON opc.oid = i.indclass[s.position]
2011
- WHERE n.nspname = $1
2012
- ORDER BY i.indrelid, i.indexrelid, s.position
2013
- `;
2014
- /** Identity sequence options joined to each generated identity column. */
2015
- const postgresIdentitiesQuery = `
2016
- SELECT a.attrelid::text AS table_oid, a.attnum::int AS ordinal_position,
2017
- s.seqstart, s.seqincrement, s.seqmin, s.seqmax, s.seqcache,
2018
- s.seqcycle, format_type(s.seqtypid, -1) AS sequence_type
2019
- FROM pg_catalog.pg_attribute a
2020
- JOIN pg_catalog.pg_class c ON c.oid = a.attrelid
2021
- JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace
2022
- JOIN pg_catalog.pg_depend d
2023
- ON d.refclassid = 'pg_catalog.pg_class'::regclass
2024
- AND d.refobjid = a.attrelid AND d.refobjsubid = a.attnum
2025
- AND d.classid = 'pg_catalog.pg_class'::regclass
2026
- AND d.deptype = 'i'
2027
- JOIN pg_catalog.pg_sequence s ON s.seqrelid = d.objid
2028
- WHERE n.nspname = $1 AND a.attidentity <> ''
2029
- ORDER BY a.attrelid, a.attnum
2030
- `;
2031
- /** Sequence metadata, including serial/identity ownership dependencies. */
2032
- const postgresSequencesQuery = `
2033
- SELECT c.oid::text AS oid, n.nspname AS namespace, c.relname AS physical_name,
2034
- format_type(s.seqtypid, -1) AS native_type,
2035
- s.seqstart, s.seqincrement, s.seqmin, s.seqmax, s.seqcache,
2036
- s.seqcycle, dep.refobjid::text AS owned_table_oid,
2037
- dep.refobjsubid::int AS owned_column_position
2038
- FROM pg_catalog.pg_sequence s
2039
- JOIN pg_catalog.pg_class c ON c.oid = s.seqrelid
2040
- JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace
2041
- LEFT JOIN pg_catalog.pg_depend dep
2042
- ON dep.classid = 'pg_catalog.pg_class'::regclass
2043
- AND dep.objid = c.oid AND dep.refclassid = 'pg_catalog.pg_class'::regclass
2044
- AND dep.deptype IN ('a', 'i')
2045
- WHERE n.nspname = $1
2046
- ORDER BY c.oid
2047
- `;
2048
- /** PostgreSQL enum labels in their declared order. */
2049
- const postgresEnumsQuery = `
2050
- SELECT t.oid::text AS oid, n.nspname AS namespace,
2051
- t.typname AS physical_name, e.oid::text AS value_oid,
2052
- e.enumlabel AS value, e.enumsortorder::float8 AS ordinal_position
2053
- FROM pg_catalog.pg_type t
2054
- JOIN pg_catalog.pg_namespace n ON n.oid = t.typnamespace
2055
- JOIN pg_catalog.pg_enum e ON e.enumtypid = t.oid
2056
- WHERE n.nspname = $1 AND t.typtype = 'e'
2057
- ORDER BY t.oid, e.enumsortorder
2058
- `;
2059
- /** PostgreSQL domains and their exact base type/default metadata. */
2060
- const postgresDomainsQuery = `
2061
- SELECT t.oid::text AS oid, n.nspname AS namespace,
2062
- t.typname AS physical_name,
2063
- format_type(t.typbasetype, t.typtypmod) AS native_type,
2064
- NOT t.typnotnull AS nullable, t.typdefault AS default_expression
2065
- FROM pg_catalog.pg_type t
2066
- JOIN pg_catalog.pg_namespace n ON n.oid = t.typnamespace
2067
- WHERE n.nspname = $1 AND t.typtype = 'd'
2068
- ORDER BY t.oid
2069
- `;
2070
- /** Domain CHECK constraints, which use pg_constraint.contypid. */
2071
- const postgresDomainConstraintsQuery = `
2072
- SELECT con.oid::text AS oid, con.contypid::text AS domain_oid,
2073
- con.conname AS physical_name, pg_get_constraintdef(con.oid, true) AS definition,
2074
- con.condeferrable, con.condeferred, con.convalidated
2075
- FROM pg_catalog.pg_constraint con
2076
- JOIN pg_catalog.pg_type t ON t.oid = con.contypid
2077
- JOIN pg_catalog.pg_namespace n ON n.oid = t.typnamespace
2078
- WHERE n.nspname = $1 AND con.contype = 'c'
2079
- ORDER BY con.contypid, con.oid
2080
- `;
2081
- /** Collation provider, locale, determinism, and version facts. */
2082
- const postgresCollationsQuery = `
2083
- SELECT c.oid::text AS oid, n.nspname AS namespace,
2084
- c.collname AS physical_name, c.collprovider, c.collcollate,
2085
- c.collctype, to_jsonb(c)->>'colllocale' AS colliculocale,
2086
- c.collisdeterministic, c.collversion
2087
- FROM pg_catalog.pg_collation c
2088
- JOIN pg_catalog.pg_namespace n ON n.oid = c.collnamespace
2089
- WHERE n.nspname = $1
2090
- ORDER BY c.oid
2091
- `;
2092
- /** User-defined triggers with decompiled condition and definition text. */
2093
- const postgresTriggersQuery = `
2094
- SELECT t.oid::text AS oid, t.tgrelid::text AS table_oid,
2095
- n.nspname AS namespace, t.tgname AS physical_name,
2096
- t.tgtype::int AS trigger_type, t.tgenabled,
2097
- pg_get_expr(t.tgqual, t.tgrelid, true) AS condition,
2098
- pg_get_triggerdef(t.oid, true) AS definition
2099
- FROM pg_catalog.pg_trigger t
2100
- JOIN pg_catalog.pg_class c ON c.oid = t.tgrelid
2101
- JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace
2102
- WHERE n.nspname = $1 AND NOT t.tgisinternal
2103
- ORDER BY t.tgrelid, t.oid
2104
- `;
2105
- /** PostgreSQL functions, procedures, aggregates, and window routines. */
2106
- const postgresRoutinesQuery = `
2107
- SELECT p.oid::text AS oid, n.nspname AS namespace,
2108
- p.proname AS physical_name, p.prokind,
2109
- format_type(p.prorettype, NULL) AS return_type,
2110
- l.lanname AS language, pg_get_functiondef(p.oid) AS definition,
2111
- pg_get_function_identity_arguments(p.oid) AS identity_arguments,
2112
- pg_get_expr(p.proargdefaults, 0, true) AS argument_defaults,
2113
- p.pronargdefaults, p.provolatile, p.proparallel, p.prosecdef
2114
- FROM pg_catalog.pg_proc p
2115
- JOIN pg_catalog.pg_namespace n ON n.oid = p.pronamespace
2116
- JOIN pg_catalog.pg_language l ON l.oid = p.prolang
2117
- WHERE n.nspname = $1 AND p.prokind IN ('f', 'p', 'a', 'w')
2118
- ORDER BY p.oid
2119
- `;
2120
- /** Routine parameter rows using PostgreSQL's complete argument type arrays. */
2121
- const postgresRoutineParametersQuery = `
2122
- SELECT p.oid::text AS routine_oid, x.position::int AS ordinal_position,
2123
- names.name AS parameter_name, modes.mode,
2124
- format_type(x.type_oid, -1) AS native_type
2125
- FROM pg_catalog.pg_proc p
2126
- JOIN pg_catalog.pg_namespace n ON n.oid = p.pronamespace
2127
- CROSS JOIN LATERAL unnest(
2128
- COALESCE(p.proallargtypes, p.proargtypes::oid[])
2129
- ) WITH ORDINALITY AS x(type_oid, position)
2130
- LEFT JOIN LATERAL unnest(p.proargnames) WITH ORDINALITY
2131
- AS names(name, position) ON names.position = x.position
2132
- LEFT JOIN LATERAL unnest(p.proargmodes) WITH ORDINALITY
2133
- AS modes(mode, position) ON modes.position = x.position
2134
- WHERE n.nspname = $1 AND p.prokind IN ('f', 'p', 'a', 'w')
2135
- ORDER BY p.oid, x.position
2136
- `;
2137
- /** Partition children, key attributes, strategy, and bound expression. */
2138
- const postgresPartitionsQuery = `
2139
- SELECT child.oid::text AS partition_oid, parent.oid::text AS parent_oid,
2140
- n.nspname AS namespace, child.relname AS physical_name,
2141
- part.partstrat, part.partattrs::text AS key_attributes,
2142
- pg_get_expr(child.relpartbound, child.oid, true) AS bound,
2143
- child.relispartition, child.relkind
2144
- FROM pg_catalog.pg_inherits inh
2145
- JOIN pg_catalog.pg_class child ON child.oid = inh.inhrelid
2146
- JOIN pg_catalog.pg_class parent ON parent.oid = inh.inhparent
2147
- JOIN pg_catalog.pg_namespace n ON n.oid = child.relnamespace
2148
- LEFT JOIN pg_catalog.pg_partitioned_table part ON part.partrelid = parent.oid
2149
- WHERE n.nspname = $1
2150
- ORDER BY parent.oid, child.oid
2151
- `;
2152
- /** Row-level security policies and their role/expression metadata. */
2153
- const postgresPoliciesQuery = `
2154
- SELECT p.oid::text AS oid, p.polrelid::text AS table_oid,
2155
- n.nspname AS namespace, p.polname AS physical_name,
2156
- p.polcmd, p.polpermissive,
2157
- ARRAY(SELECT r.rolname FROM pg_catalog.pg_roles r
2158
- WHERE r.oid = ANY(p.polroles)) AS roles,
2159
- pg_get_expr(p.polqual, p.polrelid, true) AS using_expression,
2160
- pg_get_expr(p.polwithcheck, p.polrelid, true) AS check_expression
2161
- FROM pg_catalog.pg_policy p
2162
- JOIN pg_catalog.pg_class c ON c.oid = p.polrelid
2163
- JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace
2164
- WHERE n.nspname = $1
2165
- ORDER BY p.polrelid, p.oid
2166
- `;
2167
- /** Installed PostgreSQL extensions scoped to the selected schema. */
2168
- const postgresExtensionsQuery = `
2169
- SELECT e.oid::text AS oid, n.nspname AS namespace,
2170
- e.extname AS physical_name, e.extversion, e.extrelocatable,
2171
- e.extconfig::text AS config_relations,
2172
- e.extcondition::text AS config_conditions
2173
- FROM pg_catalog.pg_extension e
2174
- JOIN pg_catalog.pg_namespace n ON n.oid = e.extnamespace
2175
- WHERE n.nspname = $1
2176
- ORDER BY e.oid
2177
- `;
2178
- /** Comments and owners for PostgreSQL objects visible in one schema. */
2179
- const postgresMetadataQuery = `
2180
- WITH objects AS (
2181
- SELECT 'pg_class'::text AS catalog_relation, 'pg_class'::regclass AS catalog_oid,
2182
- c.oid::text AS object_oid, 0::int AS object_subid,
2183
- CASE c.relkind WHEN 'r' THEN 'table' WHEN 'p' THEN 'table'
2184
- WHEN 'v' THEN 'view' WHEN 'm' THEN 'materialized-view'
2185
- WHEN 'S' THEN 'sequence' WHEN 'i' THEN 'index'
2186
- WHEN 'I' THEN 'index' WHEN 'f' THEN 'deferred-object'
2187
- ELSE 'opaque-object' END AS object_kind,
2188
- c.relname AS object_name, n.nspname AS namespace,
2189
- c.relowner::oid AS owner_oid, NULL::text AS parent_oid
2190
- FROM pg_catalog.pg_class c
2191
- JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace
2192
- WHERE n.nspname = $1
2193
- UNION ALL
2194
- SELECT 'pg_class', 'pg_class'::regclass, c.oid::text, a.attnum::int,
2195
- 'column', a.attname, n.nspname, c.relowner::oid, c.oid::text
2196
- FROM pg_catalog.pg_attribute a
2197
- JOIN pg_catalog.pg_class c ON c.oid = a.attrelid
2198
- JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace
2199
- WHERE n.nspname = $1 AND c.relkind IN ('r', 'p', 'v', 'm')
2200
- AND a.attnum > 0 AND NOT a.attisdropped
2201
- UNION ALL
2202
- SELECT 'pg_proc', 'pg_proc'::regclass, p.oid::text, 0,
2203
- 'routine', p.proname, n.nspname, p.proowner::oid, NULL
2204
- FROM pg_catalog.pg_proc p
2205
- JOIN pg_catalog.pg_namespace n ON n.oid = p.pronamespace
2206
- WHERE n.nspname = $1 AND p.prokind IN ('f', 'p', 'a', 'w')
2207
- UNION ALL
2208
- SELECT 'pg_type', 'pg_type'::regclass, t.oid::text, 0,
2209
- CASE t.typtype WHEN 'e' THEN 'enum' ELSE 'domain' END,
2210
- t.typname, n.nspname, t.typowner::oid, NULL
2211
- FROM pg_catalog.pg_type t
2212
- JOIN pg_catalog.pg_namespace n ON n.oid = t.typnamespace
2213
- WHERE n.nspname = $1 AND t.typtype IN ('e', 'd')
2214
- UNION ALL
2215
- SELECT 'pg_collation', 'pg_collation'::regclass, c.oid::text, 0,
2216
- 'collation', c.collname, n.nspname, c.collowner::oid, NULL
2217
- FROM pg_catalog.pg_collation c
2218
- JOIN pg_catalog.pg_namespace n ON n.oid = c.collnamespace
2219
- WHERE n.nspname = $1
2220
- UNION ALL
2221
- SELECT 'pg_extension', 'pg_extension'::regclass, e.oid::text, 0,
2222
- 'extension', e.extname, n.nspname, e.extowner::oid, NULL
2223
- FROM pg_catalog.pg_extension e
2224
- JOIN pg_catalog.pg_namespace n ON n.oid = e.extnamespace
2225
- WHERE n.nspname = $1
2226
- UNION ALL
2227
- SELECT 'pg_constraint', 'pg_constraint'::regclass, con.oid::text, 0,
2228
- 'constraint', con.conname, n.nspname, c.relowner::oid,
2229
- con.conrelid::text
2230
- FROM pg_catalog.pg_constraint con
2231
- JOIN pg_catalog.pg_class c ON c.oid = con.conrelid
2232
- JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace
2233
- WHERE n.nspname = $1
2234
- UNION ALL
2235
- SELECT 'pg_trigger', 'pg_trigger'::regclass, t.oid::text, 0,
2236
- 'trigger', t.tgname, n.nspname, c.relowner::oid,
2237
- t.tgrelid::text
2238
- FROM pg_catalog.pg_trigger t
2239
- JOIN pg_catalog.pg_class c ON c.oid = t.tgrelid
2240
- JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace
2241
- WHERE n.nspname = $1 AND NOT t.tgisinternal
2242
- UNION ALL
2243
- SELECT 'pg_policy', 'pg_policy'::regclass, p.oid::text, 0,
2244
- 'policy', p.polname, n.nspname, c.relowner::oid,
2245
- p.polrelid::text
2246
- FROM pg_catalog.pg_policy p
2247
- JOIN pg_catalog.pg_class c ON c.oid = p.polrelid
2248
- JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace
2249
- WHERE n.nspname = $1
2250
- )
2251
- SELECT o.catalog_relation, o.object_oid, o.object_subid,
2252
- o.object_kind, o.object_name, o.namespace, o.parent_oid,
2253
- d.description, pg_get_userbyid(o.owner_oid) AS owner
2254
- FROM objects o
2255
- LEFT JOIN pg_catalog.pg_description d
2256
- ON d.classoid = o.catalog_oid AND d.objoid::text = o.object_oid
2257
- AND d.objsubid = o.object_subid
2258
- ORDER BY o.catalog_relation, o.object_oid, o.object_subid
2259
- `;
2260
- async function query$1(connection, text, parameters, options, diagnostics, operation) {
2261
- try {
2262
- return await connection.query({
2263
- text,
2264
- parameters
2265
- }, { signal: options.signal });
2266
- } catch {
2267
- diagnostics.push(createIntrospectionDiagnostic({
2268
- severity: "error",
2269
- code: "query-failed",
2270
- message: `PostgreSQL catalog query failed while reading ${operation}`,
2271
- path: [operation],
2272
- remediation: "Check PostgreSQL permissions and the selected schema."
2273
- }));
2274
- return [];
2275
- }
2276
- }
2277
- function serverInfo$1(row, diagnostics) {
2278
- const rawVersion = text$1(row?.server_version) ?? "unknown";
2279
- const numericVersion = number$1(row?.server_version_num);
2280
- if (!row) diagnostics.push(createIntrospectionDiagnostic({
2281
- severity: "error",
2282
- code: "unsupported-server",
2283
- message: "PostgreSQL server version metadata was unavailable",
2284
- path: ["server"],
2285
- remediation: "Provide access to current_setting(server_version_num)."
2286
- }));
2287
- const major = numericVersion ? Math.floor(numericVersion / 1e4) : void 0;
2288
- const supported = major !== void 0 && major >= 12;
2289
- if (!supported) diagnostics.push(createIntrospectionDiagnostic({
2290
- severity: "error",
2291
- code: "unsupported-server",
2292
- message: "PostgreSQL introspection requires server version 12 or newer",
2293
- path: ["server", "version"],
2294
- remediation: "Use PostgreSQL 12+ or an adapter capability extension."
2295
- }));
2296
- return {
2297
- product: "postgresql",
2298
- rawVersion,
2299
- parsedVersion: major === void 0 ? void 0 : { major },
2300
- capabilities: {
2301
- generatedColumns: supported,
2302
- identityMetadata: numericVersion !== void 0 && numericVersion >= 1e5,
2303
- checkConstraints: true,
2304
- checkConstraintEnforcement: "enforced",
2305
- expressionDecompilation: true,
2306
- indexExpressions: true,
2307
- indexPredicates: true,
2308
- indexIncludedColumns: true,
2309
- namespaces: true,
2310
- visibility: "complete"
2311
- }
2312
- };
2313
- }
2314
- function emptyCatalog$1(namespace, diagnostics) {
2315
- return {
2316
- dialect: "postgresql",
2317
- server: {
2318
- product: "postgresql",
2319
- rawVersion: "unknown",
2320
- capabilities: {
2321
- generatedColumns: false,
2322
- identityMetadata: false,
2323
- checkConstraints: false,
2324
- checkConstraintEnforcement: "unknown",
2325
- expressionDecompilation: false,
2326
- indexExpressions: false,
2327
- indexPredicates: false,
2328
- indexIncludedColumns: false,
2329
- namespaces: false,
2330
- visibility: "unknown"
2331
- }
2332
- },
2333
- namespace: {
2334
- kind: "postgres-schema",
2335
- name: namespace
2336
- },
2337
- tables: [],
2338
- deferredObjects: [],
2339
- diagnostics: Object.freeze(diagnostics)
2340
- };
2341
- }
2342
- function viewObject(row, namespace, diagnostics) {
2343
- const physicalName = text$1(row.physical_name) ?? "unnamed_view";
2344
- const kind = row.relkind === "m" ? "materialized-view" : "view";
2345
- const physicalReference = reference$1(kind, physicalName, text$1(row.namespace) ?? namespace, "pg_class", "oid", row.oid);
2346
- const definition = text$1(row.definition);
2347
- if (definition === void 0) {
2348
- diagnostics.push(createIntrospectionDiagnostic({
2349
- severity: "warning",
2350
- code: "unmodeled-object",
2351
- message: `PostgreSQL ${kind} ${physicalName} has no recoverable definition`,
2352
- path: [
2353
- "views",
2354
- physicalName,
2355
- "definition"
2356
- ],
2357
- physicalReference,
2358
- remediation: "Grant access to pg_get_viewdef before treating this object as migration input."
2359
- }));
2360
- return deferredCatalogObject(kind === "view" ? "view" : "materialized-view", physicalName, physicalReference, [{
2361
- name: "definition",
2362
- value: expression("/* view definition unavailable */", "decompiler", physicalReference)
2363
- }]);
2364
- }
2365
- const options = stringArray(row.reloptions);
2366
- const checkOption = (() => {
2367
- const value = text$1(row.check_option)?.toLowerCase();
2368
- return value === "none" || value === "local" || value === "cascaded" ? value : void 0;
2369
- })();
2370
- return {
2371
- kind,
2372
- id: stableId$1(physicalName),
2373
- identitySource: "physical-name",
2374
- physicalName,
2375
- columns: [],
2376
- definition: expression(definition, "decompiler", physicalReference),
2377
- ...checkOption === "local" || checkOption === "cascaded" ? { checkOption } : checkOption === "none" ? { checkOption: "none" } : {},
2378
- ...booleanOption(options, "security_barrier") === void 0 ? {} : { securityBarrier: booleanOption(options, "security_barrier") },
2379
- ...booleanOption(options, "security_invoker") === void 0 ? {} : { securityInvoker: booleanOption(options, "security_invoker") },
2380
- reference: physicalReference
2381
- };
2382
- }
2383
- function columnKey(tableOid, ordinalPosition) {
2384
- return `${text$1(tableOid) ?? "unknown"}:${number$1(ordinalPosition) ?? 0}`;
2385
- }
2386
- function compareOrdinal(left, right) {
2387
- return (number$1(left.ordinal_position) ?? 0) - (number$1(right.ordinal_position) ?? 0);
2388
- }
2389
- function identityOptions(row) {
2390
- const options = {};
2391
- for (const [key, value] of [
2392
- ["start", row.seqstart],
2393
- ["increment", row.seqincrement],
2394
- ["minimum", row.seqmin],
2395
- ["maximum", row.seqmax],
2396
- ["cache", row.seqcache]
2397
- ]) {
2398
- const fact = literalFact(value);
2399
- if (fact !== void 0) options[key] = fact;
2400
- }
2401
- if (row.seqcycle !== void 0) options.cycle = {
2402
- kind: "literal",
2403
- value: boolean$1(row.seqcycle)
2404
- };
2405
- if (text$1(row.sequence_type) !== void 0) options.type = {
2406
- kind: "literal",
2407
- value: text$1(row.sequence_type)
2408
- };
2409
- return options;
2410
- }
2411
- function sequenceObject(row, namespace, tableByOid, diagnostics) {
2412
- const physicalName = text$1(row.physical_name) ?? `sequence_${text$1(row.oid) ?? "unknown"}`;
2413
- const physicalReference = reference$1("sequence", physicalName, text$1(row.namespace) ?? namespace, "pg_class", "oid", row.oid);
2414
- const ownedTable = tableByOid.get(text$1(row.owned_table_oid));
2415
- const ownedBy = ownedTable ? {
2416
- kind: "table",
2417
- id: ownedTable.id
2418
- } : void 0;
2419
- const ownedTableOid = text$1(row.owned_table_oid);
2420
- const ownedColumnPosition = number$1(row.owned_column_position);
2421
- if (ownedTableOid !== void 0 && ownedBy === void 0) diagnostics.push(createIntrospectionDiagnostic({
2422
- severity: "warning",
2423
- code: "unresolved-reference",
2424
- message: `PostgreSQL sequence ${physicalName} has an ownership target outside the selected schema`,
2425
- path: [
2426
- "sequences",
2427
- physicalName,
2428
- "ownedBy"
2429
- ],
2430
- physicalReference,
2431
- remediation: "Select the owning table schema or inspect the retained ownership catalog reference."
2432
- }));
2433
- const data = {};
2434
- if (ownedTableOid !== void 0) data.ownedTableOid = ownedTableOid;
2435
- if (ownedColumnPosition !== void 0) data.ownedColumnPosition = ownedColumnPosition;
2436
- return {
2437
- kind: "sequence",
2438
- id: stableId$1(physicalName),
2439
- identitySource: "physical-name",
2440
- physicalName,
2441
- storage: storage(row.native_type),
2442
- ...factIfPresent(row.seqstart) === void 0 ? {} : { start: factIfPresent(row.seqstart) },
2443
- ...factIfPresent(row.seqincrement) === void 0 ? {} : { increment: factIfPresent(row.seqincrement) },
2444
- ...factIfPresent(row.seqmin) === void 0 ? {} : { minimum: factIfPresent(row.seqmin) },
2445
- ...factIfPresent(row.seqmax) === void 0 ? {} : { maximum: factIfPresent(row.seqmax) },
2446
- ...factIfPresent(row.seqcache) === void 0 ? {} : { cache: factIfPresent(row.seqcache) },
2447
- ...row.seqcycle === void 0 || row.seqcycle === null ? {} : { cycle: boolean$1(row.seqcycle) },
2448
- ...ownedBy === void 0 ? {} : { ownedBy },
2449
- ...Object.keys(data).length === 0 ? {} : { dialect: {
2450
- dialect: "postgresql",
2451
- version: 1,
2452
- data
2453
- } },
2454
- reference: physicalReference
2455
- };
2456
- }
2457
- function mapEnums(rows, namespace) {
2458
- const groups = /* @__PURE__ */ new Map();
2459
- for (const row of rows) {
2460
- const key = text$1(row.oid) ?? text$1(row.physical_name) ?? "unknown";
2461
- const values = groups.get(key) ?? [];
2462
- values.push(row);
2463
- groups.set(key, values);
2464
- }
2465
- return [...groups.values()].map((enumRows) => {
2466
- const first = enumRows[0];
2467
- const physicalName = text$1(first.physical_name) ?? `enum_${text$1(first.oid) ?? "unknown"}`;
2468
- const physicalReference = reference$1("enum", physicalName, text$1(first.namespace) ?? namespace, "pg_type", "oid", first.oid);
2469
- const values = [...enumRows].sort((left, right) => (number$1(left.ordinal_position) ?? 0) - (number$1(right.ordinal_position) ?? 0)).map((row, index) => ({
2470
- value: text$1(row.value) ?? "",
2471
- ordinalPosition: index + 1,
2472
- provenance: {
2473
- kind: "catalog",
2474
- dialect: "postgresql",
2475
- reference: reference$1("enum", physicalName, text$1(row.namespace) ?? namespace, "pg_enum", "oid", row.value_oid)
2476
- }
2477
- }));
2478
- return {
2479
- kind: "enum",
2480
- id: stableId$1(physicalName),
2481
- identitySource: "physical-name",
2482
- physicalName,
2483
- values,
2484
- reference: physicalReference
2485
- };
2486
- });
2487
- }
2488
- function mapDomains(rows, constraintRows, namespace) {
2489
- const constraintsByDomain = groupBy(constraintRows, (row) => text$1(row.domain_oid) ?? "unknown");
2490
- return rows.map((row) => {
2491
- const physicalName = text$1(row.physical_name) ?? `domain_${text$1(row.oid) ?? "unknown"}`;
2492
- const physicalReference = reference$1("domain", physicalName, text$1(row.namespace) ?? namespace, "pg_type", "oid", row.oid);
2493
- const domainConstraints = (constraintsByDomain.get(text$1(row.oid)) ?? []).map((constraintRow) => {
2494
- const constraintName = text$1(constraintRow.physical_name) ?? `domain_constraint_${text$1(constraintRow.oid) ?? "unknown"}`;
2495
- const constraintReference = reference$1("constraint", constraintName, text$1(row.namespace) ?? namespace, "pg_constraint", "oid", constraintRow.oid);
2496
- return {
2497
- kind: "check",
2498
- id: stableId$1(constraintName),
2499
- identitySource: "physical-name",
2500
- physicalName: constraintName,
2501
- expression: expression(text$1(constraintRow.definition) ?? "CHECK (true)", "decompiler", constraintReference),
2502
- deferrable: constraintRow.condeferrable === void 0 ? void 0 : boolean$1(constraintRow.condeferrable),
2503
- initially: constraintRow.condeferred === void 0 ? void 0 : boolean$1(constraintRow.condeferred) ? "deferred" : "immediate",
2504
- validated: constraintRow.convalidated === void 0 ? void 0 : boolean$1(constraintRow.convalidated),
2505
- reference: constraintReference
2506
- };
2507
- });
2508
- return {
2509
- kind: "domain",
2510
- id: stableId$1(physicalName),
2511
- identitySource: "physical-name",
2512
- physicalName,
2513
- storage: storage(row.native_type),
2514
- ...row.nullable === void 0 || row.nullable === null ? {} : { nullable: boolean$1(row.nullable) },
2515
- ...factIfPresent(row.default_expression) === void 0 ? {} : { default: factIfPresent(row.default_expression) },
2516
- ...domainConstraints.length === 0 ? {} : { constraints: domainConstraints },
2517
- reference: physicalReference
2518
- };
2519
- });
2520
- }
2521
- function collationObject(row, namespace) {
2522
- const physicalName = text$1(row.physical_name) ?? `collation_${text$1(row.oid) ?? "unknown"}`;
2523
- return {
2524
- kind: "collation",
2525
- id: stableId$1(physicalName),
2526
- identitySource: "physical-name",
2527
- physicalName,
2528
- ...text$1(row.collprovider) === void 0 ? {} : { provider: text$1(row.collprovider) },
2529
- ...(text$1(row.colliculocale) ?? text$1(row.collcollate) ?? text$1(row.collctype)) === void 0 ? {} : { locale: text$1(row.colliculocale) ?? text$1(row.collcollate) ?? text$1(row.collctype) },
2530
- ...row.collisdeterministic === void 0 || row.collisdeterministic === null ? {} : { deterministic: boolean$1(row.collisdeterministic) },
2531
- ...text$1(row.collversion) === void 0 ? {} : { version: text$1(row.collversion) },
2532
- reference: reference$1("collation", physicalName, text$1(row.namespace) ?? namespace, "pg_collation", "oid", row.oid)
2533
- };
2534
- }
2535
- function triggerObject(row, namespace, relationReferences, diagnostics) {
2536
- const physicalName = text$1(row.physical_name) ?? `trigger_${text$1(row.oid) ?? "unknown"}`;
2537
- const physicalReference = reference$1("trigger", physicalName, text$1(row.namespace) ?? namespace, "pg_trigger", "oid", row.oid);
2538
- const table = relationReferences.get(text$1(row.table_oid));
2539
- const definition = text$1(row.definition);
2540
- if (table === void 0 || definition === void 0) {
2541
- diagnostics.push(createIntrospectionDiagnostic({
2542
- severity: "warning",
2543
- code: table === void 0 ? "unresolved-reference" : "unmodeled-object",
2544
- message: table === void 0 ? `PostgreSQL trigger ${physicalName} has no selected parent relation` : `PostgreSQL trigger ${physicalName} has no recoverable definition`,
2545
- path: ["triggers", physicalName],
2546
- physicalReference,
2547
- remediation: "Retain the deferred trigger until its parent relation and definition are visible."
2548
- }));
2549
- return deferredCatalogObject("trigger", physicalName, physicalReference, [...table === void 0 ? [{
2550
- name: "tableOid",
2551
- value: text$1(row.table_oid) ?? "unknown"
2552
- }] : [], ...definition === void 0 ? [] : [{
2553
- name: "definition",
2554
- value: expression(definition, "decompiler", physicalReference)
2555
- }]]);
2556
- }
2557
- const triggerType = number$1(row.trigger_type) ?? 0;
2558
- const timing = triggerType & 64 ? "instead-of" : triggerType & 2 ? "before" : "after";
2559
- const events = triggerEvents$1(triggerType);
2560
- const mode = triggerType & 1 ? "row" : "statement";
2561
- const enabled = triggerEnabled(row.tgenabled);
2562
- return {
2563
- kind: "trigger",
2564
- id: stableId$1(physicalName),
2565
- identitySource: "physical-name",
2566
- physicalName,
2567
- table,
2568
- timing,
2569
- events,
2570
- orientation: mode,
2571
- ...text$1(row.condition) === void 0 ? {} : { condition: expression(text$1(row.condition), "decompiler", physicalReference) },
2572
- body: expression(definition, "decompiler", physicalReference),
2573
- ...enabled === void 0 ? {} : { enabled },
2574
- reference: physicalReference
2575
- };
2576
- }
2577
- function mapRoutines(rows, parameterRows, namespace, diagnostics) {
2578
- const parametersByRoutine = groupBy(parameterRows, (row) => text$1(row.routine_oid) ?? "unknown");
2579
- const names = /* @__PURE__ */ new Map();
2580
- for (const row of rows) {
2581
- const name = text$1(row.physical_name) ?? `routine_${text$1(row.oid) ?? "unknown"}`;
2582
- names.set(name, (names.get(name) ?? 0) + 1);
2583
- }
2584
- return rows.map((row) => {
2585
- const physicalName = text$1(row.physical_name) ?? `routine_${text$1(row.oid) ?? "unknown"}`;
2586
- const physicalReference = reference$1("routine", physicalName, text$1(row.namespace) ?? namespace, "pg_proc", "oid", row.oid);
2587
- const identityArguments = text$1(row.identity_arguments);
2588
- const defaultArguments = text$1(row.argument_defaults);
2589
- if (defaultArguments !== void 0) diagnostics.push(createIntrospectionDiagnostic({
2590
- severity: "info",
2591
- code: "unmodeled-object",
2592
- message: `PostgreSQL routine ${physicalName} retains its argument defaults as opaque catalog text`,
2593
- path: [
2594
- "routines",
2595
- physicalName,
2596
- "argumentDefaults"
2597
- ],
2598
- physicalReference,
2599
- remediation: "Review routine argument defaults before using the complete snapshot for migration planning."
2600
- }));
2601
- if (text$1(row.definition) === void 0) diagnostics.push(createIntrospectionDiagnostic({
2602
- severity: "warning",
2603
- code: "unmodeled-object",
2604
- message: `PostgreSQL routine ${physicalName} has no recoverable definition`,
2605
- path: [
2606
- "routines",
2607
- physicalName,
2608
- "definition"
2609
- ],
2610
- physicalReference,
2611
- remediation: "Grant access to pg_get_functiondef before treating this routine as migration input."
2612
- }));
2613
- const routineUnknownFields = [...identityArguments === void 0 ? [] : [{
2614
- name: "identityArguments",
2615
- value: expression(identityArguments, "decompiler", physicalReference)
2616
- }], ...defaultArguments === void 0 ? [] : [{
2617
- name: "argumentDefaults",
2618
- value: expression(defaultArguments, "decompiler", physicalReference)
2619
- }]];
2620
- const parameters = (parametersByRoutine.get(text$1(row.oid)) ?? []).sort((left, right) => (number$1(left.ordinal_position) ?? 0) - (number$1(right.ordinal_position) ?? 0)).map((parameter) => ({
2621
- ...text$1(parameter.parameter_name) === void 0 ? {} : { name: text$1(parameter.parameter_name) },
2622
- ...routineParameterMode(parameter.mode) === void 0 ? {} : { mode: routineParameterMode(parameter.mode) },
2623
- storage: storage(parameter.native_type),
2624
- ordinalPosition: number$1(parameter.ordinal_position) ?? 0,
2625
- provenance: {
2626
- kind: "catalog",
2627
- dialect: "postgresql",
2628
- reference: physicalReference
2629
- }
2630
- }));
2631
- return {
2632
- kind: "routine",
2633
- id: stableId$1((names.get(physicalName) ?? 0) < 2 || identityArguments === void 0 ? physicalName : `${physicalName}_${identityArguments.replace(/[^a-zA-Z0-9_]+/g, "_")}`),
2634
- identitySource: "physical-name",
2635
- physicalName,
2636
- routineKind: routineKind(row.prokind),
2637
- parameters,
2638
- ...text$1(row.return_type) === void 0 ? {} : { returnType: storage(row.return_type) },
2639
- ...text$1(row.language) === void 0 ? {} : { language: text$1(row.language) },
2640
- ...text$1(row.definition) === void 0 ? {} : { body: expression(text$1(row.definition), "decompiler", physicalReference) },
2641
- ...routineVolatility(row.provolatile) === void 0 ? {} : { volatility: routineVolatility(row.provolatile) },
2642
- ...routineParallel(row.proparallel) === void 0 ? {} : { parallel: routineParallel(row.proparallel) },
2643
- ...row.prosecdef === void 0 || row.prosecdef === null ? {} : { security: boolean$1(row.prosecdef) ? "definer" : "invoker" },
2644
- ...routineUnknownFields.length === 0 ? {} : { unknownFields: routineUnknownFields },
2645
- reference: physicalReference
2646
- };
2647
- });
2648
- }
2649
- function partitionObject(row, namespace, tableByOid, diagnostics) {
2650
- const physicalName = text$1(row.physical_name) ?? `partition_${text$1(row.partition_oid) ?? "unknown"}`;
2651
- const physicalReference = reference$1("partition", physicalName, text$1(row.namespace) ?? namespace, "pg_class", "oid", row.partition_oid);
2652
- const parent = tableByOid.get(text$1(row.parent_oid));
2653
- if (parent === void 0) diagnostics.push(createIntrospectionDiagnostic({
2654
- severity: "error",
2655
- code: "unresolved-reference",
2656
- message: `PostgreSQL partition ${physicalName} has no parent table in the selected schema`,
2657
- path: [
2658
- "partitions",
2659
- physicalName,
2660
- "parent"
2661
- ],
2662
- physicalReference,
2663
- remediation: "Select the parent table schema before mapping partitions."
2664
- }));
2665
- const parentReference = parent ? {
2666
- kind: "table",
2667
- id: parent.id
2668
- } : {
2669
- kind: "table",
2670
- id: stableId$1(`missing_parent_${text$1(row.parent_oid) ?? "unknown"}`)
2671
- };
2672
- const keyColumns = partitionKeyColumns(row.key_attributes, parent?.columns ?? []);
2673
- const bound = text$1(row.bound);
2674
- return {
2675
- kind: "partition",
2676
- id: stableId$1(physicalName),
2677
- identitySource: "physical-name",
2678
- physicalName,
2679
- parent: parentReference,
2680
- strategy: partitionStrategy(row.partstrat),
2681
- ...keyColumns.length === 0 ? {} : { keyColumns },
2682
- ...bound === void 0 ? {} : { bound: expression(bound, "decompiler", physicalReference) },
2683
- ...bound !== void 0 && /^default$/i.test(bound.trim()) ? { default: true } : {},
2684
- reference: physicalReference
2685
- };
2686
- }
2687
- function policyObject(row, namespace, tableByOid, diagnostics) {
2688
- const physicalName = text$1(row.physical_name) ?? `policy_${text$1(row.oid) ?? "unknown"}`;
2689
- const physicalReference = reference$1("policy", physicalName, text$1(row.namespace) ?? namespace, "pg_policy", "oid", row.oid);
2690
- const table = tableByOid.get(text$1(row.table_oid));
2691
- if (table === void 0) diagnostics.push(createIntrospectionDiagnostic({
2692
- severity: "error",
2693
- code: "unresolved-reference",
2694
- message: `PostgreSQL policy ${physicalName} has no selected table`,
2695
- path: [
2696
- "policies",
2697
- physicalName,
2698
- "table"
2699
- ],
2700
- physicalReference,
2701
- remediation: "Select the policy table schema before mapping row-level security."
2702
- }));
2703
- return {
2704
- kind: "policy",
2705
- id: stableId$1(physicalName),
2706
- identitySource: "physical-name",
2707
- physicalName,
2708
- table: table ? {
2709
- kind: "table",
2710
- id: table.id
2711
- } : {
2712
- kind: "table",
2713
- id: stableId$1(`missing_table_${text$1(row.table_oid) ?? "unknown"}`)
2714
- },
2715
- command: policyCommand(row.polcmd),
2716
- ...stringArray(row.roles).length === 0 ? {} : { roles: stringArray(row.roles) },
2717
- ...row.polpermissive === void 0 || row.polpermissive === null ? {} : { permissive: boolean$1(row.polpermissive) },
2718
- ...text$1(row.using_expression) === void 0 ? {} : { using: expression(text$1(row.using_expression), "decompiler", physicalReference) },
2719
- ...text$1(row.check_expression) === void 0 ? {} : { check: expression(text$1(row.check_expression), "decompiler", physicalReference) },
2720
- reference: physicalReference
2721
- };
2722
- }
2723
- function extensionObject(row, namespace) {
2724
- const physicalName = text$1(row.physical_name) ?? `extension_${text$1(row.oid) ?? "unknown"}`;
2725
- const physicalReference = reference$1("extension", physicalName, text$1(row.namespace) ?? namespace, "pg_extension", "oid", row.oid);
2726
- const data = { relocatable: boolean$1(row.extrelocatable) };
2727
- const configuration = {};
2728
- if (text$1(row.config_relations) !== void 0) configuration.relations = text$1(row.config_relations);
2729
- if (text$1(row.config_conditions) !== void 0) configuration.conditions = text$1(row.config_conditions);
2730
- return {
2731
- kind: "extension",
2732
- id: stableId$1(physicalName),
2733
- identitySource: "physical-name",
2734
- physicalName,
2735
- extensionName: physicalName,
2736
- ...text$1(row.extversion) === void 0 ? {} : { extensionVersion: text$1(row.extversion) },
2737
- ...text$1(row.namespace) === void 0 ? {} : { schema: text$1(row.namespace) },
2738
- data,
2739
- ...Object.keys(configuration).length === 0 ? {} : { configuration },
2740
- dialect: {
2741
- dialect: "postgresql",
2742
- version: 1,
2743
- data: { relocatable: boolean$1(row.extrelocatable) }
2744
- },
2745
- reference: physicalReference
2746
- };
2747
- }
2748
- function deferredCatalogObject(objectKind, physicalName, physicalReference, unknownFields = []) {
2749
- return {
2750
- kind: "deferred-object",
2751
- objectKind,
2752
- id: stableId$1(`deferred_${objectKind}_${physicalName}`),
2753
- identitySource: "physical-name",
2754
- physicalName,
2755
- reference: physicalReference,
2756
- ...unknownFields.length === 0 ? {} : { unknownFields }
2757
- };
2758
- }
2759
- function triggerEvents$1(triggerType) {
2760
- const events = [];
2761
- if (triggerType & 4) events.push("insert");
2762
- if (triggerType & 8) events.push("delete");
2763
- if (triggerType & 16) events.push("update");
2764
- if (triggerType & 32) events.push("truncate");
2765
- return events.sort();
2766
- }
2767
- function triggerEnabled(value) {
2768
- const code = text$1(value)?.toUpperCase();
2769
- if (code === "D") return false;
2770
- if (code === "O" || code === "R" || code === "A") return true;
2771
- }
2772
- function routineKind(value) {
2773
- return {
2774
- f: "function",
2775
- p: "procedure",
2776
- a: "aggregate",
2777
- w: "window"
2778
- }[text$1(value)] ?? "unknown";
2779
- }
2780
- function routineParameterMode(value) {
2781
- return {
2782
- i: "in",
2783
- o: "out",
2784
- b: "inout",
2785
- v: "variadic",
2786
- t: "table"
2787
- }[text$1(value)];
2788
- }
2789
- function routineVolatility(value) {
2790
- return {
2791
- i: "immutable",
2792
- s: "stable",
2793
- v: "volatile"
2794
- }[text$1(value)];
2795
- }
2796
- function routineParallel(value) {
2797
- return {
2798
- s: "safe",
2799
- r: "restricted",
2800
- u: "unsafe"
2801
- }[text$1(value)];
2802
- }
2803
- function partitionStrategy(value) {
2804
- return {
2805
- r: "range",
2806
- l: "list",
2807
- h: "hash"
2808
- }[text$1(value)] ?? "unknown";
2809
- }
2810
- function partitionKeyColumns(value, columns) {
2811
- const byOrdinal = new Map(columns.map((column) => [column.ordinalPosition, column.physicalName]));
2812
- return integerArray(value).filter((position) => position > 0).map((position) => byOrdinal.get(position) ?? `attnum_${position}`);
2813
- }
2814
- function policyCommand(value) {
2815
- return {
2816
- "*": "all",
2817
- r: "select",
2818
- a: "insert",
2819
- w: "update",
2820
- d: "delete"
2821
- }[text$1(value)] ?? "unknown";
2822
- }
2823
- function storage(value) {
2824
- return { nativeType: text$1(value) ?? "unknown" };
2825
- }
2826
- function factIfPresent(value) {
2827
- if (value === void 0 || value === null) return;
2828
- return literalFact(value);
2829
- }
2830
- function literalFact(value) {
2831
- if (value === void 0) return;
2832
- if (value === null) return {
2833
- kind: "literal",
2834
- value: null
2835
- };
2836
- if (typeof value === "boolean") return {
2837
- kind: "literal",
2838
- value
2839
- };
2840
- if (typeof value === "bigint") return {
2841
- kind: "literal",
2842
- value
2843
- };
2844
- if (typeof value === "number") return Number.isFinite(value) ? {
2845
- kind: "literal",
2846
- value
2847
- } : {
2848
- kind: "literal",
2849
- value: String(value)
2850
- };
2851
- const textValue = String(value);
2852
- if (/^[+-]?\d+$/.test(textValue.trim())) try {
2853
- const integerValue = BigInt(textValue);
2854
- if (integerValue > BigInt(Number.MAX_SAFE_INTEGER) || integerValue < BigInt(Number.MIN_SAFE_INTEGER)) return {
2855
- kind: "literal",
2856
- value: integerValue
2857
- };
2858
- } catch {}
2859
- const numericValue = Number(textValue);
2860
- return textValue.trim() !== "" && Number.isFinite(numericValue) ? {
2861
- kind: "literal",
2862
- value: numericValue
2863
- } : {
2864
- kind: "literal",
2865
- value: textValue
2866
- };
2867
- }
2868
- function relationTable(row) {
2869
- const physicalName = text$1(row.relname) ?? "unnamed_table";
2870
- return {
2871
- kind: "table",
2872
- id: stableId$1(physicalName),
2873
- identitySource: "physical-name",
2874
- physicalName,
2875
- reference: reference$1("table", physicalName, text$1(row.namespace), "pg_class", "oid", row.oid),
2876
- columns: [],
2877
- constraints: [],
2878
- indexes: [],
2879
- unknownFields: boolean$1(row.relispartition) ? [{
2880
- name: "partitioned",
2881
- value: true
2882
- }] : void 0
2883
- };
2884
- }
2885
- function deferredObject(row, objectKind = "other") {
2886
- const physicalName = text$1(row.relname) ?? "unnamed_object";
2887
- return {
2888
- kind: "deferred-object",
2889
- objectKind,
2890
- id: stableId$1(`deferred:${objectKind}:${physicalName}`),
2891
- identitySource: "physical-name",
2892
- physicalName,
2893
- reference: reference$1("deferred-object", physicalName, text$1(row.namespace), "pg_class", "oid", row.oid)
2894
- };
2895
- }
2896
- function opaqueRelationObject(row, namespace, diagnostics) {
2897
- const physicalName = text$1(row.relname) ?? "unnamed_object";
2898
- const relkind = text$1(row.relkind) ?? "unknown";
2899
- const physicalReference = reference$1("opaque-object", physicalName, text$1(row.namespace) ?? namespace, "pg_class", "oid", row.oid);
2900
- diagnostics.push(createIntrospectionDiagnostic({
2901
- severity: "warning",
2902
- code: "unmodeled-object",
2903
- message: `PostgreSQL relation ${physicalName} (${relkind}) was retained as an opaque object`,
2904
- path: ["opaqueObjects", physicalName],
2905
- physicalReference,
2906
- remediation: "Inspect the opaque object before treating it as migration input."
2907
- }));
2908
- return {
2909
- kind: "opaque-object",
2910
- id: stableId$1(`relation:${relkind}:${physicalName}`),
2911
- identitySource: "physical-name",
2912
- physicalName,
2913
- objectKind: `postgres-relation:${relkind}`,
2914
- data: {
2915
- relkind,
2916
- relispartition: boolean$1(row.relispartition)
2917
- },
2918
- reference: physicalReference
2919
- };
2920
- }
2921
- function column$1(row, table, namespace, identityOptionValues) {
2922
- const physicalName = text$1(row.physical_name) ?? "unnamed_column";
2923
- const defaultExpression = text$1(row.default_expression);
2924
- const identityValue = text$1(row.attidentity);
2925
- const generatedValue = text$1(row.attgenerated);
2926
- const identity = identityValue === "a" || identityValue === "d" ? {
2927
- kind: "identity",
2928
- generation: identityValue === "a" ? "always" : "by-default",
2929
- options: identityOptionValues ?? {}
2930
- } : void 0;
2931
- const generated = (generatedValue === "s" || generatedValue === "v") && defaultExpression ? {
2932
- kind: "generated",
2933
- mode: generatedValue === "s" ? "stored" : "virtual",
2934
- expression: sql$1(defaultExpression, namespace, table, physicalName)
2935
- } : void 0;
2936
- const ordinaryDefault = defaultExpression && !identity && !generated ? {
2937
- kind: "expression",
2938
- expression: sql$1(defaultExpression, namespace, table, physicalName)
2939
- } : void 0;
2940
- return {
2941
- kind: "column",
2942
- id: stableId$1(physicalName),
2943
- identitySource: "physical-name",
2944
- physicalName,
2945
- ordinalPosition: number$1(row.ordinal_position) ?? 0,
2946
- nullable: boolean$1(row.nullable),
2947
- storage: { nativeType: text$1(row.native_type) ?? "unknown" },
2948
- ...ordinaryDefault ? { default: ordinaryDefault } : {},
2949
- ...generated ? { generated } : {},
2950
- identity,
2951
- reference: reference$1("column", physicalName, namespace, "pg_attribute", "attrelid", row.table_oid)
2952
- };
2953
- }
2954
- function constraint(row, table, columnsByNumber, tableByOid, namespace, diagnostics, indexReferences) {
2955
- const kind = text$1(row.contype);
2956
- const physicalName = text$1(row.physical_name) ?? `constraint_${text$1(row.oid) ?? "unknown"}`;
2957
- const columns = integerArray(row.conkey).map((numberValue) => columnsByNumber.get(numberValue) ?? `attnum_${numberValue}`);
2958
- const common = {
2959
- id: stableId$1(physicalName),
2960
- identitySource: "physical-name",
2961
- physicalName,
2962
- deferrable: boolean$1(row.condeferrable),
2963
- initially: boolean$1(row.condeferred) ? "deferred" : "immediate",
2964
- validated: boolean$1(row.convalidated),
2965
- reference: reference$1("constraint", physicalName, namespace, "pg_constraint", "oid", row.oid),
2966
- dialect: row.convalidated === false ? {
2967
- dialect: "postgresql",
2968
- version: 1,
2969
- data: { notValid: true }
2970
- } : void 0
2971
- };
2972
- const backingOid = text$1(row.backing_index_oid);
2973
- const backing = backingOid ? indexReferences.get(`pg_class:${backingOid}`) : void 0;
2974
- const backingIndex = backing ? {
2975
- kind: "index",
2976
- id: backing.id
2977
- } : void 0;
2978
- if (kind === "p") return {
2979
- kind: "primary-key",
2980
- ...common,
2981
- columns,
2982
- ...backingIndex === void 0 ? {} : { backingIndex }
2983
- };
2984
- if (kind === "u") return {
2985
- kind: "unique",
2986
- ...common,
2987
- columns,
2988
- nulls: boolean$1(row.indnullsnotdistinct) ? "not-distinct" : "distinct",
2989
- ...backingIndex === void 0 ? {} : { backingIndex }
2990
- };
2991
- if (kind === "c") return {
2992
- kind: "check",
2993
- ...common,
2994
- expression: sql$1(text$1(row.definition) ?? "CHECK (true)", namespace, table, physicalName)
2995
- };
2996
- if (kind !== "f") return;
2997
- const targetTable = tableByOid.get(text$1(row.target_table_oid));
2998
- if (!targetTable) {
2999
- diagnostics.push(createIntrospectionDiagnostic({
3000
- severity: "error",
3001
- code: "unresolved-reference",
3002
- message: `PostgreSQL foreign key target ${text$1(row.target_table_oid) ?? "unknown"} was not found`,
3003
- path: [
3004
- "tables",
3005
- table.id,
3006
- "constraints",
3007
- physicalName
3008
- ]
3009
- }));
3010
- return;
3011
- }
3012
- const targetColumns = integerArray(row.confkey).map((numberValue) => {
3013
- return targetTable.columns.find((column) => column.ordinalPosition === numberValue)?.physicalName ?? `attnum_${numberValue}`;
3014
- });
3015
- return {
3016
- kind: "foreign-key",
3017
- ...common,
3018
- columns,
3019
- target: {
3020
- table: targetTable.physicalName,
3021
- columns: targetColumns
3022
- },
3023
- onUpdate: referentialAction(row.confupdtype),
3024
- onDelete: referentialAction(row.confdeltype),
3025
- match: matchType(row.confmatchtype)
3026
- };
3027
- }
3028
- function mapIndexes(rows, table, columnsByNumber, namespace) {
3029
- const grouped = /* @__PURE__ */ new Map();
3030
- for (const row of rows) {
3031
- const key = text$1(row.index_oid) ?? text$1(row.physical_name) ?? "unknown";
3032
- const existing = grouped.get(key) ?? [];
3033
- existing.push(row);
3034
- grouped.set(key, existing);
3035
- }
3036
- return [...grouped.values()].map((indexRows) => {
3037
- const orderedRows = [...indexRows].sort((left, right) => (number$1(left.position) ?? 0) - (number$1(right.position) ?? 0));
3038
- const first = orderedRows[0];
3039
- const physicalName = text$1(first.physical_name) ?? `index_${text$1(first.index_oid) ?? "unknown"}`;
3040
- const keyCount = number$1(first.indnkeyatts) ?? indexRows.length;
3041
- const terms = [];
3042
- const includedColumns = [];
3043
- for (const row of orderedRows) {
3044
- const position = number$1(row.position) ?? 0;
3045
- const attnum = number$1(row.attnum) ?? 0;
3046
- const columnName = attnum > 0 ? columnsByNumber.get(attnum) : void 0;
3047
- if (position > keyCount) {
3048
- if (columnName) includedColumns.push(columnName);
3049
- continue;
3050
- }
3051
- terms.push(columnName ? {
3052
- kind: "column",
3053
- column: columnName,
3054
- position,
3055
- ...indexTermOptions(row, text$1(first.method)),
3056
- ...text$1(row.operator_class) === void 0 ? {} : { operatorClass: text$1(row.operator_class) }
3057
- } : {
3058
- kind: "expression",
3059
- expression: sql$1(text$1(row.term_definition) ?? "/* expression unavailable */", namespace, table, physicalName),
3060
- position,
3061
- ...indexTermOptions(row, text$1(first.method)),
3062
- ...text$1(row.operator_class) === void 0 ? {} : { operatorClass: text$1(row.operator_class) }
3063
- });
3064
- }
3065
- return {
3066
- kind: "index",
3067
- id: stableId$1(physicalName),
3068
- identitySource: "physical-name",
3069
- physicalName,
3070
- unique: boolean$1(first.indisunique),
3071
- terms,
3072
- predicate: text$1(first.predicate) ? sql$1(text$1(first.predicate), namespace, table, physicalName) : void 0,
3073
- includedColumns: includedColumns.length > 0 ? includedColumns : void 0,
3074
- method: text$1(first.method),
3075
- dialect: text$1(first.method) && text$1(first.method) !== "btree" ? {
3076
- dialect: "postgresql",
3077
- version: 1,
3078
- data: { method: text$1(first.method) }
3079
- } : void 0,
3080
- reference: reference$1("index", physicalName, namespace, "pg_class", "oid", first.index_oid)
3081
- };
3082
- });
3083
- }
3084
- function mapMetadataRows(rows, namespace, tables, views, sequences, enums, domains, collations, routines, triggers, policies, extensions, deferredObjects, opaqueObjects, indexReferences, relationReferences, diagnostics) {
3085
- const targets = /* @__PURE__ */ new Map();
3086
- const add = (relation, oid, object, physicalName, objectReference) => {
3087
- const ref = objectReference ?? reference$1(object.kind, physicalName, namespace, relation, "oid", oid);
3088
- targets.set(metadataKey(relation, oid, 0), {
3089
- object,
3090
- reference: ref,
3091
- physicalName
3092
- });
3093
- };
3094
- for (const table of tables) if (table.reference?.catalog !== void 0) add("pg_class", table.reference.catalog.value, {
3095
- kind: "table",
3096
- id: table.id
3097
- }, table.physicalName, table.reference);
3098
- for (const view of views) if (view.reference?.catalog !== void 0) add("pg_class", view.reference.catalog.value, {
3099
- kind: view.kind,
3100
- id: view.id
3101
- }, view.physicalName, view.reference);
3102
- for (const sequence of sequences) if (sequence.reference?.catalog !== void 0) add("pg_class", sequence.reference.catalog.value, {
3103
- kind: "sequence",
3104
- id: sequence.id
3105
- }, sequence.physicalName, sequence.reference);
3106
- for (const deferred of deferredObjects) if (deferred.reference?.catalog !== void 0 && deferred.id !== void 0) add("pg_class", deferred.reference.catalog.value, {
3107
- kind: "deferred-object",
3108
- id: deferred.id
3109
- }, deferred.physicalName, deferred.reference);
3110
- for (const opaque of opaqueObjects) if (opaque.reference?.catalog !== void 0) add("pg_class", opaque.reference.catalog.value, {
3111
- kind: "opaque-object",
3112
- id: opaque.id
3113
- }, opaque.physicalName, opaque.reference);
3114
- for (const index of indexReferences.values()) if (index.reference?.catalog !== void 0) add("pg_class", index.reference.catalog.value, {
3115
- kind: "index",
3116
- id: index.id
3117
- }, index.physicalName, index.reference);
3118
- for (const enumObject of enums) if (enumObject.reference?.catalog !== void 0) add("pg_type", enumObject.reference.catalog.value, {
3119
- kind: "enum",
3120
- id: enumObject.id
3121
- }, enumObject.physicalName, enumObject.reference);
3122
- for (const domain of domains) if (domain.reference?.catalog !== void 0) add("pg_type", domain.reference.catalog.value, {
3123
- kind: "domain",
3124
- id: domain.id
3125
- }, domain.physicalName, domain.reference);
3126
- for (const collation of collations) if (collation.reference?.catalog !== void 0) add("pg_collation", collation.reference.catalog.value, {
3127
- kind: "collation",
3128
- id: collation.id
3129
- }, collation.physicalName, collation.reference);
3130
- for (const routine of routines) if (routine.reference?.catalog !== void 0) add("pg_proc", routine.reference.catalog.value, {
3131
- kind: "routine",
3132
- id: routine.id
3133
- }, routine.physicalName, routine.reference);
3134
- for (const trigger of triggers) if (trigger.reference?.catalog !== void 0) add("pg_trigger", trigger.reference.catalog.value, {
3135
- kind: "trigger",
3136
- id: trigger.id
3137
- }, trigger.physicalName, trigger.reference);
3138
- for (const policy of policies) if (policy.reference?.catalog !== void 0) add("pg_policy", policy.reference.catalog.value, {
3139
- kind: "policy",
3140
- id: policy.id
3141
- }, policy.physicalName, policy.reference);
3142
- for (const extension of extensions) if (extension.reference?.catalog !== void 0) add("pg_extension", extension.reference.catalog.value, {
3143
- kind: "extension",
3144
- id: extension.id
3145
- }, extension.physicalName, extension.reference);
3146
- for (const table of tables) addNestedColumns(targets, "pg_class", table, namespace);
3147
- for (const view of views) addNestedColumns(targets, "pg_class", view, namespace);
3148
- for (const table of tables) for (const constraint of table.constraints) if (constraint.reference?.catalog !== void 0) targets.set(metadataKey("pg_constraint", constraint.reference.catalog.value, 0), {
3149
- object: {
3150
- kind: "constraint",
3151
- id: constraint.id
3152
- },
3153
- reference: constraint.reference,
3154
- physicalName: constraint.physicalName ?? constraint.id
3155
- });
3156
- for (const domain of domains) for (const constraint of domain.constraints ?? []) if (constraint.reference?.catalog !== void 0) targets.set(metadataKey("pg_constraint", constraint.reference.catalog.value, 0), {
3157
- object: {
3158
- kind: "constraint",
3159
- id: constraint.id
3160
- },
3161
- reference: constraint.reference,
3162
- physicalName: constraint.physicalName ?? constraint.id
3163
- });
3164
- const comments = [];
3165
- const ownership = [];
3166
- const opaque = [];
3167
- for (const [index, row] of rows.entries()) {
3168
- const relation = text$1(row.catalog_relation) ?? "unknown";
3169
- const oid = text$1(row.object_oid);
3170
- const subid = number$1(row.object_subid) ?? 0;
3171
- const target = targets.get(metadataKey(relation, oid, subid));
3172
- if (target === void 0) {
3173
- const unknownReference = reference$1("opaque-object", text$1(row.object_name) ?? `metadata_${oid ?? "unknown"}`, text$1(row.namespace) ?? namespace, relation, "oid", oid);
3174
- diagnostics.push(createIntrospectionDiagnostic({
3175
- severity: "warning",
3176
- code: "unmodeled-object",
3177
- message: `PostgreSQL metadata row for ${text$1(row.object_name) ?? "unknown object"} could not be attached to a normalized object`,
3178
- path: ["metadata", index],
3179
- physicalReference: unknownReference,
3180
- remediation: "Inspect the retained opaque metadata record before using it as migration input."
3181
- }));
3182
- opaque.push({
3183
- kind: "opaque-object",
3184
- id: stableId$1(`metadata_${relation}_${oid ?? "unknown"}_${subid}`),
3185
- identitySource: "physical-name",
3186
- physicalName: text$1(row.object_name) ?? `metadata_${oid ?? "unknown"}`,
3187
- objectKind: `postgres-metadata:${text$1(row.object_kind) ?? "unknown"}`,
3188
- data: {
3189
- catalogRelation: relation,
3190
- objectOid: oid ?? "unknown",
3191
- objectSubid: subid,
3192
- ...text$1(row.description) === void 0 ? {} : { description: text$1(row.description) },
3193
- ...text$1(row.owner) === void 0 ? {} : { owner: text$1(row.owner) }
3194
- },
3195
- reference: unknownReference
3196
- });
3197
- continue;
3198
- }
3199
- const description = text$1(row.description);
3200
- if (description !== void 0) comments.push({
3201
- kind: "comment",
3202
- id: stableId$1(`${target.object.kind}_${target.object.id}_comment`),
3203
- object: target.object,
3204
- text: description,
3205
- reference: target.reference,
3206
- provenance: {
3207
- kind: "catalog",
3208
- dialect: "postgresql",
3209
- reference: target.reference
3210
- }
3211
- });
3212
- const owner = text$1(row.owner);
3213
- if (owner !== void 0) ownership.push({
3214
- kind: "ownership",
3215
- id: stableId$1(`${target.object.kind}_${target.object.id}_ownership`),
3216
- object: target.object,
3217
- owner,
3218
- reference: target.reference,
3219
- provenance: {
3220
- kind: "catalog",
3221
- dialect: "postgresql",
3222
- reference: target.reference
3223
- }
3224
- });
3225
- }
3226
- return {
3227
- comments,
3228
- ownership,
3229
- opaqueObjects: opaque
3230
- };
3231
- }
3232
- function addNestedColumns(targets, relation, owner, namespace) {
3233
- const tableOid = owner.reference?.catalog?.value;
3234
- if (tableOid === void 0) return;
3235
- for (const column of owner.columns) targets.set(metadataKey(relation, tableOid, column.ordinalPosition), {
3236
- object: {
3237
- kind: "column",
3238
- id: column.id
3239
- },
3240
- reference: column.reference ?? reference$1("column", column.physicalName, namespace, "pg_attribute", "attrelid", tableOid),
3241
- physicalName: column.physicalName
3242
- });
3243
- }
3244
- function metadataKey(relation, oid, subid) {
3245
- return `${relation}:${text$1(oid) ?? "unknown"}:${number$1(subid) ?? 0}`;
3246
- }
3247
- function indexTermOptions(row, method) {
3248
- const option = number$1(row.indoption);
3249
- if (method !== "btree" || option === void 0) return {};
3250
- return {
3251
- direction: option & 1 ? "DESC" : "ASC",
3252
- nulls: option & 2 ? "FIRST" : "LAST"
3253
- };
3254
- }
3255
- function sql$1(textValue, namespace, owner, name) {
3256
- return expression(textValue, "decompiler", owner.reference ?? reference$1("table", name, namespace, "pg_class", "relname", owner.physicalName));
3257
- }
3258
- function expression(textValue, provenanceKind, physicalReference) {
3259
- return {
3260
- kind: "sql",
3261
- dialect: "postgresql",
3262
- text: textValue,
3263
- provenance: {
3264
- kind: provenanceKind,
3265
- dialect: "postgresql",
3266
- ...physicalReference === void 0 ? {} : { reference: physicalReference }
3267
- }
3268
- };
3269
- }
3270
- function reference$1(kind, name, namespace, relation, key, value = name) {
3271
- return {
3272
- kind,
3273
- name,
3274
- namespace,
3275
- catalog: {
3276
- relation,
3277
- key,
3278
- value: typeof value === "number" ? value : String(value)
3279
- }
3280
- };
3281
- }
3282
- function stableId$1(value) {
3283
- if (value.length > 0 && !/[.\\\u0000-\u001f\u007f]/.test(value)) return value;
3284
- let hash = 2166136261;
3285
- for (let index = 0; index < value.length; index += 1) {
3286
- hash ^= value.charCodeAt(index);
3287
- hash = Math.imul(hash, 16777619);
3288
- }
3289
- return `introspected_${(hash >>> 0).toString(16)}`;
3290
- }
3291
- function groupBy(rows, key) {
3292
- const result = /* @__PURE__ */ new Map();
3293
- for (const row of rows) {
3294
- const value = key(row);
3295
- const group = result.get(value) ?? [];
3296
- group.push(row);
3297
- result.set(value, group);
3298
- }
3299
- return result;
3300
- }
3301
- function text$1(value) {
3302
- return value === null || value === void 0 ? void 0 : String(value);
3303
- }
3304
- function number$1(value) {
3305
- if (typeof value === "number" && Number.isFinite(value)) return value;
3306
- if (typeof value === "string" && value.trim() !== "") {
3307
- const parsed = Number(value);
3308
- return Number.isFinite(parsed) ? parsed : void 0;
3309
- }
3310
- }
3311
- function boolean$1(value) {
3312
- return value === true || value === "t" || value === "true" || value === 1;
3313
- }
3314
- function stringArray(value) {
3315
- if (Array.isArray(value)) return value.map((item) => text$1(item)).filter((item) => item !== void 0);
3316
- const source = text$1(value)?.trim();
3317
- if (source === void 0 || source === "") return [];
3318
- if (source.startsWith("{") && source.endsWith("}")) {
3319
- const values = [];
3320
- let current = "";
3321
- let quoted = false;
3322
- let escaped = false;
3323
- for (const character of source.slice(1, -1)) if (escaped) {
3324
- current += character;
3325
- escaped = false;
3326
- } else if (character === "\\" && quoted) escaped = true;
3327
- else if (character === "\"") quoted = !quoted;
3328
- else if (character === "," && !quoted) {
3329
- values.push(current);
3330
- current = "";
3331
- } else current += character;
3332
- if (current !== "" || source !== "{}") values.push(current);
3333
- return values.filter((value) => value !== "");
3334
- }
3335
- return source.split(",").map((item) => item.trim()).filter((item) => item !== "");
3336
- }
3337
- function booleanOption(options, name) {
3338
- const value = options.find((option) => option.startsWith(`${name}=`));
3339
- if (value === void 0) return;
3340
- const setting = value.slice(name.length + 1).toLowerCase();
3341
- if (setting === "true" || setting === "on" || setting === "yes") return true;
3342
- if (setting === "false" || setting === "off" || setting === "no") return false;
3343
- }
3344
- function integerArray(value) {
3345
- if (Array.isArray(value)) return value.map((item) => number$1(item) ?? 0);
3346
- const parsed = text$1(value)?.replace(/[{}]/g, "").trim();
3347
- if (!parsed) return [];
3348
- return parsed.split(",").map((item) => number$1(item.trim()) ?? 0);
3349
- }
3350
- function referentialAction(value) {
3351
- return {
3352
- a: "no-action",
3353
- r: "restrict",
3354
- c: "cascade",
3355
- n: "set-null",
3356
- d: "set-default"
3357
- }[text$1(value)];
3358
- }
3359
- function matchType(value) {
3360
- return {
3361
- s: "simple",
3362
- f: "full",
3363
- p: "partial"
3364
- }[text$1(value)];
3365
- }
3366
- //#endregion
3367
- //#region src/introspection/sqlite.ts
3368
- const sqliteServerQuery = `SELECT sqlite_version() AS version, sqlite_source_id() AS source_id`;
3369
- const sqliteDatabaseListQuery = `
3370
- SELECT seq, name, file
3371
- FROM pragma_database_list()
3372
- ORDER BY seq
3373
- `;
3374
- const sqliteSchemaQuery = `
3375
- SELECT type, name, tbl_name, sql
3376
- FROM main.sqlite_schema
3377
- WHERE name NOT LIKE 'sqlite_%'
3378
- ORDER BY type, name
3379
- `;
3380
- const sqliteTempSchemaQuery = `
3381
- SELECT type, name, tbl_name, sql
3382
- FROM temp.sqlite_schema
3383
- WHERE name NOT LIKE 'sqlite_%'
3384
- ORDER BY type, name
3385
- `;
3386
- const sqliteTableListQuery = `
3387
- SELECT schema, name, type, ncol, wr, strict
3388
- FROM pragma_table_list
3389
- WHERE schema = ? AND name NOT LIKE 'sqlite_%'
3390
- ORDER BY name
3391
- `;
3392
- const sqliteTableInfoQuery = `
3393
- SELECT cid, name, type, "notnull" AS not_null, dflt_value, pk, hidden
3394
- FROM pragma_table_xinfo(?, ?)
3395
- ORDER BY cid
3396
- `;
3397
- const sqliteIndexListQuery = `
3398
- SELECT seq, name, "unique" AS unique_index, origin, partial
3399
- FROM pragma_index_list(?, ?)
3400
- ORDER BY seq
3401
- `;
3402
- const sqliteIndexInfoQuery = `
3403
- SELECT seqno, cid, name, "desc" AS descending, coll, key
3404
- FROM pragma_index_xinfo(?, ?)
3405
- ORDER BY seqno
3406
- `;
3407
- const sqliteForeignKeyQuery = `
3408
- SELECT id, seq, "table" AS target_table, "from" AS source_column,
3409
- "to" AS target_column, on_update, on_delete, match
3410
- FROM pragma_foreign_key_list(?, ?)
3411
- ORDER BY id, seq
3412
- `;
3413
- /** Read the selected SQLite database namespace into the normalized catalog. */
3414
- async function readSqliteCatalog(connection, options) {
3415
- const diagnostics = [];
3416
- if (connection.dialect !== "sqlite") {
3417
- diagnostics.push(createIntrospectionDiagnostic({
3418
- severity: "error",
3419
- code: "dialect-mismatch",
3420
- message: "SQLite catalog reading requires a SQLite CatalogConnection",
3421
- path: ["connection", "dialect"]
3422
- }));
3423
- return emptyCatalog(options.namespace, diagnostics);
3424
- }
3425
- const serverRows = await query(connection, sqliteServerQuery, [], options, diagnostics, "server");
3426
- const server = serverInfo(serverRows[0], diagnostics);
3427
- const databaseRows = await query(connection, sqliteDatabaseListQuery, [], options, diagnostics, "database-list");
3428
- const databaseNames = databaseRows.map((row) => text(row.name)).filter((name) => name !== void 0);
3429
- if (databaseNames.length > 0 && !databaseNames.includes(options.namespace)) diagnostics.push(createIntrospectionDiagnostic({
3430
- severity: "error",
3431
- code: "missing-catalog-row",
3432
- message: `SQLite database ${options.namespace} is not attached to the selected connection`,
3433
- path: ["namespace", options.namespace],
3434
- remediation: "Attach the database before starting introspection."
3435
- }));
3436
- const schemaRows = options.namespace === "main" || options.namespace === "temp" ? await query(connection, options.namespace === "temp" ? sqliteTempSchemaQuery : sqliteSchemaQuery, [], options, diagnostics, "schema") : [];
3437
- if (options.namespace !== "main" && options.namespace !== "temp" && databaseNames.includes(options.namespace)) diagnostics.push(createIntrospectionDiagnostic({
3438
- severity: "warning",
3439
- code: "partial-result",
3440
- message: `SQLite attached database ${options.namespace} exposes table PRAGMAs but its schema SQL is outside the fixed main/temp catalog statements`,
3441
- path: [
3442
- "namespace",
3443
- options.namespace,
3444
- "schema"
3445
- ],
3446
- remediation: "Use a driver adapter that exposes the attached schema through a fixed statement before relying on generated SQL."
3447
- }));
3448
- const tableRows = await query(connection, sqliteTableListQuery, [options.namespace], options, diagnostics, "table-list");
3449
- const tableSql = new Map(schemaRows.map((row) => [text(row.name), text(row.sql)]).filter((entry) => entry[0] !== void 0));
3450
- const tables = tableRows.filter((row) => normalizeType(row.type) === "table").map((row) => table(row, tableSql.get(text(row.name) ?? "") ?? void 0, options.namespace));
3451
- const deferredObjects = [];
3452
- const opaqueObjects = [];
3453
- for (const row of tableRows) {
3454
- const type = normalizeType(row.type);
3455
- if (type !== "virtual" && type !== "shadow") continue;
3456
- const physicalName = text(row.name) ?? "unnamed_object";
3457
- deferredObjects.push(deferred(type === "virtual" ? "virtual-table" : "shadow-table", physicalName, tableSql.get(physicalName), options.namespace));
3458
- diagnostics.push(createIntrospectionDiagnostic({
3459
- severity: "warning",
3460
- code: "unmodeled-object",
3461
- message: `SQLite ${type} table ${physicalName} is retained as a deferred object`,
3462
- path: ["deferredObjects", physicalName],
3463
- physicalReference: reference("deferred-object", physicalName, options.namespace, "pragma_table_list", "name"),
3464
- remediation: "Inspect the deferred record before using it as migration input."
3465
- }));
3466
- }
3467
- for (const row of databaseRows) {
3468
- const name = text(row.name);
3469
- if (!name || name === options.namespace || name === "main" || name === "temp") continue;
3470
- const boundary = attachedDatabaseObject(row, options.namespace);
3471
- opaqueObjects.push(boundary);
3472
- diagnostics.push(createIntrospectionDiagnostic({
3473
- severity: "info",
3474
- code: "partial-result",
3475
- message: `Attached SQLite database ${name} is outside the selected namespace`,
3476
- path: [
3477
- "namespace",
3478
- "attached",
3479
- name
3480
- ],
3481
- physicalReference: boundary.reference,
3482
- remediation: "Run a separate catalog read with this database name to inspect it."
3483
- }));
3484
- }
3485
- const views = [];
3486
- for (const row of tableRows.filter((row) => normalizeType(row.type) === "view")) {
3487
- const physicalName = text(row.name) ?? "unnamed_view";
3488
- const view = sqliteView(row, tableSql.get(physicalName), options.namespace, diagnostics);
3489
- if (view.kind === "deferred-object") deferredObjects.push(view);
3490
- else views.push(view);
3491
- }
3492
- const relationReferences = /* @__PURE__ */ new Map();
3493
- for (const table of tables) relationReferences.set(table.physicalName, {
3494
- kind: "table",
3495
- id: table.id
3496
- });
3497
- for (const view of views) relationReferences.set(view.physicalName, {
3498
- kind: view.kind,
3499
- id: view.id
3500
- });
3501
- const triggers = [];
3502
- for (const currentTable of tables) {
3503
- const tableName = currentTable.physicalName;
3504
- const rows = await query(connection, sqliteTableInfoQuery, [tableName, options.namespace], options, diagnostics, `table-xinfo:${tableName}`);
3505
- const sqlText = tableSql.get(tableName);
3506
- const rowidPrimaryKey = rows.filter((row) => (number(row.pk) ?? 0) > 0).length === 1;
3507
- const columns = rows.filter((row) => number(row.hidden) !== 1).map((row) => column(row, currentTable, options.namespace, sqlText, rowidPrimaryKey, diagnostics));
3508
- currentTable.columns = columns;
3509
- currentTable.constraints = tableConstraints(currentTable, rows, columns, sqlText, options.namespace);
3510
- const indexRows = await query(connection, sqliteIndexListQuery, [tableName, options.namespace], options, diagnostics, `index-list:${tableName}`);
3511
- const mappedIndexes = [];
3512
- const mappedConstraints = [...currentTable.constraints];
3513
- for (const indexRow of indexRows) {
3514
- const indexName = text(indexRow.name);
3515
- if (!indexName || indexName.startsWith("sqlite_autoindex_") && text(indexRow.origin)?.toLowerCase() !== "u") continue;
3516
- const index = sqliteIndex(currentTable, indexRow, await query(connection, sqliteIndexInfoQuery, [indexName, options.namespace], options, diagnostics, `index-info:${indexName}`), text(indexRow.origin)?.toLowerCase() === "u" ? sqlText : tableSql.get(indexName), options.namespace, diagnostics, opaqueObjects);
3517
- if (!index) continue;
3518
- if (index.kind === "index") mappedIndexes.push(index);
3519
- else mappedConstraints.push(index);
3520
- }
3521
- const foreignRows = await query(connection, sqliteForeignKeyQuery, [tableName, options.namespace], options, diagnostics, `foreign-key:${tableName}`);
3522
- mappedConstraints.push(...foreignKeys(currentTable, foreignRows, options.namespace));
3523
- currentTable.indexes = mappedIndexes;
3524
- currentTable.constraints = mappedConstraints;
3525
- }
3526
- for (const view of views) view.columns = (await query(connection, sqliteTableInfoQuery, [view.physicalName, options.namespace], options, diagnostics, `view-xinfo:${view.physicalName}`)).filter((row) => number(row.hidden) !== 1).map((row) => column(row, view, options.namespace, void 0, false, diagnostics));
3527
- for (const row of schemaRows.filter((row) => normalizeType(row.type) === "trigger")) {
3528
- const trigger = sqliteTrigger(row, options.namespace, relationReferences, diagnostics);
3529
- if (trigger.kind === "deferred-object") deferredObjects.push(trigger);
3530
- else triggers.push(trigger);
3531
- }
3532
- for (const row of schemaRows) {
3533
- const type = normalizeType(row.type);
3534
- if (type === "table" || type === "view" || type === "trigger" || type === "index") continue;
3535
- const physicalName = text(row.name) ?? "unnamed_object";
3536
- opaqueObjects.push(opaqueSchemaObject(row, options.namespace, diagnostics));
3537
- diagnostics.push(createIntrospectionDiagnostic({
3538
- severity: "warning",
3539
- code: "unmodeled-object",
3540
- message: `SQLite schema object ${physicalName} (${type || "unknown"}) is retained as opaque data`,
3541
- path: ["opaqueObjects", physicalName],
3542
- physicalReference: reference("opaque-object", physicalName, options.namespace, "sqlite_schema", "name")
3543
- }));
3544
- }
3545
- const visibility = databaseRows.length > 0 && options.namespace !== "main" && options.namespace !== "temp" ? "limited" : server.capabilities.visibility;
3546
- const capabilities = {
3547
- generatedColumns: server.capabilities.generatedColumns,
3548
- identityMetadata: server.capabilities.identityMetadata,
3549
- checkConstraints: server.capabilities.checkConstraints,
3550
- checkConstraintEnforcement: server.capabilities.checkConstraintEnforcement,
3551
- expressionDecompilation: server.capabilities.expressionDecompilation,
3552
- indexExpressions: server.capabilities.indexExpressions,
3553
- indexPredicates: server.capabilities.indexPredicates,
3554
- indexIncludedColumns: server.capabilities.indexIncludedColumns,
3555
- namespaces: server.capabilities.namespaces,
3556
- visibility
3557
- };
3558
- const serverCapabilities = {
3559
- ...server.capabilities,
3560
- attachedDatabases: true,
3561
- views: true,
3562
- triggers: true,
3563
- virtualTables: true,
3564
- shadowTables: true,
3565
- comments: false,
3566
- ownership: false,
3567
- typedExtensions: true,
3568
- affinityFacts: true,
3569
- generatedSql: true,
3570
- selectedNamespace: options.namespace,
3571
- visibility
3572
- };
3573
- return Object.freeze({
3574
- dialect: "sqlite",
3575
- server: {
3576
- ...server,
3577
- capabilities: serverCapabilities
3578
- },
3579
- namespace: {
3580
- kind: "sqlite-database",
3581
- name: options.namespace,
3582
- reference: reference("namespace", options.namespace, options.namespace, "sqlite_schema", "name"),
3583
- dialect: sqliteExtension({
3584
- selectedNamespace: options.namespace,
3585
- sourceIdAvailable: serverSourceIdAvailable(serverRows[0]),
3586
- views: true,
3587
- triggers: true,
3588
- virtualTables: true,
3589
- shadowTables: true,
3590
- comments: false,
3591
- ownership: false,
3592
- typedExtensions: true,
3593
- affinityFacts: true,
3594
- generatedSql: true,
3595
- visibility,
3596
- attachedDatabases: databaseNames.filter((name) => name !== options.namespace)
3597
- })
3598
- },
3599
- tables: Object.freeze(tables),
3600
- views: Object.freeze(views),
3601
- triggers: Object.freeze(triggers),
3602
- deferredObjects: Object.freeze(deferredObjects),
3603
- opaqueObjects: Object.freeze(opaqueObjects),
3604
- capabilities,
3605
- diagnostics: Object.freeze(diagnostics)
3606
- });
3607
- }
3608
- async function query(connection, textValue, parameters, options, diagnostics, operation) {
3609
- try {
3610
- return await connection.query({
3611
- text: textValue,
3612
- parameters
3613
- }, { signal: options.signal });
3614
- } catch {
3615
- diagnostics.push(createIntrospectionDiagnostic({
3616
- severity: "error",
3617
- code: "query-failed",
3618
- message: `SQLite catalog query failed while reading ${operation}`,
3619
- path: [operation],
3620
- remediation: "Check SQLite metadata visibility and the selected database."
3621
- }));
3622
- return [];
3623
- }
3624
- }
3625
- function serverInfo(row, diagnostics) {
3626
- const rawVersion = text(row?.version) ?? "unknown";
3627
- const parts = rawVersion.split(".").map((item) => Number(item));
3628
- const supported = parts.length >= 2 && parts[0] === 3 && parts[1] >= 37;
3629
- if (!supported) diagnostics.push(createIntrospectionDiagnostic({
3630
- severity: "error",
3631
- code: "unsupported-server",
3632
- message: "SQLite introspection requires SQLite 3.37 or newer",
3633
- path: ["server", "version"],
3634
- remediation: "Use SQLite 3.37+ or provide a compatible adapter capability set."
3635
- }));
3636
- return {
3637
- product: "sqlite",
3638
- rawVersion,
3639
- parsedVersion: Number.isFinite(parts[0]) ? {
3640
- major: parts[0],
3641
- minor: parts[1],
3642
- patch: parts[2]
3643
- } : void 0,
3644
- capabilities: {
3645
- generatedColumns: supported,
3646
- identityMetadata: true,
3647
- checkConstraints: true,
3648
- checkConstraintEnforcement: "enforced",
3649
- expressionDecompilation: false,
3650
- indexExpressions: true,
3651
- indexPredicates: true,
3652
- indexIncludedColumns: false,
3653
- namespaces: false,
3654
- visibility: "complete",
3655
- sourceIdAvailable: text(row?.source_id) !== void 0
3656
- }
3657
- };
3658
- }
3659
- function serverSourceIdAvailable(row) {
3660
- return text(row?.source_id) !== void 0;
3661
- }
3662
- function normalizeType(value) {
3663
- return text(value)?.trim().toLowerCase() ?? "";
3664
- }
3665
- function sqliteView(row, sqlText, namespace, diagnostics) {
3666
- const physicalName = text(row.name) ?? "unnamed_view";
3667
- const physicalReference = reference("view", physicalName, namespace, "sqlite_schema", "name");
3668
- const definition = viewDefinition(sqlText);
3669
- if (!definition) {
3670
- diagnostics.push(createIntrospectionDiagnostic({
3671
- severity: "error",
3672
- code: "expression-parse-failed",
3673
- message: `SQLite view ${physicalName} has no recoverable SELECT definition`,
3674
- path: [
3675
- "views",
3676
- physicalName,
3677
- "definition"
3678
- ],
3679
- physicalReference,
3680
- remediation: "Preserve the CREATE VIEW SQL returned by sqlite_schema."
3681
- }));
3682
- return deferred("view", physicalName, sqlText, namespace);
3683
- }
3684
- return {
3685
- kind: "view",
3686
- id: stableId(physicalName),
3687
- identitySource: "physical-name",
3688
- physicalName,
3689
- columns: [],
3690
- definition: sql(definition, namespace, {
3691
- kind: "view",
3692
- physicalName,
3693
- reference: physicalReference
3694
- }, physicalName),
3695
- reference: physicalReference,
3696
- provenance: {
3697
- kind: "create-sql",
3698
- dialect: "sqlite",
3699
- reference: physicalReference
3700
- },
3701
- dialect: sqliteExtension({ objectKind: "view" })
3702
- };
3703
- }
3704
- function viewDefinition(sqlText) {
3705
- if (!sqlText) return;
3706
- return sqlText.match(/\bAS\b([\s\S]*)$/i)?.[1]?.trim().replace(/;\s*$/, "") || void 0;
3707
- }
3708
- function attachedDatabaseObject(row, selectedNamespace) {
3709
- const physicalName = text(row.name) ?? "unnamed_database";
3710
- const physicalReference = reference("opaque-object", physicalName, selectedNamespace, "pragma_database_list", "name");
3711
- return {
3712
- kind: "opaque-object",
3713
- id: stableId(`attached:${physicalName}`),
3714
- identitySource: "physical-name",
3715
- objectKind: "attached-database",
3716
- physicalName,
3717
- data: {
3718
- ...number(row.seq) === void 0 ? {} : { sequence: number(row.seq) },
3719
- ...text(row.file) === void 0 ? {} : { file: text(row.file) },
3720
- selected: false
3721
- },
3722
- reference: physicalReference,
3723
- provenance: {
3724
- kind: "catalog",
3725
- dialect: "sqlite",
3726
- reference: physicalReference
3727
- },
3728
- dialect: sqliteExtension({ selectedNamespace })
3729
- };
3730
- }
3731
- function opaqueSchemaObject(row, namespace, _diagnostics) {
3732
- const physicalName = text(row.name) ?? "unnamed_object";
3733
- const type = normalizeType(row.type) || "unknown";
3734
- const physicalReference = reference("opaque-object", physicalName, namespace, "sqlite_schema", "name");
3735
- const sqlText = text(row.sql);
3736
- return {
3737
- kind: "opaque-object",
3738
- id: stableId(`opaque:${type}:${physicalName}`),
3739
- identitySource: "physical-name",
3740
- objectKind: type,
3741
- physicalName,
3742
- data: {
3743
- type,
3744
- ...text(row.tbl_name) === void 0 ? {} : { tableName: text(row.tbl_name) }
3745
- },
3746
- ...sqlText === void 0 ? {} : { sql: {
3747
- kind: "sql",
3748
- dialect: "sqlite",
3749
- text: sqlText,
3750
- provenance: {
3751
- kind: "create-sql",
3752
- dialect: "sqlite",
3753
- reference: physicalReference
3754
- }
3755
- } },
3756
- reference: physicalReference,
3757
- provenance: {
3758
- kind: "catalog",
3759
- dialect: "sqlite",
3760
- reference: physicalReference
3761
- },
3762
- dialect: sqliteExtension({ objectKind: type })
3763
- };
3764
- }
3765
- function sqliteTrigger(row, namespace, relations, diagnostics) {
3766
- const physicalName = text(row.name) ?? "unnamed_trigger";
3767
- const sqlText = text(row.sql);
3768
- const physicalReference = reference("trigger", physicalName, namespace, "sqlite_schema", "name");
3769
- const onMatch = sqlText?.match(/\bON\s+("(?:[^"]|"")*"|`[^`]*`|\[[^\]]*\]|[A-Za-z_][A-Za-z0-9_$]*)/i);
3770
- const targetName = unquoteIdentifier(onMatch?.[1]) ?? text(row.tbl_name);
3771
- const target = targetName === void 0 ? void 0 : relations.get(targetName);
3772
- const beginIndex = sqlText?.search(/\bBEGIN\b/i) ?? -1;
3773
- const header = sqlText === void 0 || beginIndex < 0 ? void 0 : sqlText.slice(0, beginIndex);
3774
- const timing = triggerTiming(header);
3775
- const events = triggerEvents(header);
3776
- if (!sqlText || !target || !header || beginIndex < 0) {
3777
- diagnostics.push(createIntrospectionDiagnostic({
3778
- severity: "error",
3779
- code: "unresolved-reference",
3780
- message: `SQLite trigger ${physicalName} does not have a recoverable body or target`,
3781
- path: ["triggers", physicalName],
3782
- physicalReference,
3783
- remediation: "Retain the CREATE TRIGGER SQL and inspect the trigger after its target is visible."
3784
- }));
3785
- return deferred("trigger", physicalName, sqlText, namespace);
3786
- }
3787
- if (events.length === 0) diagnostics.push(createIntrospectionDiagnostic({
3788
- severity: "warning",
3789
- code: "unsupported-feature",
3790
- message: `SQLite trigger ${physicalName} has no recognized event`,
3791
- path: [
3792
- "triggers",
3793
- physicalName,
3794
- "events"
3795
- ],
3796
- physicalReference
3797
- }));
3798
- const bodyText = sqlText.slice(beginIndex + 5).replace(/END\s*;?\s*$/i, "").trim();
3799
- const condition = triggerCondition(sqlText, onMatch?.index, beginIndex);
3800
- return {
3801
- kind: "trigger",
3802
- id: stableId(physicalName),
3803
- identitySource: "physical-name",
3804
- physicalName,
3805
- table: target,
3806
- timing,
3807
- events,
3808
- orientation: /\bFOR\s+EACH\s+ROW\b/i.test(header) ? "row" : void 0,
3809
- ...condition === void 0 ? {} : { condition: sql(condition, namespace, {
3810
- kind: target.kind,
3811
- physicalName: target.id,
3812
- reference: physicalReference
3813
- }, physicalName) },
3814
- body: sql(bodyText || sqlText, namespace, {
3815
- kind: "trigger",
3816
- physicalName,
3817
- reference: physicalReference
3818
- }, physicalName),
3819
- reference: physicalReference,
3820
- provenance: {
3821
- kind: "create-sql",
3822
- dialect: "sqlite",
3823
- reference: physicalReference
3824
- },
3825
- dialect: sqliteExtension({
3826
- objectKind: "trigger",
3827
- ...sqlText === void 0 ? {} : { rawSql: sqlText }
3828
- })
3829
- };
3830
- }
3831
- function triggerTiming(header) {
3832
- const value = header?.match(/\b(INSTEAD\s+OF|BEFORE|AFTER)\b/i)?.[1];
3833
- return value?.toLowerCase() === "before" ? "before" : value?.toLowerCase() === "after" ? "after" : value?.toLowerCase() === "instead of" ? "instead-of" : "unknown";
3834
- }
3835
- function triggerEvents(header) {
3836
- const values = header?.match(/\b(INSERT|UPDATE|DELETE)\b/gi) ?? [];
3837
- return [...new Set(values.map((value) => value.toLowerCase()))];
3838
- }
3839
- function triggerCondition(sqlText, _onIndex, beginIndex) {
3840
- return sqlText.slice(0, beginIndex).match(/\bWHEN\s+([\s\S]+)$/i)?.[1]?.trim();
3841
- }
3842
- function unquoteIdentifier(value) {
3843
- if (!value) return;
3844
- const trimmed = value.trim();
3845
- if (trimmed.length < 2) return trimmed;
3846
- if (trimmed.startsWith("\"") && trimmed.endsWith("\"") || trimmed.startsWith("`") && trimmed.endsWith("`")) return trimmed.slice(1, -1).replace(/(""|``)/g, (match) => match[0]);
3847
- if (trimmed.startsWith("[") && trimmed.endsWith("]")) return trimmed.slice(1, -1);
3848
- return trimmed;
3849
- }
3850
- function sqliteAffinity(type) {
3851
- const normalized = type.trim().toUpperCase();
3852
- if (/INT/.test(normalized)) return "INTEGER";
3853
- if (/CHAR|CLOB|TEXT/.test(normalized)) return "TEXT";
3854
- if (/REAL|FLOA|DOUB/.test(normalized)) return "REAL";
3855
- if (normalized === "" || normalized === "BLOB") return "BLOB";
3856
- return "NUMERIC";
3857
- }
3858
- function sqliteExtension(data) {
3859
- return {
3860
- dialect: "sqlite",
3861
- version: 1,
3862
- data
3863
- };
3864
- }
3865
- function indexExpressionFor(sqlText, position) {
3866
- if (!sqlText) return;
3867
- const open = sqlText.indexOf("(", sqlText.search(/\bON\b/i));
3868
- if (open < 0) return;
3869
- const close = matchingParen(sqlText, open);
3870
- if (close < 0) return;
3871
- const term = splitSqlList(sqlText.slice(open + 1, close))[position]?.trim();
3872
- return term && !isSimpleIdentifier(term) ? term : void 0;
3873
- }
3874
- function opaqueIndexExpression(table, indexName, position, info, sqlText, namespace) {
3875
- const physicalReference = reference("opaque-object", `${indexName}:${position}`, namespace, "pragma_index_xinfo", "seqno", position);
3876
- return {
3877
- kind: "opaque-object",
3878
- id: stableId(`index-expression:${table.physicalName}:${indexName}:${position}`),
3879
- identitySource: "deterministic-fallback",
3880
- objectKind: "index-expression-term",
3881
- physicalName: `${indexName}:${position}`,
3882
- data: {
3883
- index: indexName,
3884
- position,
3885
- cid: number(info.cid) ?? -2
3886
- },
3887
- ...sqlText === void 0 ? {} : { sql: sql(sqlText, namespace, table, indexName) },
3888
- reference: physicalReference,
3889
- provenance: {
3890
- kind: "catalog",
3891
- dialect: "sqlite",
3892
- reference: physicalReference
3893
- },
3894
- dialect: sqliteExtension({ objectKind: "index-expression-term" })
3895
- };
3896
- }
3897
- function matchingParen(source, open) {
3898
- let depth = 0;
3899
- let quote;
3900
- for (let index = open; index < source.length; index++) {
3901
- const character = source[index];
3902
- if (quote === "single") {
3903
- if (character === "'" && source[index + 1] === "'") index++;
3904
- else if (character === "'") quote = void 0;
3905
- continue;
3906
- }
3907
- if (quote === "double") {
3908
- if (character === "\"" && source[index + 1] === "\"") index++;
3909
- else if (character === "\"") quote = void 0;
3910
- continue;
3911
- }
3912
- if (quote === "backtick") {
3913
- if (character === "`") quote = void 0;
3914
- continue;
3915
- }
3916
- if (quote === "bracket") {
3917
- if (character === "]") quote = void 0;
3918
- continue;
3919
- }
3920
- if (character === "'") quote = "single";
3921
- else if (character === "\"") quote = "double";
3922
- else if (character === "`") quote = "backtick";
3923
- else if (character === "[") quote = "bracket";
3924
- else if (character === "(") depth++;
3925
- else if (character === ")" && --depth === 0) return index;
3926
- }
3927
- return -1;
3928
- }
3929
- function splitSqlList(source) {
3930
- const values = [];
3931
- let start = 0;
3932
- let depth = 0;
3933
- let quote;
3934
- for (let index = 0; index < source.length; index++) {
3935
- const character = source[index];
3936
- if (quote === "single") {
3937
- if (character === "'" && source[index + 1] === "'") index++;
3938
- else if (character === "'") quote = void 0;
3939
- continue;
3940
- }
3941
- if (quote === "double") {
3942
- if (character === "\"" && source[index + 1] === "\"") index++;
3943
- else if (character === "\"") quote = void 0;
3944
- continue;
3945
- }
3946
- if (quote === "backtick") {
3947
- if (character === "`") quote = void 0;
3948
- continue;
3949
- }
3950
- if (quote === "bracket") {
3951
- if (character === "]") quote = void 0;
3952
- continue;
3953
- }
3954
- if (character === "'") quote = "single";
3955
- else if (character === "\"") quote = "double";
3956
- else if (character === "`") quote = "backtick";
3957
- else if (character === "[") quote = "bracket";
3958
- else if (character === "(") depth++;
3959
- else if (character === ")") depth--;
3960
- else if (character === "," && depth === 0) {
3961
- values.push(source.slice(start, index));
3962
- start = index + 1;
3963
- }
3964
- }
3965
- values.push(source.slice(start));
3966
- return values;
3967
- }
3968
- function isSimpleIdentifier(value) {
3969
- return /^(?:[A-Za-z_][A-Za-z0-9_$]*|"(?:[^"]|"")*"|`[^`]*`|\[[^\]]*\])(?:\s+(?:ASC|DESC))?$/i.test(value);
3970
- }
3971
- function table(row, sqlText, namespace) {
3972
- const physicalName = text(row.name) ?? "unnamed_table";
3973
- const withoutRowid = boolean(row.wr);
3974
- const strict = boolean(row.strict);
3975
- return {
3976
- kind: "table",
3977
- id: stableId(physicalName),
3978
- identitySource: "physical-name",
3979
- physicalName,
3980
- reference: reference("table", physicalName, namespace, "sqlite_schema", "name"),
3981
- columns: [],
3982
- constraints: [],
3983
- indexes: [],
3984
- dialect: sqliteExtension({
3985
- tableType: "table",
3986
- withoutRowid,
3987
- strict,
3988
- rowid: !withoutRowid
3989
- }),
3990
- unknownFields: [
3991
- ...withoutRowid ? [{
3992
- name: "withoutRowid",
3993
- value: true
3994
- }] : [],
3995
- ...strict ? [{
3996
- name: "strict",
3997
- value: true
3998
- }] : [],
3999
- ...sqlText ? [{
4000
- name: "createSql",
4001
- value: sqlText
4002
- }] : []
4003
- ]
4004
- };
4005
- }
4006
- function deferred(objectKind, physicalName, sqlText, namespace) {
4007
- return {
4008
- kind: "deferred-object",
4009
- id: stableId(`deferred:${objectKind}:${physicalName}`),
4010
- identitySource: "physical-name",
4011
- objectKind,
4012
- physicalName,
4013
- reference: reference("deferred-object", physicalName, namespace, "sqlite_schema", "name"),
4014
- dialect: sqliteExtension({ objectKind }),
4015
- unknownFields: sqlText ? [{
4016
- name: "createSql",
4017
- value: sqlText
4018
- }] : void 0
4019
- };
4020
- }
4021
- function column(row, table, namespace, sqlText, rowidPrimaryKey, diagnostics) {
4022
- const physicalName = text(row.name) ?? "unnamed_column";
4023
- const hidden = number(row.hidden) ?? 0;
4024
- const type = text(row.type) ?? "";
4025
- const defaultValue = text(row.dflt_value);
4026
- const generatedExpression = hidden === 2 || hidden === 3 ? generatedExpressionFor(sqlText, physicalName) : void 0;
4027
- if ((hidden === 2 || hidden === 3) && !generatedExpression) diagnostics.push(createIntrospectionDiagnostic({
4028
- severity: "error",
4029
- code: "expression-parse-failed",
4030
- message: `SQLite generated expression for ${physicalName} could not be recovered`,
4031
- path: [
4032
- table.id,
4033
- "columns",
4034
- physicalName,
4035
- "generated"
4036
- ],
4037
- remediation: "Preserve the CREATE TABLE SQL or use lossy mode."
4038
- }));
4039
- const rowid = table.kind === "table" && rowidPrimaryKey && (number(row.pk) ?? 0) > 0 && type.toUpperCase() === "INTEGER" && !/WITHOUT\s+ROWID/i.test(sqlText ?? "");
4040
- const identity = rowid ? {
4041
- kind: "identity",
4042
- generation: "by-default",
4043
- options: {},
4044
- dialect: {
4045
- dialect: "sqlite",
4046
- version: 1,
4047
- data: {
4048
- rowidAlias: true,
4049
- autoIncrement: /AUTOINCREMENT/i.test(sqlText ?? ""),
4050
- withoutRowid: false
4051
- }
4052
- }
4053
- } : void 0;
4054
- return {
4055
- kind: "column",
4056
- id: stableId(physicalName),
4057
- identitySource: "physical-name",
4058
- physicalName,
4059
- ordinalPosition: number(row.cid) ?? 0,
4060
- nullable: !boolean(row.not_null) && !(rowid || (number(row.pk) ?? 0) > 0 && (/WITHOUT\s+ROWID/i.test(sqlText ?? "") || /\bSTRICT\b/i.test(sqlText ?? ""))),
4061
- storage: { nativeType: type || "BLOB" },
4062
- default: defaultValue !== void 0 && !generatedExpression ? {
4063
- kind: "expression",
4064
- expression: sql(defaultValue, namespace, table, physicalName)
4065
- } : void 0,
4066
- generated: generatedExpression ? {
4067
- kind: "generated",
4068
- mode: hidden === 2 ? "virtual" : "stored",
4069
- expression: sql(generatedExpression, namespace, table, physicalName)
4070
- } : void 0,
4071
- identity,
4072
- reference: reference("column", physicalName, namespace, "pragma_table_xinfo", "name"),
4073
- dialect: sqliteExtension({
4074
- declaredType: type,
4075
- affinity: sqliteAffinity(type),
4076
- hidden
4077
- })
4078
- };
4079
- }
4080
- function tableConstraints(table, rows, columns, sqlText, namespace) {
4081
- const primaryNames = new Map(rows.filter((row) => (number(row.pk) ?? 0) > 0).map((row) => [text(row.name), number(row.pk) ?? 0]));
4082
- const primaryColumns = columns.filter((column) => primaryNames.has(column.physicalName)).sort((left, right) => primaryNames.get(left.physicalName) - primaryNames.get(right.physicalName));
4083
- const constraints = [];
4084
- if (primaryColumns.length > 0) {
4085
- const declaredName = declaredConstraintName(sqlText, "PRIMARY\\s+KEY", primaryColumns.map((column) => column.physicalName));
4086
- const primaryName = declaredName ?? `primary_${table.physicalName}`;
4087
- const primary = {
4088
- kind: "primary-key",
4089
- id: stableId(primaryName),
4090
- identitySource: declaredName ? "physical-name" : "deterministic-fallback",
4091
- physicalName: primaryName,
4092
- columns: primaryColumns.map((column) => column.physicalName),
4093
- dialect: sqliteExtension({ source: "pragma_table_xinfo" }),
4094
- reference: reference("constraint", primaryName, namespace, "sqlite_schema", "tbl_name")
4095
- };
4096
- constraints.push(primary);
4097
- }
4098
- [...sqlText?.matchAll(/(?:CONSTRAINT\s+("(?:[^"]|"")*"|`[^`]*`|\[[^\]]*\]|[A-Za-z_][A-Za-z0-9_$]*)\s+)?CHECK\s*\(([^()]*(?:\([^()]*\)[^()]*)*)\)/gi) ?? []].forEach((match, index) => {
4099
- const name = unquoteIdentifier(match[1]) ?? `check_${index}_${table.physicalName}`;
4100
- const check = {
4101
- kind: "check",
4102
- id: stableId(name),
4103
- identitySource: "deterministic-fallback",
4104
- physicalName: name,
4105
- expression: sql(match[2] ?? "true", namespace, table, name),
4106
- dialect: sqliteExtension({ source: "create-sql" })
4107
- };
4108
- constraints.push(check);
4109
- });
4110
- return constraints;
4111
- }
4112
- function sqliteIndex(table, row, infoRows, sqlText, namespace, diagnostics, opaqueObjects) {
4113
- const physicalName = text(row.name);
4114
- if (!physicalName) return;
4115
- const terms = [];
4116
- const collations = [];
4117
- for (const info of infoRows.filter((item) => boolean(item.key))) {
4118
- const position = number(info.seqno) ?? 0;
4119
- const cid = number(info.cid) ?? -1;
4120
- const collation = text(info.coll);
4121
- if (collation) collations.push(collation);
4122
- if (cid === -1) continue;
4123
- if (cid === -2) {
4124
- const expressionText = indexExpressionFor(sqlText, position);
4125
- if (expressionText) terms.push({
4126
- kind: "expression",
4127
- expression: sql(expressionText, namespace, table, physicalName),
4128
- position,
4129
- direction: boolean(info.descending) ? "DESC" : "ASC"
4130
- });
4131
- else {
4132
- opaqueObjects.push(opaqueIndexExpression(table, physicalName, position, info, sqlText, namespace));
4133
- diagnostics.push(createIntrospectionDiagnostic({
4134
- severity: "error",
4135
- code: "unsupported-feature",
4136
- message: `SQLite index ${physicalName} has an expression term that was not recovered`,
4137
- path: [
4138
- table.id,
4139
- "indexes",
4140
- physicalName,
4141
- "terms",
4142
- position
4143
- ],
4144
- physicalReference: reference("index", physicalName, namespace, "sqlite_schema", "name"),
4145
- remediation: "Preserve the CREATE INDEX SQL for expression terms."
4146
- }));
4147
- }
4148
- continue;
4149
- }
4150
- const columnName = text(info.name);
4151
- if (cid >= 0 && columnName) terms.push({
4152
- kind: "column",
4153
- column: columnName,
4154
- position,
4155
- direction: boolean(info.descending) ? "DESC" : "ASC"
4156
- });
4157
- else diagnostics.push(createIntrospectionDiagnostic({
4158
- severity: "error",
4159
- code: "unsupported-feature",
4160
- message: `SQLite index ${physicalName} has an expression term that was not recovered`,
4161
- path: [
4162
- table.id,
4163
- "indexes",
4164
- physicalName,
4165
- "terms",
4166
- position
4167
- ],
4168
- physicalReference: reference("index", physicalName, namespace, "sqlite_schema", "name")
4169
- }));
4170
- }
4171
- const unique = boolean(row.unique_index);
4172
- if (text(row.origin) === "u") {
4173
- const internalName = physicalName.startsWith("sqlite_autoindex_");
4174
- const termNames = terms.map((term) => term.kind === "column" ? term.column : `expression_${term.position}`);
4175
- const declaredName = declaredConstraintName(sqlText, "UNIQUE", termNames);
4176
- const constraintName = internalName ? declaredName ?? `unique_${table.physicalName}_${termNames.join("_") || "constraint"}` : physicalName;
4177
- return {
4178
- kind: "unique",
4179
- id: stableId(constraintName),
4180
- identitySource: internalName && !declaredName ? "deterministic-fallback" : "physical-name",
4181
- physicalName: constraintName,
4182
- columns: terms.flatMap((term) => term.kind === "column" ? [term.column] : []),
4183
- nulls: "distinct",
4184
- dialect: sqliteExtension({
4185
- origin: text(row.origin) ?? "unknown",
4186
- collations,
4187
- ...internalName ? { internalName } : {}
4188
- }),
4189
- reference: reference("constraint", constraintName, namespace, "pragma_index_list", "name", physicalName)
4190
- };
4191
- }
4192
- return {
4193
- kind: "index",
4194
- id: stableId(physicalName),
4195
- identitySource: "physical-name",
4196
- physicalName,
4197
- unique,
4198
- terms,
4199
- dialect: sqliteExtension({
4200
- origin: text(row.origin) ?? "unknown",
4201
- partial: boolean(row.partial),
4202
- collations
4203
- }),
4204
- predicate: boolean(row.partial) ? partialPredicate(sqlText, physicalName, namespace, table) : void 0,
4205
- reference: reference("index", physicalName, namespace, "sqlite_schema", "name")
4206
- };
4207
- }
4208
- function declaredConstraintName(sqlText, keyword, columns) {
4209
- if (!sqlText) return void 0;
4210
- const pattern = new RegExp(`CONSTRAINT\\s+("(?:[^"]|"")*"|\`[^\`]*\`|\\[[^\\]]*\\]|[A-Za-z_][A-Za-z0-9_\$]*)\\s+${keyword}\\s*\\(([^)]*)\\)`, "gi");
4211
- for (const match of sqlText.matchAll(pattern)) {
4212
- const found = (match[2] ?? "").split(",").map((value) => unquoteIdentifier(value.trim())).filter((value) => value !== void 0);
4213
- if (found.length === columns.length && found.every((value, index) => value === columns[index])) return unquoteIdentifier(match[1]);
4214
- }
4215
- }
4216
- function foreignKeys(table, rows, namespace) {
4217
- const grouped = /* @__PURE__ */ new Map();
4218
- for (const row of rows) {
4219
- const id = text(row.id) ?? "0";
4220
- const group = grouped.get(id) ?? [];
4221
- group.push(row);
4222
- grouped.set(id, group);
4223
- }
4224
- return [...grouped.entries()].map(([key, group]) => {
4225
- const first = group[0];
4226
- const physicalName = `foreign_key_${table.physicalName}_${key}`;
4227
- return {
4228
- kind: "foreign-key",
4229
- id: stableId(physicalName),
4230
- identitySource: "deterministic-fallback",
4231
- physicalName,
4232
- columns: group.sort((left, right) => (number(left.seq) ?? 0) - (number(right.seq) ?? 0)).map((row) => text(row.source_column) ?? "unknown"),
4233
- target: {
4234
- table: text(first.target_table) ?? "unknown",
4235
- columns: group.map((row) => text(row.target_column) ?? "unknown")
4236
- },
4237
- onUpdate: action(first.on_update),
4238
- onDelete: action(first.on_delete),
4239
- match: match(first.match),
4240
- dialect: sqliteExtension({ foreignKeyId: key }),
4241
- reference: reference("constraint", physicalName, namespace, "pragma_foreign_key_list", "id", key)
4242
- };
4243
- });
4244
- }
4245
- function partialPredicate(sqlText, indexName, namespace, table) {
4246
- const predicate = (sqlText?.match(/\bWHERE\s+([\s\S]+)$/i))?.[1]?.trim().replace(/;\s*$/, "");
4247
- return predicate ? sql(predicate, namespace, table, indexName) : void 0;
4248
- }
4249
- function generatedExpressionFor(sqlText, columnName) {
4250
- if (!sqlText) return;
4251
- const open = sqlText.indexOf("(");
4252
- if (open < 0) return;
4253
- const close = matchingParen(sqlText, open);
4254
- if (close < 0) return;
4255
- const definitions = splitSqlList(sqlText.slice(open + 1, close));
4256
- for (const definition of definitions) {
4257
- const identifier = definition.trim().match(/^("(?:[^"]|"")*"|`[^`]*`|\[[^\]]*\]|[A-Za-z_][A-Za-z0-9_$]*)/)?.[1];
4258
- if (unquoteIdentifier(identifier) !== columnName) continue;
4259
- const generated = definition.match(/\bAS\s*\(/i);
4260
- if (!generated || generated.index === void 0) return;
4261
- const generatedOpen = definition.indexOf("(", generated.index);
4262
- if (generatedOpen < 0) return;
4263
- const generatedClose = matchingParen(definition, generatedOpen);
4264
- return generatedClose < 0 ? void 0 : definition.slice(generatedOpen + 1, generatedClose).trim();
4265
- }
4266
- }
4267
- function sql(textValue, dialectNamespace, owner, name) {
4268
- const ownerReference = owner.reference ?? reference(owner.kind, owner.physicalName, dialectNamespace, "sqlite_schema", "name");
4269
- return {
4270
- kind: "sql",
4271
- dialect: "sqlite",
4272
- text: textValue,
4273
- provenance: {
4274
- kind: "create-sql",
4275
- dialect: "sqlite",
4276
- reference: reference(ownerReference.kind, name, dialectNamespace, ownerReference.catalog?.relation ?? "sqlite_schema", ownerReference.catalog?.key ?? "name", ownerReference.catalog?.value ?? ownerReference.name)
4277
- }
4278
- };
4279
- }
4280
- function reference(kind, name, namespace, relation, key, value = name) {
4281
- return {
4282
- kind,
4283
- name,
4284
- namespace,
4285
- catalog: {
4286
- relation,
4287
- key,
4288
- value
4289
- }
4290
- };
4291
- }
4292
- function emptyCatalog(namespace, diagnostics) {
4293
- return {
4294
- dialect: "sqlite",
4295
- server: {
4296
- product: "sqlite",
4297
- rawVersion: "unknown",
4298
- capabilities: {
4299
- generatedColumns: false,
4300
- identityMetadata: false,
4301
- checkConstraints: false,
4302
- checkConstraintEnforcement: "unknown",
4303
- expressionDecompilation: false,
4304
- indexExpressions: false,
4305
- indexPredicates: false,
4306
- indexIncludedColumns: false,
4307
- namespaces: false,
4308
- visibility: "unknown"
4309
- }
4310
- },
4311
- namespace: {
4312
- kind: "sqlite-database",
4313
- name: namespace
4314
- },
4315
- tables: [],
4316
- deferredObjects: [],
4317
- diagnostics
4318
- };
4319
- }
4320
- function stableId(value) {
4321
- if (value && !/[.\\\u0000-\u001f\u007f]/.test(value)) return value;
4322
- let hash = 2166136261;
4323
- for (const character of value) {
4324
- hash ^= character.charCodeAt(0);
4325
- hash = Math.imul(hash, 16777619);
4326
- }
4327
- return `introspected_${(hash >>> 0).toString(16)}`;
4328
- }
4329
- function text(value) {
4330
- return value === null || value === void 0 ? void 0 : String(value);
4331
- }
4332
- function number(value) {
4333
- if (typeof value === "number" && Number.isFinite(value)) return value;
4334
- if (typeof value === "string" && value.trim() !== "") {
4335
- const result = Number(value);
4336
- return Number.isFinite(result) ? result : void 0;
4337
- }
4338
- }
4339
- function boolean(value) {
4340
- return value === true || value === 1 || value === "1" || value === "t" || value === "true";
4341
- }
4342
- function action(value) {
4343
- const normalized = text(value)?.toLowerCase();
4344
- return normalized === "cascade" ? "cascade" : normalized === "restrict" ? "restrict" : normalized === "set null" ? "set-null" : normalized === "set default" ? "set-default" : "no-action";
4345
- }
4346
- function match(value) {
4347
- const normalized = text(value)?.toLowerCase();
4348
- return normalized === "full" ? "full" : normalized === "partial" ? "partial" : "simple";
4349
- }
4350
- //#endregion
4351
- export { IntrospectionError, createCompleteIntrospectionCatalog, createIntrospectionDiagnostic, freezeIntrospectionCatalog, hasIntrospectionErrors, introspectedPhysicalIdentityPolicy, mapCatalogToCompleteSnapshot, mapCatalogToSnapshot, mapCatalogToSnapshotV2, mysqlChecksQuery, mysqlCollationsQuery, mysqlColumnsQuery, mysqlEventsQuery, mysqlKeyUsageQuery, mysqlPartitionsQuery, mysqlRoutineParametersQuery, mysqlRoutinesQuery, mysqlServerQuery, mysqlStatisticsQuery, mysqlTablesQuery, mysqlTriggersQuery, mysqlViewsQuery, postgresCollationsQuery, postgresColumnsQuery, postgresConstraintsQuery, postgresDomainConstraintsQuery, postgresDomainsQuery, postgresEnumsQuery, postgresExtensionsQuery, postgresIdentitiesQuery, postgresIndexesQuery, postgresMetadataQuery, postgresPartitionsQuery, postgresPoliciesQuery, postgresRelationsQuery, postgresRoutineParametersQuery, postgresRoutinesQuery, postgresSequencesQuery, postgresServerQuery, postgresTriggersQuery, postgresViewsQuery, readMysqlCatalog, readPostgresCatalog, readSqliteCatalog, sqliteDatabaseListQuery, sqliteForeignKeyQuery, sqliteIndexInfoQuery, sqliteIndexListQuery, sqliteSchemaQuery, sqliteServerQuery, sqliteTableInfoQuery, sqliteTableListQuery, sqliteTempSchemaQuery, toIntrospectionCatalog };
673
+ export { IntrospectionError, createCompleteIntrospectionCatalog, createIntrospectionDiagnostic, freezeIntrospectionCatalog, hasIntrospectionErrors, introspectedPhysicalIdentityPolicy, mapCatalogToCompleteSnapshot, mapCatalogToSnapshot, mapCatalogToSnapshotV2, toIntrospectionCatalog };