@prisma-next/target-sqlite 0.12.0 → 0.13.0-dev.2

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 (126) hide show
  1. package/dist/{codec-ids-CYwMu3-4.d.mts → codec-ids-BfPkjMmk.d.mts} +1 -1
  2. package/dist/{codec-ids-CYwMu3-4.d.mts.map → codec-ids-BfPkjMmk.d.mts.map} +1 -1
  3. package/dist/{codec-ids-CuUxYcd0.mjs → codec-ids-DSU7S2Li.mjs} +1 -1
  4. package/dist/{codec-ids-CuUxYcd0.mjs.map → codec-ids-DSU7S2Li.mjs.map} +1 -1
  5. package/dist/codec-ids.d.mts +1 -1
  6. package/dist/codec-ids.mjs +1 -1
  7. package/dist/{codec-types-DNauB5UT.d.mts → codec-types-izdPhp_9.d.mts} +6 -7
  8. package/dist/codec-types-izdPhp_9.d.mts.map +1 -0
  9. package/dist/codec-types.d.mts +3 -3
  10. package/dist/{codecs-BAlEiSeP.d.mts → codecs-BGeJavlQ.d.mts} +16 -18
  11. package/dist/codecs-BGeJavlQ.d.mts.map +1 -0
  12. package/dist/{codecs-DVnHtVWW.mjs → codecs-DsC4OGmU.mjs} +2 -2
  13. package/dist/{codecs-DVnHtVWW.mjs.map → codecs-DsC4OGmU.mjs.map} +1 -1
  14. package/dist/codecs.d.mts +2 -2
  15. package/dist/codecs.mjs +1 -1
  16. package/dist/contract-free.d.mts +55 -0
  17. package/dist/contract-free.d.mts.map +1 -0
  18. package/dist/contract-free.mjs +111 -0
  19. package/dist/contract-free.mjs.map +1 -0
  20. package/dist/control-tables-7KwMyJ6i.mjs +12 -0
  21. package/dist/control-tables-7KwMyJ6i.mjs.map +1 -0
  22. package/dist/control-tables.d.mts +11 -0
  23. package/dist/control-tables.d.mts.map +1 -0
  24. package/dist/control-tables.mjs +2 -0
  25. package/dist/control.d.mts +31 -15
  26. package/dist/control.d.mts.map +1 -1
  27. package/dist/control.mjs +66 -124
  28. package/dist/control.mjs.map +1 -1
  29. package/dist/ddl.d.mts +2 -0
  30. package/dist/ddl.mjs +2 -0
  31. package/dist/{default-normalizer-3Fccw7yw.mjs → default-normalizer-DuoHj9-O.mjs} +1 -1
  32. package/dist/{default-normalizer-3Fccw7yw.mjs.map → default-normalizer-DuoHj9-O.mjs.map} +1 -1
  33. package/dist/default-normalizer.mjs +1 -1
  34. package/dist/descriptor-meta-Dxx2A6PT.mjs +17 -0
  35. package/dist/descriptor-meta-Dxx2A6PT.mjs.map +1 -0
  36. package/dist/descriptor-meta-runtime-BkXK3OjD.mjs +12 -0
  37. package/dist/descriptor-meta-runtime-BkXK3OjD.mjs.map +1 -0
  38. package/dist/migration.d.mts +2 -2
  39. package/dist/migration.mjs +3 -3
  40. package/dist/{native-type-normalizer-BlN5XfD-.mjs → native-type-normalizer-CiSyVmMP.mjs} +1 -1
  41. package/dist/{native-type-normalizer-BlN5XfD-.mjs.map → native-type-normalizer-CiSyVmMP.mjs.map} +1 -1
  42. package/dist/native-type-normalizer.mjs +1 -1
  43. package/dist/nodes-D0k4z7NL.mjs +33 -0
  44. package/dist/nodes-D0k4z7NL.mjs.map +1 -0
  45. package/dist/nodes-VzaaeUTb.d.mts +29 -0
  46. package/dist/nodes-VzaaeUTb.d.mts.map +1 -0
  47. package/dist/{op-factory-call-BnPhI25-.mjs → op-factory-call-DymqdXQW.mjs} +2 -2
  48. package/dist/{op-factory-call-BnPhI25-.mjs.map → op-factory-call-DymqdXQW.mjs.map} +1 -1
  49. package/dist/op-factory-call.d.mts +2 -2
  50. package/dist/op-factory-call.d.mts.map +1 -1
  51. package/dist/op-factory-call.mjs +1 -1
  52. package/dist/pack.d.mts +9 -7
  53. package/dist/pack.d.mts.map +1 -1
  54. package/dist/pack.mjs +1 -1
  55. package/dist/{planner-CEKTRydl.mjs → planner-DSNDwQy9.mjs} +9 -9
  56. package/dist/planner-DSNDwQy9.mjs.map +1 -0
  57. package/dist/{planner-produced-sqlite-migration-CI9LdXPr.d.mts → planner-produced-sqlite-migration-C1yqJAiM.d.mts} +3 -3
  58. package/dist/{planner-produced-sqlite-migration-CI9LdXPr.d.mts.map → planner-produced-sqlite-migration-C1yqJAiM.d.mts.map} +1 -1
  59. package/dist/{planner-produced-sqlite-migration-DCsg3RDZ.mjs → planner-produced-sqlite-migration-DowV_vHw.mjs} +3 -3
  60. package/dist/{planner-produced-sqlite-migration-DCsg3RDZ.mjs.map → planner-produced-sqlite-migration-DowV_vHw.mjs.map} +1 -1
  61. package/dist/planner-produced-sqlite-migration.d.mts +1 -1
  62. package/dist/planner-produced-sqlite-migration.mjs +1 -1
  63. package/dist/{planner-target-details-Bm71XPKb.mjs → planner-target-details-H8z9TFDg.mjs} +1 -1
  64. package/dist/{planner-target-details-Bm71XPKb.mjs.map → planner-target-details-H8z9TFDg.mjs.map} +1 -1
  65. package/dist/{planner-target-details-vhvZDWK1.d.mts → planner-target-details-xR6UfIcz.d.mts} +1 -1
  66. package/dist/{planner-target-details-vhvZDWK1.d.mts.map → planner-target-details-xR6UfIcz.d.mts.map} +1 -1
  67. package/dist/planner-target-details.d.mts +1 -1
  68. package/dist/planner-target-details.mjs +1 -1
  69. package/dist/planner.d.mts +2 -2
  70. package/dist/planner.d.mts.map +1 -1
  71. package/dist/planner.mjs +1 -1
  72. package/dist/{render-ops-CSRDT4YL.mjs → render-ops-CFRbJ3Yb.mjs} +1 -1
  73. package/dist/{render-ops-CSRDT4YL.mjs.map → render-ops-CFRbJ3Yb.mjs.map} +1 -1
  74. package/dist/render-ops.d.mts +1 -1
  75. package/dist/render-ops.mjs +1 -1
  76. package/dist/runtime.d.mts +17 -1
  77. package/dist/runtime.d.mts.map +1 -1
  78. package/dist/runtime.mjs +4 -3
  79. package/dist/runtime.mjs.map +1 -1
  80. package/dist/{shared-qLsgTOZs.d.mts → shared-Dhc8mLK1.d.mts} +2 -2
  81. package/dist/{shared-qLsgTOZs.d.mts.map → shared-Dhc8mLK1.d.mts.map} +1 -1
  82. package/dist/{sql-utils-DhevMgef.mjs → sql-utils-CV8Bdgtc.mjs} +1 -1
  83. package/dist/{sql-utils-DhevMgef.mjs.map → sql-utils-CV8Bdgtc.mjs.map} +1 -1
  84. package/dist/sql-utils.mjs +1 -1
  85. package/dist/sqlite-contract-serializer-jcRu8aHh.mjs +101 -0
  86. package/dist/sqlite-contract-serializer-jcRu8aHh.mjs.map +1 -0
  87. package/dist/{sqlite-migration-BBJktVVw.mjs → sqlite-migration-CUqgmzQH.mjs} +1 -1
  88. package/dist/{sqlite-migration-BBJktVVw.mjs.map → sqlite-migration-CUqgmzQH.mjs.map} +1 -1
  89. package/dist/{sqlite-migration-DAb2NEX6.d.mts → sqlite-migration-D4XGYzgQ.d.mts} +2 -2
  90. package/dist/{sqlite-migration-DAb2NEX6.d.mts.map → sqlite-migration-D4XGYzgQ.d.mts.map} +1 -1
  91. package/dist/{tables-DGRRJasz.mjs → tables-CjB7vXCr.mjs} +5 -11
  92. package/dist/tables-CjB7vXCr.mjs.map +1 -0
  93. package/package.json +23 -21
  94. package/src/contract-free/columns.ts +44 -0
  95. package/src/contract-free/control-bootstrap.ts +54 -0
  96. package/src/contract-free/ddl.ts +26 -0
  97. package/src/core/authoring.ts +1 -1
  98. package/src/core/control-tables.ts +11 -0
  99. package/src/core/control-target.ts +4 -6
  100. package/src/core/ddl/nodes.ts +54 -0
  101. package/src/core/descriptor-meta-runtime.ts +28 -0
  102. package/src/core/descriptor-meta.ts +4 -6
  103. package/src/core/migrations/issue-planner.ts +1 -1
  104. package/src/core/migrations/operations/shared.ts +1 -8
  105. package/src/core/migrations/planner-strategies.ts +1 -1
  106. package/src/core/migrations/runner.ts +78 -83
  107. package/src/core/runtime-target.ts +2 -2
  108. package/src/core/sqlite-contract-serializer.ts +21 -9
  109. package/src/core/sqlite-unbound-database.ts +113 -26
  110. package/src/exports/contract-free.ts +6 -0
  111. package/src/exports/control-tables.ts +5 -0
  112. package/src/exports/ddl.ts +6 -0
  113. package/src/exports/runtime.ts +1 -0
  114. package/dist/codec-types-DNauB5UT.d.mts.map +0 -1
  115. package/dist/codecs-BAlEiSeP.d.mts.map +0 -1
  116. package/dist/descriptor-meta-CE2Kbn9b.mjs +0 -17
  117. package/dist/descriptor-meta-CE2Kbn9b.mjs.map +0 -1
  118. package/dist/planner-CEKTRydl.mjs.map +0 -1
  119. package/dist/statement-builders-Dne-LkAV.mjs +0 -158
  120. package/dist/statement-builders-Dne-LkAV.mjs.map +0 -1
  121. package/dist/statement-builders.d.mts +0 -68
  122. package/dist/statement-builders.d.mts.map +0 -1
  123. package/dist/statement-builders.mjs +0 -2
  124. package/dist/tables-DGRRJasz.mjs.map +0 -1
  125. package/src/core/migrations/statement-builders.ts +0 -212
  126. package/src/exports/statement-builders.ts +0 -12
@@ -1,3 +1,7 @@
1
+ import { SqlNamespaceTablesInput, SqlStorage } from "@prisma-next/sql-contract/types";
2
+ import { Namespace } from "@prisma-next/framework-components/ir";
3
+ import { SqlContractSerializerBase } from "@prisma-next/family-sql/ir";
4
+ import { Contract } from "@prisma-next/contract/types";
1
5
  import { RuntimeTargetInstance } from "@prisma-next/framework-components/execution";
2
6
  import { SqlRuntimeTargetDescriptor } from "@prisma-next/sql-runtime";
3
7
 
@@ -5,5 +9,17 @@ import { SqlRuntimeTargetDescriptor } from "@prisma-next/sql-runtime";
5
9
  interface SqliteRuntimeTargetInstance extends RuntimeTargetInstance<'sql', 'sqlite'> {}
6
10
  declare const sqliteRuntimeTargetDescriptor: SqlRuntimeTargetDescriptor<'sqlite', SqliteRuntimeTargetInstance>;
7
11
  //#endregion
