@lunora/d1 1.0.0-alpha.234 → 1.0.0-alpha.236

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE.md CHANGED
@@ -1,108 +1,205 @@
1
- # Functional Source License, Version 1.1, Apache 2.0 Future License
2
1
 
3
- ## Abbreviation
4
-
5
- FSL-1.1-Apache-2.0
6
-
7
- ## Notice
8
-
9
- Copyright 2026 anolilab and contributors
10
-
11
- ## Terms and Conditions
12
-
13
- ### Licensor ("We")
14
-
15
- The party offering the Software under these Terms and Conditions.
16
-
17
- ### The Software
18
-
19
- The "Software" is each version of the software that we make available under
20
- these Terms and Conditions, as indicated by our inclusion of these Terms and
21
- Conditions with the Software.
22
-
23
- ### License Grant
24
-
25
- Subject to your compliance with this License Grant and the Patents,
26
- Redistribution and Trademark clauses below, we hereby grant you the right to
27
- use, copy, modify, create derivative works, publicly perform, publicly display
28
- and redistribute the Software for any Permitted Purpose identified below.
29
-
30
- ### Permitted Purpose
31
-
32
- A Permitted Purpose is any purpose other than a Competing Use. A Competing Use
33
- means making the Software available to others in a commercial product or service
34
- that:
35
-
36
- 1. substitutes for the Software;
37
-
38
- 2. substitutes for any other product or service we offer using the Software that
39
- exists as of the date we make the Software available; or
40
-
41
- 3. offers the same or substantially similar functionality as the Software.
42
-
43
- Permitted Purposes specifically include using the Software:
44
-
45
- 1. for your internal use and access;
46
-
47
- 2. for non-commercial education;
48
-
49
- 3. for non-commercial research; and
50
-
51
- 4. in connection with professional services that you provide to a licensee using
52
- the Software in accordance with these Terms and Conditions.
53
-
54
- ### Patents
55
-
56
- To the extent your use for a Permitted Purpose would necessarily infringe our
57
- patents, the license grant above includes a license under our patents. If you
58
- make a claim against any party that the Software infringes or contributes to the
59
- infringement of any patent, then your patent license to the Software ends
60
- immediately.
61
-
62
- ### Redistribution
63
-
64
- The Terms and Conditions apply to all copies, modifications and derivatives of
65
- the Software.
66
-
67
- If you redistribute any copies, modifications or derivatives of the Software,
68
- you must include a copy of or a link to these Terms and Conditions and not
69
- remove any copyright notices provided in or with the Software.
70
-
71
- ### Disclaimer
72
-
73
- THE SOFTWARE IS PROVIDED "AS IS" AND WITHOUT WARRANTIES OF ANY KIND, EXPRESS OR
74
- IMPLIED, INCLUDING WITHOUT LIMITATION WARRANTIES OF FITNESS FOR A PARTICULAR
75
- PURPOSE, MERCHANTABILITY, TITLE OR NON-INFRINGEMENT.
76
-
77
- IN NO EVENT WILL WE HAVE ANY LIABILITY TO YOU ARISING OUT OF OR RELATED TO THE
78
- SOFTWARE, INCLUDING INDIRECT, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES, EVEN
79
- IF WE HAVE BEEN INFORMED OF THEIR POSSIBILITY IN ADVANCE.
80
-
81
- ### Trademarks
82
-
83
- Except for displaying the License Details and identifying us as the origin of
84
- the Software, you have no right under these Terms and Conditions to use our
85
- trademarks, trade names, service marks or product names.
86
-
87
- ## Grant of Future License
88
-
89
- We hereby irrevocably grant you an additional license to use the Software under
90
- the Apache License, Version 2.0 that is effective on the second anniversary of
91
- the date we make the Software available. On or after that date, you may use the
92
- Software under the Apache License, Version 2.0, in which case the following will
93
- apply:
94
-
95
- Licensed under the Apache License, Version 2.0 (the "License"); you may not use
96
- this file except in compliance with the License.
97
-
98
- You may obtain a copy of the License at
99
-
100
- http://www.apache.org/licenses/LICENSE-2.0
101
-
102
- Unless required by applicable law or agreed to in writing, software distributed
103
- under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
104
- CONDITIONS OF ANY KIND, either express or implied. See the License for the
105
- specific language governing permissions and limitations under the License.
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
106
203
 
107
204
  <!-- DEPENDENCIES -->
108
205
  <!-- /DEPENDENCIES -->
package/README.md CHANGED
@@ -15,7 +15,7 @@
15
15
  <div align="center">
16
16
 
17
17
  [![typescript-image][typescript-badge]][typescript-url]
18
- [![FSL-1.1-Apache-2.0 licence][license-badge]][license]
18
+ [![Apache-2.0 licence][license-badge]][license]
19
19
  [![npm version][npm-version-badge]][npm-version]
20
20
  [![npm downloads][npm-downloads-badge]][npm-downloads]
21
21
  [![PRs Welcome][prs-welcome-badge]][prs-welcome]
@@ -107,11 +107,11 @@ This is an open source project and will always remain free to use. If you think
107
107
 
108
108
  ## License
109
109
 
110
- The Lunora d1 package is open-sourced software licensed under the [FSL-1.1-Apache-2.0][license].
110
+ The Lunora d1 package is open-sourced software licensed under the [Apache-2.0][license].
111
111
 
112
112
  <!-- badges -->
113
113
 
114
- [license-badge]: https://img.shields.io/badge/license-FSL--1.1--Apache--2.0-blue.svg?style=for-the-badge
114
+ [license-badge]: https://img.shields.io/badge/license-Apache--2.0-blue.svg?style=for-the-badge
115
115
  [license]: https://github.com/anolilab/lunora/blob/alpha/LICENSE.md
116
116
  [npm-version-badge]: https://img.shields.io/npm/v/@lunora/d1?style=for-the-badge
117
117
  [npm-version]: https://www.npmjs.com/package/@lunora/d1