8
- export { type SqliteRuntimeTargetInstance, sqliteRuntimeTargetDescriptor as default };
12
+ //#region src/core/sqlite-contract-serializer.d.ts
13
+ /**
14
+ * SQLite target `ContractSerializer` concretion. Mirrors the Postgres
15
+ * shape: inherits the full SQL-family deserialization pipeline and
16
+ * materialises namespace entries as SQLite database concretions that
17
+ * expose `qualifyTable()` for runtime SQL rendering.
18
+ */
19
+ declare class SqliteContractSerializer extends SqlContractSerializerBase<Contract<SqlStorage>> {
20
+ constructor();
21
+ protected hydrateSqlNamespaceEntry(nsId: string, raw: Namespace | Record<string, unknown>): Namespace | SqlNamespaceTablesInput;
22
+ }
23
+ //#endregion
24
+ export { SqliteContractSerializer, type SqliteRuntimeTargetInstance, sqliteRuntimeTargetDescriptor as default };
9
25
  //# sourceMappingURL=runtime.d.mts.map
@@ -1 +1 @@
1
- {"version":3,"file":"runtime.d.mts","names":[],"sources":["../src/core/runtime-target.ts"],"mappings":";;;;UAIiB,2BAAA,SAAoC,qBAAqB;AAAA,cAEpE,6BAAA,EAA+B,0BAA0B,WAE7D,2BAAA"}
1
+ {"version":3,"file":"runtime.d.mts","names":[],"sources":["../src/core/runtime-target.ts","../src/core/sqlite-contract-serializer.ts"],"mappings":";;;;;;;;UAIiB,2BAAA,SAAoC,qBAAqB;AAAA,cAEpE,6BAAA,EAA+B,0BAA0B,WAE7D,2BAAA;;;;;;;AAJF;;cCSa,wBAAA,SAAiC,yBAAA,CAA0B,QAAA,CAAS,UAAA;;YAK5D,wBAAA,CACjB,IAAA,UACA,GAAA,EAAK,SAAA,GAAY,MAAA,oBAChB,SAAA,GAAY,uBAAA;AAAA"}
package/dist/runtime.mjs CHANGED
@@ -1,7 +1,8 @@
1
- import { t as sqliteTargetDescriptorMeta } from "./descriptor-meta-CE2Kbn9b.mjs";
1
+ import { t as sqliteTargetDescriptorMetaRuntime } from "./descriptor-meta-runtime-BkXK3OjD.mjs";
2
+ import { t as SqliteContractSerializer } from "./sqlite-contract-serializer-jcRu8aHh.mjs";
2
3
  //#region src/core/runtime-target.ts