package/dist/index.d.mts CHANGED
@@ -358,6 +358,74 @@ declare const withD1Retry: <T>(operation: () => Promise<T>, options?: D1RetryOpt
358
358
  * RETURNING` runs through `all` too.
359
359
  */
360
360
  declare const retryingExec: (exec: SqlCtxExec, options?: D1RetryOptions) => SqlCtxExec;
361
+ /** One SQL file: its name under `lunora/migrations/` and its text. */
362
+ interface SqlMigrationFile {
363
+ name: string;
364
+ sql: string;
365
+ }
366
+ /**
367
+ * Where a file stands. `applied`: recorded with the same SQL, so skipped. `pending`: not recorded yet, so it runs.
368
+ * `changed`: recorded with different SQL, or its SQL is recorded under another name, which is refused rather than run
369
+ * again. `ran`: applied by this call. `baselined`: recorded by a baseline call, which records files without executing them.
370
+ */
371
+ type SqlMigrationState = "applied" | "baselined" | "changed" | "pending" | "ran";
372
+ interface SqlMigrationEntry {
373
+ /** Destructive statements (drops, renames, truncates, replaces), in file order. */
374
+ destructive: string[];
375
+ name: string;
376
+ /** Statements a migrations-scoped token may not run: anything but a new table, a non-unique index or an added column. */
377
+ rootOnly: string[];
378
+ /** Statements left out because the column they add is already there, provisioned by the runtime on first use. */
379
+ skipped: string[];
380
+ state: SqlMigrationState;
381
+ /** Statements this file would run, or ran, in file order. Empty for an applied or changed file. */
382
+ statements: string[];
383
+ }
384
+ interface SqlMigrationResult {
385
+ files: SqlMigrationEntry[];
386
+ /** A dry run only: the pending files a real run with the same options would refuse. Nothing is refused by a dry run. */
387
+ refused?: string[];
388
+ }
389
+ interface ApplySqlMigrationOptions {
390
+ /**
391
+ * Run only additive statements (a new table or index, an added column). A file with any other statement is refused
392
+ * before anything runs. Set for a caller that holds a migrations scope rather than the root token.
393
+ */
394
+ additiveOnly?: boolean;
395
+ /**
396
+ * Record every pending file as applied without running it. For a database whose files were applied by hand or
397
+ * predate this tracking. Drift is still refused; nothing is executed.
398
+ */
399
+ baseline?: boolean;
400
+ /**
401
+ * Like `baseline`, but only for the pending files up to and including the named one, in the order given. The
402
+ * files after it stay pending, so a later run can apply them, including destructive ones, on a database that now
403
+ * has a recorded file. Use it to record what already ran on a stage before a DROP that has not.
404
+ */
405
+ baselineThrough?: string;
406
+ /** Run files that hold destructive statements. Without it such a file is refused and nothing runs. */
407
+ confirmDestructive?: boolean;
408
+ /** Report each file's state and statements without running or recording anything. Never refuses. */
409
+ dryRun?: boolean;
410
+ /**
411
+ * The app's schema. A column a file adds to a `.global()` table is filled with the value its declaration gives, in the
412
+ * same batch, as the runtime does when it adds the column itself. Without it, the rows that predate the column read NULL.
413
+ */
414
+ schema?: SchemaLike;
415
+ }
416
+ /**
417
+ * Apply the pending SQL files, in the order given, against one D1 database.
418
+ *
419
+ * Every refusal is decided before the first file runs, so a drifted or unconfirmed file late in the list cannot leave
420
+ * the earlier ones applied. Each file's statements and its tracking row commit in one `batch()`. A second call finds
421
+ * every file recorded and runs nothing.
422
+ *
423
+ * Throws `MIGRATION_DRIFT` when an applied file's SQL changed or was renamed; `MIGRATION_DESTRUCTIVE` when a pending
424
+ * file cannot run (see {@link assertDestructiveConfirmed}); `MIGRATION_ROOT_REQUIRED` when an additive-only caller sends a
425
+ * file with any other statement; `VALIDATION_ERROR` for transaction control in a file that
426
+ * is applied, a `baselineThrough` that names no file, or a batch that failed and rolled back.
427
+ */
428
+ declare const applySqlMigrationFiles: (database: D1DatabaseLike, files: ReadonlyArray<SqlMigrationFile>, options?: ApplySqlMigrationOptions) => Promise<SqlMigrationResult>;
361
429
  /**
362
430
  * The canonical SQLite dialect: column affinities, `RETURNING` support (both D1
363
431
  * and `node:sqlite`), and `sqlite_master` table probing. The rest of the
@@ -365,4 +433,4 @@ declare const retryingExec: (exec: SqlCtxExec, options?: D1RetryOptions) => SqlC
365
433
  * the store core runs `sqliteEncode`/`sqliteDecode` on every engine.
366
434
  */
367
435
  declare const sqliteDialect: SqlDialect;
368
- export { ALLOW_DESTRUCTIVE_MARKER, D1Client, type D1ContextDatabaseOptions as D1CtxDbOptions, type D1QueryCost, type D1RetryOptions, D1Session, D1TimeoutError, type Migration, MigrationRunner, type MigrationRunnerResult, backfillD1SearchIndexes, createD1ContextDatabase as createD1CtxDb, d1QueryTag, emitD1QueryCost, exportGlobalRows, facetGlobalColumn, importGlobalRows, isTransientD1Error, listGlobalTables, readD1CdcChanges, readD1QueryCost, readGlobalTablePage, retryingExec, runD1AggregateMigrations, runD1CdcMigration, runD1GlobalTableMigrations, runD1RankMigrations, runD1SearchMigrations, sqliteDialect, sweepD1CdcRetention, withD1Retry };
436
+ export { ALLOW_DESTRUCTIVE_MARKER, type ApplySqlMigrationOptions, D1Client, type D1ContextDatabaseOptions as D1CtxDbOptions, type D1QueryCost, type D1RetryOptions, D1Session, D1TimeoutError, type Migration, MigrationRunner, type MigrationRunnerResult, type SqlMigrationEntry, type SqlMigrationFile, type SqlMigrationResult, type SqlMigrationState, applySqlMigrationFiles, backfillD1SearchIndexes, createD1ContextDatabase as createD1CtxDb, d1QueryTag, emitD1QueryCost, exportGlobalRows, facetGlobalColumn, importGlobalRows, isTransientD1Error, listGlobalTables, readD1CdcChanges, readD1QueryCost, readGlobalTablePage, retryingExec, runD1AggregateMigrations, runD1CdcMigration, runD1GlobalTableMigrations, runD1RankMigrations, runD1SearchMigrations, sqliteDialect, sweepD1CdcRetention, withD1Retry };
package/dist/index.d.ts CHANGED
@@ -358,6 +358,74 @@ declare const withD1Retry: <T>(operation: () => Promise<T>, options?: D1RetryOpt
358
358
  * RETURNING` runs through `all` too.
359
359
  */
360
360
  declare const retryingExec: (exec: SqlCtxExec, options?: D1RetryOptions) => SqlCtxExec;
361
+ /** One SQL file: its name under `lunora/migrations/` and its text. */
362
+ interface SqlMigrationFile {
363
+ name: string;
364
+ sql: string;
365
+ }
366
+ /**
367
+ * Where a file stands. `applied`: recorded with the same SQL, so skipped. `pending`: not recorded yet, so it runs.
368
+ * `changed`: recorded with different SQL, or its SQL is recorded under another name, which is refused rather than run
369
+ * again. `ran`: applied by this call. `baselined`: recorded by a baseline call, which records files without executing them.
370
+ */
371
+ type SqlMigrationState = "applied" | "baselined" | "changed" | "pending" | "ran";
372
+ interface SqlMigrationEntry {
373
+ /** Destructive statements (drops, renames, truncates, replaces), in file order. */
374
+ destructive: string[];
375
+ name: string;
376
+ /** Statements a migrations-scoped token may not run: anything but a new table, a non-unique index or an added column. */
377
+ rootOnly: string[];
378
+ /** Statements left out because the column they add is already there, provisioned by the runtime on first use. */
379
+ skipped: string[];
380
+ state: SqlMigrationState;
381
+ /** Statements this file would run, or ran, in file order. Empty for an applied or changed file. */
382
+ statements: string[];
383
+ }
384
+ interface SqlMigrationResult {
385
+ files: SqlMigrationEntry[];
386
+ /** A dry run only: the pending files a real run with the same options would refuse. Nothing is refused by a dry run. */
387
+ refused?: string[];
388
+ }
389
+ interface ApplySqlMigrationOptions {
390
+ /**
391
+ * Run only additive statements (a new table or index, an added column). A file with any other statement is refused
392
+ * before anything runs. Set for a caller that holds a migrations scope rather than the root token.
393
+ */
394
+ additiveOnly?: boolean;
395
+ /**
396
+ * Record every pending file as applied without running it. For a database whose files were applied by hand or
397
+ * predate this tracking. Drift is still refused; nothing is executed.
398
+ */
399
+ baseline?: boolean;
400
+ /**
401
+ * Like `baseline`, but only for the pending files up to and including the named one, in the order given. The
402
+ * files after it stay pending, so a later run can apply them, including destructive ones, on a database that now
403
+ * has a recorded file. Use it to record what already ran on a stage before a DROP that has not.
404
+ */
405
+ baselineThrough?: string;
406
+ /** Run files that hold destructive statements. Without it such a file is refused and nothing runs. */
407
+ confirmDestructive?: boolean;
408
+ /** Report each file's state and statements without running or recording anything. Never refuses. */
409
+ dryRun?: boolean;
410
+ /**
411
+ * The app's schema. A column a file adds to a `.global()` table is filled with the value its declaration gives, in the
412
+ * same batch, as the runtime does when it adds the column itself. Without it, the rows that predate the column read NULL.
413
+ */
414
+ schema?: SchemaLike;
415
+ }
416
+ /**
417
+ * Apply the pending SQL files, in the order given, against one D1 database.
418
+ *
419
+ * Every refusal is decided before the first file runs, so a drifted or unconfirmed file late in the list cannot leave
420
+ * the earlier ones applied. Each file's statements and its tracking row commit in one `batch()`. A second call finds
421
+ * every file recorded and runs nothing.
422
+ *
423
+ * Throws `MIGRATION_DRIFT` when an applied file's SQL changed or was renamed; `MIGRATION_DESTRUCTIVE` when a pending
424
+ * file cannot run (see {@link assertDestructiveConfirmed}); `MIGRATION_ROOT_REQUIRED` when an additive-only caller sends a
425
+ * file with any other statement; `VALIDATION_ERROR` for transaction control in a file that
426
+ * is applied, a `baselineThrough` that names no file, or a batch that failed and rolled back.
427
+ */
428
+ declare const applySqlMigrationFiles: (database: D1DatabaseLike, files: ReadonlyArray<SqlMigrationFile>, options?: ApplySqlMigrationOptions) => Promise<SqlMigrationResult>;
361
429
  /**
362
430
  * The canonical SQLite dialect: column affinities, `RETURNING` support (both D1
363
431
  * and `node:sqlite`), and `sqlite_master` table probing. The rest of the
@@ -365,4 +433,4 @@ declare const retryingExec: (exec: SqlCtxExec, options?: D1RetryOptions) => SqlC
365
433
  * the store core runs `sqliteEncode`/`sqliteDecode` on every engine.
366
434
  */
367
435
  declare const sqliteDialect: SqlDialect;
368
- export { ALLOW_DESTRUCTIVE_MARKER, D1Client, type D1ContextDatabaseOptions as D1CtxDbOptions, type D1QueryCost, type D1RetryOptions, D1Session, D1TimeoutError, type Migration, MigrationRunner, type MigrationRunnerResult, backfillD1SearchIndexes, createD1ContextDatabase as createD1CtxDb, d1QueryTag, emitD1QueryCost, exportGlobalRows, facetGlobalColumn, importGlobalRows, isTransientD1Error, listGlobalTables, readD1CdcChanges, readD1QueryCost, readGlobalTablePage, retryingExec, runD1AggregateMigrations, runD1CdcMigration, runD1GlobalTableMigrations, runD1RankMigrations, runD1SearchMigrations, sqliteDialect, sweepD1CdcRetention, withD1Retry };
436
+ export { ALLOW_DESTRUCTIVE_MARKER, type ApplySqlMigrationOptions, D1Client, type D1ContextDatabaseOptions as D1CtxDbOptions, type D1QueryCost, type D1RetryOptions, D1Session, D1TimeoutError, type Migration, MigrationRunner, type MigrationRunnerResult, type SqlMigrationEntry, type SqlMigrationFile, type SqlMigrationResult, type SqlMigrationState, applySqlMigrationFiles, backfillD1SearchIndexes, createD1ContextDatabase as createD1CtxDb, d1QueryTag, emitD1QueryCost, exportGlobalRows, facetGlobalColumn, importGlobalRows, isTransientD1Error, listGlobalTables, readD1CdcChanges, readD1QueryCost, readGlobalTablePage, retryingExec, runD1AggregateMigrations, runD1CdcMigration, runD1GlobalTableMigrations, runD1RankMigrations, runD1SearchMigrations, sqliteDialect, sweepD1CdcRetention, withD1Retry };
package/dist/index.mjs CHANGED
@@ -1 +1 @@
1
- import{exportGlobalRows as o,importGlobalRows as t}from"./packem_shared/exportGlobalRows-IncHgv-p.mjs";import{D1Client as l,D1Session as i}from"./packem_shared/D1Client-CzS0Qfa6.mjs";import{backfillD1SearchIndexes as s,createD1CtxDb as D,readD1CdcChanges as p,runD1AggregateMigrations as x,runD1CdcMigration as m,runD1GlobalTableMigrations as b,runD1RankMigrations as f,runD1SearchMigrations as g,sweepD1CdcRetention as c}from"./packem_shared/backfillD1SearchIndexes-BHgn1SNb.mjs";import{facetGlobalColumn as u,listGlobalTables as d,readGlobalTablePage as R}from"./packem_shared/facetGlobalColumn-BqK1_P3S.mjs";import{MigrationRunner as G}from"./packem_shared/MigrationRunner-CDF339nT.mjs";import{d1QueryTag as y,emitD1QueryCost as E,readD1QueryCost as h}from"./packem_shared/d1QueryTag-BcEGW4q1.mjs";import{D1TimeoutError as w,isTransientD1Error as A,retryingExec as Q,withD1Retry as k}from"./packem_shared/D1TimeoutError-D4YUqZPk.mjs";import{default as I}from"./packem_shared/sqliteDialect-B_3JNtdq.mjs";import{applyCdcChanges as _}from"@lunora/shard-engine";import{ALLOW_DESTRUCTIVE_MARKER as O}from"./packem_shared/ALLOW_DESTRUCTIVE_MARKER-CwYNPwK3.mjs";import{createSqlCtxDb as U,selectGlobalTables as V}from"@lunora/sql-store";export{O as ALLOW_DESTRUCTIVE_MARKER,l as D1Client,i as D1Session,w as D1TimeoutError,G as MigrationRunner,_ as applyCdcChanges,s as backfillD1SearchIndexes,D as createD1CtxDb,U as createSqlCtxDb,y as d1QueryTag,E as emitD1QueryCost,o as exportGlobalRows,u as facetGlobalColumn,t as importGlobalRows,A as isTransientD1Error,d as listGlobalTables,p as readD1CdcChanges,h as readD1QueryCost,R as readGlobalTablePage,Q as retryingExec,x as runD1AggregateMigrations,m as runD1CdcMigration,b as runD1GlobalTableMigrations,f as runD1RankMigrations,g as runD1SearchMigrations,V as selectGlobalTables,I as sqliteDialect,c as sweepD1CdcRetention,k as withD1Retry};
1
+ import{exportGlobalRows as o,importGlobalRows as t}from"./packem_shared/exportGlobalRows-IncHgv-p.mjs";import{D1Client as l,D1Session as i}from"./packem_shared/D1Client-CzS0Qfa6.mjs";import{backfillD1SearchIndexes as s,createD1CtxDb as D,readD1CdcChanges as p,runD1AggregateMigrations as x,runD1CdcMigration as m,runD1GlobalTableMigrations as f,runD1RankMigrations as g,runD1SearchMigrations as b,sweepD1CdcRetention as c}from"./packem_shared/backfillD1SearchIndexes-BHgn1SNb.mjs";import{facetGlobalColumn as u,listGlobalTables as d,readGlobalTablePage as R}from"./packem_shared/facetGlobalColumn-BqK1_P3S.mjs";import{MigrationRunner as M}from"./packem_shared/MigrationRunner-CD5zcqp6.mjs";import{d1QueryTag as G,emitD1QueryCost as E,readD1QueryCost as S}from"./packem_shared/d1QueryTag-BcEGW4q1.mjs";import{D1TimeoutError as w,isTransientD1Error as q,retryingExec as A,withD1Retry as Q}from"./packem_shared/D1TimeoutError-D4YUqZPk.mjs";import{applySqlMigrationFiles as I}from"./packem_shared/applySqlMigrationFiles-CUiRKrxP.mjs";import{default as _}from"./packem_shared/sqliteDialect-B_3JNtdq.mjs";import{applyCdcChanges as K}from"@lunora/shard-engine";import{ALLOW_DESTRUCTIVE_MARKER as P}from"./packem_shared/ALLOW_DESTRUCTIVE_MARKER-CwYNPwK3.mjs";import{createSqlCtxDb as V,selectGlobalTables as W}from"@lunora/sql-store";export{P as ALLOW_DESTRUCTIVE_MARKER,l as D1Client,i as D1Session,w as D1TimeoutError,M as MigrationRunner,K as applyCdcChanges,I as applySqlMigrationFiles,s as backfillD1SearchIndexes,D as createD1CtxDb,V as createSqlCtxDb,G as d1QueryTag,E as emitD1QueryCost,o as exportGlobalRows,u as facetGlobalColumn,t as importGlobalRows,q as isTransientD1Error,d as listGlobalTables,p as readD1CdcChanges,S as readD1QueryCost,R as readGlobalTablePage,A as retryingExec,x as runD1AggregateMigrations,m as runD1CdcMigration,f as runD1GlobalTableMigrations,g as runD1RankMigrations,b as runD1SearchMigrations,W as selectGlobalTables,_ as sqliteDialect,c as sweepD1CdcRetention,Q as withD1Retry};
@@ -0,0 +1,8 @@
1
+ import{LunoraError as w}from"@lunora/errors";import{sql as u}from"drizzle-orm";import{ALLOW_DESTRUCTIVE_MARKER as $}from"./ALLOW_DESTRUCTIVE_MARKER-CwYNPwK3.mjs";import{D1Client as C}from"./D1Client-CzS0Qfa6.mjs";const R="__drizzle_migrations",P=`CREATE TABLE IF NOT EXISTS ${R} (id INTEGER PRIMARY KEY AUTOINCREMENT, hash TEXT NOT NULL UNIQUE, created_at NUMERIC, version INTEGER)`,b=`CREATE UNIQUE INDEX IF NOT EXISTS ${R}_version ON ${R} (version)`,L=/\s/u,G=/[$\w]/u,S=String.raw`(?:\s|--[^\n]*\n|\/\*[\s\S]*?\*\/)`,v=/(?:\s|--[^\n]*(?:\n|$)|\/\*[\s\S]*?\*\/)*/uy,O=new RegExp(String.raw`CREATE${S}+(?:TEMP${S}+|TEMPORARY${S}+)?TRIGGER\b`,"iuy"),x=/^[0-9a-f]{64}$/u,N=String.raw`[$\w\u{80}-\u{10FFFF}]`,_=`${N}+`,A=n=>new RegExp(String.raw`(?<!${N})${n.replaceAll(" ",String.raw`\s+`)}(?!${N})`,"iu"),M=n=>new RegExp(String.raw`^\s*ALTER\s+TABLE\s+${_}(?:\s*\.\s*${_})?\s+${n}\b`,"iu"),B=[["DROP",/^\s*DROP\s+(?:TABLE|INDEX|VIEW|TRIGGER)\b/iu],["DROP",M("DROP")],["RENAME",M("RENAME")],["TRUNCATE",/^\s*TRUNCATE\b/iu],["INSERT OR REPLACE",A("INSERT OR REPLACE")],["REPLACE INTO",A("REPLACE INTO")],["UPDATE OR REPLACE",A("UPDATE OR REPLACE")],["ON CONFLICT REPLACE",A("ON CONFLICT REPLACE")]],V=/^\s*(?:BEGIN|COMMIT|END|ROLLBACK|SAVEPOINT|RELEASE)\b/iu,F={'"':'"',"'":"'","[":"]","`":"`"},H=new RegExp(String.raw`UNIQUE constraint failed:\s*${R}\.(?:hash|version)`,"iu"),y=n=>`Migration "${n.name}" (v${String(n.version)})`,D=(n,e,t)=>({codeIndex:e,ownLine:n.slice(n.lastIndexOf(`
2
+ `,e-1)+1,e).trim()==="",text:t}),k=(n,e,t=0,c=!1)=>{v.lastIndex=t,v.exec(n),O.lastIndex=v.lastIndex;const i=O.test(n),d=[];let s="",o,l,r=0,a=0,h,T="",I=!1,f=!1;for(let m=t;m<n.length;m+=1){const E=n.charAt(m),g=n.charAt(m+1);if(l==="line"){E===`
3
+ `&&(d.push(D(s,a,n.slice(r,m))),l=void 0),s+=E===`
4
+ `?`
5
+ `:" ";continue}if(l==="block"){s+=" ",E==="*"&&g==="/"&&(s+=" ",l=void 0,m+=1);continue}if(o!==void 0){s+=" ",E===o&&o!=="]"&&g===o?(s+=" ",m+=1):E===o&&(o=void 0);continue}if(E==="-"&&g==="-"||E==="/"&&g==="*"){l=E==="-"?"line":"block",r=m,a=s.length,s+=" ",m+=1;continue}if(h!==void 0){if(!L.test(E))throw new w("INTERNAL",`${e} contains more than one SQL statement. Split it into separate migrations — batch() runs them atomically.`);s+=E;continue}if(i){if(G.test(E)){T+=E,s+=E;continue}const p=T.toUpperCase();T="",p!==""?(I=f&&p==="END",f=!1):E!==";"&&!L.test(E)&&(I=!1,f=!1)}if(o=F[E],o!==void 0){s+=" _ ";continue}if(s+=E,E===";"){if(i&&!I)f=!0;else if(h=m,c)break}}return l==="line"&&d.push(D(s,a,n.slice(r))),{code:s,end:h===void 0?n.length:h+1,lineComments:d,statementText:n.slice(t,h??n.length).trim()}},q=n=>V.test(n.code),Q=n=>{let e;for(const[t,c]of B){const i=c.exec(n.code),d=i===null?void 0:i.index+i[0].length-i[0].trimStart().length;d!==void 0&&(e===void 0||d<e.index)&&(e={index:d,statement:t})}return e},K=(n,e)=>{if(q(e))throw new w("INTERNAL",`${n} is transaction control (BEGIN/COMMIT/END/ROLLBACK/SAVEPOINT/RELEASE). Each migration already runs atomically with its tracking row in one batch(); remove it.`);const t=Q(e);if(t===void 0)return;if(!e.lineComments.some(i=>i.ownLine&&i.codeIndex<t.index&&i.text.trimEnd()===$))throw new w("MIGRATION_DESTRUCTIVE",`${n} has not run yet and contains a destructive statement (${t.statement}). If it is meant to discard data or rename what readers depend on, add a \`${$}\` line comment on its own line before the statement. Only pending migrations are checked, so never add it to one that already ran: that changes its hash and is refused as drift.`)},U=async n=>{const e=new TextEncoder().encode(n),t=await crypto.subtle.digest("SHA-256",e);return[...new Uint8Array(t)].map(c=>c.toString(16).padStart(2,"0")).join("")},W=/^\uFEFF/u,X=n=>{let e=n.length;for(;e>0&&n[e-1]===`
6
+ `;)e-=1;return n.slice(0,e)},z=n=>X(n.replace(W,"").replaceAll(`\r
7
+ `,`
8
+ `)),j=async n=>({normalized:await U(z(n)),raw:await U(n)}),Y=(n,e)=>n===e?.normalized||n===e?.raw;class te{client;migrations;constructor(e,t){this.client=e instanceof C?e:new C(e),this.migrations=[...t].toSorted((c,i)=>c.version-i.version),this.assertUniqueVersions(),this.assertUniqueSql()}async run(){await this.ensureTrackingTable();const e=await Promise.all(this.migrations.map(async r=>j(r.sql))),t=await this.readTrackingRows(e),c=new Map(t.filter(r=>r.version!==null).map(r=>[r.version,r.hash])),i=[];for(const[r,a]of this.migrations.entries()){const h=c.get(a.version),T=String(e[r]?.normalized);if(h===void 0)i.push({hash:T,migration:a});else if(!Y(h,e[r]))throw new w("MIGRATION_DRIFT",`${y(a)} was already applied from different SQL (recorded sha256 ${h}, now ${T}). An applied migration is never re-run: revert the edit and put the change in a new migration. If the edit is inert (a comment, whitespace, line endings), record the new text as applied: UPDATE ${R} SET hash = '${T}' WHERE version = ${String(a.version)};`)}const d=t.filter(r=>r.version===null);if(i.length>0&&d.length>0){const r=i.map(({migration:a})=>a.version);throw new w("MIGRATION_DRIFT",`${R} holds ${String(d.length)} row(s) recorded before versions were tracked whose SQL matches no current migration (id ${d.map(a=>String(a.id)).join(", ")}), and ${r.map(a=>`v${String(a)}`).join(", ")} ${r.length===1?"is":"are"} not recorded as applied — one of them may be an edited copy of what already ran. Refusing to guess: give each row the version it recorded (UPDATE ${R} SET version = <n> WHERE id = <id>; for a migration that no longer exists, any version no current migration uses), then run again.`)}const s=new Map(i.map(({hash:r,migration:a})=>{const h=y(a),T=k(a.sql,h);return K(h,T),[a.version,{hash:r,migration:a,statementText:T.statementText}]})),o=[],l=[];for(const r of this.migrations){const a=s.get(r.version),h={name:r.name,version:r.version};if(a===void 0){l.push(h);continue}await this.applyOne(a)?o.push(h):l.push(h)}return{applied:o,skipped:l}}async hasVersionColumn(){return(await this.client.drizzle.all(u.raw(`SELECT name FROM pragma_table_info('${R}') WHERE name = 'version'`))).length>0}async ensureTrackingTable(){if(await this.client.drizzle.run(u.raw(P)),!await this.hasVersionColumn())try{await this.client.drizzle.run(u.raw(`ALTER TABLE ${R} ADD COLUMN version INTEGER`))}catch(e){if(!await this.hasVersionColumn())throw e}await this.client.drizzle.run(u.raw(b))}async readTrackingRows(e){const t=u.raw(`SELECT id, hash, version FROM ${R} ORDER BY id`),c=await this.client.drizzle.all(t),i=new Map(this.migrations.flatMap((o,l)=>[[String(e[l]?.raw),o.version],[String(e[l]?.normalized),o.version]])),d=new Set(c.map(o=>o.version).filter(o=>o!==null));let s=!1;for(const o of c){const l=o.version===null?i.get(o.hash):void 0;l===void 0||d.has(l)||(await this.client.drizzle.run(u`UPDATE ${u.raw(R)} SET version = ${l} WHERE id = ${o.id} AND version IS NULL`),d.add(l),s=!0)}return s?await this.client.drizzle.all(t):c}async applyOne({hash:e,migration:t,statementText:c}){if(!x.test(e))throw new w("INTERNAL",`migration "${t.name}" produced a non-hex hash; refusing to inline into SQL`);const i=`INSERT INTO ${R} (hash, created_at, version) VALUES ('${e}', ${String(Date.now())}, ${String(t.version)})`,d=[this.client.drizzle.run(u.raw(c)),this.client.drizzle.run(u.raw(i))];try{await this.client.batch(d)}catch(s){if(H.test(s instanceof Error?s.message:String(s)))return!1;throw s}return!0}assertUniqueVersions(){const e=new Set;for(const t of this.migrations){if(!Number.isSafeInteger(t.version))throw new w("INTERNAL",`Migration "${t.name}" has version ${String(t.version)}; a version must be an integer`);if(e.has(t.version))throw new w("INTERNAL",`Duplicate migration version ${String(t.version)}`);e.add(t.version)}}assertUniqueSql(){const e=new Map;for(const t of this.migrations){const c=z(t.sql),i=e.get(c);if(i!==void 0)throw new w("INTERNAL",`Migrations ${String(i)} and ${String(t.version)} have identical SQL — bump the content, not just the version.`);e.set(c,t.version)}}}export{$ as ALLOW_DESTRUCTIVE_MARKER,te as MigrationRunner,R as TRACKING_TABLE_NAME,Q as firstDestructive,q as isTransactionControl,z as normalizeMigrationText,k as scanStatement,U as sha256Hex};
@@ -0,0 +1,8 @@
1
+ import{LunoraError as h}from"@lunora/errors";import{globalColumnBackfill as z}from"@lunora/sql-store";import{sql as A}from"drizzle-orm";import{D1Client as Q}from"./D1Client-CzS0Qfa6.mjs";import{sha256Hex as V,normalizeMigrationText as X,scanStatement as q,firstDestructive as H,isTransactionControl as K}from"./MigrationRunner-CD5zcqp6.mjs";const _="__lunora_sql_migrations",W=`CREATE TABLE IF NOT EXISTS ${_} (name TEXT PRIMARY KEY, sha256 TEXT NOT NULL, applied_at INTEGER NOT NULL, baselined INTEGER NOT NULL DEFAULT 0, written_by TEXT NOT NULL DEFAULT 'root')`,j=/^\w[\w.-]*\.sql$/u,Y=new RegExp(String.raw`UNIQUE constraint failed:\s*${_}\.name`,"iu"),Z=/duplicate column name/iu,$="`",p=String.raw`"(?:[^"]|"")+"|\[[^\]]+\]|${$}(?:[^${$}]|${$}${$})+${$}|[_a-z]\w*`,c=String.raw`(?:\s|--[^\n]*\n|\/\*(?:[^*]|\*(?!\/))*\*\/)+`,I=String.raw`(?:\s|--[^\n]*\n|\/\*(?:[^*]|\*(?!\/))*\*\/)*`,J=new RegExp(String.raw`^${I}`,"u"),T=String.raw`(?:(?:${p})${I}\.${I})?`,ee=new RegExp(String.raw`^ALTER${c}TABLE${c}${T}(${p})${c}ADD${c}(?:COLUMN${c})?(${p})`,"iu"),te=new RegExp(String.raw`^(?:DROP${c}TABLE(?:${c}IF${c}EXISTS)?${c}${T}(${p})|CREATE${c}TABLE(?!${c}IF${c}NOT${c}EXISTS\b)${c}${T}(${p})|ALTER${c}TABLE${c}${T}(${p})${c}(?:RENAME|DROP)\b)`,"iu"),ne=/^(?:WITH|INSERT|UPDATE|DELETE|REPLACE)\b/iu,re=new RegExp(String.raw`^CREATE${c}TABLE(?:${c}IF${c}NOT${c}EXISTS)?${c}${T}(?:${p})${c}AS\b`,"iu"),g=String.raw`[_a-z][\w$]*`,L=String.raw`(?:${g}\s*\.\s*)?`,se=new RegExp(String.raw`^\s*CREATE\s+TABLE(?:\s+IF\s+NOT\s+EXISTS)?\s+${L}${g}\s*\(`,"iu"),ae=new RegExp(String.raw`^\s*CREATE\s+INDEX(?:\s+IF\s+NOT\s+EXISTS)?\s+${L}${g}\s+ON\s+${L}${g}\s*\(([^()]*)\)[\s;]*$`,"iu"),oe=new RegExp(String.raw`^\s*${g}(?:\s+COLLATE\s+${g})?(?:\s+(?:ASC|DESC))?\s*$`,"iu"),ie=new RegExp(String.raw`^\s*ALTER\s+TABLE\s+${L}${g}\s+ADD\s+(?:COLUMN\s+)?${g}`,"iu"),ce=/\b(?:DEFAULT|GENERATED|AS|CHECK|REFERENCES|UNIQUE|NOT\s+NULL|NOTNULL)\b/iu,le=/\bREFERENCES\b/iu,de=/__lunora_|__drizzle_|__cdc_|__agg_|__rank_|__fts_|sqlite_|_cf_/iu,ue=new RegExp(String.raw`\btemp["\]${$}]?${I}\.`,"iu"),Ee=new RegExp(String.raw`^PRAGMA${c}${T}(?:foreign_keys|"foreign_keys")${I}(?:=|\()`,"iu"),N=t=>{if(t.startsWith("["))return t.slice(1,-1);if(t.startsWith('"')||t.startsWith("`")){const e=t.charAt(0);return t.slice(1,-1).replaceAll(e+e,e)}return t},f=t=>t.replaceAll(/[A-Z]+/gu,e=>e.toLowerCase()),O=t=>t.slice(J.exec(t)?.[0].length??0),S=t=>t.replaceAll(/--[^\n]*/gu," ").replaceAll(/\s+/gu," ").trim(),M=t=>Ee.test(O(t)),b=t=>{const e=ee.exec(O(t));if(e!==null)return{column:N(e[2]??""),table:N(e[1]??"")}},he=t=>{const e=te.exec(O(t)),n=e?.[1]??e?.[2]??e?.[3];return n===void 0?void 0:N(n)},me=async(t,e,n)=>{const r=`"${e.replaceAll('"','""')}"`,s=await t.drizzle.all(A.raw(`PRAGMA table_info(${r})`)),o=f(n);return s.some(i=>f(i.name)===o)},fe=t=>{if(de.test(t.statementText)||ue.test(t.statementText))return!1;const e=ie.exec(t.code);if(e!==null)return!ce.test(t.code.slice(e[0].length));if(le.test(t.code))return!1;const n=ae.exec(t.code);return n!==null?(n[1]??"").split(",").every(r=>oe.test(r)):se.test(t.code)},U=(t,e)=>{const n=he(t);n!==void 0&&e.add(f(n))},F=t=>{const e=O(t);return ne.test(e)||re.test(e)},pe=(t,e)=>e||F(t),B=()=>({present:new Map,stale:new Set}),we=new RegExp(String.raw`^ALTER${c}TABLE${c}${T}(${p})${c}DROP${c}(?:COLUMN${c})?(${p})`,"iu"),P=t=>{const e=we.exec(O(t));if(e!==null)return{column:N(e[2]??""),table:N(e[1]??"")}},Re=t=>{const e=b(t);if(e!==void 0)return{column:f(e.column),present:!0,table:f(e.table)};const n=P(t);return n===void 0?void 0:{column:f(n.column),present:!1,table:f(n.table)}},ge=async(t,e,n,r)=>{const s=b(e);if(s===void 0)return!1;const o=f(s.table);return n.has(o)||r.stale.has(o)?!1:r.present.get(o)?.get(f(s.column))??await me(t,s.table,s.column)},ye=(t,e,n)=>{for(const r of e){const s=t.present.get(r.table)??new Map;s.set(r.column,r.present),t.present.set(r.table,s)}for(const r of n)t.stale.add(r)},Ae=(t,e)=>{if(K(e))throw new h("VALIDATION_ERROR",`${t.name} is transaction control (BEGIN/COMMIT/END/ROLLBACK/SAVEPOINT/RELEASE). Each file already runs atomically with its tracking row in one batch(); remove it.`);if(M(e.statementText))throw new h("VALIDATION_ERROR",`${t.name} changes foreign-key enforcement (PRAGMA foreign_keys). A migration file may not; remove it.`)},Te=(t,e)=>{const n=b(t);return n===void 0||e===void 0?void 0:z(e,n.table,n.column)},$e=(t,e,n)=>{const r=Re(t);r!==void 0&&e.push(r),P(t)===void 0&&U(t,n)},_e=(t,e)=>{const n=Te(t,e);return n===void 0?[t]:[t,n]},x=async(t,e,n,r,s=B())=>{const o=[],i=[],l=[],a=[],u=new Set,m=new Set,E=[];let d=!1,y=0;for(;y<e.sql.length;){const w=q(e.sql,e.name,y,!0);if(y=w.end,w.code.replaceAll(/[\s;]/gu,"")==="")continue;n&&Ae(e,w);const{statementText:R}=w,C=H(w)!==void 0;if($e(R,E,m),C&&o.push(R),fe(w)||i.push(R),await ge(t,R,u,s)){a.push(R);continue}l.push(..._e(R,r)),d||=pe(R,C),U(R,u)}return ye(s,E,m),{destructive:o,replayUnsafe:d,rootOnly:i,runs:l,skipped:a,statements:l.filter(w=>typeof w=="string")}},Oe=t=>{const e=new Set;for(const n of t){if(!j.test(n.name))throw new h("VALIDATION_ERROR",`migration file name "${n.name}" must be a plain *.sql file name`);if(e.has(n.name))throw new h("VALIDATION_ERROR",`migration file "${n.name}" was sent more than once`);e.add(n.name)}},Ie=async(t,e)=>{if(e){if((await t.drizzle.all(A.raw(`SELECT name FROM sqlite_master WHERE type = 'table' AND name = '${_}'`))).length===0)return{fresh:!0,recorded:new Map}}else await t.drizzle.run(A.raw(W));const n=await t.drizzle.all(A.raw(`SELECT name, sha256, written_by FROM ${_}`));return{fresh:!n.some(r=>r.written_by==="root"),recorded:new Map(n.map(r=>[r.name,{sha256:r.sha256,writtenBy:r.written_by}]))}},D=(t,e,n,r)=>({entry:{destructive:[],name:t.name,rootOnly:[],skipped:[],state:n,statements:[]},file:t,hash:e,...r===void 0?{}:{renamedFrom:r},replayUnsafe:!1}),Ne=(t,e)=>{const n=new Map;for(const[r,s]of t)!e.has(r)&&s.writtenBy==="root"&&n.set(s.sha256,r);return n},Le=async(t,e,n,r)=>{const s=await Promise.all(e.map(async a=>({file:a,hash:await V(X(a.sql))}))),o=Ne(n,new Set(e.map(a=>a.name))),i=B(),l=[];for(const{file:a,hash:u}of s){const m=n.get(a.name);if(m!==void 0){l.push(D(a,u,m.sha256===u?"applied":"changed"));continue}const E=o.get(u);if(E!==void 0){l.push(D(a,u,"changed",E));continue}const d=await x(t,a,r,void 0,i);l.push({entry:{destructive:d.destructive,name:a.name,rootOnly:d.rootOnly,skipped:d.skipped,state:"pending",statements:d.statements},file:a,hash:u,replayUnsafe:d.replayUnsafe})}return l},k=t=>{const e=new Map,n=[];for(const r of t.filter(s=>s.entry.state==="pending")){const s=e.get(r.hash);s===void 0?e.set(r.hash,r):n.push([s,r])}return n},Se=t=>{const e=k(t);if(e.length===0)return;const n=e.map(([r,s])=>`${s.entry.name} repeats ${r.entry.name}`).join("; ");throw new h("VALIDATION_ERROR",`${n}. Identical SQL would run once per name. Delete the extra file, or change its SQL.`)},be=t=>{const e=t.filter(o=>o.entry.state==="changed");if(e.length===0)return;const n=e.filter(o=>o.renamedFrom!==void 0),r=e.filter(o=>o.renamedFrom===void 0),s=[];if(r.length>0){const o=r.map(i=>i.entry.name).join(", ");s.push(`${o} ${r.length===1?"was":"were"} already applied from different SQL. Revert the edit and put the change in a new file.`)}if(n.length>0){const o=n.map(i=>`${i.entry.name} (applied as ${String(i.renamedFrom)})`).join(", ");s.push(`${o} ${n.length===1?"was":"were"} renamed. Rename it back: an applied file is never run again under a new name.`)}throw new h("MIGRATION_DRIFT",`${s.join(" ")} An applied file is never run again.`)},Ce=t=>t.statements.filter(e=>t.destructive.includes(e)||F(e)),De=/^(?:BEGIN|COMMIT|END|ROLLBACK|SAVEPOINT|RELEASE)\b/iu,ve=(t,e,n)=>{const r=t.filter(a=>a.entry.state==="pending");if(e.baseline===!0||e.baselineThrough!==void 0)return e.additiveOnly===!0?r.map(a=>a.entry.name):[];const o=a=>n&&a.replayUnsafe||e.additiveOnly===!0&&a.entry.rootOnly.length>0||a.entry.statements.some(u=>De.test(O(u))||M(u)),i=r.filter(a=>o(a)).map(a=>a.entry.name),l=k(t).flat().map(a=>a.entry.name);return[...new Set([...i,...l])]},Me=(t,e,n)=>{const r=t.filter(i=>i.entry.state==="pending");if(n){const i=r.filter(l=>l.replayUnsafe);if(i.length>0){const l=i.flatMap(a=>Ce(a.entry).map(u=>`${a.entry.name}: ${S(u)}`));throw new h("MIGRATION_DESTRUCTIVE",`no SQL migration file is recorded on this database, so these statements are refused. They drop, replace or write rows, and may already have run by hand or predate this tracking:
2
+ ${l.join(`
3
+ `)}
4
+ Record the files that already ran with \`migrate apply --baseline-through <last file that ran>\`, then run the new ones.`)}return}const s=r.filter(i=>i.entry.destructive.length>0);if(s.length===0||e)return;const o=s.flatMap(i=>i.entry.destructive.map(l=>`${i.entry.name}: ${S(l)}`));throw new h("MIGRATION_DESTRUCTIVE",`these files drop, rename, truncate or replace data and have not run yet. Re-run with --allow-destructive to apply them:
5
+ ${o.join(`
6
+ `)}`)},Ue=(t,e)=>{if(!e)return;const n=t.filter(s=>s.entry.state==="pending"&&s.entry.rootOnly.length>0);if(n.length===0)return;const r=n.flatMap(s=>s.entry.rootOnly.map(o=>`${s.entry.name}: ${S(o)}`));throw new h("MIGRATION_ROOT_REQUIRED",`these files run statements that a migrations-scoped token may not run (only CREATE TABLE, a CREATE INDEX that is not UNIQUE, and ADD COLUMN). Run them with the root admin token:
7
+ ${r.join(`
8
+ `)}`)},Fe=async(t,e)=>(await t.drizzle.all(A.raw(`SELECT sha256, baselined FROM ${_} WHERE name = '${e}'`)))[0],G=async(t,e,n,r,s)=>{const o=s.origin==="baselined"?1:0,l=[t.drizzle.run(A.raw(`INSERT INTO ${_} (name, sha256, applied_at, baselined, written_by) VALUES ('${e.name}', '${n}', ${String(Date.now())}, ${String(o)}, '${s.writtenBy}')`)),...r.map(a=>t.drizzle.run(typeof a=="string"?A.raw(a):a))];try{return await t.batch(l),"ran"}catch(a){const u=a instanceof Error?a.message:String(a);if(!Y.test(u))throw new h("VALIDATION_ERROR",`${e.name} failed and was rolled back, so none of its statements took effect: ${u}`,{cause:a});const m=await Fe(t,e.name);if(m?.sha256===n){if(s.origin==="applied"&&m.baselined===1)throw new h("CONFLICT",`${e.name} was recorded as a baseline by a concurrent run, which records a file without running it. Its SQL did not run here, so this apply stopped; run it again to see the file's state.`,{cause:a});return"applied"}throw new h("MIGRATION_DRIFT",`${e.name} was recorded by a concurrent run from different SQL. An applied file is never run again: revert the edit and put the change in a new file.`,{cause:a})}},v=async(t,e,n)=>{const r=await x(t,e.file,!0,n.schema),s={origin:"applied",writtenBy:n.writtenBy};return{skipped:r.skipped,state:await G(t,e.file,e.hash,r.runs,s),statements:r.statements}},Be=async(t,e,n)=>{try{return await v(t,e,n)}catch(r){if(!(r instanceof Error)||!Z.test(r.message))throw r;return v(t,e,n)}},Pe=(t,e)=>{if(e.baseline===!0&&e.baselineThrough!==void 0)throw new h("VALIDATION_ERROR","pass either baseline or baselineThrough, not both");if(e.baselineThrough===void 0)return t.length-1;const n=t.findIndex(r=>r.name===e.baselineThrough);if(n===-1)throw new h("VALIDATION_ERROR",`baselineThrough names "${e.baselineThrough}", which is not among the files sent`);return n},xe=async(t,e,n)=>{for(const[r,s]of e.entries())if(s.entry.state==="pending"&&r<=n){const o={origin:"baselined",writtenBy:"root"};s.entry.state=await G(t,s.file,s.hash,[],o)==="ran"?"baselined":"applied"}},Xe=async(t,e,n={})=>{Oe(e);const r=n.baseline===!0||n.baselineThrough!==void 0,s=Pe(e,n),o=new Q(t),i=n.dryRun===!0,{fresh:l,recorded:a}=await Ie(o,i),u=n.additiveOnly===!0?"migrations":"root",m={schema:n.schema,writtenBy:u},E=await Le(o,e,a,!i&&!r);if(i)return{files:E.map(d=>d.entry),refused:ve(E,n,l)};if(be(E),r&&n.additiveOnly===!0)throw new h("MIGRATION_ROOT_REQUIRED","a baseline records files as applied without running them, so only the root admin token may run one");if(r)return await xe(o,E,s),{files:E.map(d=>d.entry)};Se(E),Ue(E,n.additiveOnly===!0),Me(E,n.confirmDestructive===!0,l);for(const d of E)if(d.entry.state==="pending"){const y=await Be(o,d,m);d.entry.skipped=y.skipped,d.entry.statements=y.statements,d.entry.state=y.state}return{files:E.map(d=>d.entry)}};export{Xe as applySqlMigrationFiles};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lunora/d1",
3
- "version": "1.0.0-alpha.234",
3
+ "version": "1.0.0-alpha.236",
4
4
  "description": "D1 adapter for Lunora .global() tables, wrapping the Sessions API for read-your-writes",
5
5
  "keywords": [
6
6
  "cloudflare",
@@ -14,7 +14,7 @@
14
14
  ],
15
15
  "homepage": "https://lunora.sh",
16
16
  "bugs": "https://github.com/anolilab/lunora/issues",
17
- "license": "FSL-1.1-Apache-2.0",
17
+ "license": "Apache-2.0",
18
18
  "author": {
19
19
  "name": "Daniel Bannert",
20
20
  "email": "d.bannert@anolilab.de"
@@ -50,10 +50,10 @@
50
50
  "access": "public"
51
51
  },
52
52
  "dependencies": {
53
- "@lunora/errors": ">=1.0.0-alpha.51 <2.0.0-0",
53
+ "@lunora/errors": ">=1.0.0-alpha.89 <2.0.0-0",
54
54
  "@lunora/platform": "1.0.0-alpha.80",
55
- "@lunora/shard-engine": "^1.0.0-alpha.187",
56
- "@lunora/sql-store": "^1.0.0-alpha.234",
55
+ "@lunora/shard-engine": "^1.0.0-alpha.193",
56
+ "@lunora/sql-store": "^1.0.0-alpha.236",
57
57
  "drizzle-orm": "1.0.0-rc.5"
58
58
  },
59
59
  "engines": {
@@ -1,8 +0,0 @@
1
- import{LunoraError as u}from"@lunora/errors";import{sql as w}from"drizzle-orm";import{ALLOW_DESTRUCTIVE_MARKER as v}from"./ALLOW_DESTRUCTIVE_MARKER-CwYNPwK3.mjs";import{D1Client as N}from"./D1Client-CzS0Qfa6.mjs";const R="__drizzle_migrations",D=`CREATE TABLE IF NOT EXISTS ${R} (id INTEGER PRIMARY KEY AUTOINCREMENT, hash TEXT NOT NULL UNIQUE, created_at NUMERIC, version INTEGER)`,U=`CREATE UNIQUE INDEX IF NOT EXISTS ${R}_version ON ${R} (version)`,p=/\s/u,y=/[$\w]/u,A=String.raw`(?:\s|--[^\n]*\n|\/\*[\s\S]*?\*\/)`,z=/^(?:\s|--[^\n]*(?:\n|$)|\/\*[\s\S]*?\*\/)*/u,P=new RegExp(String.raw`^CREATE${A}+(?:TEMP${A}+|TEMPORARY${A}+)?TRIGGER\b`,"iu"),b=/^[0-9a-f]{64}$/u,S=String.raw`[$\w\u{80}-\u{10FFFF}]`,$=`${S}+`,f=n=>new RegExp(String.raw`(?<!${S})${n.replaceAll(" ",String.raw`\s+`)}(?!${S})`,"iu"),L=n=>new RegExp(String.raw`^\s*ALTER\s+TABLE\s+${$}(?:\s*\.\s*${$})?\s+${n}\b`,"iu"),G=[["DROP",/^\s*DROP\s+(?:TABLE|INDEX|VIEW|TRIGGER)\b/iu],["DROP",L("DROP")],["RENAME",L("RENAME")],["TRUNCATE",/^\s*TRUNCATE\b/iu],["INSERT OR REPLACE",f("INSERT OR REPLACE")],["REPLACE INTO",f("REPLACE INTO")],["UPDATE OR REPLACE",f("UPDATE OR REPLACE")],["ON CONFLICT REPLACE",f("ON CONFLICT REPLACE")]],B=/^\s*(?:BEGIN|COMMIT|END|ROLLBACK|SAVEPOINT|RELEASE)\b/iu,V={'"':'"',"'":"'","[":"]","`":"`"},F=new RegExp(String.raw`UNIQUE constraint failed:\s*${R}\.(?:hash|version)`,"iu"),C=n=>`Migration "${n.name}" (v${String(n.version)})`,O=(n,e,t)=>({codeIndex:e,ownLine:n.slice(n.lastIndexOf(`
2
- `,e-1)+1,e).trim()==="",text:t}),H=(n,e)=>{const t=P.test(n.slice(z.exec(n)?.[0].length??0)),c=[];let i="",l,o,a=0,d=0,r,s="",h=!1,T=!1;for(let m=0;m<n.length;m+=1){const E=n.charAt(m),g=n.charAt(m+1);if(o==="line"){E===`
3
- `&&(c.push(O(i,d,n.slice(a,m))),o=void 0),i+=E===`
4
- `?`
5
- `:" ";continue}if(o==="block"){i+=" ",E==="*"&&g==="/"&&(i+=" ",o=void 0,m+=1);continue}if(l!==void 0){i+=" ",E===l&&l!=="]"&&g===l?(i+=" ",m+=1):E===l&&(l=void 0);continue}if(E==="-"&&g==="-"||E==="/"&&g==="*"){o=E==="-"?"line":"block",a=m,d=i.length,i+=" ",m+=1;continue}if(r!==void 0){if(!p.test(E))throw new u("INTERNAL",`${e} contains more than one SQL statement. Split it into separate migrations — batch() runs them atomically.`);i+=E;continue}if(t){if(y.test(E)){s+=E,i+=E;continue}const I=s.toUpperCase();s="",I!==""?(h=T&&I==="END",T=!1):E!==";"&&!p.test(E)&&(h=!1,T=!1)}if(l=V[E],l!==void 0){i+=" _ ";continue}i+=E,E===";"&&(t&&!h?T=!0:r=m)}return o==="line"&&c.push(O(i,d,n.slice(a))),{code:i,lineComments:c,statementText:n.slice(0,r??n.length).trim()}},x=(n,e)=>{if(B.test(e.code))throw new u("INTERNAL",`${n} is transaction control (BEGIN/COMMIT/END/ROLLBACK/SAVEPOINT/RELEASE). Each migration already runs atomically with its tracking row in one batch(); remove it.`);let t;for(const[i,l]of G){const o=l.exec(e.code),a=o===null?void 0:o.index+o[0].length-o[0].trimStart().length;a!==void 0&&(t===void 0||a<t.index)&&(t={index:a,statement:i})}if(t===void 0)return;if(!e.lineComments.some(i=>i.ownLine&&i.codeIndex<t.index&&i.text.trimEnd()===v))throw new u("MIGRATION_DESTRUCTIVE",`${n} has not run yet and contains a destructive statement (${t.statement}). If it is meant to discard data or rename what readers depend on, add a \`${v}\` line comment on its own line before the statement. Only pending migrations are checked, so never add it to one that already ran: that changes its hash and is refused as drift.`)},_=async n=>{const e=new TextEncoder().encode(n),t=await crypto.subtle.digest("SHA-256",e);return[...new Uint8Array(t)].map(c=>c.toString(16).padStart(2,"0")).join("")},k=/^\uFEFF/u,q=n=>{let e=n.length;for(;e>0&&n[e-1]===`
6
- `;)e-=1;return n.slice(0,e)},M=n=>q(n.replace(k,"").replaceAll(`\r
7
- `,`
8
- `)),Q=async n=>({normalized:await _(M(n)),raw:await _(n)}),K=(n,e)=>n===e?.normalized||n===e?.raw;class J{client;migrations;constructor(e,t){this.client=e instanceof N?e:new N(e),this.migrations=[...t].toSorted((c,i)=>c.version-i.version),this.assertUniqueVersions(),this.assertUniqueSql()}async run(){await this.ensureTrackingTable();const e=await Promise.all(this.migrations.map(async r=>Q(r.sql))),t=await this.readTrackingRows(e),c=new Map(t.filter(r=>r.version!==null).map(r=>[r.version,r.hash])),i=[];for(const[r,s]of this.migrations.entries()){const h=c.get(s.version),T=String(e[r]?.normalized);if(h===void 0)i.push({hash:T,migration:s});else if(!K(h,e[r]))throw new u("MIGRATION_DRIFT",`${C(s)} was already applied from different SQL (recorded sha256 ${h}, now ${T}). An applied migration is never re-run: revert the edit and put the change in a new migration. If the edit is inert (a comment, whitespace, line endings), record the new text as applied: UPDATE ${R} SET hash = '${T}' WHERE version = ${String(s.version)};`)}const l=t.filter(r=>r.version===null);if(i.length>0&&l.length>0){const r=i.map(({migration:s})=>s.version);throw new u("MIGRATION_DRIFT",`${R} holds ${String(l.length)} row(s) recorded before versions were tracked whose SQL matches no current migration (id ${l.map(s=>String(s.id)).join(", ")}), and ${r.map(s=>`v${String(s)}`).join(", ")} ${r.length===1?"is":"are"} not recorded as applied — one of them may be an edited copy of what already ran. Refusing to guess: give each row the version it recorded (UPDATE ${R} SET version = <n> WHERE id = <id>; for a migration that no longer exists, any version no current migration uses), then run again.`)}const o=new Map(i.map(({hash:r,migration:s})=>{const h=C(s),T=H(s.sql,h);return x(h,T),[s.version,{hash:r,migration:s,statementText:T.statementText}]})),a=[],d=[];for(const r of this.migrations){const s=o.get(r.version),h={name:r.name,version:r.version};if(s===void 0){d.push(h);continue}await this.applyOne(s)?a.push(h):d.push(h)}return{applied:a,skipped:d}}async hasVersionColumn(){return(await this.client.drizzle.all(w.raw(`SELECT name FROM pragma_table_info('${R}') WHERE name = 'version'`))).length>0}async ensureTrackingTable(){if(await this.client.drizzle.run(w.raw(D)),!await this.hasVersionColumn())try{await this.client.drizzle.run(w.raw(`ALTER TABLE ${R} ADD COLUMN version INTEGER`))}catch(e){if(!await this.hasVersionColumn())throw e}await this.client.drizzle.run(w.raw(U))}async readTrackingRows(e){const t=w.raw(`SELECT id, hash, version FROM ${R} ORDER BY id`),c=await this.client.drizzle.all(t),i=new Map(this.migrations.flatMap((a,d)=>[[String(e[d]?.raw),a.version],[String(e[d]?.normalized),a.version]])),l=new Set(c.map(a=>a.version).filter(a=>a!==null));let o=!1;for(const a of c){const d=a.version===null?i.get(a.hash):void 0;d===void 0||l.has(d)||(await this.client.drizzle.run(w`UPDATE ${w.raw(R)} SET version = ${d} WHERE id = ${a.id} AND version IS NULL`),l.add(d),o=!0)}return o?await this.client.drizzle.all(t):c}async applyOne({hash:e,migration:t,statementText:c}){if(!b.test(e))throw new u("INTERNAL",`migration "${t.name}" produced a non-hex hash; refusing to inline into SQL`);const i=`INSERT INTO ${R} (hash, created_at, version) VALUES ('${e}', ${String(Date.now())}, ${String(t.version)})`,l=[this.client.drizzle.run(w.raw(c)),this.client.drizzle.run(w.raw(i))];try{await this.client.batch(l)}catch(o){if(F.test(o instanceof Error?o.message:String(o)))return!1;throw o}return!0}assertUniqueVersions(){const e=new Set;for(const t of this.migrations){if(!Number.isSafeInteger(t.version))throw new u("INTERNAL",`Migration "${t.name}" has version ${String(t.version)}; a version must be an integer`);if(e.has(t.version))throw new u("INTERNAL",`Duplicate migration version ${String(t.version)}`);e.add(t.version)}}assertUniqueSql(){const e=new Map;for(const t of this.migrations){const c=M(t.sql),i=e.get(c);if(i!==void 0)throw new u("INTERNAL",`Migrations ${String(i)} and ${String(t.version)} have identical SQL — bump the content, not just the version.`);e.set(c,t.version)}}}export{v as ALLOW_DESTRUCTIVE_MARKER,J as MigrationRunner,R as TRACKING_TABLE_NAME};