3
4
  const sqliteRuntimeTargetDescriptor = {
4
- ...sqliteTargetDescriptorMeta,
5
+ ...sqliteTargetDescriptorMetaRuntime,
5
6
  codecs: () => [],
6
7
  create() {
7
8
  return {
@@ -11,6 +12,6 @@ const sqliteRuntimeTargetDescriptor = {
11
12
  }
12
13
  };
13
14
  //#endregion
14
- export { sqliteRuntimeTargetDescriptor as default };
15
+ export { SqliteContractSerializer, sqliteRuntimeTargetDescriptor as default };
15
16
 
16
17
  //# sourceMappingURL=runtime.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"runtime.mjs","names":[],"sources":["../src/core/runtime-target.ts"],"sourcesContent":["import type { RuntimeTargetInstance } from '@prisma-next/framework-components/execution';\nimport type { SqlRuntimeTargetDescriptor } from '@prisma-next/sql-runtime';\nimport { sqliteTargetDescriptorMeta } from './descriptor-meta';\n\nexport interface SqliteRuntimeTargetInstance extends RuntimeTargetInstance<'sql', 'sqlite'> {}\n\nconst sqliteRuntimeTargetDescriptor: SqlRuntimeTargetDescriptor<\n 'sqlite',\n SqliteRuntimeTargetInstance\n> = {\n ...sqliteTargetDescriptorMeta,\n codecs: () => [],\n create(): SqliteRuntimeTargetInstance {\n return {\n familyId: 'sql',\n targetId: 'sqlite',\n };\n },\n};\n\nexport default sqliteRuntimeTargetDescriptor;\n"],"mappings":";;AAMA,MAAM,gCAGF;CACF,GAAG;CACH,cAAc,CAAC;CACf,SAAsC;EACpC,OAAO;GACL,UAAU;GACV,UAAU;EACZ;CACF;AACF"}
1
+ {"version":3,"file":"runtime.mjs","names":[],"sources":["../src/core/runtime-target.ts"],"sourcesContent":["import type { RuntimeTargetInstance } from '@prisma-next/framework-components/execution';\nimport type { SqlRuntimeTargetDescriptor } from '@prisma-next/sql-runtime';\nimport { sqliteTargetDescriptorMetaRuntime } from './descriptor-meta-runtime';\n\nexport interface SqliteRuntimeTargetInstance extends RuntimeTargetInstance<'sql', 'sqlite'> {}\n\nconst sqliteRuntimeTargetDescriptor: SqlRuntimeTargetDescriptor<\n 'sqlite',\n SqliteRuntimeTargetInstance\n> = {\n ...sqliteTargetDescriptorMetaRuntime,\n codecs: () => [],\n create(): SqliteRuntimeTargetInstance {\n return {\n familyId: 'sql',\n targetId: 'sqlite',\n };\n },\n};\n\nexport default sqliteRuntimeTargetDescriptor;\n"],"mappings":";;;AAMA,MAAM,gCAGF;CACF,GAAG;CACH,cAAc,CAAC;CACf,SAAsC;EACpC,OAAO;GACL,UAAU;GACV,UAAU;EACZ;CACF;AACF"}
@@ -1,4 +1,4 @@
1
- import { t as SqlitePlanTargetDetails } from "./planner-target-details-vhvZDWK1.mjs";
1
+ import { t as SqlitePlanTargetDetails } from "./planner-target-details-xR6UfIcz.mjs";
2
2
  import { SqlMigrationPlanOperation } from "@prisma-next/family-sql/control";
3
3
  import { ReferentialAction } from "@prisma-next/sql-contract/types";
4
4
 
@@ -66,4 +66,4 @@ interface SqliteIndexSpec {
66
66
  }
67
67
  //#endregion
68
68
  export { SqliteTableSpec as i, SqliteColumnSpec as n, SqliteIndexSpec as r, Op as t };
69
- //# sourceMappingURL=shared-qLsgTOZs.d.mts.map
69
+ //# sourceMappingURL=shared-Dhc8mLK1.d.mts.map
@@ -1 +1 @@
1
- {"version":3,"file":"shared-qLsgTOZs.d.mts","names":[],"sources":["../src/core/migrations/operations/shared.ts"],"mappings":";;;;;KAKY,EAAA,GAAK,yBAAyB,CAAC,uBAAA;;AAAuB;AAsBlE;;;;;;;;;;AAKwC;AAGxC;;;UARiB,gBAAA;EAAA,SACN,IAAA;EAAA,SACA,OAAA;EAAA,SACA,UAAA;EAAA,SACA,QAAA;EAAA,SACA,6BAAA;AAAA;AAAA,UAGM,oBAAA;EAAA,SACN,OAAO;AAAA;AAAA,UAGD,gBAAA;EAAA,SACN,OAAA;EAAA,SACA,IAAI;AAAA;AAAA,UAGE,oBAAA;EAAA,SACN,OAAA;EAAA,SACA,UAAA;IAAA,SACE,KAAA;IAAA,SACA,OAAA;EAAA;EAAA,SAEF,IAAA;EAAA,SACA,QAAA,GAAW,iBAAA;EAAA,SACX,QAAA,GAAW,iBAAiB;EAAA,SAC5B,UAAA;AAAA;;;;;UAOM,eAAA;EAAA,SACN,OAAA,WAAkB,gBAAA;EAAA,SAClB,UAAA,GAAa,oBAAA;EAAA,SACb,OAAA,YAAmB,gBAAA;EAAA,SACnB,WAAA,YAAuB,oBAAA;AAAA;;;;;;UAQjB,eAAA;EAAA,SACN,IAAA;EAAA,SACA,OAAO;AAAA"}
1
+ {"version":3,"file":"shared-Dhc8mLK1.d.mts","names":[],"sources":["../src/core/migrations/operations/shared.ts"],"mappings":";;;;;KAMY,EAAA,GAAK,yBAAyB,CAAC,uBAAA;;AAAuB;AAsBlE;;;;;;;;;;AAKwC;AAGxC;;;UARiB,gBAAA;EAAA,SACN,IAAA;EAAA,SACA,OAAA;EAAA,SACA,UAAA;EAAA,SACA,QAAA;EAAA,SACA,6BAAA;AAAA;AAAA,UAGM,oBAAA;EAAA,SACN,OAAO;AAAA;AAAA,UAGD,gBAAA;EAAA,SACN,OAAA;EAAA,SACA,IAAI;AAAA;AAAA,UAGE,oBAAA;EAAA,SACN,OAAA;EAAA,SACA,UAAA;IAAA,SACE,KAAA;IAAA,SACA,OAAA;EAAA;EAAA,SAEF,IAAA;EAAA,SACA,QAAA,GAAW,iBAAA;EAAA,SACX,QAAA,GAAW,iBAAiB;EAAA,SAC5B,UAAA;AAAA;;;;;UAOM,eAAA;EAAA,SACN,OAAA,WAAkB,gBAAA;EAAA,SAClB,UAAA,GAAa,oBAAA;EAAA,SACb,OAAA,YAAmB,gBAAA;EAAA,SACnB,WAAA,YAAuB,oBAAA;AAAA;;;;;;UAQjB,eAAA;EAAA,SACN,IAAA;EAAA,SACA,OAAO;AAAA"}
@@ -32,4 +32,4 @@ function escapeLiteral(value) {
32
32
  //#endregion
33
33
  export { escapeLiteral as n, quoteIdentifier as r, SqlEscapeError as t };
34
34
 
35
- //# sourceMappingURL=sql-utils-DhevMgef.mjs.map
35
+ //# sourceMappingURL=sql-utils-CV8Bdgtc.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"sql-utils-DhevMgef.mjs","names":[],"sources":["../src/core/sql-utils.ts"],"sourcesContent":["/**\n * Shared SQL utility functions for the SQLite target.\n *\n * These functions handle safe SQL identifier and literal escaping. They\n * live in `target-sqlite` (mirroring `target-postgres/src/core/sql-utils.ts`)\n * so both the control adapter (used at emit time) and the runtime adapter\n * (used at execute time) can depend on them through a single one-way edge:\n * `adapter-sqlite → target-sqlite`. Hosting them target-side avoids the\n * cyclic workspace dependency that would arise if `target-sqlite` reached\n * back into `adapter-sqlite` for these primitives.\n */\n\nexport class SqlEscapeError extends Error {\n constructor(\n message: string,\n public readonly value: string,\n public readonly kind: 'identifier' | 'literal',\n ) {\n super(message);\n this.name = 'SqlEscapeError';\n }\n}\n\nexport function quoteIdentifier(identifier: string): string {\n if (identifier.length === 0) {\n throw new SqlEscapeError('Identifier cannot be empty', identifier, 'identifier');\n }\n if (identifier.includes('\\0')) {\n throw new SqlEscapeError(\n 'Identifier cannot contain null bytes',\n identifier.replace(/\\0/g, '\\\\0'),\n 'identifier',\n );\n }\n return `\"${identifier.replace(/\"/g, '\"\"')}\"`;\n}\n\nexport function escapeLiteral(value: string): string {\n if (value.includes('\\0')) {\n throw new SqlEscapeError(\n 'Literal value cannot contain null bytes',\n value.replace(/\\0/g, '\\\\0'),\n 'literal',\n );\n }\n return value.replace(/'/g, \"''\");\n}\n"],"mappings":";;;;;;;;;;;;AAYA,IAAa,iBAAb,cAAoC,MAAM;CAGtB;CACA;CAHlB,YACE,SACA,OACA,MACA;EACA,MAAM,OAAO;EAHG,KAAA,QAAA;EACA,KAAA,OAAA;EAGhB,KAAK,OAAO;CACd;AACF;AAEA,SAAgB,gBAAgB,YAA4B;CAC1D,IAAI,WAAW,WAAW,GACxB,MAAM,IAAI,eAAe,8BAA8B,YAAY,YAAY;CAEjF,IAAI,WAAW,SAAS,IAAI,GAC1B,MAAM,IAAI,eACR,wCACA,WAAW,QAAQ,OAAO,KAAK,GAC/B,YACF;CAEF,OAAO,IAAI,WAAW,QAAQ,MAAM,MAAI,EAAE;AAC5C;AAEA,SAAgB,cAAc,OAAuB;CACnD,IAAI,MAAM,SAAS,IAAI,GACrB,MAAM,IAAI,eACR,2CACA,MAAM,QAAQ,OAAO,KAAK,GAC1B,SACF;CAEF,OAAO,MAAM,QAAQ,MAAM,IAAI;AACjC"}
1
+ {"version":3,"file":"sql-utils-CV8Bdgtc.mjs","names":[],"sources":["../src/core/sql-utils.ts"],"sourcesContent":["/**\n * Shared SQL utility functions for the SQLite target.\n *\n * These functions handle safe SQL identifier and literal escaping. They\n * live in `target-sqlite` (mirroring `target-postgres/src/core/sql-utils.ts`)\n * so both the control adapter (used at emit time) and the runtime adapter\n * (used at execute time) can depend on them through a single one-way edge:\n * `adapter-sqlite → target-sqlite`. Hosting them target-side avoids the\n * cyclic workspace dependency that would arise if `target-sqlite` reached\n * back into `adapter-sqlite` for these primitives.\n */\n\nexport class SqlEscapeError extends Error {\n constructor(\n message: string,\n public readonly value: string,\n public readonly kind: 'identifier' | 'literal',\n ) {\n super(message);\n this.name = 'SqlEscapeError';\n }\n}\n\nexport function quoteIdentifier(identifier: string): string {\n if (identifier.length === 0) {\n throw new SqlEscapeError('Identifier cannot be empty', identifier, 'identifier');\n }\n if (identifier.includes('\\0')) {\n throw new SqlEscapeError(\n 'Identifier cannot contain null bytes',\n identifier.replace(/\\0/g, '\\\\0'),\n 'identifier',\n );\n }\n return `\"${identifier.replace(/\"/g, '\"\"')}\"`;\n}\n\nexport function escapeLiteral(value: string): string {\n if (value.includes('\\0')) {\n throw new SqlEscapeError(\n 'Literal value cannot contain null bytes',\n value.replace(/\\0/g, '\\\\0'),\n 'literal',\n );\n }\n return value.replace(/'/g, \"''\");\n}\n"],"mappings":";;;;;;;;;;;;AAYA,IAAa,iBAAb,cAAoC,MAAM;CAGtB;CACA;CAHlB,YACE,SACA,OACA,MACA;EACA,MAAM,OAAO;EAHG,KAAA,QAAA;EACA,KAAA,OAAA;EAGhB,KAAK,OAAO;CACd;AACF;AAEA,SAAgB,gBAAgB,YAA4B;CAC1D,IAAI,WAAW,WAAW,GACxB,MAAM,IAAI,eAAe,8BAA8B,YAAY,YAAY;CAEjF,IAAI,WAAW,SAAS,IAAI,GAC1B,MAAM,IAAI,eACR,wCACA,WAAW,QAAQ,OAAO,KAAK,GAC/B,YACF;CAEF,OAAO,IAAI,WAAW,QAAQ,MAAM,MAAI,EAAE;AAC5C;AAEA,SAAgB,cAAc,OAAuB;CACnD,IAAI,MAAM,SAAS,IAAI,GACrB,MAAM,IAAI,eACR,2CACA,MAAM,QAAQ,OAAO,KAAK,GAC1B,SACF;CAEF,OAAO,MAAM,QAAQ,MAAM,IAAI;AACjC"}
@@ -1,2 +1,2 @@
1
- import { n as escapeLiteral, r as quoteIdentifier, t as SqlEscapeError } from "./sql-utils-DhevMgef.mjs";
1
+ import { n as escapeLiteral, r as quoteIdentifier, t as SqlEscapeError } from "./sql-utils-CV8Bdgtc.mjs";
2
2
  export { SqlEscapeError, escapeLiteral, quoteIdentifier };
@@ -0,0 +1,101 @@
1
+ import { StorageTable } from "@prisma-next/sql-contract/types";
2
+ import { NamespaceBase, UNBOUND_NAMESPACE_ID, freezeNode } from "@prisma-next/framework-components/ir";
3
+ import { SqlContractSerializerBase } from "@prisma-next/family-sql/ir";
4
+ import { blindCast, castAs } from "@prisma-next/utils/casts";
5
+ //#region src/core/sqlite-unbound-database.ts
6
+ const SQLITE_NAMESPACE_KIND = "sqlite-namespace";
7
+ /**
8
+ * SQLite namespace concretion carrying table metadata under
9
+ * `entries.table` and unqualified `qualifyTable()` emission for runtime
10
+ * SQL rendering.
11
+ */
12
+ var SqliteDatabase = class extends NamespaceBase {
13
+ id;
14
+ entries;
15
+ constructor(input) {
16
+ super();
17
+ this.id = input.id;
18
+ this.entries = Object.freeze({ table: Object.freeze(Object.fromEntries(Object.entries(input.entries.table).map(([k, v]) => [k, v instanceof StorageTable ? v : new StorageTable(v)]))) });
19
+ Object.defineProperty(this, "kind", {
20
+ value: SQLITE_NAMESPACE_KIND,
21
+ writable: false,
22
+ enumerable: false,
23
+ configurable: true
24
+ });
25
+ freezeNode(this);
26
+ }
27
+ qualifier() {
28
+ return "";
29
+ }
30
+ qualifyTable(tableName) {
31
+ return `"${tableName}"`;
32
+ }
33
+ };
34
+ /**
35
+ * SQLite target `Namespace` concretion. SQLite has no schema or
36
+ * database-namespacing concept at the SQL level — there is exactly one
37
+ * effective namespace per connection, so the target ships a single
38
+ * singleton bound to the framework's `UNBOUND_NAMESPACE_ID` slot.
39
+ *
40
+ * Qualifier emission elides the prefix entirely: rendered DDL and
41
+ * queries look unqualified (`CREATE TABLE "users" (...)`), matching
42
+ * SQLite's native dialect. Call sites stay polymorphic — they ask the
43
+ * namespace for its qualifier and consume the empty/unqualified result
44
+ * the same way Postgres consumes a `"schema"` prefix.
45
+ *
46
+ * The SQLite PSL interpreter rejects every explicit `namespace { … }`
47
+ * block with a diagnostic naming SQLite; only the implicit
48
+ * `__unspecified__` AST bucket reaches the SQLite interpreter, which
49
+ * lowers it to this singleton.
50
+ */
51
+ var SqliteUnboundDatabase = class SqliteUnboundDatabase extends SqliteDatabase {
52
+ static instance = new SqliteUnboundDatabase();
53
+ constructor() {
54
+ super({
55
+ id: UNBOUND_NAMESPACE_ID,
56
+ entries: { table: {} }
57
+ });
58
+ }
59
+ };
60
+ function buildSqliteNamespace(input) {
61
+ if (input.id !== UNBOUND_NAMESPACE_ID) throw new Error(`buildSqliteNamespace: SQLite has no schema concept; the only valid namespace id is "${UNBOUND_NAMESPACE_ID}" (received "${input.id}").`);
62
+ if (Object.keys(input.entries.table).length === 0) return castAs(SqliteUnboundDatabase.instance);
63
+ return new SqliteDatabase({
64
+ id: input.id,
65
+ entries: input.entries
66
+ });
67
+ }
68
+ /**
69
+ * Target-supplied `Namespace` factory the SQLite target plumbs through
70
+ * `defineContract({ createNamespace })`. SQLite has only one
71
+ * effective namespace slot — the framework `UNBOUND_NAMESPACE_ID`
72
+ * sentinel — so the factory always returns the singleton or a fresh
73
+ * `SqliteDatabase` for the unbound slot with tables. The SQL family's
74
+ * defensive validation in `defineContract` already rejects
75
+ * user-declared SQLite namespaces, so this throw is a structural
76
+ * safety net rather than a user-facing surface.
77
+ */
78
+ function sqliteCreateNamespace(input) {
79
+ return buildSqliteNamespace(input);
80
+ }
81
+ //#endregion
82
+ //#region src/core/sqlite-contract-serializer.ts
83
+ /**
84
+ * SQLite target `ContractSerializer` concretion. Mirrors the Postgres
85
+ * shape: inherits the full SQL-family deserialization pipeline and
86
+ * materialises namespace entries as SQLite database concretions that
87
+ * expose `qualifyTable()` for runtime SQL rendering.
88
+ */
89
+ var SqliteContractSerializer = class extends SqlContractSerializerBase {
90
+ constructor() {
91
+ super(/* @__PURE__ */ new Map());
92
+ }
93
+ hydrateSqlNamespaceEntry(nsId, raw) {
94
+ if (raw instanceof NamespaceBase) return raw;
95
+ return buildSqliteNamespace(blindCast(super.hydrateSqlNamespaceEntry(nsId, raw)));
96
+ }
97
+ };
98
+ //#endregion
99
+ export { SqliteUnboundDatabase as n, sqliteCreateNamespace as r, SqliteContractSerializer as t };
100
+
101
+ //# sourceMappingURL=sqlite-contract-serializer-jcRu8aHh.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"sqlite-contract-serializer-jcRu8aHh.mjs","names":[],"sources":["../src/core/sqlite-unbound-database.ts","../src/core/sqlite-contract-serializer.ts"],"sourcesContent":["import {\n freezeNode,\n type Namespace,\n NamespaceBase,\n UNBOUND_NAMESPACE_ID,\n} from '@prisma-next/framework-components/ir';\nimport {\n type SqlNamespaceTablesInput,\n StorageTable,\n type StorageTableInput,\n} from '@prisma-next/sql-contract/types';\nimport { blindCast, castAs } from '@prisma-next/utils/casts';\n\nexport type SqliteDatabaseInput = {\n readonly id: string;\n readonly entries: {\n readonly table: Readonly<Record<string, StorageTable | StorageTableInput>>;\n };\n};\n\nconst SQLITE_NAMESPACE_KIND = 'sqlite-namespace' as const;\n\nfunction isMaterializedSqliteNamespace(\n ns: Namespace | SqlNamespaceTablesInput,\n): ns is SqliteDatabase | SqliteUnboundDatabase {\n if (typeof ns !== 'object' || ns === null) {\n return false;\n }\n const proto = Object.getPrototypeOf(ns);\n if (proto === Object.prototype || proto === null) {\n return false;\n }\n return (ns as { kind?: unknown }).kind === SQLITE_NAMESPACE_KIND;\n}\n\n/**\n * SQLite namespace concretion carrying table metadata under\n * `entries.table` and unqualified `qualifyTable()` emission for runtime\n * SQL rendering.\n */\nexport class SqliteDatabase extends NamespaceBase {\n declare readonly kind: string;\n\n readonly id: string;\n readonly entries: Readonly<{\n readonly table: Readonly<Record<string, StorageTable>>;\n }>;\n\n constructor(input: SqliteDatabaseInput) {\n super();\n this.id = input.id;\n this.entries = Object.freeze({\n table: Object.freeze(\n Object.fromEntries(\n Object.entries(input.entries.table).map(([k, v]) => [\n k,\n v instanceof StorageTable ? v : new StorageTable(v as StorageTableInput),\n ]),\n ),\n ),\n });\n Object.defineProperty(this, 'kind', {\n value: SQLITE_NAMESPACE_KIND,\n writable: false,\n enumerable: false,\n configurable: true,\n });\n freezeNode(this);\n }\n\n qualifier(): string {\n return '';\n }\n\n qualifyTable(tableName: string): string {\n return `\"${tableName}\"`;\n }\n}\n\n/**\n * SQLite target `Namespace` concretion. SQLite has no schema or\n * database-namespacing concept at the SQL level — there is exactly one\n * effective namespace per connection, so the target ships a single\n * singleton bound to the framework's `UNBOUND_NAMESPACE_ID` slot.\n *\n * Qualifier emission elides the prefix entirely: rendered DDL and\n * queries look unqualified (`CREATE TABLE \"users\" (...)`), matching\n * SQLite's native dialect. Call sites stay polymorphic — they ask the\n * namespace for its qualifier and consume the empty/unqualified result\n * the same way Postgres consumes a `\"schema\"` prefix.\n *\n * The SQLite PSL interpreter rejects every explicit `namespace { … }`\n * block with a diagnostic naming SQLite; only the implicit\n * `__unspecified__` AST bucket reaches the SQLite interpreter, which\n * lowers it to this singleton.\n */\nexport class SqliteUnboundDatabase extends SqliteDatabase {\n static readonly instance: SqliteUnboundDatabase = new SqliteUnboundDatabase();\n\n private constructor() {\n super({ id: UNBOUND_NAMESPACE_ID, entries: { table: {} } });\n }\n}\n\nexport function buildSqliteNamespace(\n input: SqlNamespaceTablesInput,\n): SqliteDatabase | SqliteUnboundDatabase {\n if (input.id !== UNBOUND_NAMESPACE_ID) {\n throw new Error(\n `buildSqliteNamespace: SQLite has no schema concept; the only valid namespace id is \"${UNBOUND_NAMESPACE_ID}\" (received \"${input.id}\").`,\n );\n }\n if (Object.keys(input.entries.table).length === 0) {\n return castAs<SqliteUnboundDatabase>(SqliteUnboundDatabase.instance);\n }\n return new SqliteDatabase({ id: input.id, entries: input.entries });\n}\n\nexport function buildSqliteNamespaceMap(\n namespaces: Readonly<Record<string, Namespace | SqlNamespaceTablesInput>>,\n): Readonly<Record<string, SqliteDatabase | SqliteUnboundDatabase>> {\n return Object.fromEntries(\n Object.entries(namespaces).map(([nsKey, ns]) => [\n nsKey,\n isMaterializedSqliteNamespace(ns)\n ? ns\n : buildSqliteNamespace(\n blindCast<\n SqlNamespaceTablesInput,\n 'non-materialized SQLite namespace map entry is a SqlNamespaceTablesInput'\n >(ns),\n ),\n ]),\n );\n}\n\n/**\n * Target-supplied `Namespace` factory the SQLite target plumbs through\n * `defineContract({ createNamespace })`. SQLite has only one\n * effective namespace slot — the framework `UNBOUND_NAMESPACE_ID`\n * sentinel — so the factory always returns the singleton or a fresh\n * `SqliteDatabase` for the unbound slot with tables. The SQL family's\n * defensive validation in `defineContract` already rejects\n * user-declared SQLite namespaces, so this throw is a structural\n * safety net rather than a user-facing surface.\n */\nexport function sqliteCreateNamespace(\n input: SqlNamespaceTablesInput,\n): SqliteDatabase | SqliteUnboundDatabase {\n return buildSqliteNamespace(input);\n}\n","import type { Contract } from '@prisma-next/contract/types';\nimport { SqlContractSerializerBase } from '@prisma-next/family-sql/ir';\nimport { type Namespace, NamespaceBase } from '@prisma-next/framework-components/ir';\nimport type { SqlNamespaceTablesInput, SqlStorage } from '@prisma-next/sql-contract/types';\nimport { blindCast } from '@prisma-next/utils/casts';\nimport { buildSqliteNamespace } from './sqlite-unbound-database';\n\n/**\n * SQLite target `ContractSerializer` concretion. Mirrors the Postgres\n * shape: inherits the full SQL-family deserialization pipeline and\n * materialises namespace entries as SQLite database concretions that\n * expose `qualifyTable()` for runtime SQL rendering.\n */\nexport class SqliteContractSerializer extends SqlContractSerializerBase<Contract<SqlStorage>> {\n constructor() {\n super(new Map());\n }\n\n protected override hydrateSqlNamespaceEntry(\n nsId: string,\n raw: Namespace | Record<string, unknown>,\n ): Namespace | SqlNamespaceTablesInput {\n if (raw instanceof NamespaceBase) {\n return raw;\n }\n const hydrated = blindCast<\n SqlNamespaceTablesInput,\n 'super.hydrateSqlNamespaceEntry returns the tables form when raw is not a NamespaceBase'\n >(super.hydrateSqlNamespaceEntry(nsId, raw));\n return buildSqliteNamespace(hydrated);\n }\n}\n"],"mappings":";;;;;AAoBA,MAAM,wBAAwB;;;;;;AAoB9B,IAAa,iBAAb,cAAoC,cAAc;CAGhD;CACA;CAIA,YAAY,OAA4B;EACtC,MAAM;EACN,KAAK,KAAK,MAAM;EAChB,KAAK,UAAU,OAAO,OAAO,EAC3B,OAAO,OAAO,OACZ,OAAO,YACL,OAAO,QAAQ,MAAM,QAAQ,KAAK,CAAC,CAAC,KAAK,CAAC,GAAG,OAAO,CAClD,GACA,aAAa,eAAe,IAAI,IAAI,aAAa,CAAsB,CACzE,CAAC,CACH,CACF,EACF,CAAC;EACD,OAAO,eAAe,MAAM,QAAQ;GAClC,OAAO;GACP,UAAU;GACV,YAAY;GACZ,cAAc;EAChB,CAAC;EACD,WAAW,IAAI;CACjB;CAEA,YAAoB;EAClB,OAAO;CACT;CAEA,aAAa,WAA2B;EACtC,OAAO,IAAI,UAAU;CACvB;AACF;;;;;;;;;;;;;;;;;;AAmBA,IAAa,wBAAb,MAAa,8BAA8B,eAAe;CACxD,OAAgB,WAAkC,IAAI,sBAAsB;CAE5E,cAAsB;EACpB,MAAM;GAAE,IAAI;GAAsB,SAAS,EAAE,OAAO,CAAC,EAAE;EAAE,CAAC;CAC5D;AACF;AAEA,SAAgB,qBACd,OACwC;CACxC,IAAI,MAAM,OAAO,sBACf,MAAM,IAAI,MACR,uFAAuF,qBAAqB,eAAe,MAAM,GAAG,IACtI;CAEF,IAAI,OAAO,KAAK,MAAM,QAAQ,KAAK,CAAC,CAAC,WAAW,GAC9C,OAAO,OAA8B,sBAAsB,QAAQ;CAErE,OAAO,IAAI,eAAe;EAAE,IAAI,MAAM;EAAI,SAAS,MAAM;CAAQ,CAAC;AACpE;;;;;;;;;;;AA8BA,SAAgB,sBACd,OACwC;CACxC,OAAO,qBAAqB,KAAK;AACnC;;;;;;;;;ACzIA,IAAa,2BAAb,cAA8C,0BAAgD;CAC5F,cAAc;EACZ,sBAAM,IAAI,IAAI,CAAC;CACjB;CAEA,yBACE,MACA,KACqC;EACrC,IAAI,eAAe,eACjB,OAAO;EAMT,OAAO,qBAJU,UAGf,MAAM,yBAAyB,MAAM,GAAG,CACP,CAAC;CACtC;AACF"}
@@ -13,4 +13,4 @@ var SqliteMigration = class extends Migration {
13
13
  //#endregion
14
14
  export { SqliteMigration as t };
15
15
 
16
- //# sourceMappingURL=sqlite-migration-BBJktVVw.mjs.map
16
+ //# sourceMappingURL=sqlite-migration-CUqgmzQH.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"sqlite-migration-BBJktVVw.mjs","names":["SqlMigration"],"sources":["../src/core/migrations/sqlite-migration.ts"],"sourcesContent":["import { Migration as SqlMigration } from '@prisma-next/family-sql/migration';\nimport type { SqlitePlanTargetDetails } from './planner-target-details';\n\n/**\n * Target-owned base class for SQLite migrations. Fixes the `SqlMigration`\n * generic to `SqlitePlanTargetDetails` and the abstract `targetId` to the\n * SQLite literal, so both user-authored migrations and renderer-generated\n * scaffolds can extend `SqliteMigration` directly without redeclaring\n * target-local identity.\n */\nexport abstract class SqliteMigration extends SqlMigration<SqlitePlanTargetDetails> {\n readonly targetId = 'sqlite' as const;\n}\n"],"mappings":";;;;;;;;;AAUA,IAAsB,kBAAtB,cAA8CA,UAAsC;CAClF,WAAoB;AACtB"}
1
+ {"version":3,"file":"sqlite-migration-CUqgmzQH.mjs","names":["SqlMigration"],"sources":["../src/core/migrations/sqlite-migration.ts"],"sourcesContent":["import { Migration as SqlMigration } from '@prisma-next/family-sql/migration';\nimport type { SqlitePlanTargetDetails } from './planner-target-details';\n\n/**\n * Target-owned base class for SQLite migrations. Fixes the `SqlMigration`\n * generic to `SqlitePlanTargetDetails` and the abstract `targetId` to the\n * SQLite literal, so both user-authored migrations and renderer-generated\n * scaffolds can extend `SqliteMigration` directly without redeclaring\n * target-local identity.\n */\nexport abstract class SqliteMigration extends SqlMigration<SqlitePlanTargetDetails> {\n readonly targetId = 'sqlite' as const;\n}\n"],"mappings":";;;;;;;;;AAUA,IAAsB,kBAAtB,cAA8CA,UAAsC;CAClF,WAAoB;AACtB"}
@@ -1,4 +1,4 @@
1
- import { t as SqlitePlanTargetDetails } from "./planner-target-details-vhvZDWK1.mjs";
1
+ import { t as SqlitePlanTargetDetails } from "./planner-target-details-xR6UfIcz.mjs";
2
2
  import { Migration } from "@prisma-next/family-sql/migration";
3
3
 
4
4
  //#region src/core/migrations/sqlite-migration.d.ts
@@ -14,4 +14,4 @@ declare abstract class SqliteMigration extends Migration<SqlitePlanTargetDetails
14
14
  }
15
15
  //#endregion
16
16
  export { SqliteMigration as t };
17
- //# sourceMappingURL=sqlite-migration-DAb2NEX6.d.mts.map
17
+ //# sourceMappingURL=sqlite-migration-D4XGYzgQ.d.mts.map
@@ -1 +1 @@
1
- {"version":3,"file":"sqlite-migration-DAb2NEX6.d.mts","names":[],"sources":["../src/core/migrations/sqlite-migration.ts"],"mappings":";;;;;;AAUA;;;;;uBAAsB,eAAA,SAAwB,SAAY,CAAC,uBAAA;EAAA,SAChD,QAAA;AAAA"}
1
+ {"version":3,"file":"sqlite-migration-D4XGYzgQ.d.mts","names":[],"sources":["../src/core/migrations/sqlite-migration.ts"],"mappings":";;;;;;AAUA;;;;;uBAAsB,eAAA,SAAwB,SAAY,CAAC,uBAAA;EAAA,SAChD,QAAA;AAAA"}
@@ -1,7 +1,8 @@
1
- import { n as stripOuterParens } from "./default-normalizer-3Fccw7yw.mjs";
2
- import { n as escapeLiteral, r as quoteIdentifier } from "./sql-utils-DhevMgef.mjs";
3
- import { t as buildTargetDetails } from "./planner-target-details-Bm71XPKb.mjs";
1
+ import { n as stripOuterParens } from "./default-normalizer-DuoHj9-O.mjs";
2
+ import { n as escapeLiteral, r as quoteIdentifier } from "./sql-utils-CV8Bdgtc.mjs";
3
+ import { t as buildTargetDetails } from "./planner-target-details-H8z9TFDg.mjs";
4
4
  import { isPostgresEnumStorageEntry } from "@prisma-next/sql-contract/types";
5
+ import { REFERENTIAL_ACTION_SQL } from "@prisma-next/sql-contract/referential-action-sql";
5
6
  //#region src/core/migrations/operations/shared.ts
6
7
  function step(description, sql) {
7
8
  return {
@@ -9,13 +10,6 @@ function step(description, sql) {
9
10
  sql
10
11
  };
11
12
  }
12
- const REFERENTIAL_ACTION_SQL = {
13
- noAction: "NO ACTION",
14
- restrict: "RESTRICT",
15
- cascade: "CASCADE",
16
- setNull: "SET NULL",
17
- setDefault: "SET DEFAULT"
18
- };
19
13
  /**
20
14
  * Renders a single column's inline DDL fragment within a `CREATE TABLE`
21
15
  * statement. Honours the `inlineAutoincrementPrimaryKey` flag — SQLite
@@ -415,4 +409,4 @@ function buildRecreatePostchecks(tableName, issues, spec) {
415
409
  //#endregion
416
410
  export { recreateTable as a, buildColumnDefaultSql as c, renderDefaultLiteral as d, addColumn as f, dropTable as i, buildColumnTypeSql as l, step as m, buildRecreateSummary as n, createIndex as o, dropColumn as p, createTable as r, dropIndex as s, buildRecreatePostchecks as t, isInlineAutoincrementPrimaryKey as u };
417
411
 
418
- //# sourceMappingURL=tables-DGRRJasz.mjs.map
412
+ //# sourceMappingURL=tables-CjB7vXCr.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"tables-CjB7vXCr.mjs","names":[],"sources":["../src/core/migrations/operations/shared.ts","../src/core/migrations/operations/columns.ts","../src/core/migrations/planner-ddl-builders.ts","../src/core/migrations/operations/indexes.ts","../src/core/migrations/operations/tables.ts"],"sourcesContent":["import type { SqlMigrationPlanOperation } from '@prisma-next/family-sql/control';\nimport { REFERENTIAL_ACTION_SQL } from '@prisma-next/sql-contract/referential-action-sql';\nimport type { ReferentialAction } from '@prisma-next/sql-contract/types';\nimport { quoteIdentifier } from '../../sql-utils';\nimport type { SqlitePlanTargetDetails } from '../planner-target-details';\n\nexport type Op = SqlMigrationPlanOperation<SqlitePlanTargetDetails>;\n\nexport function step(description: string, sql: string): { description: string; sql: string } {\n return { description, sql };\n}\n\n/**\n * Flat, fully-resolved column shape consumed by `createTable`, `addColumn`,\n * and `recreateTable`. Codec / `typeRef` / default expansion happens at the\n * call-construction site (in the issue-planner / strategies) so the\n * operation factories deal only in pre-rendered SQL fragments — mirrors the\n * Postgres `ColumnSpec` pattern.\n *\n * - `typeSql` is the column's DDL type token (e.g. `\"INTEGER\"`, `\"TEXT\"`).\n * - `defaultSql` is the full `DEFAULT …` clause (or empty when there is no\n * default and when the column is rendered as `INTEGER PRIMARY KEY\n * AUTOINCREMENT`, since SQLite forbids a default on an autoincrement PK).\n * - `inlineAutoincrementPrimaryKey` directs the renderer to emit\n * `INTEGER PRIMARY KEY AUTOINCREMENT` inline and to skip the table-level\n * primary-key constraint for this column. SQLite-specific: the column\n * becomes an alias for `rowid` only when this exact form is used.\n */\nexport interface SqliteColumnSpec {\n readonly name: string;\n readonly typeSql: string;\n readonly defaultSql: string;\n readonly nullable: boolean;\n readonly inlineAutoincrementPrimaryKey?: boolean;\n}\n\nexport interface SqlitePrimaryKeySpec {\n readonly columns: readonly string[];\n}\n\nexport interface SqliteUniqueSpec {\n readonly columns: readonly string[];\n readonly name?: string;\n}\n\nexport interface SqliteForeignKeySpec {\n readonly columns: readonly string[];\n readonly references: {\n readonly table: string;\n readonly columns: readonly string[];\n };\n readonly name?: string;\n readonly onDelete?: ReferentialAction;\n readonly onUpdate?: ReferentialAction;\n readonly constraint: boolean;\n}\n\n/**\n * Flat shape of a contract table for DDL emission. Used by both\n * `createTable` (additive) and `recreateTable` (widening/destructive).\n */\nexport interface SqliteTableSpec {\n readonly columns: readonly SqliteColumnSpec[];\n readonly primaryKey?: SqlitePrimaryKeySpec;\n readonly uniques?: readonly SqliteUniqueSpec[];\n readonly foreignKeys?: readonly SqliteForeignKeySpec[];\n}\n\n/**\n * Index recreation spec for `recreateTable`. Both declared indexes and\n * FK-backing indexes flatten to the same shape; the planner dedupes by\n * column-set before constructing the call.\n */\nexport interface SqliteIndexSpec {\n readonly name: string;\n readonly columns: readonly string[];\n}\n\n/**\n * Renders a single column's inline DDL fragment within a `CREATE TABLE`\n * statement. Honours the `inlineAutoincrementPrimaryKey` flag — SQLite\n * treats `INTEGER PRIMARY KEY AUTOINCREMENT` as a special form that aliases\n * `rowid`, and the column must not carry a `DEFAULT` or repeat `NOT NULL`.\n */\nexport function renderColumnDefinition(column: SqliteColumnSpec): string {\n const parts: string[] = [quoteIdentifier(column.name), column.typeSql];\n if (column.inlineAutoincrementPrimaryKey) {\n parts.push('PRIMARY KEY AUTOINCREMENT');\n } else {\n if (column.defaultSql) parts.push(column.defaultSql);\n if (!column.nullable) parts.push('NOT NULL');\n }\n return parts.join(' ');\n}\n\n/**\n * Renders an inline FOREIGN KEY constraint clause for a `CREATE TABLE`\n * body. Returns the empty string when `constraint` is false (the FK is\n * tracked at the contract level for index-creation purposes only and must\n * not produce DDL).\n */\nexport function renderForeignKeyClause(fk: SqliteForeignKeySpec): string {\n if (!fk.constraint) return '';\n const name = fk.name ? `CONSTRAINT ${quoteIdentifier(fk.name)} ` : '';\n let sql = `${name}FOREIGN KEY (${fk.columns.map(quoteIdentifier).join(', ')}) REFERENCES ${quoteIdentifier(fk.references.table)} (${fk.references.columns.map(quoteIdentifier).join(', ')})`;\n if (fk.onDelete !== undefined) {\n sql += ` ON DELETE ${REFERENTIAL_ACTION_SQL[fk.onDelete]}`;\n }\n if (fk.onUpdate !== undefined) {\n sql += ` ON UPDATE ${REFERENTIAL_ACTION_SQL[fk.onUpdate]}`;\n }\n return sql;\n}\n","import { escapeLiteral, quoteIdentifier } from '../../sql-utils';\nimport { buildTargetDetails } from '../planner-target-details';\nimport { type Op, type SqliteColumnSpec, step } from './shared';\n\nexport function addColumn(tableName: string, column: SqliteColumnSpec): Op {\n const parts = [\n `ALTER TABLE ${quoteIdentifier(tableName)}`,\n `ADD COLUMN ${quoteIdentifier(column.name)} ${column.typeSql}`,\n column.defaultSql,\n column.nullable ? '' : 'NOT NULL',\n ].filter(Boolean);\n const addSql = parts.join(' ');\n\n return {\n id: `column.${tableName}.${column.name}`,\n label: `Add column ${column.name} on ${tableName}`,\n summary: `Adds column ${column.name} on ${tableName}`,\n operationClass: 'additive',\n target: { id: 'sqlite', details: buildTargetDetails('column', column.name, tableName) },\n precheck: [\n step(\n `ensure column \"${column.name}\" is missing`,\n `SELECT COUNT(*) = 0 FROM pragma_table_info('${escapeLiteral(tableName)}') WHERE name = '${escapeLiteral(column.name)}'`,\n ),\n ],\n execute: [step(`add column \"${column.name}\"`, addSql)],\n postcheck: [\n step(\n `verify column \"${column.name}\" exists`,\n `SELECT COUNT(*) > 0 FROM pragma_table_info('${escapeLiteral(tableName)}') WHERE name = '${escapeLiteral(column.name)}'`,\n ),\n ],\n };\n}\n\nexport function dropColumn(tableName: string, columnName: string): Op {\n return {\n id: `dropColumn.${tableName}.${columnName}`,\n label: `Drop column ${columnName} on ${tableName}`,\n summary: `Drops column ${columnName} on ${tableName} which is not in the contract`,\n operationClass: 'destructive',\n target: { id: 'sqlite', details: buildTargetDetails('column', columnName, tableName) },\n precheck: [\n step(\n `ensure column \"${columnName}\" exists on \"${tableName}\"`,\n `SELECT COUNT(*) > 0 FROM pragma_table_info('${escapeLiteral(tableName)}') WHERE name = '${escapeLiteral(columnName)}'`,\n ),\n ],\n execute: [\n step(\n `drop column \"${columnName}\" from \"${tableName}\"`,\n `ALTER TABLE ${quoteIdentifier(tableName)} DROP COLUMN ${quoteIdentifier(columnName)}`,\n ),\n ],\n postcheck: [\n step(\n `verify column \"${columnName}\" is gone from \"${tableName}\"`,\n `SELECT COUNT(*) = 0 FROM pragma_table_info('${escapeLiteral(tableName)}') WHERE name = '${escapeLiteral(columnName)}'`,\n ),\n ],\n };\n}\n","/**\n * Low-level DDL fragment builders for SQLite migrations.\n *\n * These helpers consume `StorageColumn` (the contract shape, possibly with\n * `typeRef`) and produce string fragments. They are called once per column\n * at the call-construction boundary in `issue-planner.ts` / strategies to\n * build flat `SqliteColumnSpec`s; the operation factories themselves never\n * see `StorageColumn` or `storageTypes`.\n */\n\nimport {\n isPostgresEnumStorageEntry,\n type PostgresEnumStorageEntry,\n type StorageColumn,\n type StorageTable,\n type StorageTypeInstance,\n} from '@prisma-next/sql-contract/types';\nimport { escapeLiteral, quoteIdentifier } from '../sql-utils';\n\ntype SqliteColumnDefault = StorageColumn['default'];\n\nconst SAFE_NATIVE_TYPE_PATTERN = /^[a-zA-Z][a-zA-Z0-9_ ]*$/;\n\nfunction assertSafeNativeType(nativeType: string): void {\n if (!SAFE_NATIVE_TYPE_PATTERN.test(nativeType)) {\n throw new Error(\n `Unsafe native type name in contract: \"${nativeType}\". ` +\n 'Native type names must match /^[a-zA-Z][a-zA-Z0-9_ ]*$/',\n );\n }\n}\n\nfunction assertSafeDefaultExpression(expression: string): void {\n if (expression.includes(';') || /--|\\/\\*|\\bSELECT\\b/i.test(expression)) {\n throw new Error(\n `Unsafe default expression in contract: \"${expression}\". ` +\n 'Default expressions must not contain semicolons, SQL comment tokens, or subqueries.',\n );\n }\n}\n\n/**\n * Renders the column's DDL type token (e.g. `\"INTEGER\"`, `\"TEXT\"`).\n * Resolves `typeRef` against `storageTypes` and validates the resulting\n * native type against a safe-identifier pattern.\n */\nexport function buildColumnTypeSql(\n column: StorageColumn,\n storageTypes: Record<string, StorageTypeInstance | PostgresEnumStorageEntry> = {},\n): string {\n const resolved = resolveColumnTypeMetadata(column, storageTypes);\n assertSafeNativeType(resolved.nativeType);\n return resolved.nativeType.toUpperCase();\n}\n\n/**\n * Renders the column's `DEFAULT …` clause. Returns the empty string when\n * there is no default, and also when the default is `autoincrement()` —\n * SQLite encodes that as `INTEGER PRIMARY KEY AUTOINCREMENT` inline on the\n * column definition, not as a separate DEFAULT.\n */\nexport function buildColumnDefaultSql(columnDefault: SqliteColumnDefault | undefined): string {\n if (!columnDefault) return '';\n\n switch (columnDefault.kind) {\n case 'literal':\n return `DEFAULT ${renderDefaultLiteral(columnDefault.value)}`;\n case 'function': {\n if (columnDefault.expression === 'autoincrement()') return '';\n if (columnDefault.expression === 'now()') return \"DEFAULT (datetime('now'))\";\n assertSafeDefaultExpression(columnDefault.expression);\n return `DEFAULT (${columnDefault.expression})`;\n }\n }\n}\n\nexport function renderDefaultLiteral(value: unknown): string {\n if (value instanceof Date) {\n return `'${escapeLiteral(value.toISOString())}'`;\n }\n if (typeof value === 'string') {\n return `'${escapeLiteral(value)}'`;\n }\n if (typeof value === 'number' || typeof value === 'bigint') {\n return String(value);\n }\n if (typeof value === 'boolean') {\n return value ? '1' : '0';\n }\n if (value === null) {\n return 'NULL';\n }\n return `'${escapeLiteral(JSON.stringify(value))}'`;\n}\n\nexport function buildCreateIndexSql(\n tableName: string,\n indexName: string,\n columns: readonly string[],\n unique = false,\n): string {\n const uniqueKeyword = unique ? 'UNIQUE ' : '';\n return `CREATE ${uniqueKeyword}INDEX ${quoteIdentifier(indexName)} ON ${quoteIdentifier(tableName)} (${columns.map(quoteIdentifier).join(', ')})`;\n}\n\nexport function buildDropIndexSql(indexName: string): string {\n return `DROP INDEX IF EXISTS ${quoteIdentifier(indexName)}`;\n}\n\n/**\n * True when the column is rendered inline as `INTEGER PRIMARY KEY\n * AUTOINCREMENT`. Requires the column's default to be `autoincrement()` and\n * the column to be the sole member of the table's primary key — anything\n * else falls back to a separate PRIMARY KEY constraint with a default\n * AUTOINCREMENT semantics expressed elsewhere.\n */\nexport function isInlineAutoincrementPrimaryKey(table: StorageTable, columnName: string): boolean {\n if (table.primaryKey?.columns.length !== 1) return false;\n if (table.primaryKey.columns[0] !== columnName) return false;\n const column = table.columns[columnName];\n return column?.default?.kind === 'function' && column.default.expression === 'autoincrement()';\n}\n\ntype ResolvedColumnTypeMetadata = Pick<StorageColumn, 'nativeType' | 'codecId' | 'typeParams'>;\n\nfunction resolveColumnTypeMetadata(\n column: StorageColumn,\n storageTypes: Record<string, StorageTypeInstance | PostgresEnumStorageEntry>,\n): ResolvedColumnTypeMetadata {\n if (!column.typeRef) {\n return column;\n }\n const referencedType = storageTypes[column.typeRef];\n if (!referencedType) {\n throw new Error(\n `Storage type \"${column.typeRef}\" referenced by column is not defined in storage.types.`,\n );\n }\n if (isPostgresEnumStorageEntry(referencedType)) {\n return {\n codecId: referencedType.codecId,\n nativeType: referencedType.nativeType,\n typeParams: { values: referencedType.values } as Record<string, unknown>,\n };\n }\n return {\n codecId: referencedType.codecId,\n nativeType: referencedType.nativeType,\n typeParams: referencedType.typeParams,\n };\n}\n","import { escapeLiteral } from '../../sql-utils';\nimport { buildCreateIndexSql, buildDropIndexSql } from '../planner-ddl-builders';\nimport { buildTargetDetails } from '../planner-target-details';\nimport { type Op, step } from './shared';\n\nexport function createIndex(tableName: string, indexName: string, columns: readonly string[]): Op {\n return {\n id: `index.${tableName}.${indexName}`,\n label: `Create index ${indexName} on ${tableName}`,\n summary: `Creates index ${indexName} on ${tableName}`,\n operationClass: 'additive',\n target: { id: 'sqlite', details: buildTargetDetails('index', indexName, tableName) },\n precheck: [\n step(\n `ensure index \"${indexName}\" is missing`,\n `SELECT COUNT(*) = 0 FROM sqlite_master WHERE type = 'index' AND name = '${escapeLiteral(indexName)}'`,\n ),\n ],\n execute: [\n step(`create index \"${indexName}\"`, buildCreateIndexSql(tableName, indexName, columns)),\n ],\n postcheck: [\n step(\n `verify index \"${indexName}\" exists`,\n `SELECT COUNT(*) > 0 FROM sqlite_master WHERE type = 'index' AND name = '${escapeLiteral(indexName)}'`,\n ),\n ],\n };\n}\n\nexport function dropIndex(tableName: string, indexName: string): Op {\n return {\n id: `dropIndex.${tableName}.${indexName}`,\n label: `Drop index ${indexName} on ${tableName}`,\n summary: `Drops index ${indexName} on ${tableName} which is not in the contract`,\n operationClass: 'destructive',\n target: { id: 'sqlite', details: buildTargetDetails('index', indexName, tableName) },\n precheck: [\n step(\n `ensure index \"${indexName}\" exists`,\n `SELECT COUNT(*) > 0 FROM sqlite_master WHERE type = 'index' AND name = '${escapeLiteral(indexName)}'`,\n ),\n ],\n execute: [step(`drop index \"${indexName}\"`, buildDropIndexSql(indexName))],\n postcheck: [\n step(\n `verify index \"${indexName}\" is gone`,\n `SELECT COUNT(*) = 0 FROM sqlite_master WHERE type = 'index' AND name = '${escapeLiteral(indexName)}'`,\n ),\n ],\n };\n}\n","import type { MigrationOperationClass } from '@prisma-next/family-sql/control';\nimport type { SchemaIssue } from '@prisma-next/framework-components/control';\nimport { stripOuterParens } from '../../default-normalizer';\nimport { escapeLiteral, quoteIdentifier } from '../../sql-utils';\nimport { buildCreateIndexSql } from '../planner-ddl-builders';\nimport { buildTargetDetails } from '../planner-target-details';\nimport {\n type Op,\n renderColumnDefinition,\n renderForeignKeyClause,\n type SqliteIndexSpec,\n type SqliteTableSpec,\n step,\n} from './shared';\n\n/**\n * Renders the body of a `CREATE TABLE <name> ( … )` statement from a flat\n * `SqliteTableSpec`. SQLite's `INTEGER PRIMARY KEY AUTOINCREMENT` form is\n * inline on the column; the table-level PRIMARY KEY clause is emitted only\n * when no column carries `inlineAutoincrementPrimaryKey`.\n */\nfunction renderCreateTableSql(tableName: string, spec: SqliteTableSpec): string {\n const columnDefs = spec.columns.map(renderColumnDefinition);\n\n const constraintDefs: string[] = [];\n const hasInlinePk = spec.columns.some((c) => c.inlineAutoincrementPrimaryKey);\n if (spec.primaryKey && !hasInlinePk) {\n constraintDefs.push(`PRIMARY KEY (${spec.primaryKey.columns.map(quoteIdentifier).join(', ')})`);\n }\n\n for (const u of spec.uniques ?? []) {\n const name = u.name ? `CONSTRAINT ${quoteIdentifier(u.name)} ` : '';\n constraintDefs.push(`${name}UNIQUE (${u.columns.map(quoteIdentifier).join(', ')})`);\n }\n\n for (const fk of spec.foreignKeys ?? []) {\n const clause = renderForeignKeyClause(fk);\n if (clause) constraintDefs.push(clause);\n }\n\n const allDefs = [...columnDefs, ...constraintDefs];\n return `CREATE TABLE ${quoteIdentifier(tableName)} (\\n ${allDefs.join(',\\n ')}\\n)`;\n}\n\nexport function createTable(tableName: string, spec: SqliteTableSpec): Op {\n return {\n id: `table.${tableName}`,\n label: `Create table ${tableName}`,\n summary: `Creates table ${tableName} with required columns`,\n operationClass: 'additive',\n target: { id: 'sqlite', details: buildTargetDetails('table', tableName) },\n precheck: [\n step(\n `ensure table \"${tableName}\" does not exist`,\n `SELECT COUNT(*) = 0 FROM sqlite_master WHERE type = 'table' AND name = '${escapeLiteral(tableName)}'`,\n ),\n ],\n execute: [step(`create table \"${tableName}\"`, renderCreateTableSql(tableName, spec))],\n postcheck: [\n step(\n `verify table \"${tableName}\" exists`,\n `SELECT COUNT(*) > 0 FROM sqlite_master WHERE type = 'table' AND name = '${escapeLiteral(tableName)}'`,\n ),\n ],\n };\n}\n\nexport function dropTable(tableName: string): Op {\n return {\n id: `dropTable.${tableName}`,\n label: `Drop table ${tableName}`,\n summary: `Drops table ${tableName} which is not in the contract`,\n operationClass: 'destructive',\n target: { id: 'sqlite', details: buildTargetDetails('table', tableName) },\n precheck: [\n step(\n `ensure table \"${tableName}\" exists`,\n `SELECT COUNT(*) > 0 FROM sqlite_master WHERE type = 'table' AND name = '${escapeLiteral(tableName)}'`,\n ),\n ],\n execute: [step(`drop table \"${tableName}\"`, `DROP TABLE ${quoteIdentifier(tableName)}`)],\n postcheck: [\n step(\n `verify table \"${tableName}\" is gone`,\n `SELECT COUNT(*) = 0 FROM sqlite_master WHERE type = 'table' AND name = '${escapeLiteral(tableName)}'`,\n ),\n ],\n };\n}\n\nexport interface RecreateTableArgs {\n readonly tableName: string;\n /** New (post-recreate) shape of the table. Same flat spec as `createTable`. */\n readonly contractTable: SqliteTableSpec;\n /**\n * Names of columns that exist in the live (pre-recreate) schema. Used to\n * compute the `INSERT INTO temp ... SELECT ... FROM old` column list — only\n * shared columns are copied, so dropped columns are left behind and added\n * columns come from defaults.\n */\n readonly schemaColumnNames: readonly string[];\n /**\n * Indexes (declared + FK-backing, deduped by column-set) to recreate after\n * the table has been replaced. The planner pre-merges these.\n */\n readonly indexes: readonly SqliteIndexSpec[];\n /** Human-readable summary of the change, built by the planner from issues. */\n readonly summary: string;\n /**\n * Per-issue postcheck steps appended after the structural postchecks. The\n * planner pre-builds these via `buildRecreatePostchecks` so the call IR\n * carries flat, serializable data only — no `SchemaIssue` references.\n */\n readonly postchecks: readonly { readonly description: string; readonly sql: string }[];\n readonly operationClass: MigrationOperationClass;\n}\n\nexport function recreateTable(args: RecreateTableArgs): Op {\n const {\n tableName,\n contractTable,\n schemaColumnNames,\n indexes,\n summary,\n postchecks,\n operationClass,\n } = args;\n const tempName = `_prisma_new_${tableName}`;\n const liveSet = new Set(schemaColumnNames);\n const sharedColumns = contractTable.columns.filter((c) => liveSet.has(c.name)).map((c) => c.name);\n const columnList = sharedColumns.map(quoteIdentifier).join(', ');\n\n const indexStatements = indexes.map((idx) => ({\n description: `recreate index \"${idx.name}\" on \"${tableName}\"`,\n sql: buildCreateIndexSql(tableName, idx.name, idx.columns),\n }));\n\n // If the contract retains no columns from the live table, an `INSERT INTO\n // tmp () SELECT FROM old` is invalid SQL — and would also be a no-op since\n // there's nothing to copy. Skip the copy step in that case; the new\n // (empty) table replaces the old one directly.\n const copyStep =\n sharedColumns.length > 0\n ? [\n step(\n `copy data from \"${tableName}\" to \"${tempName}\"`,\n `INSERT INTO ${quoteIdentifier(tempName)} (${columnList}) SELECT ${columnList} FROM ${quoteIdentifier(tableName)}`,\n ),\n ]\n : [];\n\n return {\n id: `recreateTable.${tableName}`,\n label: `Recreate table ${tableName}`,\n summary,\n operationClass,\n target: { id: 'sqlite', details: buildTargetDetails('table', tableName) },\n precheck: [\n step(\n `ensure table \"${tableName}\" exists`,\n `SELECT COUNT(*) > 0 FROM sqlite_master WHERE type = 'table' AND name = '${escapeLiteral(tableName)}'`,\n ),\n step(\n `ensure temp table \"${tempName}\" does not exist`,\n `SELECT COUNT(*) = 0 FROM sqlite_master WHERE type = 'table' AND name = '${escapeLiteral(tempName)}'`,\n ),\n ],\n execute: [\n step(\n `create new table \"${tempName}\" with desired schema`,\n renderCreateTableSql(tempName, contractTable),\n ),\n ...copyStep,\n step(`drop old table \"${tableName}\"`, `DROP TABLE ${quoteIdentifier(tableName)}`),\n step(\n `rename \"${tempName}\" to \"${tableName}\"`,\n `ALTER TABLE ${quoteIdentifier(tempName)} RENAME TO ${quoteIdentifier(tableName)}`,\n ),\n ...indexStatements,\n ],\n postcheck: [\n step(\n `verify table \"${tableName}\" exists`,\n `SELECT COUNT(*) > 0 FROM sqlite_master WHERE type = 'table' AND name = '${escapeLiteral(tableName)}'`,\n ),\n step(\n `verify temp table \"${tempName}\" is gone`,\n `SELECT COUNT(*) = 0 FROM sqlite_master WHERE type = 'table' AND name = '${escapeLiteral(tempName)}'`,\n ),\n ...postchecks,\n ],\n };\n}\n\n/**\n * Build a one-line summary of a recreate-table operation from the schema\n * issues that triggered it. Lives next to `recreateTable` so the planner\n * (which has the issues) can produce the same description the factory\n * used to build inline. Keeping the formatting target-side keeps\n * `RecreateTableCall` issue-free at the IR layer.\n */\nexport function buildRecreateSummary(tableName: string, issues: readonly SchemaIssue[]): string {\n const messages = issues.map((i) => i.message).join('; ');\n return `Recreates table ${tableName} to apply schema changes: ${messages}`;\n}\n\nconst COLUMN_LEVEL_ISSUE_KINDS = new Set<SchemaIssue['kind']>([\n 'nullability_mismatch',\n 'default_mismatch',\n 'default_missing',\n 'extra_default',\n 'type_mismatch',\n]);\n\nconst PK_ISSUE_KINDS = new Set<SchemaIssue['kind']>(['primary_key_mismatch', 'extra_primary_key']);\n\nconst UNIQUE_ISSUE_KINDS = new Set<SchemaIssue['kind']>([\n 'unique_constraint_mismatch',\n 'extra_unique_constraint',\n]);\n\nconst FK_ISSUE_KINDS = new Set<SchemaIssue['kind']>(['foreign_key_mismatch', 'extra_foreign_key']);\n\n/**\n * Returns the columns the contract expects as the table's primary key. Picks\n * up SQLite's inline `INTEGER PRIMARY KEY AUTOINCREMENT` form when no\n * explicit `primaryKey` clause is set on the spec.\n */\nfunction expectedPrimaryKeyColumns(spec: SqliteTableSpec): readonly string[] {\n if (spec.primaryKey) return spec.primaryKey.columns;\n const inlinePk = spec.columns.find((c) => c.inlineAutoincrementPrimaryKey);\n return inlinePk ? [inlinePk.name] : [];\n}\n\nfunction quoteSqlList(values: readonly string[]): string {\n return values.map((v) => `'${escapeLiteral(v)}'`).join(', ');\n}\n\n/**\n * Per-issue postchecks verifying the recreated table's shape against the\n * contract spec. Column-level issues (`nullability_mismatch`,\n * `default_mismatch`, …) emit one targeted check each; constraint-level\n * issues (`primary_key_mismatch`, `unique_constraint_mismatch`,\n * `foreign_key_mismatch`, plus their `extra_*` siblings) emit one\n * `pragma_*`-driven check per declared constraint in the contract spec, so\n * a recreated table with the right columns but the wrong PK / unique / FK\n * shape fails the postcheck instead of passing silently. Exported so the\n * planner can pre-build the list at construction time and\n * `RecreateTableCall` doesn't have to carry `SchemaIssue` objects through\n * to render time.\n */\nexport function buildRecreatePostchecks(\n tableName: string,\n issues: readonly SchemaIssue[],\n spec: SqliteTableSpec,\n): Array<{ description: string; sql: string }> {\n const checks: Array<{ description: string; sql: string }> = [];\n const t = escapeLiteral(tableName);\n const byName = new Map(spec.columns.map((c) => [c.name, c]));\n\n for (const issue of issues) {\n if (issue.kind === 'enum_values_changed') continue;\n if (!COLUMN_LEVEL_ISSUE_KINDS.has(issue.kind)) continue;\n if (!issue.column) continue;\n const c = escapeLiteral(issue.column);\n if (issue.kind === 'nullability_mismatch') {\n // `expected` carries the contract's nullable flag as a string. We only\n // emit a postcheck when the value is recognized — anything else\n // (case-folded, numeric coding, etc.) is left to the structural\n // verifier so a typo here can't silently invert the meaning.\n let wantNotNull: boolean | undefined;\n if (issue.expected === 'false') wantNotNull = true;\n else if (issue.expected === 'true') wantNotNull = false;\n if (wantNotNull !== undefined) {\n checks.push({\n description: `verify \"${issue.column}\" nullability on \"${tableName}\"`,\n sql: `SELECT COUNT(*) > 0 FROM pragma_table_info('${t}') WHERE name = '${c}' AND \"notnull\" = ${wantNotNull ? 1 : 0}`,\n });\n }\n }\n if (issue.kind === 'default_mismatch' || issue.kind === 'default_missing') {\n const colSpec = byName.get(issue.column);\n const expectedRaw = colSpec?.defaultSql.startsWith('DEFAULT ')\n ? // SQLite's pragma_table_info.dflt_value strips outer parens for\n // expression defaults (per the SQLite docs), so `(datetime('now'))`\n // is stored as `datetime('now')`. Strip them here so the postcheck\n // matches.\n stripOuterParens(colSpec.defaultSql.slice('DEFAULT '.length))\n : null;\n if (expectedRaw) {\n checks.push({\n description: `verify \"${issue.column}\" default on \"${tableName}\"`,\n sql: `SELECT COUNT(*) > 0 FROM pragma_table_info('${t}') WHERE name = '${c}' AND dflt_value = '${escapeLiteral(expectedRaw)}'`,\n });\n }\n }\n if (issue.kind === 'type_mismatch') {\n const colSpec = byName.get(issue.column);\n if (colSpec) {\n checks.push({\n description: `verify \"${issue.column}\" type on \"${tableName}\"`,\n sql: `SELECT COUNT(*) > 0 FROM pragma_table_info('${t}') WHERE name = '${c}' AND LOWER(type) = '${escapeLiteral(colSpec.typeSql.toLowerCase())}'`,\n });\n }\n }\n if (issue.kind === 'extra_default') {\n checks.push({\n description: `verify \"${issue.column}\" has no default on \"${tableName}\"`,\n sql: `SELECT COUNT(*) > 0 FROM pragma_table_info('${t}') WHERE name = '${c}' AND dflt_value IS NULL`,\n });\n }\n }\n\n // Constraint-level issues — emit one postcheck per declared constraint in\n // the contract spec when *any* issue of that kind fires, since recreate\n // rebuilds the entire table at once.\n const hasPkIssue = issues.some((i) => PK_ISSUE_KINDS.has(i.kind));\n const hasUniqueIssue = issues.some((i) => UNIQUE_ISSUE_KINDS.has(i.kind));\n const hasFkIssue = issues.some((i) => FK_ISSUE_KINDS.has(i.kind));\n\n if (hasPkIssue) {\n const pkColumns = expectedPrimaryKeyColumns(spec);\n // Verify pragma_table_info reports exactly these columns as PK members\n // (count + named membership); zero columns expected ⇒ no PK at all.\n const colCount = pkColumns.length;\n if (colCount === 0) {\n checks.push({\n description: `verify \"${tableName}\" has no primary key`,\n sql: `SELECT (SELECT COUNT(*) FROM pragma_table_info('${t}') WHERE pk > 0) = 0`,\n });\n } else {\n checks.push({\n description: `verify primary key on \"${tableName}\"`,\n sql:\n `SELECT (SELECT COUNT(*) FROM pragma_table_info('${t}') WHERE pk > 0) = ${colCount}` +\n ` AND (SELECT COUNT(*) FROM pragma_table_info('${t}') WHERE pk > 0 AND name IN (${quoteSqlList(pkColumns)})) = ${colCount}`,\n });\n }\n }\n\n if (hasUniqueIssue) {\n for (const u of spec.uniques ?? []) {\n const colCount = u.columns.length;\n const description = u.name\n ? `verify unique constraint \"${u.name}\" on \"${tableName}\"`\n : `verify unique constraint (${u.columns.join(', ')}) on \"${tableName}\"`;\n // Match any unique index whose covered columns are exactly the expected\n // set. Order is intentionally not checked — SQLite's unique-index\n // identity is column-set, not column-sequence.\n checks.push({\n description,\n sql:\n `SELECT EXISTS (SELECT 1 FROM pragma_index_list('${t}') l` +\n ` WHERE l.\"unique\" = 1` +\n ` AND (SELECT COUNT(*) FROM pragma_index_info(l.name)) = ${colCount}` +\n ` AND (SELECT COUNT(*) FROM pragma_index_info(l.name) WHERE name IN (${quoteSqlList(u.columns)})) = ${colCount})`,\n });\n }\n }\n\n if (hasFkIssue) {\n for (const fk of spec.foreignKeys ?? []) {\n const refTable = escapeLiteral(fk.references.table);\n const colCount = fk.columns.length;\n // Build a `SUM(CASE WHEN (\"from\",\"to\") IN ((…)) …)` so the check works\n // for both single- and multi-column FKs without depending on FK row\n // ordering inside `pragma_foreign_key_list`.\n const tuples = fk.columns\n .map((from, i) => {\n const to = fk.references.columns[i] ?? from;\n return `('${escapeLiteral(from)}', '${escapeLiteral(to)}')`;\n })\n .join(', ');\n const description = `verify foreign key (${fk.columns.join(', ')}) → ${fk.references.table}(${fk.references.columns.join(', ')}) on \"${tableName}\"`;\n checks.push({\n description,\n sql:\n `SELECT EXISTS (SELECT 1 FROM pragma_foreign_key_list('${t}') f` +\n ` WHERE f.\"table\" = '${refTable}'` +\n ' GROUP BY f.id' +\n ` HAVING COUNT(*) = ${colCount}` +\n ` AND SUM(CASE WHEN (f.\"from\", f.\"to\") IN (${tuples}) THEN 1 ELSE 0 END) = ${colCount})`,\n });\n }\n }\n\n return checks;\n}\n"],"mappings":";;;;;;AAQA,SAAgB,KAAK,aAAqB,KAAmD;CAC3F,OAAO;EAAE;EAAa;CAAI;AAC5B;;;;;;;AA0EA,SAAgB,uBAAuB,QAAkC;CACvE,MAAM,QAAkB,CAAC,gBAAgB,OAAO,IAAI,GAAG,OAAO,OAAO;CACrE,IAAI,OAAO,+BACT,MAAM,KAAK,2BAA2B;MACjC;EACL,IAAI,OAAO,YAAY,MAAM,KAAK,OAAO,UAAU;EACnD,IAAI,CAAC,OAAO,UAAU,MAAM,KAAK,UAAU;CAC7C;CACA,OAAO,MAAM,KAAK,GAAG;AACvB;;;;;;;AAQA,SAAgB,uBAAuB,IAAkC;CACvE,IAAI,CAAC,GAAG,YAAY,OAAO;CAE3B,IAAI,MAAM,GADG,GAAG,OAAO,cAAc,gBAAgB,GAAG,IAAI,EAAE,KAAK,GACjD,eAAe,GAAG,QAAQ,IAAI,eAAe,CAAC,CAAC,KAAK,IAAI,EAAE,eAAe,gBAAgB,GAAG,WAAW,KAAK,EAAE,IAAI,GAAG,WAAW,QAAQ,IAAI,eAAe,CAAC,CAAC,KAAK,IAAI,EAAE;CAC1L,IAAI,GAAG,aAAa,KAAA,GAClB,OAAO,cAAc,uBAAuB,GAAG;CAEjD,IAAI,GAAG,aAAa,KAAA,GAClB,OAAO,cAAc,uBAAuB,GAAG;CAEjD,OAAO;AACT;;;AC5GA,SAAgB,UAAU,WAAmB,QAA8B;CAOzE,MAAM,SANQ;EACZ,eAAe,gBAAgB,SAAS;EACxC,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WAAW,EAAE,QAAQ;EAC3B,MAAM,cAAc,EAAE,OAClB,6BAA6B,EAAE,KAAK,QAAQ,UAAU,KACtD,6BAA6B,EAAE,QAAQ,KAAK,IAAI,EAAE,QAAQ,UAAU;EAIxE,OAAO,KAAK;GACV;GACA,KACE,mDAAmD,EAAE,mFAEM,SAAA,sEACY,aAAa,EAAE,OAAO,EAAE,OAAO,SAAS;EACnH,CAAC;CACH;CAGF,IAAI,YACF,KAAK,MAAM,MAAM,KAAK,eAAe,CAAC,GAAG;EACvC,MAAM,WAAW,cAAc,GAAG,WAAW,KAAK;EAClD,MAAM,WAAW,GAAG,QAAQ;EAI5B,MAAM,SAAS,GAAG,QACf,KAAK,MAAM,MAAM;GAChB,MAAM,KAAK,GAAG,WAAW,QAAQ,MAAM;GACvC,OAAO,KAAK,cAAc,IAAI,EAAE,MAAM,cAAc,EAAE,EAAE;EAC1D,CAAC,CAAC,CACD,KAAK,IAAI;EACZ,MAAM,cAAc,uBAAuB,GAAG,QAAQ,KAAK,IAAI,EAAE,MAAM,GAAG,WAAW,MAAM,GAAG,GAAG,WAAW,QAAQ,KAAK,IAAI,EAAE,QAAQ,UAAU;EACjJ,OAAO,KAAK;GACV;GACA,KACE,yDAAyD,EAAE,0BACpC,SAAS,oCAEV,SAAA,4CACuB,OAAO,yBAAyB,SAAS;EAC1F,CAAC;CACH;CAGF,OAAO;AACT"}
package/package.json CHANGED
@@ -1,33 +1,33 @@
1
1
  {
2
2
  "name": "@prisma-next/target-sqlite",
3
- "version": "0.12.0",
3
+ "version": "0.13.0-dev.2",
4
4
  "license": "Apache-2.0",
5
5
  "type": "module",
6
6
  "sideEffects": false,
7
7
  "dependencies": {
8
- "@prisma-next/cli": "0.12.0",
9
- "@prisma-next/contract": "0.12.0",
10
- "@prisma-next/errors": "0.12.0",
11
- "@prisma-next/family-sql": "0.12.0",
12
- "@prisma-next/framework-components": "0.12.0",
13
- "@prisma-next/migration-tools": "0.12.0",
14
- "@prisma-next/sql-contract": "0.12.0",
15
- "@prisma-next/sql-errors": "0.12.0",
16
- "@prisma-next/sql-relational-core": "0.12.0",
17
- "@prisma-next/sql-runtime": "0.12.0",
18
- "@prisma-next/sql-schema-ir": "0.12.0",
19
- "@prisma-next/ts-render": "0.12.0",
20
- "@prisma-next/utils": "0.12.0",
8
+ "@prisma-next/cli": "0.13.0-dev.2",
9
+ "@prisma-next/contract": "0.13.0-dev.2",
10
+ "@prisma-next/errors": "0.13.0-dev.2",
11
+ "@prisma-next/family-sql": "0.13.0-dev.2",
12
+ "@prisma-next/framework-components": "0.13.0-dev.2",
13
+ "@prisma-next/migration-tools": "0.13.0-dev.2",
14
+ "@prisma-next/sql-contract": "0.13.0-dev.2",
15
+ "@prisma-next/sql-errors": "0.13.0-dev.2",
16
+ "@prisma-next/sql-relational-core": "0.13.0-dev.2",
17
+ "@prisma-next/sql-runtime": "0.13.0-dev.2",
18
+ "@prisma-next/sql-schema-ir": "0.13.0-dev.2",
19
+ "@prisma-next/ts-render": "0.13.0-dev.2",
20
+ "@prisma-next/utils": "0.13.0-dev.2",
21
21
  "@standard-schema/spec": "1.1.0"
22
22
  },
23
23
  "devDependencies": {
24
- "@prisma-next/driver-sqlite": "0.12.0",
25
- "@prisma-next/test-utils": "0.12.0",
26
- "@prisma-next/tsconfig": "0.12.0",
27
- "@prisma-next/tsdown": "0.12.0",
28
- "tsdown": "0.22.0",
24
+ "@prisma-next/driver-sqlite": "0.13.0-dev.2",
25
+ "@prisma-next/test-utils": "0.13.0-dev.2",
26
+ "@prisma-next/tsconfig": "0.13.0-dev.2",
27
+ "@prisma-next/tsdown": "0.13.0-dev.2",
28
+ "tsdown": "0.22.1",
29
29
  "typescript": "5.9.3",
30
- "vitest": "4.1.6"
30
+ "vitest": "4.1.8"
31
31
  },
32
32
  "peerDependencies": {
33
33
  "typescript": ">=5.9"
@@ -45,7 +45,10 @@
45
45
  "./codec-ids": "./dist/codec-ids.mjs",
46
46
  "./codec-types": "./dist/codec-types.mjs",
47
47
  "./codecs": "./dist/codecs.mjs",
48
+ "./contract-free": "./dist/contract-free.mjs",
48
49
  "./control": "./dist/control.mjs",
50
+ "./control-tables": "./dist/control-tables.mjs",
51
+ "./ddl": "./dist/ddl.mjs",
49
52
  "./default-normalizer": "./dist/default-normalizer.mjs",
50
53
  "./migration": "./dist/migration.mjs",
51
54
  "./native-type-normalizer": "./dist/native-type-normalizer.mjs",
@@ -57,7 +60,6 @@
57
60
  "./render-ops": "./dist/render-ops.mjs",
58
61
  "./runtime": "./dist/runtime.mjs",
59
62
  "./sql-utils": "./dist/sql-utils.mjs",
60
- "./statement-builders": "./dist/statement-builders.mjs",
61
63
  "./package.json": "./package.json"
62
64
  },
63
65
  "engines": {
@@ -0,0 +1,44 @@
1
+ import { TableSource } from '@prisma-next/sql-relational-core/ast';
2
+ import {
3
+ type ColumnDescriptor,
4
+ type ColumnSchema,
5
+ type TableHandle,
6
+ table,
7
+ } from '@prisma-next/sql-relational-core/contract-free';
8
+ import {
9
+ SQLITE_DATETIME_CODEC_ID,
10
+ SQLITE_INTEGER_CODEC_ID,
11
+ SQLITE_JSON_CODEC_ID,
12
+ SQLITE_TEXT_CODEC_ID,
13
+ } from '../core/codec-ids';
14
+
15
+ type ColOpts = { readonly nullable?: boolean };
16
+
17
+ const desc = (codecId: string, opts?: ColOpts): ColumnDescriptor => ({
18
+ codecId,
19
+ nullable: opts?.nullable ?? false,
20
+ });
21
+
22
+ export const text = (opts?: ColOpts): ColumnDescriptor => desc(SQLITE_TEXT_CODEC_ID, opts);
23
+ export const integer = (opts?: ColOpts): ColumnDescriptor => desc(SQLITE_INTEGER_CODEC_ID, opts);
24
+ export const jsonText = (opts?: ColOpts): ColumnDescriptor => desc(SQLITE_JSON_CODEC_ID, opts);
25
+ export const datetime = (opts?: ColOpts): ColumnDescriptor => desc(SQLITE_DATETIME_CODEC_ID, opts);
26
+
27
+ /**
28
+ * Declare a SQLite control-plane table with a typed column schema. SQLite tables
29
+ * are addressed by a flat name (no schema prefix).
30
+ *
31
+ * ```ts
32
+ * const marker = sqliteTable('_prisma_marker', {
33
+ * space: text(),
34
+ * core_hash: text(),
35
+ * updated_at: datetime(),
36
+ * });
37
+ * ```
38
+ */
39
+ export function sqliteTable<Schema extends ColumnSchema>(
40
+ name: string,
41
+ columns: Schema,
42
+ ): TableHandle<Schema> {
43
+ return table(TableSource.named(name), columns);
44
+ }
@@ -0,0 +1,54 @@
1
+ import { APP_SPACE_ID } from '@prisma-next/framework-components/control';
2
+ import type { DdlNode } from '@prisma-next/sql-relational-core/ast';
3
+ import { col, fn, lit } from '@prisma-next/sql-relational-core/contract-free';
4
+ import { createTable } from './ddl';
5
+
6
+ const markerColumns = [
7
+ col('space', 'TEXT', { notNull: true, primaryKey: true, default: lit(APP_SPACE_ID) }),
8
+ col('core_hash', 'TEXT', { notNull: true }),
9
+ col('profile_hash', 'TEXT', { notNull: true }),
10
+ col('contract_json', 'TEXT'),
11
+ col('canonical_version', 'INTEGER'),
12
+ col('updated_at', 'TEXT', { notNull: true, default: fn("datetime('now')") }),
13
+ col('app_tag', 'TEXT'),
14
+ col('meta', 'TEXT', { notNull: true, default: lit('{}') }),
15
+ col('invariants', 'TEXT', { notNull: true, default: lit('[]') }),
16
+ ] as const;
17
+
18
+ const ledgerColumns = [
19
+ col('id', 'INTEGER PRIMARY KEY AUTOINCREMENT'),
20
+ col('created_at', 'TEXT', {
21
+ notNull: true,
22
+ default: fn("strftime('%Y-%m-%dT%H:%M:%fZ','now')"),
23
+ }),
24
+ col('space', 'TEXT', { notNull: true }),
25
+ col('migration_name', 'TEXT', { notNull: true }),
26
+ col('migration_hash', 'TEXT', { notNull: true }),
27
+ col('origin_core_hash', 'TEXT'),
28
+ col('origin_profile_hash', 'TEXT'),
29
+ col('destination_core_hash', 'TEXT', { notNull: true }),
30
+ col('destination_profile_hash', 'TEXT'),
31
+ col('contract_json_before', 'TEXT'),
32
+ col('contract_json_after', 'TEXT'),
33
+ col('operations', 'TEXT', { notNull: true }),
34
+ ] as const;
35
+
36
+ const markerTable = createTable({
37
+ table: '_prisma_marker',
38
+ ifNotExists: true,
39
+ columns: markerColumns,
40
+ });
41
+
42
+ const ledgerTable = createTable({
43
+ table: '_prisma_ledger',
44
+ ifNotExists: true,
45
+ columns: ledgerColumns,
46
+ });
47
+
48
+ export function buildSignMarkerBootstrapQueries(): readonly DdlNode[] {
49
+ return [markerTable];
50
+ }
51
+
52
+ export function buildControlTableBootstrapQueries(): readonly DdlNode[] {
53
+ return [markerTable, ledgerTable];
54
+ }
@@ -0,0 +1,26 @@
1
+ import type { DdlColumn, DdlTableConstraint } from '@prisma-next/sql-relational-core/ast';
2
+ import { SqliteCreateTable } from '../core/ddl/nodes';
3
+
4
+ /**
5
+ * Build a SQLite `CREATE TABLE` query node.
6
+ *
7
+ * Pass `constraints` for table-level composite primary keys, foreign keys, and
8
+ * unique constraints — use the {@link PrimaryKeyConstraint}, {@link ForeignKeyConstraint},
9
+ * and {@link UniqueConstraint} classes from `@prisma-next/sql-relational-core/ast`.
10
+ *
11
+ * Precondition: identifiers (`table`, column names/types) are emitted to SQL
12
+ * verbatim — they are not quoted or escaped, so callers must pass pre-trusted
13
+ * values (e.g. fixed control-plane identifiers). String-literal default values,
14
+ * by contrast, are single-quote-escaped (embedded `'` doubled) by the renderer.
15
+ * Identifier quoting for untrusted identifiers is added when the migration
16
+ * planner adopts this lowering path.
17
+ */
18
+ export function createTable(options: {
19
+ readonly table: string;
20
+ readonly schema?: string;
21
+ readonly ifNotExists?: boolean;
22
+ readonly columns: readonly DdlColumn[];
23
+ readonly constraints?: readonly DdlTableConstraint[];
24
+ }): SqliteCreateTable {
25
+ return new SqliteCreateTable(options);
26
+ }
@@ -2,7 +2,7 @@ import { temporalAuthoringPresets } from '@prisma-next/family-sql/control';
2
2
  import type { AuthoringFieldNamespace } from '@prisma-next/framework-components/authoring';
3
3
 
4
4
  export const sqliteAuthoringFieldPresets = {
5
- temporal: temporalAuthoringPresets({
5
+ temporal: /* @__PURE__ */ temporalAuthoringPresets({
6
6
  codecId: 'sqlite/datetime@1',
7
7
  nativeType: 'text',
8
8
  }),
@@ -0,0 +1,11 @@
1
+ export const MARKER_TABLE_NAME = '_prisma_marker';
2
+ export const LEDGER_TABLE_NAME = '_prisma_ledger';
3
+
4
+ /**
5
+ * Control tables the runner creates/manages. The planner must not drop these
6
+ * when reconciling "extra" tables against the contract.
7
+ */
8
+ export const CONTROL_TABLE_NAMES: ReadonlySet<string> = new Set([
9
+ MARKER_TABLE_NAME,
10
+ LEDGER_TABLE_NAME,
11
+ ]);