@lunora/sql-store 1.0.0-alpha.235 → 1.0.0-alpha.237
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 +201 -104
- package/README.md +3 -3
- package/dist/index.d.mts +9 -2
- package/dist/index.d.ts +9 -2
- package/dist/index.mjs +1 -1
- package/dist/packem_shared/{SEARCH_STATE_TABLE-CRLusd2n.mjs → SEARCH_STATE_TABLE-DWvn-9ks.mjs} +1 -1
- package/dist/packem_shared/backfillSqlSearchIndexes-DUB3nz00.mjs +1 -0
- package/dist/packem_shared/column-provisioning-DsVyt-k5.mjs +1 -0
- package/dist/packem_shared/{createSqlCtxDb-CynuXqB2.mjs → createSqlCtxDb-CBGjLZPE.mjs} +1 -1
- package/dist/packem_shared/ctx-db-search-C-Gs6PkL.mjs +1 -0
- package/dist/packem_shared/{ctx-db-search-state-BBPiVWjf.mjs → ctx-db-search-state-CcUMouNm.mjs} +1 -1
- package/dist/packem_shared/decodeBigint-sFl0mLky.mjs +1 -0
- package/dist/packem_shared/{decodeGlobalRow-C0Tg01Ov.mjs → decodeGlobalRow-ChC6aM1T.mjs} +1 -1
- package/dist/packem_shared/{exportSqlGlobalRows-DzCIGW9D.mjs → exportSqlGlobalRows-BMOYQhJf.mjs} +1 -1
- package/dist/packem_shared/{facetSqlGlobalColumn-BPU8EBYc.mjs → facetSqlGlobalColumn-DF3p8q4R.mjs} +1 -1
- package/dist/packem_shared/globalColumnBackfill-DrinZ7s9.mjs +1 -0
- package/dist/packem_shared/runSqlAggregateMigrations-l-lqWvIq.mjs +1 -0
- package/dist/packem_shared/runSqlGlobalTableMigrations-B00G2E1V.mjs +1 -0
- package/dist/packem_shared/{sql-exec-enIOMsv0.mjs → sql-exec-j9zVLMn5.mjs} +1 -1
- package/dist/packem_shared/{value-codec-CbyTgWR3.mjs → value-codec-DhzLXsqv.mjs} +1 -1
- package/package.json +3 -3
- package/dist/packem_shared/backfillSqlSearchIndexes-D6vFITGZ.mjs +0 -1
- package/dist/packem_shared/ctx-db-search-bBDPdaOs.mjs +0 -1
- package/dist/packem_shared/decodeBigint-dy86jtCM.mjs +0 -1
- package/dist/packem_shared/runSqlAggregateMigrations-D5_8KDaC.mjs +0 -1
- package/dist/packem_shared/runSqlGlobalTableMigrations-BARAefvR.mjs +0 -1
package/LICENSE.md
CHANGED
|
@@ -1,108 +1,205 @@
|
|
|
1
|
-
# Functional Source License, Version 1.1, Apache 2.0 Future License
|
|
2
1
|
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
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
|
-
[![
|
|
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]
|
|
@@ -124,11 +124,11 @@ This is an open source project and will always remain free to use. If you think
|
|
|
124
124
|
|
|
125
125
|
## License
|
|
126
126
|
|
|
127
|
-
The Lunora sql-store package is open-sourced software licensed under the [
|
|
127
|
+
The Lunora sql-store package is open-sourced software licensed under the [Apache-2.0][license].
|
|
128
128
|
|
|
129
129
|
<!-- badges -->
|
|
130
130
|
|
|
131
|
-
[license-badge]: https://img.shields.io/badge/license-
|
|
131
|
+
[license-badge]: https://img.shields.io/badge/license-Apache--2.0-blue.svg?style=for-the-badge
|
|
132
132
|
[license]: https://github.com/anolilab/lunora/blob/alpha/LICENSE.md
|
|
133
133
|
[npm-version-badge]: https://img.shields.io/npm/v/@lunora/sql-store?style=for-the-badge
|
|
134
134
|
[npm-version]: https://www.npmjs.com/package/@lunora/sql-store
|
package/dist/index.d.mts
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
import { TableDefinitionLike, ImportConflictMode, SchemaLike, DatabaseWriterLike, ServerDefaultContextLike, CrossShardReadArgs, QueryPage, SchedulerLike, CdcChange, ValidatorLike } from '@lunora/shard-engine';
|
|
2
2
|
import { SqlRunResult, SqlDialect } from "./dialect.mjs";
|
|
3
3
|
export type { SqlExec } from "./dialect.mjs";
|
|
4
|
+
import { SQL } from 'drizzle-orm';
|
|
4
5
|
import { LunoraError } from '@lunora/errors';
|
|
5
|
-
import 'drizzle-orm';
|
|
6
6
|
/**
|
|
7
7
|
* Async SQL surface the D1 ORM needs: `all` for reads, `run` for writes.
|
|
8
8
|
* Satisfied by a `D1Session`/`D1Client` in production and a `node:sqlite`
|
|
@@ -132,6 +132,13 @@ interface ImportGlobalArgs {
|
|
|
132
132
|
* because a trigger can create or delete rows in the table mid-import.
|
|
133
133
|
*/
|
|
134
134
|
declare const importSqlGlobalRows: (writer: DatabaseWriterLike, schema: SchemaLike, dialect: SqlDialect, args: ImportGlobalArgs) => Promise<ImportResult>;
|
|
135
|
+
/**
|
|
136
|
+
* The `UPDATE` that fills the rows a column predates, for a column a SQL migration file adds. It is the one the
|
|
137
|
+
* provisioner writes when it adds the same column itself, so a file that runs first does not leave NULL rows that
|
|
138
|
+
* provisioning would have filled. Undefined when the schema has no such `.global()` field, or its declaration gives no
|
|
139
|
+
* value. Names match without case, as they do in SQL.
|
|
140
|
+
*/
|
|
141
|
+
declare const globalColumnBackfill: (schema: SchemaLike, tableName: string, column: string) => SQL | undefined;
|
|
135
142
|
/** Arm a timer that calls `fire` after `ms`, returning the function that disarms it. Injectable so tests fire it by hand. */
|
|
136
143
|
type QueryTimer = (fire: () => void, ms: number) => () => void;
|
|
137
144
|
/** The bound a `.global()` statement gets when the host names none: past it, the dispatch waiting on it is released. */
|
|
@@ -714,4 +721,4 @@ type ImportGlobalArgs,
|
|
|
714
721
|
* This package is internal: consumers depend on `@lunora/d1` or
|
|
715
722
|
* `@lunora/hyperdrive`, which assemble the concrete dialect and wrap the core.
|
|
716
723
|
*/
|
|
717
|
-
type ImportResult, type QueryTimer, type ReadGlobalTablePageOptions, SEARCH_STATE_TABLE, type SqlCtxDbOptions, type SqlCtxExec, type SqlDialect, SqlQueryTimeoutError, type SqlRunResult, type SqlSearchBackfillResult, backfillSqlSearchIndexes, createSqlCtxDb, decodeBigint, decodeGlobalRow, effectiveColumnKind, exportSqlGlobalRows, facetSqlGlobalColumn, importSqlGlobalRows, listSqlGlobalTables, migrateSearchState, readSqlCdcChangedTables, readSqlCdcChanges, readSqlCdcFloor, readSqlGlobalTablePage, runSqlAggregateMigrations, runSqlCdcMigration, runSqlGlobalTableMigrations, runSqlRankMigrations, runSqlSearchMigrations, selectGlobalTables, sqliteDecode, sqliteEncode, sweepSqlCdcRetention, tryJsonParse };
|
|
724
|
+
type ImportResult, type QueryTimer, type ReadGlobalTablePageOptions, SEARCH_STATE_TABLE, type SqlCtxDbOptions, type SqlCtxExec, type SqlDialect, SqlQueryTimeoutError, type SqlRunResult, type SqlSearchBackfillResult, backfillSqlSearchIndexes, createSqlCtxDb, decodeBigint, decodeGlobalRow, effectiveColumnKind, exportSqlGlobalRows, facetSqlGlobalColumn, globalColumnBackfill, importSqlGlobalRows, listSqlGlobalTables, migrateSearchState, readSqlCdcChangedTables, readSqlCdcChanges, readSqlCdcFloor, readSqlGlobalTablePage, runSqlAggregateMigrations, runSqlCdcMigration, runSqlGlobalTableMigrations, runSqlRankMigrations, runSqlSearchMigrations, selectGlobalTables, sqliteDecode, sqliteEncode, sweepSqlCdcRetention, tryJsonParse };
|
package/dist/index.d.ts
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
import { TableDefinitionLike, ImportConflictMode, SchemaLike, DatabaseWriterLike, ServerDefaultContextLike, CrossShardReadArgs, QueryPage, SchedulerLike, CdcChange, ValidatorLike } from '@lunora/shard-engine';
|
|
2
2
|
import { SqlRunResult, SqlDialect } from "./dialect.js";
|
|
3
3
|
export type { SqlExec } from "./dialect.js";
|
|
4
|
+
import { SQL } from 'drizzle-orm';
|
|
4
5
|
import { LunoraError } from '@lunora/errors';
|
|
5
|
-
import 'drizzle-orm';
|
|
6
6
|
/**
|
|
7
7
|
* Async SQL surface the D1 ORM needs: `all` for reads, `run` for writes.
|
|
8
8
|
* Satisfied by a `D1Session`/`D1Client` in production and a `node:sqlite`
|
|
@@ -132,6 +132,13 @@ interface ImportGlobalArgs {
|
|
|
132
132
|
* because a trigger can create or delete rows in the table mid-import.
|
|
133
133
|
*/
|
|
134
134
|
declare const importSqlGlobalRows: (writer: DatabaseWriterLike, schema: SchemaLike, dialect: SqlDialect, args: ImportGlobalArgs) => Promise<ImportResult>;
|
|
135
|
+
/**
|
|
136
|
+
* The `UPDATE` that fills the rows a column predates, for a column a SQL migration file adds. It is the one the
|
|
137
|
+
* provisioner writes when it adds the same column itself, so a file that runs first does not leave NULL rows that
|
|
138
|
+
* provisioning would have filled. Undefined when the schema has no such `.global()` field, or its declaration gives no
|
|
139
|
+
* value. Names match without case, as they do in SQL.
|
|
140
|
+
*/
|
|
141
|
+
declare const globalColumnBackfill: (schema: SchemaLike, tableName: string, column: string) => SQL | undefined;
|
|
135
142
|
/** Arm a timer that calls `fire` after `ms`, returning the function that disarms it. Injectable so tests fire it by hand. */
|
|
136
143
|
type QueryTimer = (fire: () => void, ms: number) => () => void;
|
|
137
144
|
/** The bound a `.global()` statement gets when the host names none: past it, the dispatch waiting on it is released. */
|
|
@@ -714,4 +721,4 @@ type ImportGlobalArgs,
|
|
|
714
721
|
* This package is internal: consumers depend on `@lunora/d1` or
|
|
715
722
|
* `@lunora/hyperdrive`, which assemble the concrete dialect and wrap the core.
|
|
716
723
|
*/
|
|
717
|
-
type ImportResult, type QueryTimer, type ReadGlobalTablePageOptions, SEARCH_STATE_TABLE, type SqlCtxDbOptions, type SqlCtxExec, type SqlDialect, SqlQueryTimeoutError, type SqlRunResult, type SqlSearchBackfillResult, backfillSqlSearchIndexes, createSqlCtxDb, decodeBigint, decodeGlobalRow, effectiveColumnKind, exportSqlGlobalRows, facetSqlGlobalColumn, importSqlGlobalRows, listSqlGlobalTables, migrateSearchState, readSqlCdcChangedTables, readSqlCdcChanges, readSqlCdcFloor, readSqlGlobalTablePage, runSqlAggregateMigrations, runSqlCdcMigration, runSqlGlobalTableMigrations, runSqlRankMigrations, runSqlSearchMigrations, selectGlobalTables, sqliteDecode, sqliteEncode, sweepSqlCdcRetention, tryJsonParse };
|
|
724
|
+
type ImportResult, type QueryTimer, type ReadGlobalTablePageOptions, SEARCH_STATE_TABLE, type SqlCtxDbOptions, type SqlCtxExec, type SqlDialect, SqlQueryTimeoutError, type SqlRunResult, type SqlSearchBackfillResult, backfillSqlSearchIndexes, createSqlCtxDb, decodeBigint, decodeGlobalRow, effectiveColumnKind, exportSqlGlobalRows, facetSqlGlobalColumn, globalColumnBackfill, importSqlGlobalRows, listSqlGlobalTables, migrateSearchState, readSqlCdcChangedTables, readSqlCdcChanges, readSqlCdcFloor, readSqlGlobalTablePage, runSqlAggregateMigrations, runSqlCdcMigration, runSqlGlobalTableMigrations, runSqlRankMigrations, runSqlSearchMigrations, selectGlobalTables, sqliteDecode, sqliteEncode, sweepSqlCdcRetention, tryJsonParse };
|
package/dist/index.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{exportSqlGlobalRows as
|
|
1
|
+
import{exportSqlGlobalRows as l,importSqlGlobalRows as r,selectGlobalTables as a}from"./packem_shared/exportSqlGlobalRows-BMOYQhJf.mjs";import{g as s}from"./packem_shared/column-provisioning-DsVyt-k5.mjs";import{createSqlCtxDb as i,readSqlCdcChangedTables as n,readSqlCdcChanges as d,readSqlCdcFloor as q,runSqlCdcMigration as c,sweepSqlCdcRetention as m}from"./packem_shared/createSqlCtxDb-CBGjLZPE.mjs";import{runSqlGlobalTableMigrations as f}from"./packem_shared/runSqlGlobalTableMigrations-B00G2E1V.mjs";import{runSqlAggregateMigrations as p,runSqlRankMigrations as x}from"./packem_shared/runSqlAggregateMigrations-l-lqWvIq.mjs";import{b as T,r as u}from"./packem_shared/ctx-db-search-C-Gs6PkL.mjs";import{S as G,m as M}from"./packem_shared/ctx-db-search-state-CcUMouNm.mjs";import{facetSqlGlobalColumn as h,listSqlGlobalTables as A,readSqlGlobalTablePage as _}from"./packem_shared/facetSqlGlobalColumn-DF3p8q4R.mjs";import{DEFAULT_QUERY_TIMEOUT_MS as k,SqlQueryTimeoutError as B}from"./packem_shared/DEFAULT_QUERY_TIMEOUT_MS-D7YkDNaV.mjs";import{d as U,e as y,s as F,a as I,t as L}from"./packem_shared/value-codec-DhzLXsqv.mjs";import{d as Q}from"./packem_shared/sql-exec-j9zVLMn5.mjs";export{k as DEFAULT_QUERY_TIMEOUT_MS,G as SEARCH_STATE_TABLE,B as SqlQueryTimeoutError,T as backfillSqlSearchIndexes,i as createSqlCtxDb,U as decodeBigint,Q as decodeGlobalRow,y as effectiveColumnKind,l as exportSqlGlobalRows,h as facetSqlGlobalColumn,s as globalColumnBackfill,r as importSqlGlobalRows,A as listSqlGlobalTables,M as migrateSearchState,n as readSqlCdcChangedTables,d as readSqlCdcChanges,q as readSqlCdcFloor,_ as readSqlGlobalTablePage,p as runSqlAggregateMigrations,c as runSqlCdcMigration,f as runSqlGlobalTableMigrations,x as runSqlRankMigrations,u as runSqlSearchMigrations,a as selectGlobalTables,F as sqliteDecode,I as sqliteEncode,m as sweepSqlCdcRetention,L as tryJsonParse};
|
package/dist/packem_shared/{SEARCH_STATE_TABLE-CRLusd2n.mjs → SEARCH_STATE_TABLE-DWvn-9ks.mjs}
RENAMED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{S as t,a as S,m as c,r as l,b as i,w as s}from"./ctx-db-search-state-
|
|
1
|
+
import{S as t,a as S,m as c,r as l,b as i,w as s}from"./ctx-db-search-state-CcUMouNm.mjs";import"./sql-exec-j9zVLMn5.mjs";export{t as SEARCH_STATE_TABLE,S as clearSearchBackfillState,c as migrateSearchState,l as readSearchBackfillState,i as readSearchIndexCoverage,s as writeSearchBackfillState};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import"./ctx-db-search-state-CcUMouNm.mjs";import{b as o,c as i,a as s,d as l,r as n}from"./ctx-db-search-C-Gs6PkL.mjs";import"./DEFAULT_QUERY_TIMEOUT_MS-D7YkDNaV.mjs";import"./sql-exec-j9zVLMn5.mjs";export{o as backfillSqlSearchIndexes,i as createSearchSync,s as reconcileSearchRow,l as runSqlSearch,n as runSqlSearchMigrations};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{sql as o}from"drizzle-orm";import{c as y,e as O}from"./value-codec-DhzLXsqv.mjs";import{O as v,a as C,q as p,b as m,z as _,s as g}from"./sql-exec-j9zVLMn5.mjs";const R=new Set(["any","null"]),E=(t,n)=>{const e=n.kindOf(t);return e!==void 0&&R.has(e)||n.nullableOf(t)?!0:e==="union"&&(n.membersOf(t)??[]).some(i=>E(i,n))},d=t=>{const n=t._meta?.inner;return t.kind==="optional"&&n?d(n):t},w=t=>E(t,{kindOf:y,membersOf:n=>d(n)._meta?.members,nullableOf:n=>d(n)._meta?.column?.notNull===!1}),b=(t,n,e=!1)=>n.columnType(O(t),{unique:e||t._meta?.column?.unique===!0}),L=new Set,h=t=>L.has(t)?!1:(L.add(t),!0),c=(t,n)=>{h(t)&&console.warn(`[@lunora/sql-store] ${n}`)},A=(t,n,e,i)=>{h(`backfill:${t}.${n}`)&&console.error(`[@lunora/sql-store] ${e}`,{column:n,error:i,table:t})},U=t=>{const n=t._meta?.column;return n?.defaultFn?n.defaultFn():n&&"defaultValue"in n?n.defaultValue:void 0},q=(t,n,e)=>e._meta?.column?.unique===!0||t.indexes.some(i=>i.unique===!0&&i.fields.includes(n)),S=(t,n,e,i)=>{if(i.kind==="optional"||w(i))return;const a=i._meta?.column;if(q(n,e,i))return{reason:"is unique, so one default cannot be written to every row"};if(a?.defaultFn===void 0&&a?.defaultValue===void 0)return{reason:"has no default"};let r;const u=()=>{try{const s=U(i);if(s===void 0){c(`backfill:${t}.${e}`,`the default of "${t}.${e}" produced no value, so rows written before it read NULL. Run UPDATE "${t}" SET "${e}" = … WHERE "${e}" IS NULL.`);return}return o`UPDATE ${o.identifier(t)} SET ${o.identifier(e)} = ${g(n,e,s)} WHERE ${o.identifier(e)} IS NULL`}catch(s){A(t,e,`could not compute the default of "${t}.${e}" (${s instanceof Error?s.message:String(s)}); rows written before it read NULL. Run UPDATE "${t}" SET "${e}" = … WHERE "${e}" IS NULL.`,s);return}};return{build:()=>(r??={query:u()},r.query)}},k=async(t,n,e,i,a)=>{try{await m(t,n,a)}catch(r){A(e,i,`could not backfill "${e}.${i}" from its default (${r instanceof Error?r.message:String(r)}); rows written before it read NULL. Run UPDATE "${e}" SET "${i}" = … WHERE "${i}" IS NULL.`,r)}},F=(t,n,e)=>{const i=Object.keys(t.tables).find(s=>s.toLowerCase()===n.toLowerCase()),a=i===void 0?void 0:t.tables[i];if(i===void 0||a?.shardMode?.kind!=="global")return;const r=Object.entries(a.shape).find(([s])=>s.toLowerCase()===e.toLowerCase());if(r?.[1]._meta?.column===void 0)return;const u=S(i,a,r[0],r[1]);return u!==void 0&&"build"in u?u.build():void 0},D=(t,n)=>[[v,n.companionTypes.integer],...Object.entries(t.shape).filter(([,e])=>e._meta?.column!==void 0).map(([e,i])=>[e,b(i,n),i])],$=async(t,n,e,i)=>{try{return await p(t,n,o`SELECT ${o.join(i.map(r=>_("t",r)),o`, `)} FROM ${o.identifier(e)} AS ${o.identifier("t")} LIMIT 0`),!0}catch{return!1}},T=async(t,n,e,i,a,r)=>{if(await $(t,n,e,[i]))return"present";const u=o`ALTER TABLE ${o.identifier(e)} ADD COLUMN ${o.identifier(i)} ${o.raw(a)}`,s=r?.();try{return await C(t,n,s===void 0?[u]:[u,s]),s===void 0?"added":"filled"}catch(l){if(await $(t,n,e,[i]))return"raced";if(s===void 0)throw l}return T(t,n,e,i,a)},I=async(t,n,e,i,a,r,u)=>{const s=u===void 0?void 0:S(n,e,a,u),l=await T(t,i,n,a,r,s!==void 0&&"build"in s?s.build:void 0);if(s===void 0||l==="present"||l==="filled")return;if("reason"in s){l==="added"&&c(`backfill:${n}.${a}`,`"${n}.${a}" was added as a required field that ${s.reason}, so rows written before it read NULL. Backfill it with a migration (UPDATE "${n}" SET "${a}" = … WHERE "${a}" IS NULL).`);return}const f=s.build();f!==void 0&&await k(t,i,n,a,f)},H=async(t,n,e,i)=>{const a=D(e,i);if(!await $(t,i,n,a.map(([r])=>r)))for(const[r,u,s]of a)await I(t,n,e,i,r,u,s)},M=(t,n,e)=>{const i=typeof e.charset=="string"?` CHARACTER SET ${e.charset} COLLATE ${String(e.collation)}`:"";return`ALTER TABLE \`${t}\` MODIFY COLUMN \`${n}\` ${String(e.type)}${i} NULL`},P=async(t,n,e,i)=>{if(i.name==="sqlite")return;const a=Object.keys(e.shape).filter(r=>{const u=e.shape[r];return u._meta?.column?.notNull===!0&&u.kind!=="optional"&&w(u)});if(a.length!==0)try{const r=i.name==="postgres"?o`column_name AS ${o.identifier("name")}`:o`column_name AS ${o.identifier("name")}, column_type AS ${o.identifier("type")}, character_set_name AS ${o.identifier("charset")}, collation_name AS ${o.identifier("collation")}`,u=i.name==="postgres"?o`table_schema = ANY (current_schemas(false))`:o`table_schema = DATABASE()`,s=await p(t,i,o`SELECT ${r} FROM information_schema.columns WHERE ${u} AND table_name = ${n} AND is_nullable = 'NO' AND column_name IN (${o.join(a.map(l=>o`${l}`),o`, `)})`);for(const l of s){const f=String(l.name);if(i.name==="postgres"){await m(t,i,o`ALTER TABLE ${o.identifier(n)} ALTER COLUMN ${o.identifier(f)} DROP NOT NULL`);continue}c(`${n}.${f}`,`"${n}"."${f}" accepts null in the schema but its column is NOT NULL, so writing null there fails. Relaxing it on MySQL can rebuild the table, so it is not done at startup; run this once, in a maintenance window: ${M(n,f,l)};`)}}catch(r){c(`${n}:relax-failed`,`could not relax NOT NULL on the null-accepting columns of "${n}" (${a.join(", ")}): ${r instanceof Error?r.message:String(r)}. Writing null to them fails until the constraint is dropped by hand.`)}};export{b as a,H as b,T as c,F as g,P as r,w as v,D as w};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{LunoraError as g}from"@lunora/errors";import{m as mn,q as Sn}from"./ctx-db-search-state-
|
|
1
|
+
import{LunoraError as g}from"@lunora/errors";import{m as mn,q as Sn}from"./ctx-db-search-state-CcUMouNm.mjs";import{c as gn,r as Tn,a as vn,A as In,C as An,R as Cn,u as Ln,d as bn,I as Mn,x as Nn,e as On}from"./ctx-db-search-C-Gs6PkL.mjs";import{throwingScheduler as qn,describeRelationWrites as kn,CDC_LOG_TABLE as W,cdcForkedError as Dn,cursorBelowRetainedFloor as Bn,cdcTrimmedError as Wn,serverInList as Fn,assertNoExplicitUndefined as Ve,hasTrigger as xn,runRowValidators as Ye,assertFlatPredicate as St,mergeWhere as x,rankTableName as Ee,sortColumnName as me,resolveRankPartition as gt,encodePartitionKey as Oe,resolveRankSeekTuple as Un,RANK_TIEBREAK as Te,CountRlsUnsupportedError as Tt,compileWhereSql as ee,ConflictError as ne,patchDependsOnRow as Pn,normalizeIdStructurally as Hn,applyInsertDefaults as Kn,assertValidClientId as jn,assertStorableRowId as Gn,aggregateSqlFunction as pe,softDeleteScope as qe,findManyPage as Vn,resolveWith as Yn,relationHooks as Xn,applySelect as Qn,NotFoundError as zn,applyOnDelete as Jn,normalizeCountArgument as Zn,selectIndexForCount as ei,encodeAggregateKey as te,aggregateTableName as ae,selectIndexForAggregate as ti,readAggregateValue as Xe,runTriggers as ni,matchesRankStaticWhere as vt,nullsOrderSuffix as It,nullsFirstOf as At,rankPivotConditionSql as Gt,CURSOR_PREFIX as ii,resolvePatch as oi,stripReservedPatchFields as ri,assertPatchAllowed as si,resolveRelationPredicates as ai,selectIndexForGroupBy as ci,composeReadPredicate as di,fanOutScalarCounts as li,matchesStaticWhere as Qe,coerceAggregateNumber as ze,whereOfFilter as ui,isPushableWhere as fi,tiebreakDirectionFor as wi,foldAggregateTally as Ct,CDC_LOG_TABLE_SEQ_INDEX as hi,NotUniqueError as $i,WORKERD_SQLITE_LIMITS as _i,unionAll as Ei}from"@lunora/shard-engine";import{parseWire as pi,needsWireEncoding as Vt,encodeWire as Yt,decodeWire as yi}from"@lunora/wire";import{sql as e,SQL as Ri}from"drizzle-orm";import{p as Lt,g as bt,q as b,b as j,c as Xt,i as mi,h as Si,j as gi,k as Q,s as ce,e as K,l as Mt,t as Ti,m as Je,n as Be,o as at,O as ye,u as Nt,a as Ot,v as qt,w as kt,x as vi,B as Ze,y as Dt,f as Bt,M as Ii}from"./sql-exec-j9zVLMn5.mjs";import{d as No}from"./sql-exec-j9zVLMn5.mjs";import{runSqlGlobalTableMigrations as Ai}from"./runSqlGlobalTableMigrations-B00G2E1V.mjs";import{runSqlAggregateMigrations as Ci,runSqlRankMigrations as Li}from"./runSqlAggregateMigrations-l-lqWvIq.mjs";import{a as Re}from"./post-commit-error-hh-zQyjO.mjs";import{withQueryTimeout as bi,DEFAULT_QUERY_TIMEOUT_MS as Mi,abandonedWork as et,SqlQueryTimeoutError as Ni}from"./DEFAULT_QUERY_TIMEOUT_MS-D7YkDNaV.mjs";import{s as Qt,e as ct}from"./value-codec-DhzLXsqv.mjs";const Wt=50,Oi=(r,a={})=>{const f=a.maxBatch??Wt,_=Number.isInteger(f)&&f>0?f:Wt,l=new Map;let E=!1;const c=async(M,T)=>{const v=[...T.keys()];for(let A=0;A<v.length;A+=_){const N=v.slice(A,A+_);try{const B=await r(M,N);for(const G of N){const z=B.get(G);for(const ie of T.get(G)??[])ie.resolve(z)}}catch(B){for(const G of N)for(const z of T.get(G)??[])z.reject(B)}}},q=()=>{E=!1;const M=[...l.entries()];l.clear();for(const[T,v]of M)c(T,v).catch(()=>{})};return{async load(M,T){return new Promise((v,A)=>{let N=l.get(M);N||(N=new Map,l.set(M,N));const B=N.get(T);B?B.push({reject:A,resolve:v}):N.set(T,[{reject:A,resolve:v}]),E||(E=!0,queueMicrotask(q))})}}},qi=new Set(["_id","id"]),ki=r=>{throw new g("INTERNAL",`no ORDER BY NULL placement for dialect "${String(r)}"`)},zt=(r,a)=>{const f=a.direction==="desc"?"DESC":"ASC",_=a.nullable===!0,l=E=>e`${Be(r,a.field)} ${e.raw(`${f}${E}`)}`;switch(r.name){case"mysql":{const E=l("");return!_||a.nulls===void 0?[E]:[e`(${Be(r,a.field)} IS NULL) ${e.raw(a.nulls==="first"?"DESC":"ASC")}`,E]}case"postgres":return[l(_?It(At(a)):"")];case"sqlite":return[l(_&&a.nulls!==void 0?It(At(a)):"")];default:return ki(r.name)}},Di=(r,a)=>{const f=r.flatMap(_=>zt(a,_));if(!r.some(_=>qi.has(_.field))){const _=wi(r);f.push(e`${K("id")} ${e.raw(_==="desc"?"DESC":"ASC")}`)}return e.join(f,e`, `)},Ft=50,Bi=r=>{const a=r.detail??r["QUERY PLAN"];return typeof a=="string"?a:Object.values(r).map(String).join(" | ")},tt=(r,a,f,_)=>{for(const[l,E]of Ti(r)){if(E.serverDefault){l in a&&(f[l]=E.serverDefault({auth:_}));continue}E.onUpdateFn&&!(l in a)&&(f[l]=E.onUpdateFn())}},Wi=r=>r.shardMode===void 0||r.shardMode.kind==="global",ue=r=>r==null?null:Number(r),Fi=(r,a,f)=>f.map(_=>{const l={};for(const E of a){const c=r.shape[E];l[E]=Qt(_[E]??null,c&&ct(c))}return{key:l,value:ue(_.value)}}),xi=(r,a,f)=>[...r.partitionBy??[],...r.sortBy.map(l=>l.field),...r.where?Object.keys(r.where):[]].every(l=>qt(a,l)===qt(f,l)),Jt=r=>r.length===1?r[0]:e`(${e.join(r,e` AND `)})`,fe=r=>e.join(r.map(a=>e`${e.identifier(a)}`),e`, `),Se=r=>e.join(r.map(a=>e`${a}`),e`, `),nt=(r,a)=>{if(r==="postgres"){for(const[f,_]of Object.entries(a))if(typeof _=="string"&&_.includes("\0"))throw new g("BAD_REQUEST",`"${f}" holds a NUL character (U+0000), which a Postgres text column cannot store`)}},We=r=>r instanceof ArrayBuffer?new Uint8Array(r):Array.isArray(r)?Uint8Array.from(r):r,Ui=(r,a,f,_,l)=>{const E=[];for(let c=0;c<f.length+1;c+=1){const q=f[c],M=a.sortBy[c],T=c<f.length&&q!==void 0&&M!==void 0,v=M?.direction==="desc"?"desc":"asc",A=T?Gt(q,We(_[q]),v,!1):e`${e.identifier(Te)} < ${l}`;if(A===void 0)continue;const N=f.slice(0,c).map(B=>at(r,e`${e.identifier(B)}`,We(_[B])));N.push(A),E.push(Jt(N))}return E.length>0?e.join(E,e` OR `):e`1 = 0`},Pi=(r,a,f)=>{if(f.length!==a.length)return;const _=[];for(const[l,E]of a.entries()){const c=Gt(E.column,We(f[l]),E.direction,!0);if(c===void 0)continue;const q=[];for(let M=0;M<l;M+=1){const T=a[M];T!==void 0&&q.push(at(r,e`${e.identifier(T.column)}`,We(f[M])))}q.push(c),_.push(Jt(q))}return _.length===0?e`(1 = 0)`:e`(${e.join(_,e` OR `)})`},Hi=(r,a)=>{if(r.sortBy.length===0)throw new g("INTERNAL",`rankIndex "${r.name}" requires at least one "sortBy" column for stable pagination`);const f=[{column:"__partition__",direction:"asc",nullable:!1}];for(const[_,l]of r.sortBy.entries())f.push({column:a[_]??me(_),direction:l.direction,nullable:!0});return f.push({column:Te,direction:"asc",nullable:!1}),f},Ki=async(r,a,f,_,l)=>{const c=[];for(let v=0;v<l.length;v+=50)c.push(l.slice(v,v+50));const q=await Promise.all(c.map(async v=>b(r,a,e`SELECT * FROM ${e.identifier(_)} WHERE ${e.identifier("id")} IN (${Se(v)})`))),M=new Map;for(const v of q)for(const A of v)M.set(A.id,A);const T=[];for(const v of l){const A=Q(f,M.get(v));A&&T.push(A)}return T},ji=r=>{const a=r.map(E=>Qt(E,"bytes")),f=JSON.stringify(Vt(a)?Yt(a):a),_=new TextEncoder().encode(f);let l="";for(const E of _)l+=String.fromCodePoint(E);return ii+btoa(l)},Zt=r=>{if(r===void 0)return!1;const a=ct(r);return a==="any"||a==="bigint"||a==="from"||a==="union"},rt=(r,a,f)=>{if(Zt(r.shape[a]))throw new g("BAD_REQUEST",`${f}: "${a}" may hold an order-preserving key rather than a value SQL can reduce or group — declare an aggregateIndex covering this (by, field, op) so the maintained companion answers it instead (its running total is a REAL, so it stays exact only while the total is inside 2^53)`)},Gi=(r,a,f,_)=>{for(const l of f)rt(r,l,`groupBy(${a}, { by: [..."${l}"] })`);_.field!==void 0&&rt(r,_.field,`groupBy(${a}, { agg: { op: "${_.op}", field: "${_.field}" } })`)},st="__cdc_sweep",ke="__cdc_log_ts",en="global",Vi=6e4,Yi=1e4,Xi=3e4;let xt=0;const Qi=async(r,a)=>{const{autoincrementPrimaryKey:f,key:_,real:l,text:E}=a.companionTypes;await j(r,a,e`CREATE TABLE IF NOT EXISTS ${e.identifier(W)} (${e.identifier("seq")} ${e.raw(f)}, ${e.identifier("ts")} ${e.raw(l)} NOT NULL, ${e.identifier("table")} ${e.raw(_)} NOT NULL, ${e.identifier("id")} ${e.raw(_)} NOT NULL, ${e.identifier("op")} ${e.raw(_)} NOT NULL, ${e.identifier("doc")} ${e.raw(E)})`);const c=a.indexKeyPrefix?.("string");await Xt(r,a,{columns:e`${c===void 0?e`${e.identifier("table")}`:e`${e.identifier("table")}(${e.raw(String(c))})`}, ${e.identifier("seq")}`,name:hi,table:W,unique:!1}),await j(r,a,e`CREATE TABLE IF NOT EXISTS ${e.identifier(st)} (${e.identifier("id")} ${e.raw(_)} NOT NULL PRIMARY KEY, ${e.identifier("lease_until")} ${e.raw(l)} NOT NULL)`),await j(r,a,e`INSERT INTO ${e.identifier(st)} (${e.identifier("id")}, ${e.identifier("lease_until")}) VALUES (${en}, ${0}) ${a.name==="mysql"?e`ON DUPLICATE KEY UPDATE ${e.identifier("id")} = ${e.identifier("id")}`:e`ON CONFLICT(${e.identifier("id")}) DO NOTHING`}`)},zi=async(r,a,f)=>{const _=e`UPDATE ${e.identifier(st)} SET ${e.identifier("lease_until")} = ${f+Vi} WHERE ${e.identifier("id")} = ${en} AND ${e.identifier("lease_until")} <= ${f}`;if(a.supportsReturning)return(await b(r,a,e`${_} RETURNING ${e.identifier("id")}`)).length>0;const l=await j(r,a,_);return(a.affectedRows?a.affectedRows(l??{rowsAffected:0}):0)>0},Ji=async(r,a,f,_)=>{if(!await zi(r,a,_))return;const l=_-f;let E=!0;try{const c=await mi(r,a,W,ke);c!=="valid"&&(c==="invalid"&&await Si(r,a,W,ke),await Xt(r,a,{columns:e`${e.identifier("ts")}`,concurrently:!0,name:ke,table:W,unique:!1}))}catch(c){E=!1,console.warn(`[@lunora/sql-store] changelog retention could not build "${ke}"; sweeping without it.`,c)}E&&(await b(r,a,e`SELECT 1 AS ${e.identifier("hit")} FROM ${e.identifier(W)} WHERE ${e.identifier("ts")} <= ${l} LIMIT 1`)).length===0||await j(r,a,e`
|
|
2
2
|
DELETE FROM ${e.identifier(W)} WHERE ${e.identifier("seq")} IN (
|
|
3
3
|
SELECT ${e.identifier("seq")} FROM (
|
|
4
4
|
SELECT ${e.identifier("seq")} FROM ${e.identifier(W)} WHERE +${e.identifier("ts")} <= ${l} ORDER BY ${e.identifier("seq")} ASC LIMIT ${e.raw(String(Yi))}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraError as p}from"@lunora/errors";import{q as U,c as qt,m as Ft,r as C,a as Ut,l as q,w as F,b as kt}from"./ctx-db-search-state-CcUMouNm.mjs";import{ftsUnmappedPage as bt,groupUnmappedRows as Ht,ftsWriteDocument as mt,ftsPurgeDocument as ht,ftsCompanionDdl as Pt,unionAll as Bt,ftsRowidMapName as Wt}from"@lunora/shard-engine";import{sql as r}from"drizzle-orm";import{abandonedWork as jt}from"./DEFAULT_QUERY_TIMEOUT_MS-D7YkDNaV.mjs";import{O as xt,q as h,o as Kt,k as X,a as N,i as L,c as J,h as v,b as y,l as pt,e as ot,m as Gt,r as Yt,y as Vt}from"./sql-exec-j9zVLMn5.mjs";const Qt=n=>{const t=atob(n),e=Uint8Array.from(t,i=>i.codePointAt(0)??0);return new TextDecoder().decode(e)},Xt=()=>new p("INVALID_CURSOR","invalid cursor"),st=16,at=8,T=1024,k=(n,t)=>t.query(n),Jt=(n,t)=>{if(!t)return{exact:!0,lower:n,upper:n};const e=[...n].at(-1)??"",i=(e.codePointAt(0)??0)+1;if(i>=55296&&i<=57343||i>1114111)return{exact:!0,lower:n,upper:n};const o=n.slice(0,n.length-e.length);return{exact:!1,lower:n,upper:o+String.fromCodePoint(i)}},Dn=(n,t,e)=>{const i={eq:(o,s)=>{if(!n.definition.filterFields?.includes(o))throw new p("INTERNAL",`field "${o}" is not a filter field of search index "${n.indexName}" on table "${t}"`);if(n.filters.length>=at)throw new p("BAD_REQUEST",`search index "${n.indexName}" on table "${t}": at most ${String(at)} .eq() filters are supported per search query`);return n.filters.push({field:o,value:s}),i},search:(o,s)=>{const a=n;if(o!==a.definition.field)throw new p("INTERNAL",`search index "${a.indexName}" on table "${t}" indexes "${a.definition.field}", not "${o}"`);const c=k(s,e).length;if(c>st)throw new p("BAD_REQUEST",`search index "${a.indexName}" on table "${t}": at most ${String(st)} search terms are supported (got ${String(c)})`);return a.field=o,a.query=s,a.hasQuery=!0,i}};return i},qn=n=>{if(n.length>T)throw new p("BAD_REQUEST",`more than ${String(T)} documents match this search — narrow it with filters or read it a page at a time with .paginate()`)},Fn=n=>Math.min(n.offset+n.numItems+1,T),zt=n=>btoa(`search:${String(n)}`),Zt=n=>{let t;try{t=Qt(n)}catch{return}if(!t.startsWith("search:"))return;const e=Number(t.slice(7));return Number.isInteger(e)&&e>=0?e:void 0},Un=n=>{if(typeof n.endCursor=="string")throw new p("BAD_REQUEST","bounded (endCursor) pagination is not supported on search queries — relevance order has no stable range boundary");if(!Number.isFinite(n.numItems))throw new p("BAD_REQUEST",`search pagination needs a finite numItems, got ${String(n.numItems)}`);const t=Math.max(0,Math.floor(n.numItems)),e=n.cursor?Zt(n.cursor):0;if(e===void 0)throw Xt();if(e+t>=T)throw new p("BAD_REQUEST",`search pagination reaches the ${String(T)}-document limit (offset ${String(e)} + ${String(t)} requested) — a page must end below the cap so the probe row that answers \`hasMore\` still fits: retry with numItems ${String(Math.max(1,T-e-1))} or fewer, or narrow the query or the filters instead`);return{numItems:t,offset:e}},kn=(n,t)=>{const e=t.offset+t.numItems,i=t.numItems>0&&n.length>e;return{continueCursor:i?zt(e):null,isDone:!i,page:n.slice(t.offset,e)}},bn=n=>{if(n===void 0)return T+1;if(!Number.isFinite(n))return T;const t=Math.max(0,Math.floor(n));if(t>T)throw new p("BAD_REQUEST",`search returns at most ${String(T)} documents (asked for ${String(t)}) — narrow the query or paginate instead`);return t},tn=(n,t)=>{if(!t.includes("."))return n[t];let e=n;for(const i of t.split(".")){if(e===null||typeof e!="object"||Array.isArray(e))return;e=e[i]}return e},b=(n,t)=>`${n}__fts_${t}`,l="__id__",g="__token__",A="__n__",nn=1e3,en=(n,t)=>t.document(n),G=(n,t)=>tn(n,t),rn=n=>typeof n=="string"?n:n==null?"":typeof n=="number"||typeof n=="bigint"||typeof n=="boolean"?String(n):JSON.stringify(n)??"",on=(n,t,e)=>n!==void 0&&t!==void 0&&G(n,e.field)===G(t,e.field),gt=(n,t)=>en(rn(G(n,t.field)),U(t.language)).slice(0,nn),z=(n,t)=>gt(n,t).join(" "),yt=(n,t)=>{const e=new Map;for(const i of gt(n,t))e.set(i,(e.get(i)??0)+1);return e},Tt=[xt,"_creationTime"],ct=50,d=(n,t)=>r`${r.identifier(n)}.${r.identifier(t)}`,M=(n,t,e)=>r`DELETE FROM ${r.identifier(n)} WHERE ${d(n,l)} = ${t}${e===void 0?r``:r` AND ${e}`}`,Rt=(n,{row:t,table:e})=>{const i=Tt.map(o=>r` AND ${Kt(n.name,d(e,o),t[o]??null)}`);return r`SELECT 1 FROM ${r.identifier(e)} WHERE ${d(e,"id")} = ${t.id}${r.join(i)}${n.name==="postgres"?r` FOR SHARE`:r``}`},D=(n,t)=>r`EXISTS (${Rt(n,t)})`,H=(n,t)=>r`NOT EXISTS (SELECT 1 FROM ${r.identifier(n)} WHERE ${d(n,"id")} = ${t})`,_t=(n,t,e,i)=>i===void 0?H(t,e):D(n,{row:i,table:t}),P=async(n,t,e,i)=>{const o=new Map;for(let s=0;s<i.length;s+=ct){const a=i.slice(s,s+ct),c=await h(n,t,r`SELECT * FROM ${r.identifier(e)} WHERE ${d(e,"id")} IN (${r.join(a.map(f=>r`${f}`),r`, `)})`);for(const f of c)o.set(String(f.id),f)}return o},Y=(n,t,e)=>n.name==="mysql"?r`${r.identifier(t)}(${r.raw(String(e))})`:n.textPatternOperatorClass===void 0?r`${r.identifier(t)}`:r`${r.identifier(t)} ${r.raw(n.textPatternOperatorClass)}`,Z=512,tt=(n,t)=>({columns:r`${Y(n,g,256)}, ${Y(n,l,Z)}`,concurrently:!0,name:`${t}__unique`,table:t,unique:!0}),x=n=>r`${n} COLLATE utf8mb4_0900_bin`,K=(n,t)=>{const e=JSON.stringify(t.map(([i,o])=>({o,t:i})));switch(n.name){case"mysql":return r`JSON_TABLE(${e}, '$[*]' COLUMNS (${r.identifier("t")} VARCHAR(256) PATH '$.t', ${r.identifier("o")} INT PATH '$.o')) AS ${r.identifier("j")}`;case"postgres":return r`json_to_recordset(${e}::text::json) AS ${r.identifier("j")}(${r.identifier("t")} text, ${r.identifier("o")} integer)`;default:return r`(SELECT json_extract(${d("e","value")}, '$.t') AS ${r.identifier("t")}, json_extract(${d("e","value")}, '$.o') AS ${r.identifier("o")} FROM json_each(${e}) AS ${r.identifier("e")}) AS ${r.identifier("j")}`}},Ot=(n,t,e,i,o)=>{const s=r.join([g,l,A].map(c=>r.identifier(c)),r`, `),a=c=>r`INSERT INTO ${r.identifier(t)} (${s}) SELECT ${d("j","t")}, ${e}, ${d("j","o")} FROM ${K(n,i)} WHERE ${c}`;switch(n.name){case"mysql":{const c=D(n,o),f=d(t,g),w=r.identifier("held");return[r`${a(r`${c} AND NOT EXISTS (SELECT 1 FROM ${r.identifier(t)} AS ${w} WHERE ${d("held",l)} = ${e} AND ${d("held",g)} = ${x(d("j","t"))})`)} ON DUPLICATE KEY UPDATE ${d(t,A)} = ${d(t,A)}`,r`UPDATE ${r.identifier(t)} JOIN ${K(n,i)} ON ${f} = ${x(d("j","t"))} SET ${d(t,A)} = ${d("j","o")} WHERE ${d(t,l)} = ${e} AND ${c}`,r`DELETE FROM ${r.identifier(t)} WHERE ${d(t,l)} = ${e} AND ${c} AND ${f} NOT IN (SELECT ${x(d("j","t"))} FROM ${K(n,i)})`]}case"postgres":{const c=r.identifier("__source__"),f=r.identifier("__purged__"),w=r`EXISTS (SELECT 1 FROM ${c})`;return[r`WITH ${c} AS (${Rt(n,o)}), ${f} AS (${M(t,e,w)} RETURNING 1) ${a(r`${w} AND (SELECT COUNT(*) FROM ${f}) >= 0`)} ON CONFLICT DO NOTHING`]}default:{const c=D(n,o);return[M(t,e,c),r`${a(c)} ON CONFLICT DO NOTHING`]}}},At={uniqueKeyMissing:!1,unmappedSkipped:0},ft=new Set,ut=(n,t)=>{ft.has(n)||(ft.add(n),console.warn(`[@lunora/sql-store] ${t}`))},dt=100,$t=3,V=async(n,t,e,i=0)=>{const{companion:o,definition:s,index:a,tableName:c}=e,f={done:!0,last:i,left:0};if((await h(n,t,t.tableExists(c))).length===0)return f;const u=await h(n,t,bt(o,dt,i));if(u.length===0)return f;const S=Math.max(...u.map(O=>Number(O.rowid))),E=Ht(u),m=await P(n,t,c,[...E.keys()]),$=[];for(const[O,et]of E){const j=m.get(O),rt=j===void 0?void 0:X(s,j),it=_t(t,c,O,j);$.push(...rt?mt(o,O,z(rt,a),{guard:it,unmappedRowids:et}):ht(o,O,{guard:it,unmappedRowids:et}))}await N(n,t,$);const _=await h(n,t,r`SELECT COUNT(*) AS ${r.identifier("n")} FROM ${r.identifier(o)} WHERE ${d(o,"rowid")} > ${Math.max(0,i)} AND ${d(o,"rowid")} <= ${S}`);return{done:u.length<dt,last:S,left:Number(_[0]?.n??0)}},sn=async(n,t,e)=>{let i=0,o=0;for(;;){let s=await V(n,t,e,i);for(let a=1;s.left>0&&a<$t;a+=1)s=await V(n,t,e,i);if(s.left>0&&(o+=s.left,console.warn(`[@lunora/sql-store] search migration of "${e.companion}": ${String(s.left)} row(s) lost every one of ${String($t)} attempts to a concurrent write and were left for a later pass.`)),s.done)return o;i=s.last}},an=async(n,t,e,i)=>i==="step"?(await V(n,t,e),At):{uniqueKeyMissing:!1,unmappedSkipped:await sn(n,t,e)},Q=n=>`${n}__btree`,cn=async(n,t,e)=>{const i=tt(t,e),o=await L(n,t,e,i.name);if(o!=="valid"){if(o==="absent"&&(await h(n,t,r`SELECT 1 AS ${r.identifier("present")} FROM ${r.identifier(e)} LIMIT 1`)).length===0)try{await J(n,t,{...i,concurrently:!1}),await v(n,t,e,Q(e));return}catch(a){if(await L(n,t,e,i.name).catch(()=>{})==="valid")return;ut(`${e}:empty`,`search companion "${e}": adding its unique key failed (${String(a)}); run backfillSqlSearchIndexes.`);return}ut(`${e}:missing`,`search companion "${e}" has no usable unique key, so two backfills racing over one row can index it twice. Run backfillSqlSearchIndexes, which adds it.`)}},fn=async(n,t,e)=>{const i=d(e,l),o=d(e,g);return(await h(n,t,r`SELECT ${i} AS ${r.identifier("id")}, ${o} AS ${r.identifier("token")}, COUNT(*) AS ${r.identifier("n")} FROM ${r.identifier(e)} GROUP BY ${i}, ${o} HAVING COUNT(*) > 1`)).map(a=>({count:Number(a.n),id:String(a.id),token:String(a.token)}))},un=(n,t,{count:e,id:i,token:o})=>{const s=r`${d(t,l)} = ${i} AND ${d(t,g)} = ${o}`;switch(n.name){case"mysql":return r`DELETE FROM ${r.identifier(t)} WHERE ${s} LIMIT ${r.raw(String(e-1))}`;case"postgres":return r`DELETE FROM ${r.identifier(t)} WHERE ctid = ANY (ARRAY(SELECT ctid FROM ${r.identifier(t)} WHERE ${s} OFFSET 1))`;default:return r`DELETE FROM ${r.identifier(t)} WHERE rowid IN (SELECT rowid FROM ${r.identifier(t)} WHERE ${s} LIMIT -1 OFFSET 1)`}},dn=async(n,t,e,i)=>{const{companion:o,definition:s,index:a,tableName:c}=e;for(const u of i)await y(n,t,un(t,o,u));const f=[...new Set(i.map(u=>u.id))],w=await P(n,t,c,f);for(const u of f){const S=w.get(u),E=S===void 0?void 0:X(s,S);if(S!==void 0&&E){const m=[...yt(E,a)];await N(n,t,Ot(t,o,u,m,{row:S,table:c}));continue}await y(n,t,M(o,u,_t(t,c,u,S)))}},$n=async(n,t,e)=>t.name!=="mysql"?"":(await h(n,t,r`SELECT COLUMN_NAME AS ${r.identifier("name")}, COLLATION_NAME AS ${r.identifier("collation")} FROM information_schema.columns WHERE table_schema = DATABASE() AND table_name = ${e} AND COLUMN_NAME IN (${g}, ${l})`)).filter(o=>!String(o.collation).endsWith("_bin")).map(o=>` Its ${String(o.name)} column uses ${String(o.collation)}, which treats values differing only in case or accents as one; convert it with ALTER TABLE \`${e}\` MODIFY \`${String(o.name)}\` VARCHAR(768) COLLATE utf8mb4_0900_bin NOT NULL.`).join(""),wn=async(n,t,e)=>{if(t.name!=="mysql")return 0;const i=d(e,l),o=await h(n,t,r`SELECT COUNT(*) AS ${r.identifier("n")} FROM (SELECT 1 AS ${r.identifier("x")} FROM ${r.identifier(e)} GROUP BY LEFT(${i}, ${r.raw(String(Z))}), ${d(e,g)} HAVING COUNT(DISTINCT ${i}) > 1) AS ${r.identifier("shared")}`);return Number(o[0]?.n??0)},Sn=async(n,t,e)=>{const i=tt(t,e),o=await L(n,t,e,i.name);if(o==="valid")return"valid";o==="invalid"&&await v(n,t,e,i.name);try{return await J(n,t,i),"built"}catch(s){const a=await L(n,t,e,i.name);if(a==="valid")return"valid";if(a==="invalid"&&await v(n,t,e,i.name),!t.isUniqueViolation(s))throw s;return"refused"}},wt=3,ln=async(n,t,e)=>{const{companion:i}=e,o=await $n(n,t,i);let s="";o!==""&&console.warn(`[@lunora/sql-store] search companion "${i}" folds case and accents in its unique key.${o}`);for(let a=0;a<wt;a+=1){const c=await Sn(n,t,i);if(c==="valid")return await v(n,t,i,Q(i)),!0;if(c==="refused"){const f=await fn(n,t,i);if(f.length>0)await dn(n,t,e,f);else{const w=await wn(n,t,i);s=w>0?` ${String(w)} token(s) are held by document ids that agree on their first ${String(Z)} characters, which the key cannot tell apart; shorten those ids.`:o}}}return await L(n,t,i,tt(t,i).name)==="valid"?(await v(n,t,i,Q(i)),!0):(console.warn(`[@lunora/sql-store] search companion "${i}" still has no unique key after ${String(wt)} attempts: writes keep working, but two backfills racing over one row can index it twice.${s}`),!1)},En=async(n,t,e,i)=>i==="step"?At:{uniqueKeyMissing:!await ln(n,t,e),unmappedSkipped:0},mn=(n,t)=>t?r`${r.identifier(g)} LIKE ${`${n}%`}`:r`${r.identifier(g)} = ${n}`,Nt=(n,t)=>{const e=t.filters.map(i=>r`m.${ot(i.field)} = ${Gt(i.value)}`);return n.softDeleteMode&&e.push(r`m.${ot(n.softDeleteMode.field)} IS NULL`),t.scope!==void 0&&e.push(r`(${t.scope})`),e},It=async(n,t,e,i,o,s,a)=>{const c=Nt(e,o);let f=r`SELECT m.* FROM (${a}) s JOIN ${r.identifier(i)} m ON m.${r.identifier("id")} = s.${r.identifier(l)}`;return c.length>0&&(f=r`${f} WHERE ${r.join(c,r` AND `)}`),f=r`${f} ORDER BY s.${r.identifier("__score__")} DESC, m.${r.identifier("_creationTime")} DESC, m.${r.identifier("id")} ASC LIMIT ${r.raw(String(s))}`,pt(e,await h(n,t,f))},hn=async(n,t,e,i,o,s)=>{const a=k(o.query,U(o.definition.language));if(a.length===0)return[];const c=b(i,o.indexName),f=a.length-1,w=a.map(($,_)=>mn($,_===f)),u=r.join(w,r` OR `),S=w.map($=>r`SUM(CASE WHEN ${$} THEN ${r.identifier(A)} ELSE 0 END)`),E=r.join(S.map($=>r`${$} > 0`),r` AND `),m=r`SELECT ${r.identifier(l)}, ${r.join(S,r` + `)} AS ${r.identifier("__score__")} FROM ${r.identifier(c)} WHERE ${u} GROUP BY ${r.identifier(l)} HAVING ${E}`;return It(n,t,e,i,o,s,m)},pn=async(n,t,e,i,o,s)=>{const a=k(o.query,U(o.definition.language));if(a.length===0)return[];const c=b(i,o.indexName),f=`${c}__vocab`,w=a.length-1,u=a.map((m,$)=>{const _=Jt(m,$===w),O=_.exact?r`${r.identifier("term")} = ${_.lower}`:r`${r.identifier("term")} >= ${_.lower} AND ${r.identifier("term")} < ${_.upper}`;return r`SELECT ${r.identifier("doc")}, ${r.raw(String($))} AS ${r.identifier("__term__")}, COUNT(*) AS ${r.identifier("__n__")} FROM ${r.identifier(f)} WHERE ${O} GROUP BY ${r.identifier("doc")}`}),S=a.map((m,$)=>r`SUM(CASE WHEN u.${r.identifier("__term__")} = ${r.raw(String($))} THEN u.${r.identifier("__n__")} ELSE 0 END)`),E=r`SELECT f.${r.identifier(l)} AS ${r.identifier(l)}, ${r.join(S,r` + `)} AS ${r.identifier("__score__")} FROM (${Bt(u)}) u JOIN ${r.identifier(c)} f ON f.rowid = u.${r.identifier("doc")} GROUP BY f.${r.identifier(l)} HAVING ${r.join(S.map(m=>r`${m} > 0`),r` AND `)}`;return It(n,t,e,i,o,s,E)},gn=async(n,t,e,i,o,s)=>{const a=t.nativeTextSearch,c=k(o.query,U(o.definition.language));if(!a||c.length===0)return[];const f=b(i,o.indexName),w=[a.matches(f,c),...Nt(e,o)],u=r`SELECT m.* FROM ${r.identifier(f)} JOIN ${r.identifier(i)} m ON m.${r.identifier("id")} = ${r.identifier(f)}.${r.identifier(l)} WHERE ${r.join(w,r` AND `)} ORDER BY ${a.rank(f,c)} DESC, m.${r.identifier("_creationTime")} DESC, m.${r.identifier("id")} ASC LIMIT ${r.raw(String(s))}`;return pt(e,await h(n,t,u))},yn={ensureCompanion:async(n,t,e)=>{const{integer:i,key:o}=t.companionTypes;await y(n,t,r`CREATE TABLE IF NOT EXISTS ${r.identifier(e)} (${r.identifier(g)} ${r.raw(o)} NOT NULL, ${r.identifier(l)} ${r.raw(o)} NOT NULL, ${r.identifier(A)} ${r.raw(i)} NOT NULL)`),await J(n,t,{columns:Y(t,l,191),name:`${e}__by_id`,table:e,unique:!1}),await cn(n,t,e)},indexDocument:async(n,t,e,i,o,s)=>{const a=[...yt(i,o)];await N(n,t,Ot(t,e,String(s.row.id),a,s))},migrate:En,name:"inverted",purgeDocument:async(n,t,e,i,o)=>{await y(n,t,M(e,i,H(o,i)))},runSearch:hn},Tn={ensureCompanion:async(n,t,e)=>{await N(n,t,Pt(e))},indexDocument:async(n,t,e,i,o,s)=>{await N(n,t,mt(e,String(s.row.id),z(i,o),{guard:D(t,s)}))},migrate:an,name:"fts5",purgeDocument:async(n,t,e,i,o)=>{await N(n,t,ht(e,i,{guard:H(o,i)}))},runSearch:pn},Rn={ensureCompanion:async(n,t,e)=>{const i=t.nativeTextSearch;if(i){await y(n,t,i.createCompanion(e,t.companionTypes.key));for(const o of i.createIndexes(e))await y(n,t,o)}},indexDocument:async(n,t,e,i,o,s)=>{const a=t.nativeTextSearch;a&&await y(n,t,a.indexDocument(e,String(s.row.id),z(i,o),D(t,s)))},name:"native",purgeDocument:async(n,t,e,i,o)=>{await y(n,t,M(e,i,H(o,i)))},runSearch:gn},I=(n,t)=>n.strategy==="native"&&t.nativeTextSearch!==void 0?Rn:t.supportsFts5?Tn:yn,B=(n,t)=>`${qt(n)}/${I(n,t).name}`,nt=function*(n){for(const[t,e]of Object.entries(n.tables)){const i=e.searchIndexes;if(!(e.shardMode!==void 0&&e.shardMode.kind!=="global"||!i))for(const o of i)yield[t,e,o]}},R=(n,t)=>b(n,t.name),_n=async(n,t,e,i)=>{const o=R(e,i);return q(await C(n,t,o),B(i,t)).finished?!0:kt(n,t,o)},Hn=async(n,t,e,i,o,s)=>{if(!await _n(n,t,i,o.definition))throw new p("SEARCH_INDEX_BUILDING",`search index "${o.indexName}" on table "${i}" is still backfilling and currently covers only part of the table — retry once it finishes${t.searchBackfillHint===void 0?"":`, or complete it now: ${t.searchBackfillHint}`}`);return I(o.definition,t).runSearch(n,t,e,i,o,s)},St=n=>n.slice(n.lastIndexOf("/")+1),lt=200,Et=5,On=async(n,t,e,i)=>{const o=[...i.keys()],s=await h(n,t,r`SELECT * FROM ${r.identifier(e)} WHERE ${r.identifier("id")} >= ${o[0]} AND ${r.identifier("id")} <= ${o.at(-1)} ORDER BY ${r.identifier("id")} ASC`),a=new Map;for(const c of s){const f=c.id,w=i.get(f)?.row;w&&Tt.some(u=>String(w[u])!==String(c[u]))&&a.set(f,{row:c})}return a},W=async(n,t,e,i,o,s,a)=>{const c=I(s,t);let f=a;for(let w=0;f.size>0&&w<Et;w+=1){for(const{document:u,row:S}of f.values()){const E=u??X(e,S);E&&await c.indexDocument(n,t,o,E,s,{row:S,table:i})}f=await On(n,t,i,f)}f.size>0&&console.warn(`[@lunora/sql-store] search index "${o}": ${String(f.size)} row(s) were rewritten on every one of ${String(Et)} re-check rounds and were left to their writers — each stays stale only if none of those writes changed its indexed text.`)},Ct=async(n,t,e,i,o)=>{const s=R(i,o),a=B(o,t);let c=await C(n,t,s),f=q(c,a);if(f.finished)return!0;if(f.wipe){await F(n,t,s,void 0,!1,a,{cursor:c.cursor,done:c.done,profile:c.profile});const $=await C(n,t,s);if($.cursor!==c.cursor||$.done!==c.done||$.profile!==c.profile){if(c=$,f=q(c,a),f.wipe)return!1;if(f.finished)return!0}else c={cursor:void 0,done:!1,profile:a},f=q(c,a)}if((await h(n,t,t.tableExists(i))).length===0)return await F(n,t,s,void 0,!0,a),!0;const u=await Yt(n,t,i,f.cursor,lt),S=u.findLast($=>typeof $.id=="string")?.id,E=new Map;for(const $ of u)typeof $.id=="string"&&E.set($.id,{row:$});await W(n,t,e,i,s,o,E);const m=u.length<lt;return await F(n,t,s,S??f.cursor,m,a,{cursor:f.cursor,done:!1,profile:c.profile}),m},Lt=async(n,t,e)=>{await Ft(n,e);for(const[i,,o]of nt(t)){const s=R(i,o),a=B(o,e),c=await C(n,e,s);c.profile!==void 0&&St(c.profile)!==St(a)&&(await y(n,e,r`DROP TABLE IF EXISTS ${r.identifier(s)}`),await y(n,e,r`DROP TABLE IF EXISTS ${r.identifier(Wt(s))}`),await Ut(n,e,s)),await I(o,e).ensureCompanion(n,e,s)}},An=async(n,t,e,i,o)=>{const s=R(i,o);if((await C(n,t,s)).profile!==void 0)return;let c=0;(await h(n,t,t.tableExists(i))).length>0&&await Vt(n,t,e,i,()=>{c+=1},{limit:1}),await F(n,t,s,void 0,c===0,B(o,t))},vt=async(n,t,e,i,o,s)=>await I(o,t).migrate?.(n,t,{companion:R(i,o),definition:e,index:o,tableName:i},s)??{uniqueKeyMissing:!1,unmappedSkipped:0},Pn=async(n,t,e)=>{await Lt(n,t,e);for(const[i,o,s]of nt(t)){if(await vt(n,e,o,i,s,"step"),s.staged){await An(n,e,o,i,s);continue}await Ct(n,e,o,i,s)}},Bn=async(n,t,e)=>{const i={uniqueKeyMissing:[],unmappedSkipped:0};await Lt(n,t,e);for(const[o,s,a]of nt(t)){const c=await vt(n,e,s,o,a,"drain");i.unmappedSkipped+=c.unmappedSkipped,c.uniqueKeyMissing&&i.uniqueKeyMissing.push(R(o,a));let f=!1;for(;!f;)f=await Ct(n,e,s,o,a)}return i},Mt=async(n,t,e,i,o,s,a)=>{await I(s,t).purgeDocument(n,t,o,a,e);const f=(await P(n,t,e,[a])).get(a);f!==void 0&&await W(n,t,i,e,o,s,new Map([[a,{row:f}]]))},Dt=async(n,t,e,i,o,s,a)=>{const f=(await P(n,t,e,[a])).get(a);await(f===void 0?Mt(n,t,e,i,o,s,a):W(n,t,i,e,o,s,new Map([[a,{row:f}]])))},Wn=async(n,t,e)=>{const i=n.schema.tables[t];for(const o of i?.searchIndexes??[])await Dt(n.exec,n.dialect,t,i,R(t,o),o,e)},jn=n=>{const{dialect:t,exec:e,schema:i}=n;return async(o,s,a)=>{const c=i.tables[o],f=c?.searchIndexes;if(!(!c||!f||f.length===0))for(const[w,u]of f.entries()){const S=R(o,u);try{if(on(a?.previous,a?.document,u))continue;if(a){await W(e,t,c,o,S,u,new Map([[s,{document:a.document,row:{...a.written,id:s}}]]));continue}await Mt(e,t,o,c,S,u,s)}catch(E){const m=async()=>{for(const $ of f.slice(w))await Dt(e,t,o,c,R(o,$),$,s)};throw jt(E)?.then(m,m).catch(()=>{}),E}}}};export{Dn as A,Un as C,bn as I,kn as R,Wn as a,Bn as b,jn as c,Hn as d,Fn as e,Pn as r,st as u,qn as x};
|
package/dist/packem_shared/{ctx-db-search-state-BBPiVWjf.mjs → ctx-db-search-state-CcUMouNm.mjs}
RENAMED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{sql as e}from"drizzle-orm";import{
|
|
1
|
+
import{sql as e}from"drizzle-orm";import{b as p,q as h,o as S,e as v}from"./sql-exec-j9zVLMn5.mjs";const N=["de","en","es","fr","it","nl","none","pt"],F=n=>N.includes(n),D="a an and are as at be but by for if in into is it no not of on or such that the their then there these they this to was will with",_="aber als am an auch auf aus bei bin bis bist da dass der den des dem die das denn dir du ein eine für hat ich im in ist mit nicht noch nur oder sich sie sind über und von vor war wie wir zu zum zur",b="a al como con de del el en es la las lo los mas no o para pero por que se su sus un una uno y ya",C="au aux avec ce ces dans de des du elle en et eux il je la le les leur lui ma mais me même mes moi mon ne nos notre nous on ou par pas pour qu que qui sa se ses son sur ta te tes toi ton tu un une vos votre vous y",H="a ai al alla anche che chi ci coi col come con da dal degli dei del della di do e ed gli ha hai hanno i il in la le lo ma mi ne nei nel non o per più quale quanto se si sono su sul tra un una uno vi",O="aan al als bij dan dat de der deze die dit door een en er het hij ij in is je kan me men met mij na naar niet nog nu of om ons ook op over te tot uit van voor was wat we wij zij zijn zo",j="a ao aos as até com como da das de do dos e em entre era essa esse esta este eu foi há isso já mais mas me mesmo meu na nas no nos num numa o os ou para pela pelo por qual que quem se sem seu só sua também te tem um uma você",z=new RegExp("(?<=\\p{Script=Cyrillic})[\\u0300-\\u0305\\u0307\\u0309-\\u036F]|(?<!\\p{Script=Cyrillic})[\\u0300-\\u036F]","gu"),U=/[\u0080-\u{10FFFF}]/u,k=/[\p{L}\p{N}]+/gu,M=/[\p{Script_Extensions=Han}\p{Script_Extensions=Hiragana}\p{Script_Extensions=Katakana}\p{Script_Extensions=Hangul}]+/gu,y=/[\p{Script_Extensions=Han}\p{Script_Extensions=Hiragana}\p{Script_Extensions=Katakana}\p{Script_Extensions=Hangul}]/u,x=n=>{if(!y.test(n))return[n];const i=[];let o=0;for(const s of n.matchAll(M)){const r=s.index,a=[...s[0]];if(r>o&&i.push(n.slice(o,r)),o=r+s[0].length,a.length===1){i.push(s[0]);continue}for(let t=0;t+1<a.length;t+=1)i.push(`${String(a[t])}${String(a[t+1])}`)}return o<n.length&&i.push(n.slice(o)),i},A=n=>U.test(n)?n.normalize("NFD").replaceAll(z,"").normalize("NFC").toLowerCase():n.toLowerCase(),$=n=>new Set(A(n).split(" ")),I={de:$(_),en:$(D),es:$(b),fr:$(C),it:$(H),nl:$(O),none:new Set,pt:$(j)},B=3,W=256,g=new Map,V=n=>{const i=n!==void 0&&F(n)?n:"none",o=g.get(i);if(o)return o;const s=I[i],r=t=>{const d=A(t),l=d.match(k)??[],f=(y.test(d)?l.flatMap(c=>x(c)):l).filter(c=>c.length<=W);return s.size===0?f:f.filter(c=>!s.has(c))},a={document:r,profile:`${i}-v${String(B)}`,query:t=>{const d=r(t),l=new Set,f=[];for(let c=d.length-1;c>=0;c-=1){const m=d[c];l.has(m)||(l.add(m),f.push(m))}return f.toReversed()}};return g.set(i,a),a},X=n=>`${V(n.language).profile}:${n.field}`,T=n=>{const i=n.slice(n.indexOf(":")+1),o=i.lastIndexOf("/");return o===-1?i:i.slice(0,o)},G=(n,i)=>n.profile!==i?{cursor:void 0,finished:!1,wipe:n.cursor!==void 0||n.done}:{cursor:n.cursor,finished:n.done,wipe:!1},K=(n,i)=>typeof n=="string"&&T(n)===T(i),u="__lunora_search_state",J=async(n,i)=>{const{integer:o,key:s}=i.companionTypes,r=async(a,t)=>{try{await p(n,i,e`ALTER TABLE ${e.identifier(u)} ADD COLUMN ${e.identifier(a)} ${e.raw(t)}`)}catch{}};await p(n,i,e`CREATE TABLE IF NOT EXISTS ${e.identifier(u)} (${e.identifier("companion")} ${e.raw(s)} PRIMARY KEY, ${e.identifier("cursor")} ${e.raw(s)}, ${e.identifier("done")} ${e.raw(o)} NOT NULL DEFAULT 0, ${e.identifier("profile")} ${e.raw(s)}, ${e.identifier("covered")} ${e.raw(o)} NOT NULL DEFAULT 0)`),await r("profile",s),await r("covered",`${o} NOT NULL DEFAULT 0`),await p(n,i,e`UPDATE ${e.identifier(u)} SET ${e.identifier("covered")} = 1 WHERE ${e.identifier("done")} = 1 AND ${e.identifier("covered")} = 0`)},L=n=>n===1||n===!0||n==="1",Q=async(n,i,o)=>{const s=await h(n,i,e`SELECT ${e.identifier("covered")} FROM ${e.identifier(u)} WHERE ${e.identifier("companion")} = ${o}`);return L(s[0]?.covered)},Z=async(n,i,o)=>{await p(n,i,e`DELETE FROM ${e.identifier(u)} WHERE ${e.identifier("companion")} = ${o}`)},ee=async(n,i,o)=>{const r=(await h(n,i,e`SELECT ${e.identifier("cursor")}, ${e.identifier("done")}, ${e.identifier("profile")} FROM ${e.identifier(u)} WHERE ${e.identifier("companion")} = ${o}`))[0];if(!r)return{cursor:void 0,done:!1,profile:void 0};const{cursor:a,profile:t}=r;return{cursor:typeof a=="string"?a:void 0,done:L(r.done),profile:typeof t=="string"?t:void 0}},ne=async(n,i,o,s,r,a,t)=>{const d=s??null,l=await h(n,i,e`SELECT ${e.identifier("profile")} FROM ${e.identifier(u)} WHERE ${e.identifier("companion")} = ${o}`),f=K(l[0]?.profile,a),c=r?1:0,m=r||!f?e`${e.identifier("covered")} = ${c}`:e`${e.identifier("covered")} = ${e.identifier("covered")}`,R=t?.done===!0?1:0,q=t===void 0?e``:e` AND ${S(i.name,v("cursor"),t.cursor??null)} AND ${S(i.name,v("profile"),t.profile??null)} AND ${e.identifier("done")} = ${R}`,E=e`UPDATE ${e.identifier(u)} SET ${e.identifier("cursor")} = ${d}, ${e.identifier("done")} = ${c}, ${e.identifier("profile")} = ${a}, ${m} WHERE ${e.identifier("companion")} = ${o}${q}`;if(l.length>0){await p(n,i,E);return}if(!(t!==void 0&&(t.cursor!==void 0||t.done||t.profile!==void 0)))try{await p(n,i,e`INSERT INTO ${e.identifier(u)} (${e.identifier("companion")}, ${e.identifier("cursor")}, ${e.identifier("done")}, ${e.identifier("profile")}, ${e.identifier("covered")}) VALUES (${o}, ${d}, ${r?1:0}, ${a}, ${r?1:0})`)}catch(w){if(!i.isUniqueViolation(w))throw w;await p(n,i,E)}};export{u as S,Z as a,Q as b,X as c,G as l,J as m,V as q,ee as r,ne as w};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{bigintSqlKey as a}from"@lunora/shard-engine";import{B as t,b as n,U as o,d as r,e as d,i as E,r as N,s as U,a as _,t as c}from"./value-codec-DhzLXsqv.mjs";export{t as BIGINT_KEY_LENGTH,n as UNTYPED_NUMBER_PREFIX,o as UNTYPED_WIRE_PREFIX,a as bigintSqlKey,r as decodeBigint,d as effectiveColumnKind,E as isUntypedColumnKind,N as rewriteLegacyUntypedNumber,U as sqliteDecode,_ as sqliteEncode,c as tryJsonParse};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{B as l,M as o,O as n,
|
|
1
|
+
import{B as l,M as o,O as n,e as r,c as t,d,k as i,l as u,h as R,n as f,y as q,i as c,u as C,o as S,g as m,j as p,p as x,x as I,z as E,q as h,f as w,b as A,r as O,a as _,m as y,s as B,w as N,t as z}from"./sql-exec-j9zVLMn5.mjs";import"./value-codec-DhzLXsqv.mjs";export{l as BACKFILL_BATCH_SIZE,o as MAX_BOUND_PARAMETERS,n as OCC_VERSION_COLUMN,r as columnRefSql,t as createIndexIfNotExists,d as decodeGlobalRow,i as decodeRow,u as decodeRows,R as dropIndexIfExists,f as fieldRefSql,q as forEachRowPaged,c as indexState,C as nextRowVersion,S as nullSafeEqualsSql,m as pathContainsNeedle,p as pathInList,x as pathTextReference,I as pathTypeGuardSql,E as qualifiedColumnRefSql,h as queryAll,w as queryBatch,A as queryRun,O as readRowsPage,_ as runInOrder,y as serializeColumnValue,B as serializeDocumentColumn,N as serializeFieldValue,z as tableColumns};
|
package/dist/packem_shared/{exportSqlGlobalRows-DzCIGW9D.mjs → exportSqlGlobalRows-BMOYQhJf.mjs}
RENAMED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{toErrorBody as b}from"@lunora/errors";import{needsWireEncoding as I,encodeWire as A,decodeWire as S}from"@lunora/wire";import{sql as m}from"drizzle-orm";import{runSqlGlobalTableMigrations as g}from"./runSqlGlobalTableMigrations-
|
|
1
|
+
import{toErrorBody as b}from"@lunora/errors";import{needsWireEncoding as I,encodeWire as A,decodeWire as S}from"@lunora/wire";import{sql as m}from"drizzle-orm";import{runSqlGlobalTableMigrations as g}from"./runSqlGlobalTableMigrations-B00G2E1V.mjs";import{t as y}from"./post-commit-error-hh-zQyjO.mjs";import{r as T,d as L,M as k,q as E}from"./sql-exec-j9zVLMn5.mjs";const $=200,v=(r,o)=>{const t=e=>r.tables[e]?.shardMode?.kind==="global";return o&&o.length>0?o.filter(e=>t(e)):Object.keys(r.tables).filter(e=>t(e))},D=r=>I(r)?A(r):r,Y=async function*(r,o,t,e){const s=v(o,e.tables),n=e.batchSize??$;await g(r,o,t);for(const i of s){const d=o.tables[i];let a,c=!0;for(;c;){const f=await T(r,t,i,a,n);for(const u of f)yield{doc:D(L(d,u)),table:i};const l=f.at(-1);l!==void 0&&(a=String(l.id)),c=f.length===n}}},w=r=>r?._meta?.column?.notNull===!1,C=(r,o)=>{const t=new Set;for(const[e,s]of Object.entries(r.shape)){if(o[e]!==null||s.kind!=="optional"||w(s))continue;const n=s._meta?.inner;w(n)||t.add(e)}return t.size===0?o:Object.fromEntries(Object.entries(o).filter(([e])=>!t.has(e)))},F=new Set(["_creationTime","_id"]),M=(r,o)=>Object.keys(o).find(t=>!F.has(t)&&!Object.hasOwn(r.shape,t)),x=r=>{const o=r._id,t=r._creationTime;if(o!==void 0&&(typeof o!="string"||o===""))return'field "_id": must be a non-empty string';if(t!==void 0&&(typeof t!="number"||!Number.isFinite(t)))return'field "_creationTime": must be a finite number'},j=(r,o,t)=>{const e=r.tables[o];if(!e)return`unknown table: ${o}`;const s=M(e,t);if(s!==void 0)return`unexpected field "${s}": not declared in table "${o}"`;const n=x(t);if(n!==void 0)return n;for(const[i,d]of Object.entries(e.shape)){const a=t[i],c=d.kind==="optional";if(a===void 0&&c)continue;const f=d.parse;if(typeof f=="function")try{f(a)}catch(l){const u=l instanceof Error?l.message:String(l);return`field "${i}": ${u}`}}},R=async(r,o,t,e,s)=>t?(await E(t,o,m`SELECT 1 FROM ${m.identifier(e)} WHERE ${m.identifier("id")} = ${s} LIMIT 1`)).length>0:await r.get(e,s)!==null,O=async(r,o,t,e,s,n)=>{try{return{existingId:await R(r,o,t,e,s)?s:void 0}}catch(i){const{body:d}=b(i,{fallbackCode:"PROBE_FAILED"});return{error:{code:d.code,line:n,message:d.message,table:e}}}},h=(r,o,t)=>{const e=r.held.get(o)??new Set;e.add(t),r.held.set(o,e)},B=async(r,o,t)=>{const e=[...t.keys()],s=new Map;let n=[],i=k;const d=async()=>{if(n.length===0)return;const a=await E(r,o,m.join(n,m` UNION ALL `));for(const c of a)h({held:s},e[Number(c.slot)],String(c.id));n=[],i=k};try{for(const[a,c]of e.entries()){const f=[...t.get(c)];for(let l=0;l<f.length;){const u=f.slice(l,l+i);n.push(m`SELECT ${m.raw(String(a))} AS slot, ${m.identifier("id")} FROM ${m.identifier(c)} WHERE ${m.identifier("id")} IN (${m.join(u.map(p=>m.param(p)),m`, `)})`),l+=u.length,i-=u.length,i===0&&await d()}}await d()}catch(a){const{body:c}=b(a,{fallbackCode:"PROBE_FAILED"});return{failure:{code:c.code,message:c.message}}}return{held:s}},N=(r,o,t,e)=>"failure"in r?{error:{...r.failure,line:e,table:o}}:{existingId:r.held.get(o)?.has(t)===!0?t:void 0},W=r=>v(r).some(o=>Object.keys(r.tables[o]?.triggerMap??{}).length>0),P=async(r,o,t,e,s)=>{const{doc:n,table:i}=e,d=n._id;if(typeof d!="string")return{committed:!1,error:{code:"BAD_ROW",line:s,message:"a delete row needs the `_id` to delete",table:i},kind:"error"};if(t.dryRun===!0)return{kind:"checked"};const a=await O(r,o,t.exec,i,d,s);if("error"in a)return{committed:!1,error:a.error,kind:"error"};if(a.existingId===void 0)return{kind:"absent"};try{return await r.delete(i,d,{hard:!0,skipOnDelete:!0}),{kind:"deleted"}}catch(c){const{body:f}=b(c,{fallbackCode:"DELETE_FAILED"}),l=y(c,i,d),u=l?`${f.message} (row "${d}" was deleted before this failure, so its triggers or companion writes may not have completed; a re-run finds it absent and does not redo them)`:f.message;return{committed:l,error:{code:f.code,line:s,message:u,table:i},kind:"error"}}},_=async(r,o,t,e,s,n)=>{try{if(e!==void 0){const i={...t};return delete i._id,await r.replace(o,e,i,{allowExplicitId:!0}),{kind:"replaced"}}return await r.insert(o,t,{allowExplicitId:!0}),{inserted:o,kind:"inserted"}}catch(i){const{body:d}=b(i,{fallbackCode:e===void 0?"INSERT_FAILED":"REPLACE_FAILED"}),a=e??(typeof t._id=="string"?t._id:void 0),c=a!==void 0&&y(i,o,a),f=n==="replace"?'re-importing it with onConflict "replace" redoes that work':'a re-import skips it while it exists; use onConflict "replace" to redo that work',l=c?`${d.message} (row "${a}" committed before this failure, so its triggers or companion writes may not have completed; ${f})`:d.message;return{committed:c,error:{code:d.code,line:s,message:l,table:o},kind:"error"}}},G=(r,o,t,e)=>{const{doc:s,table:n}=t;if(typeof n!="string"||n.length===0)return{kind:"settled",outcome:{committed:!1,error:{code:"BAD_ROW",line:e,message:"row is missing `table`",table:n},kind:"error"}};if(r.tables[n]?.shardMode?.kind!=="global")return{kind:"settled",outcome:{kind:"skip"}};if(!s||typeof s!="object"||Array.isArray(s))return{kind:"settled",outcome:{committed:!1,error:{code:"BAD_ROW",line:e,message:"row is missing or malformed `doc`",table:n},kind:"error"}};if(t.op==="delete")return{kind:"delete",line:e,row:t};let i;try{i=S(s)}catch(a){return{kind:"settled",outcome:{committed:!1,error:{code:"BAD_ROW",line:e,message:a instanceof Error?a.message:String(a),table:n},kind:"error"}}}i=C(r.tables[n],i);const d=j(r,n,i);return d!==void 0?{kind:"settled",outcome:{committed:!1,error:{code:"VALIDATION_ERROR",line:e,message:d,table:n},kind:"error"}}:o?{kind:"settled",outcome:{kind:"checked"}}:{decoded:i,explicitId:typeof i._id=="string"?i._id:void 0,kind:"ready",line:e,table:n}},H=async(r,o,t,e,s,n)=>{const{decoded:i,explicitId:d,line:a,table:c}=s;try{if(!await R(r,o,t,c,d))return}catch{return}return e.snapshot!==void 0&&"held"in e.snapshot&&h(e.snapshot,c,d),n==="replace"?_(r,c,i,d,a,n):{kind:"conflict"}},z=async(r,o,t,e,s)=>{const{decoded:n,explicitId:i,line:d,table:a}=e;let c={existingId:void 0};if(i!==void 0&&(c=s.snapshot===void 0?await O(r,o,t.exec,a,i,d):N(s.snapshot,a,i,d)),"error"in c)return{committed:!1,error:c.error,kind:"error"};const{existingId:f}=c;if(f!==void 0&&t.onConflict!=="replace")return{kind:"conflict"};const l=await _(r,a,n,f,d,t.onConflict);if(i===void 0)return l;const{snapshot:u}=s;return u!==void 0&&"held"in u&&(l.kind==="inserted"||l.kind==="replaced"||l.kind==="error"&&l.committed)&&h(u,a,i),l.kind==="error"&&!l.committed&&l.error.code==="CONFLICT"&&f===void 0?await H(r,o,t.exec,s,{...e,explicitId:i},t.onConflict)??l:l},q=async(r,o,t,e,s)=>{const n=new Map;for(const i of e)if(i.kind==="ready"&&i.explicitId!==void 0){const d=n.get(i.table)??new Set;d.add(i.explicitId),n.set(i.table,d)}if(n.size===0)return s?{held:new Map}:void 0;try{await g(r,o,t)}catch(i){const{body:d}=b(i,{fallbackCode:"PROBE_FAILED"});return{failure:{code:d.code,message:d.message}}}return s?B(r,t,n):void 0},U=(r,o,t,e,s)=>e.kind==="settled"?Promise.resolve(e.outcome):e.kind==="delete"?P(r,o,t,e.row,e.line):z(r,o,t,e,s),ee=async(r,o,t,e)=>{const s=[],n={};let i=0,d=0,a=0,c=(e.startLine??1)-1;const f=e.rows.map(u=>(c+=1,G(o,e.dryRun===!0,u,u.line??c))),l={};e.exec&&e.dryRun!==!0&&(l.snapshot=await q(e.exec,o,t,f,!W(o)));for(const u of f){const p=await U(r,t,e,u,l);switch(p.kind){case"conflict":{i+=1;break}case"deleted":{d+=1;break}case"error":{s.push(p.error);break}case"inserted":{n[p.inserted]=(n[p.inserted]??0)+1;break}case"replaced":{a+=1;break}}}return{conflicts:i,deleted:d,errors:s,inserted:n,replaced:a}};export{Y as exportSqlGlobalRows,ee as importSqlGlobalRows,v as selectGlobalTables};
|
package/dist/packem_shared/{facetSqlGlobalColumn-BPU8EBYc.mjs → facetSqlGlobalColumn-DF3p8q4R.mjs}
RENAMED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{LunoraError as w}from"@lunora/errors";import{isInternalTableName as G}from"@lunora/shard-engine";import{needsWireEncoding as v,encodeWire as M}from"@lunora/wire";import{sql as o}from"drizzle-orm";import{runSqlGlobalTableMigrations as k}from"./runSqlGlobalTableMigrations-
|
|
1
|
+
import{LunoraError as w}from"@lunora/errors";import{isInternalTableName as G}from"@lunora/shard-engine";import{needsWireEncoding as v,encodeWire as M}from"@lunora/wire";import{sql as o}from"drizzle-orm";import{runSqlGlobalTableMigrations as k}from"./runSqlGlobalTableMigrations-B00G2E1V.mjs";import{q as u,M as T,d as P}from"./sql-exec-j9zVLMn5.mjs";import{s as W,e as Y,a as O}from"./value-codec-DhzLXsqv.mjs";const H=50,j=500,X=30,J=200,Q=(t,n,e)=>Math.min(Math.max(t,n),e),g=(t,n,e,a)=>Q(Math.trunc(t!==void 0&&Number.isFinite(t)?t:n),e,a),V=(t,n)=>G(t)||n.name==="sqlite"&&t.startsWith("d1_"),y=t=>t.name==="postgres"?o`current_schema()`:o`DATABASE()`,C=t=>t.filter(n=>Number(n.pk??0)>0).toSorted((n,e)=>Number(n.pk)-Number(e.pk)).map(n=>String(n.name)),p={columns:async(t,n,e)=>(n.name==="sqlite"?await u(t,n,o`PRAGMA table_info(${o.identifier(e)})`):await u(t,n,o`SELECT column_name AS name FROM information_schema.columns WHERE table_schema = ${y(n)} AND table_name = ${e} ORDER BY ordinal_position`)).map(r=>String(r.name)),foreignKeys:async(t,n,e)=>{let a;return n.name==="sqlite"?a=o`PRAGMA foreign_key_list(${o.identifier(e)})`:n.name==="mysql"?a=o`SELECT column_name AS ${o.identifier("from")}, referenced_table_name AS ${o.identifier("table")} FROM information_schema.key_column_usage WHERE table_schema = DATABASE() AND table_name = ${e} AND referenced_table_name IS NOT NULL AND referenced_table_schema = DATABASE()`:a=o`SELECT kcu.column_name AS ${o.identifier("from")}, ccu.table_name AS ${o.identifier("table")} FROM information_schema.table_constraints AS tc JOIN information_schema.key_column_usage AS kcu ON kcu.constraint_name = tc.constraint_name AND kcu.constraint_schema = tc.constraint_schema AND kcu.table_schema = tc.table_schema AND kcu.table_name = tc.table_name JOIN information_schema.constraint_column_usage AS ccu ON ccu.constraint_name = tc.constraint_name AND ccu.constraint_schema = tc.constraint_schema WHERE tc.constraint_type = 'FOREIGN KEY' AND tc.table_schema = current_schema() AND tc.table_name = ${e} AND ccu.table_schema = current_schema()`,(await u(t,n,a)).map(s=>({from:String(s.from),target:String(s.table)}))},primaryKey:async(t,n,e)=>n.name==="sqlite"?C(await u(t,n,o`PRAGMA table_info(${o.identifier(e)})`)):(await u(t,n,o`SELECT kcu.column_name AS name FROM information_schema.table_constraints AS tc JOIN information_schema.key_column_usage AS kcu ON kcu.constraint_name = tc.constraint_name AND kcu.table_schema = tc.table_schema AND kcu.table_name = tc.table_name WHERE tc.constraint_type = 'PRIMARY KEY' AND tc.table_schema = ${y(n)} AND tc.table_name = ${e} ORDER BY kcu.ordinal_position`)).map(r=>String(r.name)),tables:async(t,n)=>(n.name==="sqlite"?await u(t,n,o`SELECT name FROM sqlite_master WHERE type = 'table' ORDER BY name`):await u(t,n,o`SELECT table_name AS name FROM information_schema.tables WHERE table_schema = ${y(n)} AND table_type = 'BASE TABLE' ORDER BY table_name`)).map(a=>String(a.name))},z=/password|secret|token|hash|salt|credential/iu,Z=new Map([["apikey",new Set(["key"])],["jwks",new Set(["privatekey"])],["twofactor",new Set(["backupcodes"])],["verification",new Set(["value"])]]),D=t=>t.toLowerCase().replaceAll("_",""),h=(t,n)=>z.test(n)||Z.get(D(t))?.has(D(n))===!0,_=(t,n)=>{const e=t.tables[n];return e?.shardMode?.kind==="global"?e:void 0},L=async(t,n)=>(await p.tables(t,n)).filter(a=>!V(a,n)),I=async(t,n,e,a)=>{if(await k(t,e,n),!(await L(t,n)).includes(a))throw new w("UNKNOWN_TABLE",`unknown table: ${a}`,{status:404})},R=async(t,n,e,a=o``)=>{const r=await u(t,n,o`SELECT COUNT(*) AS c FROM ${o.identifier(e)}${a}`);return Number(r[0]?.c??0)},q=(t,n,e)=>_(t,n)!==void 0&&e==="_id"?"id":e,B=(t,n,e)=>{const a=_(t,n)?.shape[e];return a===void 0?void 0:Y(a)},x=/^-?\d+$/u,F=(t,n)=>{if(n>T)throw new w("BAD_REQUEST",`the query over ${t} binds ${String(n)} parameters, and a statement takes at most ${String(T)} — remove some filters`)},tt=(t,n,e)=>{if(e)return t instanceof ArrayBuffer?new Uint8Array(t):t;if(n!=="bigint")return O(t);const a=typeof t=="number"||typeof t=="string"?String(t).trim():void 0;return O(a!==void 0&&x.test(a)?BigInt(a):t,n)},nt=t=>{if(t.operator!==void 0&&t.operator!=="eq")throw new w("BAD_REQUEST",`operator "${t.operator}" is not supported on the global browser — only eq is`);if(t.path!==void 0&&!(Array.isArray(t.path)&&t.path.length===0))throw new w("BAD_REQUEST",`a nested path is not supported on the global browser, so ${t.column} must be a top-level column`)},U=(t,n,e,a,r)=>{const s=[],i=_(t,e)===void 0&&n.name!=="sqlite";let m=0;for(const c of r??[]){if(nt(c),!a.includes(c.column))throw new w("UNKNOWN_COLUMN",`unknown column: ${c.column}`,{status:404});if(_(t,e)===void 0&&h(e,c.column))throw new w("FORBIDDEN",`cannot filter on a redacted column: ${c.column}`,{status:403});const f=o.identifier(q(t,e,c.column));if(c.value===null||c.value===void 0)s.push(o`${f} IS NULL`);else{const l=tt(c.value,B(t,e,c.column),i);s.push(i&&n.name==="postgres"&&l instanceof Date?o`${f}::timestamptz = ${l}::timestamptz`:o`${f} = ${l}`),m+=1}}return{bound:m,where:s.length>0?o` WHERE ${o.join(s,o` AND `)}`:o``}},et=(t,n,e)=>{const a=_(t,n);if(a)return P(a,e);const r={};for(const[s,i]of Object.entries(e))r[s]=i!=null&&h(n,s)?"•••":i;return r},K=async(t,n,e,a)=>{const r=_(e,a);if(r)return{columns:["_id","_creationTime",...Object.keys(r.shape)],primaryKey:()=>Promise.resolve([])};if(n.name==="sqlite"){const s=await u(t,n,o`PRAGMA table_info(${o.identifier(a)})`);return{columns:s.map(i=>String(i.name)),primaryKey:()=>Promise.resolve(C(s))}}return{columns:await p.columns(t,n,a),primaryKey:()=>p.primaryKey(t,n,a)}},ot=async(t,n,e,a)=>{if(_(e,a))return;const r=await p.foreignKeys(t,n,a);if(r.length===0)return;const s={};for(const i of r){const{from:m,target:c}=i;s[m]??=c}return s},ft=async(t,n,e)=>{await k(t,n,e);const a=await L(t,e);return Promise.all(a.map(async r=>({name:r,rowCount:await R(t,e,r)})))},at=async(t,n,e,a,r)=>{if(_(n,e)!==void 0)return o`${o.identifier("id")}`;const s=await r();return s.length>0?o.join(s.map(i=>o.identifier(i)),o`, `):a.includes("id")?o`${o.identifier("id")}`:t.name==="sqlite"?o.raw("rowid"):o.join(a.map(i=>t.name==="postgres"?o`${o.identifier(i)}::text`:o.identifier(i)),o`, `)},_t=async(t,n,e,a)=>{const{table:r}=a;await I(t,e,n,r);const s=g(a.limit,H,1,j),i=g(a.offset,0,0,Number.MAX_SAFE_INTEGER),{columns:m,primaryKey:c}=await K(t,e,n,r),{bound:f,where:l}=U(n,e,r,m,a.filters);F(r,f);const A=await R(t,e,r,l),d=await at(e,n,r,m,c),S=(await u(t,e,o`SELECT * FROM ${o.identifier(r)}${l} ORDER BY ${d} LIMIT ${o.raw(String(s))} OFFSET ${o.raw(String(i))}`)).map(E=>{const N=et(n,r,E);return v(N)?M(N):N}),b=await ot(t,e,n,r);return b===void 0?{columns:m,rows:S,total:A}:{columns:m,refs:b,rows:S,total:A}},Et=async(t,n,e,a)=>{const{column:r,table:s}=a;await I(t,e,n,s);const{columns:i}=await K(t,e,n,s);if(!i.includes(r))throw new w("UNKNOWN_COLUMN",`unknown column: ${r}`,{status:404});const{bound:m,where:c}=U(n,e,s,i,a.filters);if(F(s,m),_(n,s)===void 0&&h(s,r)){const E=await R(t,e,s,c);return{truncated:!1,values:E===0?[]:[{count:E,value:"•••"}]}}const f=g(a.limit,X,1,J),l=o.identifier(q(n,s,r)),A=await u(t,e,o`SELECT ${l} AS value, COUNT(*) AS count FROM ${o.identifier(s)}${c} GROUP BY ${l} ORDER BY count DESC, ${l} ASC LIMIT ${o.raw(String(f+1))}`),d=A.length>f,$=d?A.slice(0,f):A,S=B(n,s,r)==="bigint",b=$.map(E=>({count:Number(E.count),value:S?W(E.value,"bigint"):E.value}));return{truncated:d,values:v(b)?M(b):b}};export{Et as facetSqlGlobalColumn,ft as listSqlGlobalTables,_t as readSqlGlobalTablePage};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{c as i,b as n,a as m,g as r,r as t,w as b}from"./column-provisioning-DsVyt-k5.mjs";import"./sql-exec-j9zVLMn5.mjs";import"./value-codec-DhzLXsqv.mjs";export{i as addColumnIfMissing,n as alterGlobalTableDrift,m as globalColumnAffinity,r as globalColumnBackfill,t as relaxNullAcceptingColumns,b as wantedGlobalColumns};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraError as I}from"@lunora/errors";import{aggregateTableName as j,rankTableName as X,sortColumnName as A,bigintSqlKey as G}from"@lunora/shard-engine";import{sql as i}from"drizzle-orm";import{a as Y,b as H,r as W,c as V,v as Q}from"./column-provisioning-DsVyt-k5.mjs";import{O as L,t as Z,b as m,M as N,c as y,e as c,q as $,f as z}from"./sql-exec-j9zVLMn5.mjs";import{e as T,B as b,r as J,i as nn,U as en,b as tn}from"./value-codec-DhzLXsqv.mjs";const q=n=>{const e=new Set;for(const t of n.indexes)t.unique===!0&&t.fields.length===1&&e.add(t.fields[0]);return e},on=(n,e,t)=>{if(t.indexKeyPrefix!==void 0)for(const o of e.indexes){if(o.unique!==!0||o.fields.length<=1)continue;const s=o.fields.filter(r=>{const a=e.shape[r];return a!==void 0&&t.indexKeyPrefix?.(T(a))!==void 0});if(s.length>0)throw new Error(`${n}.${o.name}: a composite unique index cannot cover ${s.join(", ")} in full on this engine (its key limit forces a prefix, which would constrain the prefix rather than the value). Split it into single-column unique indexes, or store those fields as a bounded type.`)}},rn=n=>n._meta?.column?.notNull===!0&&n.kind!=="optional"&&!Q(n),sn=(n,e,t)=>{const o=[],s=q(e);for(const[u,d]of Object.entries(e.shape)){if(!d._meta?.column)continue;const f=rn(d)?" NOT NULL":"";o.push(i`${i.identifier(u)} ${i.raw(`${Y(d,t,s.has(u))}${f}`)}`)}const r=[...t.frameworkColumns().map(u=>i`${i.identifier(u.name)} ${i.raw(u.type)}`),i`${i.identifier(L)} ${i.raw(t.companionTypes.integer)}`],a=r.length+o.length,l=t.maxTableColumns;if(l!==void 0&&a>l){const u=a-1===l,d="Move one or more fields into a single object field, or split the table — either way the existing rows need a data migration (`defineMigration` + `lunora migrate up`); there is no in-place path.";throw new I("VALIDATION_ERROR",`@lunora/sql-store: global table "${n}" needs ${String(a)} columns, over this engine's ${String(l)}-column limit. ${u?`One of them is "${L}", the row version every guarded write reads, which caps declared fields at ${String(l-r.length)}. A table provisioned at ${String(l)} columns before that column existed cannot be widened to hold it. `:""}${d}`)}return i.join([...r,...o],i`, `)},v=n=>{if(n.indexKeyPrefix?.("string")===void 0)return i`${c("_creationTime")}, ${c("id")}`},O=new Set,x=async(n,e,t,o)=>{const s=i.join(t.refs.map(a=>i`${a} IS NOT NULL`),i` AND `);if((await $(n,e,i`SELECT ${t.columns} FROM ${i.identifier(t.table)} WHERE ${s} GROUP BY ${t.columns} HAVING COUNT(*) > 1 LIMIT 1`)).length>0){const a=`unique index "${t.name}" on "${t.table}" ${o}: existing rows are duplicates under it. De-duplicate the table with a data migration first.`;throw O.has(a)||(O.add(a),console.error(`[@lunora/sql-store] ${a}`)),new I("UNIQUE_INDEX_DUPLICATES",a)}},an=async(n,e,t)=>{if(!t.unique){await y(n,e,t);return}try{await y(n,e,t)}catch(o){throw e.isUniqueViolation(o)&&await x(n,e,t,"cannot be created"),o}},D=n=>{const e=n.indexOf("(");return e===-1?void 0:n.slice(e,n.lastIndexOf(")")+1)},ln=(n,e)=>{const t=e.unique?i`UNIQUE `:i``;return D(n.render(i`CREATE ${t}INDEX ${i.identifier(e.name)} ON ${i.identifier(e.table)} (${e.columns})`).sql)},un=(n,e,t)=>{const o=ln(n,t);return o!==void 0&&o!==D(e)},U=async(n,e,t)=>{if(e.name!=="sqlite")return;const s=(await $(n,e,i`SELECT sql FROM sqlite_master WHERE type = 'index' AND name = ${t.name} COLLATE NOCASE AND tbl_name = ${t.table} COLLATE NOCASE`))[0]?.sql;typeof s=="string"&&un(e,s,t)&&(t.unique&&await x(n,e,t,"cannot be re-created with its new column list; the previous index is left in place"),await m(n,e,i`DROP INDEX IF EXISTS ${i.identifier(t.name)}`))},dn=(n,e,t)=>{on(n,e,t);const o=q(e),s=l=>{const u=c(l),d=e.shape[l],f=d&&t.indexKeyPrefix&&d._meta?.column?.unique!==!0&&!o.has(l)?t.indexKeyPrefix(T(d)):void 0;return f===void 0?u:i`${u}(${i.raw(String(f))})`},r=v(t),a=[];for(const l of e.indexes){const u=l.fields.map(E=>s(E)),d=i.join(u,i`, `),f=l.unique??!1;a.push({columns:f||r===void 0?d:i`${d}, ${r}`,kind:"declared",name:`${n}_${l.name}`,refs:u,table:n,unique:f})}r!==void 0&&a.push({columns:r,kind:"default-order",name:`${n}__by_creation`,refs:[],table:n,unique:!1});for(const[l,u]of Z(e)){if(!u.unique)continue;const d=s(l);a.push({columns:d,kind:"unique-column",name:`${n}_unique_${l}`,refs:[d],table:n,unique:!0})}return a},fn=/^\s*create\s+unique\s/iu,w="__lunora_framework_indexes",cn=()=>i`CREATE TABLE IF NOT EXISTS ${i.identifier(w)} (name TEXT PRIMARY KEY COLLATE NOCASE, table_name TEXT NOT NULL)`,k=(n,e)=>i`INSERT OR IGNORE INTO ${i.identifier(w)} (name, table_name) VALUES (${n}, ${e})`,g=n=>n.replaceAll(/[A-Z]/gu,e=>e.toLowerCase()),mn=async(n,e,t)=>{if(e.name!=="sqlite"||(await $(n,e,i`SELECT 1 AS present FROM sqlite_master WHERE type = 'table' AND name = ${w} COLLATE NOCASE`)).length>0)return;await m(n,e,cn());const s=v(e),r=s===void 0?void 0:`, ${e.render(s).sql})`;for(const a of t){const l=`${g(a)}_`,u=await $(n,e,i`SELECT name, sql FROM sqlite_master WHERE type = 'index' AND tbl_name = ${a} COLLATE NOCASE AND sql IS NOT NULL`);for(const d of u){const f=String(d.name),E=String(d.sql);g(f).startsWith(l)&&g(f)!==g(`${a}__by_creation`)&&(fn.test(E)||r!==void 0&&E.trimEnd().endsWith(r))&&await m(n,e,k(f,a))}}},En=(n,e,t)=>{if(n.name!=="sqlite")return[];const o=new Set(e.map(s=>g(s.name)));return t.filter(s=>!o.has(g(s)))},$n=async(n,e,t,o)=>{if(o.name!=="sqlite")return;const s=await $(n,o,i`SELECT "l"."name" FROM ${i.identifier(w)} AS "l" WHERE "l"."table_name" = ${e} COLLATE NOCASE`);for(const r of En(o,t,s.map(a=>String(a.name))))await m(n,o,i`DROP INDEX IF EXISTS ${i.identifier(r)}`),await m(n,o,i`DELETE FROM ${i.identifier(w)} WHERE ${i.identifier(w)}."name" = ${r}`)},gn=async(n,e,t,o)=>{const s=dn(e,t,o);for(const r of s){if(r.kind==="default-order"){await y(n,o,r);continue}r.kind==="declared"&&await U(n,o,r),await an(n,o,r),o.name==="sqlite"&&await m(n,o,k(r.name,r.table))}await $n(n,e,s,o)},R="__lunora_migration_state",wn=async(n,e)=>{await m(n,e,i`CREATE TABLE IF NOT EXISTS ${i.identifier(R)} (${i.identifier("name")} ${i.raw(e.companionTypes.key)} PRIMARY KEY)`)},Tn=async(n,e,t)=>(await $(n,e,i`SELECT ${i.identifier("name")} FROM ${i.identifier(R)} WHERE ${i.identifier("name")} = ${t}`)).length>0,_n=async(n,e,t,o,s,r)=>{s>0&&r!==void 0&&console.warn(`[@lunora/sql-store] storage migration "${t}" on "${o}": ${String(s)} row(s) ${r} and were left as stored — range filters and ORDER BY over them stay wrong until they are corrected by hand.`);try{await m(n,e,i`INSERT INTO ${i.identifier(R)} (${i.identifier("name")}) VALUES (${t})`)}catch(a){if(!e.isUniqueViolation(a))throw a}},hn=100,pn=(n,e)=>{const t=[],o=[];for(const s of e.fields){const r=n[s],a=e.convert(r);a!==void 0&&(t.push(i`${c(s)} = ${a}`),o.push(i`${c(s)} = ${r}`))}return{assignments:t,guards:o}},yn=n=>i.join(n.fields.map(e=>n.probe(e)),i` OR `),M=async(n,e,t,o)=>{if(o.fields.length===0||(await wn(n,t),await Tn(n,t,o.marker)))return;const s=yn(o),r=i.join([c("id"),...o.fields.map(u=>c(u))],i`, `);let a="",l=0;for(;;){const u=await $(n,t,i`SELECT ${r} FROM ${i.identifier(e)} WHERE (${s}) AND ${c("id")} > ${a} ORDER BY ${c("id")} LIMIT ${i.raw(String(hn))}`);if(u.length===0){await _n(n,t,o.marker,e,l,o.describeUnconvertible);return}const d=[];for(const E of u){const{id:_}=E,{assignments:h,guards:p}=typeof _=="string"?pn(E,o):{assignments:[],guards:[]};if(h.length===0){l+=1;continue}d.push(i`UPDATE ${i.identifier(e)} SET ${i.join(h,i`, `)} WHERE ${c("id")} = ${_} AND ${i.join(p,i` AND `)}`)}await z(n,t,d);const f=u.at(-1)?.id;if(typeof f!="string")return;a=f}},C=n=>`'${n}%'`,Sn=n=>Object.entries(n.shape).filter(([,e])=>e._meta?.column!==void 0&&T(e)==="bigint").map(([e])=>e),In=n=>Object.entries(n.shape).filter(([,e])=>e._meta?.column!==void 0&&nn(T(e))).map(([e])=>e),B=(n,e)=>({convert:t=>{if(!(typeof t!="string"||t.length===b))try{return G(BigInt(t))}catch{return}},describeUnconvertible:"hold a value the order-preserving key cannot represent (non-numeric text, or a magnitude past 39 digits)",fields:Sn(e),marker:`bigint-key:${n}`,probe:t=>i`(${c(t)} IS NOT NULL AND LENGTH(${c(t)}) <> ${b})`}),An=async(n,e,t,o)=>M(n,e,o,B(e,t)),F=(n,e)=>({convert:J,fields:In(e),marker:`untyped-number-key:${n}`,probe:t=>i`(${c(t)} LIKE ${i.raw(C(en))} AND ${c(t)} NOT LIKE ${i.raw(C(tn))})`}),Rn=async(n,e,t,o)=>M(n,e,o,F(e,t)),Ln=async(n,e,t,o)=>{const s=sn(e,t,o);await m(n,o,i`CREATE TABLE IF NOT EXISTS ${i.identifier(e)} (${s})`),await H(n,e,t,o),await W(n,e,t,o),await gn(n,e,t,o),await An(n,e,t,o),await Rn(n,e,t,o)},Bn=(n,e)=>[B(n,e),F(n,e)].filter(t=>t.fields.length>0),Fn=async(n,e,t,o)=>{let s=!1;for(const[r,a]of Object.entries(e.tables))a.shardMode?.kind!=="global"||o!==void 0&&!o.has(r)||(s||(s=!0,await mn(n,t,Object.entries(e.tables).filter(([,l])=>l.shardMode?.kind==="global").map(([l])=>l))),await Ln(n,r,a,t))},P=n=>n.shardMode===void 0||n.shardMode.kind==="global",Pn=async(n,e,t)=>{const{integer:o,key:s,real:r}=t.companionTypes;for(const[a,l]of Object.entries(e.tables)){const u=l.aggregateIndexes;if(!(!u||u.length===0||!P(l)))for(const d of u){const f=j(a,d.name);await m(n,t,i`CREATE TABLE IF NOT EXISTS ${i.identifier(f)} (${i.identifier("__key__")} ${i.raw(s)} PRIMARY KEY, ${i.identifier("__value__")} ${i.raw(r)}, ${i.identifier("__count__")} ${i.raw(o)} NOT NULL DEFAULT 0)`),t.name==="sqlite"&&await V(n,t,f,"__count__",`${o} NOT NULL DEFAULT 0`)}}},S=(n,e,t,o)=>{const s=n.name==="mysql"&&o?i`${i.identifier(e)}(191)`:i`${i.identifier(e)}`;return i`${s} ${i.raw(t)}`},Nn=(n,e,t)=>{const o=[S(n,"__partition__","ASC",!0)];for(const[s,r]of e.sortBy.entries()){const a=t.shape[r.field],l=a!==void 0&&n.indexKeyPrefix?.(T(a))!==void 0;o.push(S(n,A(s),r.direction==="desc"?"DESC":"ASC",l))}return o.push(S(n,"__id__","ASC",!0)),o},bn=(n,e,t)=>e.sortBy.map((o,s)=>{const r=t.shape[o.field],a=n.columnType(r?T(r):void 0);return i`${i.identifier(A(s))} ${i.raw(a)}`}),On=/__sort_k\d+__/gu,Cn=async(n,e,t,o)=>{if(e.name!=="sqlite")return;const r=(await $(n,e,i`SELECT sql FROM sqlite_master WHERE type = 'table' AND name = ${t} COLLATE NOCASE`))[0]?.sql;if(typeof r!="string")return;const a=r.match(On)??[];(a.length!==o.length||a.some((l,u)=>l!==o[u]))&&await m(n,e,i`DROP TABLE ${i.identifier(t)}`)},Kn=async(n,e,t)=>{const{key:o}=t.companionTypes;for(const[s,r]of Object.entries(e.tables)){const a=r.rankIndexes;if(!(!a||a.length===0||!P(r)))for(const l of a){const u=N-4;if(l.sortBy.length>u)throw new I("BAD_REQUEST",`rank index "${l.name}" on ${s} has ${String(l.sortBy.length)} sort keys; at most ${String(u)} fit the ${String(N)} parameters one statement binds`);const d=X(s,l.name),f=bn(t,l,r);await Cn(n,t,d,l.sortBy.map((qn,K)=>A(K)));const E=f.length>0?i`, ${i.join(f,i`, `)}`:i``;await m(n,t,i`CREATE TABLE IF NOT EXISTS ${i.identifier(d)} (${i.identifier("__id__")} ${i.raw(o)} PRIMARY KEY, ${i.identifier("__partition__")} ${i.raw(o)} NOT NULL${E})`);const _=Nn(t,l,r),h=`${s}__rank_${l.name}__btree`,p={columns:i.join(_,i`, `),name:h,refs:[],table:d,unique:!1};await U(n,t,p),await y(n,t,p)}}};export{w as INDEX_LEDGER_TABLE,R as MIGRATION_STATE_TABLE,ln as declaredIndexColumnList,g as foldIdentifier,sn as globalTableColumnsDdl,dn as globalTableIndexSpecs,D as indexColumnList,cn as indexLedgerDdl,un as indexShapeChanged,Bn as legacyRewrites,yn as legacyRowPredicate,Ln as provisionGlobalTable,Fn as provisionGlobalTablesSequentially,k as recordIndexStatement,Pn as runSqlAggregateMigrations,Kn as runSqlRankMigrations,En as undeclaredFrameworkIndexes};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{sql as a}from"drizzle-orm";import{w as A}from"./column-provisioning-DsVyt-k5.mjs";import{provisionGlobalTablesSequentially as m,foldIdentifier as f,globalTableColumnsDdl as L,globalTableIndexSpecs as O,legacyRewrites as R,indexLedgerDdl as k,undeclaredFrameworkIndexes as y,indexShapeChanged as $,INDEX_LEDGER_TABLE as T,MIGRATION_STATE_TABLE as E,recordIndexStatement as M,legacyRowPredicate as C}from"./runSqlAggregateMigrations-l-lqWvIq.mjs";import{a as q,q as g}from"./sql-exec-j9zVLMn5.mjs";const v=50,h=new Map([["'","'"],["[","]"],["`","`"],['"','"']]),N=/^[\w$]+/u,b=(e,r)=>{const n=h.get(e[r]);let t=r+1;for(;t<e.length;)if(e[t]!==n)t+=1;else if(n!=="]"&&e[t+1]===n)t+=2;else return t+1;return t},_=e=>{const r=e.trim(),n=h.get(r[0]??"");if(n===void 0)return N.exec(r)?.[0];const t=b(r,0),s=r.slice(1,r[t-1]===n?t-1:t);return n==="]"?s:s.replaceAll(`${n}${n}`,n)},B=e=>{const r=new Set,n=i=>{const d=_(i);d!==void 0&&r.add(d)};let t=0,s=0,o=0;for(;o<e.length;){const i=e[o];if(h.has(i)){o=b(e,o);continue}if(i==="(")t+=1,s=t===1?o+1:s;else if(i===")"){if(t-=1,t===0)return n(e.slice(s,o)),r}else i===","&&t===1&&(n(e.slice(s,o)),s=o+1);o+=1}return r},F=async(e,r,n)=>{const t=new Set,s=new Map,o=n.has(f(T)),i=[];if(n.has(f(E))&&i.push(a`SELECT 'marker' AS kind, name, NULL AS owner FROM ${a.identifier(E)}`),o&&i.push(a`SELECT 'index' AS kind, "l"."name" AS name, "l"."table_name" AS owner FROM ${a.identifier(T)} AS "l"`),i.length===0)return{hasLedger:o,markers:t,owned:s};for(const d of await g(e,r,a.join(i,a` UNION ALL `)))if(d.kind==="marker")t.add(String(d.name));else{const c=f(String(d.owner));s.set(c,[...s.get(c)??[],String(d.name)])}return{hasLedger:o,markers:t,owned:s}},D=async(e,r)=>{try{const n=await g(e,r,a`SELECT type, name, tbl_name, sql FROM sqlite_master WHERE type IN ('table', 'index')`),t=new Set,s=new Map,o=new Map;for(const l of n){const u=String(l.name);if(u.startsWith("sqlite_"))continue;const S=typeof l.sql=="string"?l.sql:void 0;l.type==="table"?(t.add(f(u)),s.set(f(u),new Set([...S===void 0?[]:B(S)].map(I=>f(I))))):o.set(f(u),S)}const{hasLedger:i,markers:d,owned:c}=await F(e,r,t);return{columns:s,hasLedger:i,indexes:o,markers:d,owned:c,tables:t}}catch{return}},w=e=>e.kind==="default-order"?[]:[M(e.name,e.table)],p=e=>{const r=e.unique?a`UNIQUE `:a``;return a`CREATE ${r}INDEX IF NOT EXISTS ${a.identifier(e.name)} ON ${a.identifier(e.table)} (${e.columns})`},x=(e,r,n)=>n.length===0?[]:[a`CREATE TABLE IF NOT EXISTS ${a.identifier(E)} (${a.identifier("name")} ${a.raw(e.companionTypes.key)} PRIMARY KEY)`,...n.map(t=>a`INSERT OR IGNORE INTO ${a.identifier(E)} (${a.identifier("name")}) SELECT ${t.marker} WHERE NOT EXISTS (SELECT 1 FROM ${a.identifier(r)} WHERE ${C(t)})`)],G=(e,r,n,t)=>{const s=L(e,r,n),o=O(e,r,n),i=R(e,r);if(!t.tables.has(f(e)))return[...t.hasLedger?[]:[k()],a`CREATE TABLE IF NOT EXISTS ${a.identifier(e)} (${s})`,...o.flatMap(l=>[p(l),...w(l)]),...x(n,e,i)];const d=t.columns.get(f(e))??new Set;if(A(r,n).some(([l])=>!d.has(f(l)))||i.some(l=>!t.markers.has(l.marker))||y(n,o,t.owned.get(f(e))??[]).length>0)return;const c=[];for(const l of o){if(!t.indexes.has(f(l.name))){c.push(p(l),...w(l));continue}const u=t.indexes.get(f(l.name));if(l.kind==="declared"&&typeof u=="string"&&$(n,u,l))return}return c},X=e=>{const r=[];let n=[],t=0;for(const s of e)n.length>0&&t+s.statements.length>v&&(r.push(n),n=[],t=0),n.push(s),t+=s.statements.length;return n.length>0&&r.push(n),r},U=(e,r)=>!r.hasLedger&&Object.entries(e.tables).some(([n,t])=>t.shardMode?.kind==="global"&&r.tables.has(f(n))),P=async(e,r,n)=>{if(!e.batch||n.name!=="sqlite"){await m(e,r,n);return}const t=await D(e,n);if(t===void 0){await m(e,r,n);return}if(U(r,t)){await m(e,r,n);return}const s=[],o=new Set;for(const[i,d]of Object.entries(r.tables)){if(d.shardMode?.kind!=="global")continue;const c=G(i,d,n,t);c===void 0?o.add(i):c.length>0&&s.push({statements:c,table:i})}for(const i of X(s))try{await q(e,n,i.flatMap(d=>d.statements))}catch{for(const d of i)o.add(d.table)}await m(e,r,n,o)};export{B as columnNamesOfCreateTable,P as runSqlGlobalTableMigrations};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{LunoraError as A}from"@lunora/errors";import{needsWireEncoding as J}from"@lunora/wire";import{sql as s,SQL as v}from"drizzle-orm";import{a as g,s as x,e as U}from"./value-codec-
|
|
1
|
+
import{LunoraError as A}from"@lunora/errors";import{needsWireEncoding as J}from"@lunora/wire";import{sql as s,SQL as v}from"drizzle-orm";import{a as g,s as x,e as U}from"./value-codec-DhzLXsqv.mjs";const W=t=>{if(t===null||typeof t!="object")return!1;const n=Object.getPrototypeOf(t);return n===null||n===Object.prototype},p=4;class T extends Error{}const S=t=>t.includes("."),w=t=>{const n=t.split(".");if(n.length>p||n.includes(""))throw new T(`field path "${t}" must have 1 to ${String(p)} non-empty segments`);return n},it=(t,n)=>{if(!S(n))return t[n];let e=t;for(const r of w(n)){if(!W(e)||!Object.hasOwn(e,r))return;e=e[r]}return e},B={boolean:"'true', 'false'",number:"'integer', 'real'",string:"'text'"},X=/^[A-Za-z_$][\w$]*$/u,R=t=>X.test(t)?t:`"${t.replaceAll("\\",String.raw`\\`).replaceAll('"',String.raw`\"`)}"`,at="_version",ct=100,I=t=>t==="_id"||t==="id"?"id":t,$=t=>s`${s.identifier(I(t))}`,C=t=>{try{return w(t)}catch(n){throw n instanceof T?new A("VALIDATION_ERROR",n.message):n}},q=new WeakMap,lt=t=>q.get(t),b=(t,n)=>{let e=s`${t}::jsonb`;for(const r of n)e=s`${e} -> ${r}::text`;return s`NULLIF(${e}, 'null'::jsonb)`},k=(t,n)=>s`CASE WHEN pg_input_is_valid(${t}, 'jsonb') THEN ${b(t,n)} END`,K=(t,n)=>s`CASE WHEN pg_input_is_valid(${t}, 'jsonb') THEN ${b(t,n)} #>> '{}' END`,L=(t,n)=>{const e=`$${n.map(r=>`.${R(r)}`).join("")}`;return s`NULLIF(JSON_EXTRACT(${t}, ${e}), CAST('null' AS JSON))`},V=(t,n)=>s`CASE WHEN JSON_VALID(${t}) THEN ${L(t,n)} END`,z=(t,n)=>s`CASE WHEN JSON_VALID(${t}) THEN JSON_UNQUOTE(${L(t,n)}) END`,ut=(t,n)=>t==="postgres"?s`(${n})::jsonb #>> '{}'`:s`JSON_UNQUOTE(${n})`,y=(t,n)=>{const[e="",...r]=C(n),o=$(e);return s`CASE WHEN json_valid(${o}) THEN ${s.raw(t)}(${o}, ${`$.${r.map(i=>R(i)).join(".")}`}) END`},G=(t,n)=>{if(!S(n))return $(n);if(t.name==="sqlite")return y("json_extract",n);const[e="",...r]=C(n),o=$(e),i=t.name==="postgres",a=i?k(o,r):V(o,r);return q.set(a,i?K(o,r):z(o,r)),a},D=new WeakMap,M=t=>s`CAST(CAST(${t} AS text) AS jsonb)`,dt=(t,n,e)=>{if(t.name==="sqlite")return s`NULLIF(${y("json_type",n)}, 'null') IN (${s.raw(B[e])})`;const r=G(t,n);if(t.name==="postgres")return s`jsonb_typeof(${r}) = ${s.raw(`'${e}'`)}`;const o={boolean:"'BOOLEAN'",number:"'INTEGER', 'UNSIGNED INTEGER', 'DOUBLE', 'DECIMAL'",string:"'STRING'"}[e];return s`JSON_TYPE(${r}) IN (${s.raw(o)})`},Q=(t,n)=>{if(n===void 0)return n;if(typeof n=="bigint"||J(n))return t==="postgres"?s`CAST(NULL AS jsonb)`:s`CAST(NULL AS JSON)`;const e=JSON.stringify(n),r=t==="postgres"?s`${M(e)}`:s`CAST(${e} AS JSON)`;return D.set(r,e),r},ft=(t,n,e,r)=>{const o=[];let i=!1;for(const u of e){if(u===void 0)throw new A("BAD_REQUEST","an `in` list holds an undefined value");const d=u instanceof v?D.get(u):void 0;d===void 0?i=!0:o.push(d)}if(o.length===0||r&&i)return s`1 = 0`;const a=`[${o.join(",")}]`,c=t==="postgres"?s`SELECT e.v FROM jsonb_array_elements(${M(a)}) AS e(v)`:s`SELECT jt.v FROM JSON_TABLE(${a}, '$[*]' COLUMNS (v JSON PATH '$')) AS jt`;return r?s`${n} NOT IN (${c})`:s`${n} IN (${c})`},Et=(t,n,e,r)=>t.name==="sqlite"||!S(n)||e===null?r(e):Q(t.name,e),$t=(t,n)=>s`${s.identifier(t)}.${s.identifier(I(n))}`,mt=t=>{const n=[];for(const[e,r]of Object.entries(t.shape)){const o=r._meta?.column;o&&n.push([e,o])}return n},f=(t,n,e)=>{const{params:r,sql:o}=n.render(e);return t.all(o,r)},l=(t,n,e)=>{const{params:r,sql:o}=n.render(e);return t.run(o,r)},St=(t,n,e)=>t==="postgres"?s`${n} IS NOT DISTINCT FROM ${e}`:t==="mysql"?s`${n} <=> ${e}`:s`${n} IS ${e}`,Nt={sql:t=>s`COALESCE(${t}, 0) + 1`,value:t=>(t==null?0:Number(t))+1},pt=async(t,n,e)=>{if(e.length!==0){if(!t.batch){for(const r of e)await l(t,n,r);return}await t.batch(e.map(r=>n.render(r)))}},_t=async(t,n,e)=>{if(t.batch&&n.name==="sqlite"){await t.batch(e.map(r=>n.render(r)));return}for(const r of e)await l(t,n,r)},Ot=async(t,n,e)=>{const r=e.unique?s`UNIQUE `:s``,o=e.concurrently===!0&&n.name==="postgres"?s`CONCURRENTLY `:s``;if(n.name==="mysql"){try{await l(t,n,s`CREATE ${r}INDEX ${s.identifier(e.name)} ON ${s.identifier(e.table)} (${e.columns})`)}catch(i){const a=i;if(a.errno!==1061&&a.code!=="ER_DUP_KEYNAME"&&a.code!==1061)throw i}return}await l(t,n,s`CREATE ${r}INDEX ${o}IF NOT EXISTS ${s.identifier(e.name)} ON ${s.identifier(e.table)} (${e.columns})`)},j=(t,n)=>s`(SELECT ${s.identifier("c")}.oid FROM pg_index ${s.identifier("i")} JOIN pg_class ${s.identifier("c")} ON ${s.identifier("c")}.oid = ${s.identifier("i")}.indexrelid WHERE ${s.identifier("i")}.indrelid = to_regclass(quote_ident(${t})) AND ${s.identifier("c")}.relname = ${n}::name)`,ht=async(t,n,e,r)=>{if(n.name==="postgres"){const[o]=await f(t,n,s`SELECT quote_ident(${s.identifier("n")}.nspname) || '.' || quote_ident(${s.identifier("c")}.relname) AS ${s.identifier("qualified")} FROM pg_class ${s.identifier("c")} JOIN pg_namespace ${s.identifier("n")} ON ${s.identifier("n")}.oid = ${s.identifier("c")}.relnamespace WHERE ${s.identifier("c")}.oid = ${j(e,r)}`),i=o?.qualified;typeof i=="string"&&await l(t,n,s`DROP INDEX IF EXISTS ${s.raw(i)}`);return}if(n.name!=="mysql"){await l(t,n,s`DROP INDEX IF EXISTS ${s.identifier(r)}`);return}try{await l(t,n,s`DROP INDEX ${s.identifier(r)} ON ${s.identifier(e)}`)}catch(o){const i=o;if(i.errno!==1091&&i.code!=="ER_CANT_DROP_FIELD_OR_KEY"&&i.code!==1091)throw o}},At=async(t,n,e,r)=>{switch(n.name){case"mysql":return(await f(t,n,s`SELECT 1 AS ${s.identifier("present")} FROM information_schema.statistics WHERE table_schema = DATABASE() AND table_name = ${e} AND index_name = ${r} LIMIT 1`)).length>0?"valid":"absent";case"postgres":{const o=await f(t,n,s`SELECT indisvalid FROM pg_index WHERE indexrelid = ${j(e,r)}`);return o.length===0?"absent":o[0]?.indisvalid===!0?"valid":"invalid"}default:return(await f(t,n,s`SELECT 1 AS ${s.identifier("present")} FROM sqlite_master WHERE type = 'index' AND name = ${r} AND tbl_name = ${e}`)).length>0?"valid":"absent"}},gt=g,m=t=>{if(t===void 0)return!1;if(t._meta?.column?.notNull===!1)return!0;switch(t.kind){case"any":case"null":return!0;case"literal":return t._meta?.value===null;case"optional":return m(t._meta?.inner);case"union":return t._meta?.members?.some(n=>m(n))===!0;default:return!1}},Y=t=>t.kind==="optional"&&!m(t),_=new WeakMap,P=t=>{let n=_.get(t);return n===void 0&&(n=Object.entries(t.shape).map(([e,r])=>[e,U(r),Y(r)]),_.set(t,n)),n},O=new WeakMap,Z=(t,n)=>{let e=O.get(t);return e===void 0&&(e=new Map(P(t).map(([r,o])=>[r,o])),O.set(t,e)),e.get(n)},Tt=(t,n,e)=>g(e,Z(t,n)),tt=(t,n)=>{const e={};for(const[r,o,i]of P(t)){const a=n[r];a===void 0||i&&a===null||(e[r]=x(a,o))}return e._id=n.id,e._creationTime=n._creationTime,e},F=(t,n)=>n?tt(t,n):null,wt=(t,n)=>{const e=[];for(const r of n){const o=F(t,r);o&&e.push(o)}return e},h=500,nt=(t,n,e,r,o)=>{const i=s`${s.identifier(e)}.${s.identifier("id")}`,a=r===void 0?s``:s` WHERE ${i} > ${r}`;return f(t,n,s`SELECT * FROM ${s.identifier(e)}${a} ORDER BY ${i} ASC LIMIT ${s.raw(String(o))}`)},Rt=async(t,n,e,r,o,i={})=>{let a=i.after,c=i.limit,u=!0;for(;u&&(c===void 0||c>0);){const d=c===void 0?h:Math.min(h,c),E=await nt(t,n,r,a,d);for(const H of E){const N=F(e,H);N&&await o(N)}a=E.at(-1)?.id,u=E.length===d,c=c===void 0?void 0:c-E.length}};export{h as B,ct as M,at as O,_t as a,l as b,Ot as c,tt as d,$ as e,pt as f,ut as g,ht as h,At as i,ft as j,F as k,wt as l,gt as m,G as n,St as o,lt as p,f as q,nt as r,Tt as s,mt as t,Nt as u,it as v,Et as w,dt as x,Rt as y,$t as z};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{LunoraError as m}from"@lunora/errors";import{bigintSqlKey as E,float64SqlKey as g,decodeBigintSqlKey as p,BIGINT_KEY_DIGITS as A,decodeFloat64SqlKey as _}from"@lunora/shard-engine";import{WIRE_TAG as y,needsWireEncoding as l,encodeWire as B,decodeWire as I}from"@lunora/wire";const N=t=>{const{value:e}=t._meta??{};if(e===null)return"null";switch(typeof e){case"bigint":case"boolean":case"number":case"string":return typeof e;default:return t.kind}},h=t=>{if(t.kind==="literal")return N(t);if(t.kind!=="optional")return t.kind;const e=t._meta?.inner;return e?h(e):t.kind},n=y,s="#",o="$",f=y+s,K=y,u=(t,e)=>{if(!t.startsWith(n))return e(t);const r=t.slice(n.length);return r.startsWith(s)?_(r.slice(s.length))??t:r.startsWith(o)?r.slice(o.length):I(e(r))},b=new Set(["any","from","union"]),S=(t,e)=>{if(!(e===void 0||!b.has(e)))return typeof t=="number"?f+g(t):typeof t=="string"?t.startsWith(n)?n+o+t:void 0:typeof t=="boolean"?n+JSON.stringify(t):void 0},d=t=>t instanceof ArrayBuffer?t:ArrayBuffer.isView(t)?new Uint8Array(t.buffer,t.byteOffset,t.byteLength).slice().buffer:Array.isArray(t)?Uint8Array.from(t).buffer:t,R=(t,e)=>{const r=S(t,e);if(r!==void 0)return r;if(typeof t=="boolean")return t?1:0;if(t===null||typeof t=="string"||typeof t=="number")return t;if(typeof t=="bigint")return E(t);if(t instanceof Uint8Array)return t;if(t instanceof ArrayBuffer)return new Uint8Array(t);try{return l(t)?n+JSON.stringify(B(t)):JSON.stringify(t)}catch(i){throw new m("BAD_REQUEST",`this value cannot be stored: ${i instanceof Error?i.message:String(i)}`)}},c=t=>{try{return JSON.parse(t)}catch{return t}},G=t=>{if(typeof t!="string"||!t.startsWith(n)||t.startsWith(f))return;const e=c(t.slice(n.length));return typeof e=="number"?f+g(e):void 0},P=t=>t!==void 0&&b.has(t),W=t=>{if(typeof t!="string")return t;const e=p(t);if(e!==void 0)return e;try{return BigInt(t)}catch{return t}},D=t=>h(t),q=(t,e)=>{if(t===null)return t;switch(e){case"any":case"from":case"union":return typeof t!="string"?t instanceof ArrayBuffer||ArrayBuffer.isView(t)||Array.isArray(t)?d(t):t:t.startsWith("{")||t.startsWith("[")||t.startsWith(n)?u(t,c):p(t)??t;case"array":case"geoPoint":case"object":case"record":return typeof t=="string"?u(t,c):t;case"bigint":return W(t);case"boolean":return t===0||t===1?t===1:t;case"bytes":return d(t);default:return t}},J=A+1;export{J as B,K as U,R as a,
|
|
1
|
+
import{LunoraError as m}from"@lunora/errors";import{bigintSqlKey as E,float64SqlKey as g,decodeBigintSqlKey as p,BIGINT_KEY_DIGITS as A,decodeFloat64SqlKey as _}from"@lunora/shard-engine";import{WIRE_TAG as y,needsWireEncoding as l,encodeWire as B,decodeWire as I}from"@lunora/wire";const N=t=>{const{value:e}=t._meta??{};if(e===null)return"null";switch(typeof e){case"bigint":case"boolean":case"number":case"string":return typeof e;default:return t.kind}},h=t=>{if(t.kind==="literal")return N(t);if(t.kind!=="optional")return t.kind;const e=t._meta?.inner;return e?h(e):t.kind},n=y,s="#",o="$",f=y+s,K=y,u=(t,e)=>{if(!t.startsWith(n))return e(t);const r=t.slice(n.length);return r.startsWith(s)?_(r.slice(s.length))??t:r.startsWith(o)?r.slice(o.length):I(e(r))},b=new Set(["any","from","union"]),S=(t,e)=>{if(!(e===void 0||!b.has(e)))return typeof t=="number"?f+g(t):typeof t=="string"?t.startsWith(n)?n+o+t:void 0:typeof t=="boolean"?n+JSON.stringify(t):void 0},d=t=>t instanceof ArrayBuffer?t:ArrayBuffer.isView(t)?new Uint8Array(t.buffer,t.byteOffset,t.byteLength).slice().buffer:Array.isArray(t)?Uint8Array.from(t).buffer:t,R=(t,e)=>{const r=S(t,e);if(r!==void 0)return r;if(typeof t=="boolean")return t?1:0;if(t===null||typeof t=="string"||typeof t=="number")return t;if(typeof t=="bigint")return E(t);if(t instanceof Uint8Array)return t;if(t instanceof ArrayBuffer)return new Uint8Array(t);try{return l(t)?n+JSON.stringify(B(t)):JSON.stringify(t)}catch(i){throw new m("BAD_REQUEST",`this value cannot be stored: ${i instanceof Error?i.message:String(i)}`)}},c=t=>{try{return JSON.parse(t)}catch{return t}},G=t=>{if(typeof t!="string"||!t.startsWith(n)||t.startsWith(f))return;const e=c(t.slice(n.length));return typeof e=="number"?f+g(e):void 0},P=t=>t!==void 0&&b.has(t),W=t=>{if(typeof t!="string")return t;const e=p(t);if(e!==void 0)return e;try{return BigInt(t)}catch{return t}},D=t=>h(t),q=(t,e)=>{if(t===null)return t;switch(e){case"any":case"from":case"union":return typeof t!="string"?t instanceof ArrayBuffer||ArrayBuffer.isView(t)||Array.isArray(t)?d(t):t:t.startsWith("{")||t.startsWith("[")||t.startsWith(n)?u(t,c):p(t)??t;case"array":case"geoPoint":case"object":case"record":return typeof t=="string"?u(t,c):t;case"bigint":return W(t);case"boolean":return t===0||t===1?t===1:t;case"bytes":return d(t);default:return t}},J=A+1;export{J as B,K as U,R as a,f as b,h as c,W as d,D as e,P as i,G as r,q as s,c as t};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@lunora/sql-store",
|
|
3
|
-
"version": "1.0.0-alpha.
|
|
3
|
+
"version": "1.0.0-alpha.237",
|
|
4
4
|
"description": "Internal dialect-parameterized SQL store core for Lunora .global() backends (D1, PlanetScale)",
|
|
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": "
|
|
17
|
+
"license": "Apache-2.0",
|
|
18
18
|
"author": {
|
|
19
19
|
"name": "Daniel Bannert",
|
|
20
20
|
"email": "d.bannert@anolilab.de"
|
|
@@ -51,7 +51,7 @@
|
|
|
51
51
|
},
|
|
52
52
|
"dependencies": {
|
|
53
53
|
"@lunora/errors": ">=1.0.0-alpha.77 <2.0.0-0",
|
|
54
|
-
"@lunora/shard-engine": "^1.0.0-alpha.
|
|
54
|
+
"@lunora/shard-engine": "^1.0.0-alpha.191",
|
|
55
55
|
"@lunora/wire": "1.0.0-alpha.6",
|
|
56
56
|
"drizzle-orm": "1.0.0-rc.5"
|
|
57
57
|
},
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import"./ctx-db-search-state-BBPiVWjf.mjs";import{b as o,c as i,a as s,d as l,r as n}from"./ctx-db-search-bBDPdaOs.mjs";import"./DEFAULT_QUERY_TIMEOUT_MS-D7YkDNaV.mjs";import"./sql-exec-enIOMsv0.mjs";export{o as backfillSqlSearchIndexes,i as createSearchSync,s as reconcileSearchRow,l as runSqlSearch,n as runSqlSearchMigrations};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{LunoraError as p}from"@lunora/errors";import{q as U,c as qt,m as Ft,r as C,a as Ut,l as q,w as F,b as kt}from"./ctx-db-search-state-BBPiVWjf.mjs";import{ftsUnmappedPage as bt,groupUnmappedRows as Ht,ftsWriteDocument as mt,ftsPurgeDocument as ht,ftsCompanionDdl as Pt,unionAll as Bt,ftsRowidMapName as Wt}from"@lunora/shard-engine";import{sql as r}from"drizzle-orm";import{abandonedWork as jt}from"./DEFAULT_QUERY_TIMEOUT_MS-D7YkDNaV.mjs";import{O as xt,q as h,n as Kt,h as X,a as N,i as L,e as J,f as v,c as y,k as pt,j as ot,l as Gt,r as Yt,x as Qt}from"./sql-exec-enIOMsv0.mjs";const Vt=n=>{const t=atob(n),e=Uint8Array.from(t,i=>i.codePointAt(0)??0);return new TextDecoder().decode(e)},Xt=()=>new p("BAD_REQUEST","invalid cursor"),st=16,at=8,T=1024,k=(n,t)=>t.query(n),Jt=(n,t)=>{if(!t)return{exact:!0,lower:n,upper:n};const e=[...n].at(-1)??"",i=(e.codePointAt(0)??0)+1;if(i>=55296&&i<=57343||i>1114111)return{exact:!0,lower:n,upper:n};const o=n.slice(0,n.length-e.length);return{exact:!1,lower:n,upper:o+String.fromCodePoint(i)}},Dn=(n,t,e)=>{const i={eq:(o,s)=>{if(!n.definition.filterFields?.includes(o))throw new p("INTERNAL",`field "${o}" is not a filter field of search index "${n.indexName}" on table "${t}"`);if(n.filters.length>=at)throw new p("BAD_REQUEST",`search index "${n.indexName}" on table "${t}": at most ${String(at)} .eq() filters are supported per search query`);return n.filters.push({field:o,value:s}),i},search:(o,s)=>{const a=n;if(o!==a.definition.field)throw new p("INTERNAL",`search index "${a.indexName}" on table "${t}" indexes "${a.definition.field}", not "${o}"`);const f=k(s,e).length;if(f>st)throw new p("BAD_REQUEST",`search index "${a.indexName}" on table "${t}": at most ${String(st)} search terms are supported (got ${String(f)})`);return a.field=o,a.query=s,a.hasQuery=!0,i}};return i},qn=n=>{if(n.length>T)throw new p("BAD_REQUEST",`more than ${String(T)} documents match this search — narrow it with filters or read it a page at a time with .paginate()`)},Fn=n=>Math.min(n.offset+n.numItems+1,T),zt=n=>btoa(`search:${String(n)}`),Zt=n=>{let t;try{t=Vt(n)}catch{return}if(!t.startsWith("search:"))return;const e=Number(t.slice(7));return Number.isInteger(e)&&e>=0?e:void 0},Un=n=>{if(typeof n.endCursor=="string")throw new p("BAD_REQUEST","bounded (endCursor) pagination is not supported on search queries — relevance order has no stable range boundary");if(!Number.isFinite(n.numItems))throw new p("BAD_REQUEST",`search pagination needs a finite numItems, got ${String(n.numItems)}`);const t=Math.max(0,Math.floor(n.numItems)),e=n.cursor?Zt(n.cursor):0;if(e===void 0)throw Xt();if(e+t>=T)throw new p("BAD_REQUEST",`search pagination reaches the ${String(T)}-document limit (offset ${String(e)} + ${String(t)} requested) — a page must end below the cap so the probe row that answers \`hasMore\` still fits: retry with numItems ${String(Math.max(1,T-e-1))} or fewer, or narrow the query or the filters instead`);return{numItems:t,offset:e}},kn=(n,t)=>{const e=t.offset+t.numItems,i=t.numItems>0&&n.length>e;return{continueCursor:i?zt(e):null,isDone:!i,page:n.slice(t.offset,e)}},bn=n=>{if(n===void 0)return T+1;if(!Number.isFinite(n))return T;const t=Math.max(0,Math.floor(n));if(t>T)throw new p("BAD_REQUEST",`search returns at most ${String(T)} documents (asked for ${String(t)}) — narrow the query or paginate instead`);return t},tn=(n,t)=>{if(!t.includes("."))return n[t];let e=n;for(const i of t.split(".")){if(e===null||typeof e!="object"||Array.isArray(e))return;e=e[i]}return e},b=(n,t)=>`${n}__fts_${t}`,l="__id__",g="__token__",O="__n__",nn=1e3,en=(n,t)=>t.document(n),G=(n,t)=>tn(n,t),rn=n=>typeof n=="string"?n:n==null?"":typeof n=="number"||typeof n=="bigint"||typeof n=="boolean"?String(n):JSON.stringify(n)??"",on=(n,t,e)=>n!==void 0&&t!==void 0&&G(n,e.field)===G(t,e.field),gt=(n,t)=>en(rn(G(n,t.field)),U(t.language)).slice(0,nn),z=(n,t)=>gt(n,t).join(" "),yt=(n,t)=>{const e=new Map;for(const i of gt(n,t))e.set(i,(e.get(i)??0)+1);return e},Tt=[xt,"_creationTime"],ft=50,d=(n,t)=>r`${r.identifier(n)}.${r.identifier(t)}`,M=(n,t,e)=>r`DELETE FROM ${r.identifier(n)} WHERE ${d(n,l)} = ${t}${e===void 0?r``:r` AND ${e}`}`,Rt=(n,{row:t,table:e})=>{const i=Tt.map(o=>r` AND ${Kt(n.name,d(e,o),t[o]??null)}`);return r`SELECT 1 FROM ${r.identifier(e)} WHERE ${d(e,"id")} = ${t.id}${r.join(i)}${n.name==="postgres"?r` FOR SHARE`:r``}`},D=(n,t)=>r`EXISTS (${Rt(n,t)})`,H=(n,t)=>r`NOT EXISTS (SELECT 1 FROM ${r.identifier(n)} WHERE ${d(n,"id")} = ${t})`,_t=(n,t,e,i)=>i===void 0?H(t,e):D(n,{row:i,table:t}),P=async(n,t,e,i)=>{const o=new Map;for(let s=0;s<i.length;s+=ft){const a=i.slice(s,s+ft),f=await h(n,t,r`SELECT * FROM ${r.identifier(e)} WHERE ${d(e,"id")} IN (${r.join(a.map(c=>r`${c}`),r`, `)})`);for(const c of f)o.set(String(c.id),c)}return o},Y=(n,t,e)=>n.name==="mysql"?r`${r.identifier(t)}(${r.raw(String(e))})`:n.textPatternOperatorClass===void 0?r`${r.identifier(t)}`:r`${r.identifier(t)} ${r.raw(n.textPatternOperatorClass)}`,Z=512,tt=(n,t)=>({columns:r`${Y(n,g,256)}, ${Y(n,l,Z)}`,concurrently:!0,name:`${t}__unique`,table:t,unique:!0}),x=n=>r`${n} COLLATE utf8mb4_0900_bin`,K=(n,t)=>{const e=JSON.stringify(t.map(([i,o])=>({o,t:i})));switch(n.name){case"mysql":return r`JSON_TABLE(${e}, '$[*]' COLUMNS (${r.identifier("t")} VARCHAR(256) PATH '$.t', ${r.identifier("o")} INT PATH '$.o')) AS ${r.identifier("j")}`;case"postgres":return r`json_to_recordset(${e}::text::json) AS ${r.identifier("j")}(${r.identifier("t")} text, ${r.identifier("o")} integer)`;default:return r`(SELECT json_extract(${d("e","value")}, '$.t') AS ${r.identifier("t")}, json_extract(${d("e","value")}, '$.o') AS ${r.identifier("o")} FROM json_each(${e}) AS ${r.identifier("e")}) AS ${r.identifier("j")}`}},At=(n,t,e,i,o)=>{const s=r.join([g,l,O].map(f=>r.identifier(f)),r`, `),a=f=>r`INSERT INTO ${r.identifier(t)} (${s}) SELECT ${d("j","t")}, ${e}, ${d("j","o")} FROM ${K(n,i)} WHERE ${f}`;switch(n.name){case"mysql":{const f=D(n,o),c=d(t,g),w=r.identifier("held");return[r`${a(r`${f} AND NOT EXISTS (SELECT 1 FROM ${r.identifier(t)} AS ${w} WHERE ${d("held",l)} = ${e} AND ${d("held",g)} = ${x(d("j","t"))})`)} ON DUPLICATE KEY UPDATE ${d(t,O)} = ${d(t,O)}`,r`UPDATE ${r.identifier(t)} JOIN ${K(n,i)} ON ${c} = ${x(d("j","t"))} SET ${d(t,O)} = ${d("j","o")} WHERE ${d(t,l)} = ${e} AND ${f}`,r`DELETE FROM ${r.identifier(t)} WHERE ${d(t,l)} = ${e} AND ${f} AND ${c} NOT IN (SELECT ${x(d("j","t"))} FROM ${K(n,i)})`]}case"postgres":{const f=r.identifier("__source__"),c=r.identifier("__purged__"),w=r`EXISTS (SELECT 1 FROM ${f})`;return[r`WITH ${f} AS (${Rt(n,o)}), ${c} AS (${M(t,e,w)} RETURNING 1) ${a(r`${w} AND (SELECT COUNT(*) FROM ${c}) >= 0`)} ON CONFLICT DO NOTHING`]}default:{const f=D(n,o);return[M(t,e,f),r`${a(f)} ON CONFLICT DO NOTHING`]}}},Ot={uniqueKeyMissing:!1,unmappedSkipped:0},ct=new Set,ut=(n,t)=>{ct.has(n)||(ct.add(n),console.warn(`[@lunora/sql-store] ${t}`))},dt=100,$t=3,Q=async(n,t,e,i=0)=>{const{companion:o,definition:s,index:a,tableName:f}=e,c={done:!0,last:i,left:0};if((await h(n,t,t.tableExists(f))).length===0)return c;const u=await h(n,t,bt(o,dt,i));if(u.length===0)return c;const S=Math.max(...u.map(A=>Number(A.rowid))),E=Ht(u),m=await P(n,t,f,[...E.keys()]),$=[];for(const[A,et]of E){const j=m.get(A),rt=j===void 0?void 0:X(s,j),it=_t(t,f,A,j);$.push(...rt?mt(o,A,z(rt,a),{guard:it,unmappedRowids:et}):ht(o,A,{guard:it,unmappedRowids:et}))}await N(n,t,$);const _=await h(n,t,r`SELECT COUNT(*) AS ${r.identifier("n")} FROM ${r.identifier(o)} WHERE ${d(o,"rowid")} > ${Math.max(0,i)} AND ${d(o,"rowid")} <= ${S}`);return{done:u.length<dt,last:S,left:Number(_[0]?.n??0)}},sn=async(n,t,e)=>{let i=0,o=0;for(;;){let s=await Q(n,t,e,i);for(let a=1;s.left>0&&a<$t;a+=1)s=await Q(n,t,e,i);if(s.left>0&&(o+=s.left,console.warn(`[@lunora/sql-store] search migration of "${e.companion}": ${String(s.left)} row(s) lost every one of ${String($t)} attempts to a concurrent write and were left for a later pass.`)),s.done)return o;i=s.last}},an=async(n,t,e,i)=>i==="step"?(await Q(n,t,e),Ot):{uniqueKeyMissing:!1,unmappedSkipped:await sn(n,t,e)},V=n=>`${n}__btree`,fn=async(n,t,e)=>{const i=tt(t,e),o=await L(n,t,e,i.name);if(o!=="valid"){if(o==="absent"&&(await h(n,t,r`SELECT 1 AS ${r.identifier("present")} FROM ${r.identifier(e)} LIMIT 1`)).length===0)try{await J(n,t,{...i,concurrently:!1}),await v(n,t,e,V(e));return}catch(a){if(await L(n,t,e,i.name).catch(()=>{})==="valid")return;ut(`${e}:empty`,`search companion "${e}": adding its unique key failed (${String(a)}); run backfillSqlSearchIndexes.`);return}ut(`${e}:missing`,`search companion "${e}" has no usable unique key, so two backfills racing over one row can index it twice. Run backfillSqlSearchIndexes, which adds it.`)}},cn=async(n,t,e)=>{const i=d(e,l),o=d(e,g);return(await h(n,t,r`SELECT ${i} AS ${r.identifier("id")}, ${o} AS ${r.identifier("token")}, COUNT(*) AS ${r.identifier("n")} FROM ${r.identifier(e)} GROUP BY ${i}, ${o} HAVING COUNT(*) > 1`)).map(a=>({count:Number(a.n),id:String(a.id),token:String(a.token)}))},un=(n,t,{count:e,id:i,token:o})=>{const s=r`${d(t,l)} = ${i} AND ${d(t,g)} = ${o}`;switch(n.name){case"mysql":return r`DELETE FROM ${r.identifier(t)} WHERE ${s} LIMIT ${r.raw(String(e-1))}`;case"postgres":return r`DELETE FROM ${r.identifier(t)} WHERE ctid = ANY (ARRAY(SELECT ctid FROM ${r.identifier(t)} WHERE ${s} OFFSET 1))`;default:return r`DELETE FROM ${r.identifier(t)} WHERE rowid IN (SELECT rowid FROM ${r.identifier(t)} WHERE ${s} LIMIT -1 OFFSET 1)`}},dn=async(n,t,e,i)=>{const{companion:o,definition:s,index:a,tableName:f}=e;for(const u of i)await y(n,t,un(t,o,u));const c=[...new Set(i.map(u=>u.id))],w=await P(n,t,f,c);for(const u of c){const S=w.get(u),E=S===void 0?void 0:X(s,S);if(S!==void 0&&E){const m=[...yt(E,a)];await N(n,t,At(t,o,u,m,{row:S,table:f}));continue}await y(n,t,M(o,u,_t(t,f,u,S)))}},$n=async(n,t,e)=>t.name!=="mysql"?"":(await h(n,t,r`SELECT COLUMN_NAME AS ${r.identifier("name")}, COLLATION_NAME AS ${r.identifier("collation")} FROM information_schema.columns WHERE table_schema = DATABASE() AND table_name = ${e} AND COLUMN_NAME IN (${g}, ${l})`)).filter(o=>!String(o.collation).endsWith("_bin")).map(o=>` Its ${String(o.name)} column uses ${String(o.collation)}, which treats values differing only in case or accents as one; convert it with ALTER TABLE \`${e}\` MODIFY \`${String(o.name)}\` VARCHAR(768) COLLATE utf8mb4_0900_bin NOT NULL.`).join(""),wn=async(n,t,e)=>{if(t.name!=="mysql")return 0;const i=d(e,l),o=await h(n,t,r`SELECT COUNT(*) AS ${r.identifier("n")} FROM (SELECT 1 AS ${r.identifier("x")} FROM ${r.identifier(e)} GROUP BY LEFT(${i}, ${r.raw(String(Z))}), ${d(e,g)} HAVING COUNT(DISTINCT ${i}) > 1) AS ${r.identifier("shared")}`);return Number(o[0]?.n??0)},Sn=async(n,t,e)=>{const i=tt(t,e),o=await L(n,t,e,i.name);if(o==="valid")return"valid";o==="invalid"&&await v(n,t,e,i.name);try{return await J(n,t,i),"built"}catch(s){const a=await L(n,t,e,i.name);if(a==="valid")return"valid";if(a==="invalid"&&await v(n,t,e,i.name),!t.isUniqueViolation(s))throw s;return"refused"}},wt=3,ln=async(n,t,e)=>{const{companion:i}=e,o=await $n(n,t,i);let s="";o!==""&&console.warn(`[@lunora/sql-store] search companion "${i}" folds case and accents in its unique key.${o}`);for(let a=0;a<wt;a+=1){const f=await Sn(n,t,i);if(f==="valid")return await v(n,t,i,V(i)),!0;if(f==="refused"){const c=await cn(n,t,i);if(c.length>0)await dn(n,t,e,c);else{const w=await wn(n,t,i);s=w>0?` ${String(w)} token(s) are held by document ids that agree on their first ${String(Z)} characters, which the key cannot tell apart; shorten those ids.`:o}}}return await L(n,t,i,tt(t,i).name)==="valid"?(await v(n,t,i,V(i)),!0):(console.warn(`[@lunora/sql-store] search companion "${i}" still has no unique key after ${String(wt)} attempts: writes keep working, but two backfills racing over one row can index it twice.${s}`),!1)},En=async(n,t,e,i)=>i==="step"?Ot:{uniqueKeyMissing:!await ln(n,t,e),unmappedSkipped:0},mn=(n,t)=>t?r`${r.identifier(g)} LIKE ${`${n}%`}`:r`${r.identifier(g)} = ${n}`,Nt=(n,t)=>{const e=t.filters.map(i=>r`m.${ot(i.field)} = ${Gt(i.value)}`);return n.softDeleteMode&&e.push(r`m.${ot(n.softDeleteMode.field)} IS NULL`),t.scope!==void 0&&e.push(r`(${t.scope})`),e},It=async(n,t,e,i,o,s,a)=>{const f=Nt(e,o);let c=r`SELECT m.* FROM (${a}) s JOIN ${r.identifier(i)} m ON m.${r.identifier("id")} = s.${r.identifier(l)}`;return f.length>0&&(c=r`${c} WHERE ${r.join(f,r` AND `)}`),c=r`${c} ORDER BY s.${r.identifier("__score__")} DESC, m.${r.identifier("_creationTime")} DESC, m.${r.identifier("id")} ASC LIMIT ${r.raw(String(s))}`,pt(e,await h(n,t,c))},hn=async(n,t,e,i,o,s)=>{const a=k(o.query,U(o.definition.language));if(a.length===0)return[];const f=b(i,o.indexName),c=a.length-1,w=a.map(($,_)=>mn($,_===c)),u=r.join(w,r` OR `),S=w.map($=>r`SUM(CASE WHEN ${$} THEN ${r.identifier(O)} ELSE 0 END)`),E=r.join(S.map($=>r`${$} > 0`),r` AND `),m=r`SELECT ${r.identifier(l)}, ${r.join(S,r` + `)} AS ${r.identifier("__score__")} FROM ${r.identifier(f)} WHERE ${u} GROUP BY ${r.identifier(l)} HAVING ${E}`;return It(n,t,e,i,o,s,m)},pn=async(n,t,e,i,o,s)=>{const a=k(o.query,U(o.definition.language));if(a.length===0)return[];const f=b(i,o.indexName),c=`${f}__vocab`,w=a.length-1,u=a.map((m,$)=>{const _=Jt(m,$===w),A=_.exact?r`${r.identifier("term")} = ${_.lower}`:r`${r.identifier("term")} >= ${_.lower} AND ${r.identifier("term")} < ${_.upper}`;return r`SELECT ${r.identifier("doc")}, ${r.raw(String($))} AS ${r.identifier("__term__")}, COUNT(*) AS ${r.identifier("__n__")} FROM ${r.identifier(c)} WHERE ${A} GROUP BY ${r.identifier("doc")}`}),S=a.map((m,$)=>r`SUM(CASE WHEN u.${r.identifier("__term__")} = ${r.raw(String($))} THEN u.${r.identifier("__n__")} ELSE 0 END)`),E=r`SELECT f.${r.identifier(l)} AS ${r.identifier(l)}, ${r.join(S,r` + `)} AS ${r.identifier("__score__")} FROM (${Bt(u)}) u JOIN ${r.identifier(f)} f ON f.rowid = u.${r.identifier("doc")} GROUP BY f.${r.identifier(l)} HAVING ${r.join(S.map(m=>r`${m} > 0`),r` AND `)}`;return It(n,t,e,i,o,s,E)},gn=async(n,t,e,i,o,s)=>{const a=t.nativeTextSearch,f=k(o.query,U(o.definition.language));if(!a||f.length===0)return[];const c=b(i,o.indexName),w=[a.matches(c,f),...Nt(e,o)],u=r`SELECT m.* FROM ${r.identifier(c)} JOIN ${r.identifier(i)} m ON m.${r.identifier("id")} = ${r.identifier(c)}.${r.identifier(l)} WHERE ${r.join(w,r` AND `)} ORDER BY ${a.rank(c,f)} DESC, m.${r.identifier("_creationTime")} DESC, m.${r.identifier("id")} ASC LIMIT ${r.raw(String(s))}`;return pt(e,await h(n,t,u))},yn={ensureCompanion:async(n,t,e)=>{const{integer:i,key:o}=t.companionTypes;await y(n,t,r`CREATE TABLE IF NOT EXISTS ${r.identifier(e)} (${r.identifier(g)} ${r.raw(o)} NOT NULL, ${r.identifier(l)} ${r.raw(o)} NOT NULL, ${r.identifier(O)} ${r.raw(i)} NOT NULL)`),await J(n,t,{columns:Y(t,l,191),name:`${e}__by_id`,table:e,unique:!1}),await fn(n,t,e)},indexDocument:async(n,t,e,i,o,s)=>{const a=[...yt(i,o)];await N(n,t,At(t,e,String(s.row.id),a,s))},migrate:En,name:"inverted",purgeDocument:async(n,t,e,i,o)=>{await y(n,t,M(e,i,H(o,i)))},runSearch:hn},Tn={ensureCompanion:async(n,t,e)=>{await N(n,t,Pt(e))},indexDocument:async(n,t,e,i,o,s)=>{await N(n,t,mt(e,String(s.row.id),z(i,o),{guard:D(t,s)}))},migrate:an,name:"fts5",purgeDocument:async(n,t,e,i,o)=>{await N(n,t,ht(e,i,{guard:H(o,i)}))},runSearch:pn},Rn={ensureCompanion:async(n,t,e)=>{const i=t.nativeTextSearch;if(i){await y(n,t,i.createCompanion(e,t.companionTypes.key));for(const o of i.createIndexes(e))await y(n,t,o)}},indexDocument:async(n,t,e,i,o,s)=>{const a=t.nativeTextSearch;a&&await y(n,t,a.indexDocument(e,String(s.row.id),z(i,o),D(t,s)))},name:"native",purgeDocument:async(n,t,e,i,o)=>{await y(n,t,M(e,i,H(o,i)))},runSearch:gn},I=(n,t)=>n.strategy==="native"&&t.nativeTextSearch!==void 0?Rn:t.supportsFts5?Tn:yn,B=(n,t)=>`${qt(n)}/${I(n,t).name}`,nt=function*(n){for(const[t,e]of Object.entries(n.tables)){const i=e.searchIndexes;if(!(e.shardMode!==void 0&&e.shardMode.kind!=="global"||!i))for(const o of i)yield[t,e,o]}},R=(n,t)=>b(n,t.name),_n=async(n,t,e,i)=>{const o=R(e,i);return q(await C(n,t,o),B(i,t)).finished?!0:kt(n,t,o)},Hn=async(n,t,e,i,o,s)=>{if(!await _n(n,t,i,o.definition))throw new p("SEARCH_INDEX_BUILDING",`search index "${o.indexName}" on table "${i}" is still backfilling and currently covers only part of the table — retry once it finishes${t.searchBackfillHint===void 0?"":`, or complete it now: ${t.searchBackfillHint}`}`);return I(o.definition,t).runSearch(n,t,e,i,o,s)},St=n=>n.slice(n.lastIndexOf("/")+1),lt=200,Et=5,An=async(n,t,e,i)=>{const o=[...i.keys()],s=await h(n,t,r`SELECT * FROM ${r.identifier(e)} WHERE ${r.identifier("id")} >= ${o[0]} AND ${r.identifier("id")} <= ${o.at(-1)} ORDER BY ${r.identifier("id")} ASC`),a=new Map;for(const f of s){const c=f.id,w=i.get(c)?.row;w&&Tt.some(u=>String(w[u])!==String(f[u]))&&a.set(c,{row:f})}return a},W=async(n,t,e,i,o,s,a)=>{const f=I(s,t);let c=a;for(let w=0;c.size>0&&w<Et;w+=1){for(const{document:u,row:S}of c.values()){const E=u??X(e,S);E&&await f.indexDocument(n,t,o,E,s,{row:S,table:i})}c=await An(n,t,i,c)}c.size>0&&console.warn(`[@lunora/sql-store] search index "${o}": ${String(c.size)} row(s) were rewritten on every one of ${String(Et)} re-check rounds and were left to their writers — each stays stale only if none of those writes changed its indexed text.`)},Ct=async(n,t,e,i,o)=>{const s=R(i,o),a=B(o,t);let f=await C(n,t,s),c=q(f,a);if(c.finished)return!0;if(c.wipe){await F(n,t,s,void 0,!1,a,{cursor:f.cursor,done:f.done,profile:f.profile});const $=await C(n,t,s);if($.cursor!==f.cursor||$.done!==f.done||$.profile!==f.profile){if(f=$,c=q(f,a),c.wipe)return!1;if(c.finished)return!0}else f={cursor:void 0,done:!1,profile:a},c=q(f,a)}if((await h(n,t,t.tableExists(i))).length===0)return await F(n,t,s,void 0,!0,a),!0;const u=await Yt(n,t,i,c.cursor,lt),S=u.findLast($=>typeof $.id=="string")?.id,E=new Map;for(const $ of u)typeof $.id=="string"&&E.set($.id,{row:$});await W(n,t,e,i,s,o,E);const m=u.length<lt;return await F(n,t,s,S??c.cursor,m,a,{cursor:c.cursor,done:!1,profile:f.profile}),m},Lt=async(n,t,e)=>{await Ft(n,e);for(const[i,,o]of nt(t)){const s=R(i,o),a=B(o,e),f=await C(n,e,s);f.profile!==void 0&&St(f.profile)!==St(a)&&(await y(n,e,r`DROP TABLE IF EXISTS ${r.identifier(s)}`),await y(n,e,r`DROP TABLE IF EXISTS ${r.identifier(Wt(s))}`),await Ut(n,e,s)),await I(o,e).ensureCompanion(n,e,s)}},On=async(n,t,e,i,o)=>{const s=R(i,o);if((await C(n,t,s)).profile!==void 0)return;let f=0;(await h(n,t,t.tableExists(i))).length>0&&await Qt(n,t,e,i,()=>{f+=1},{limit:1}),await F(n,t,s,void 0,f===0,B(o,t))},vt=async(n,t,e,i,o,s)=>await I(o,t).migrate?.(n,t,{companion:R(i,o),definition:e,index:o,tableName:i},s)??{uniqueKeyMissing:!1,unmappedSkipped:0},Pn=async(n,t,e)=>{await Lt(n,t,e);for(const[i,o,s]of nt(t)){if(await vt(n,e,o,i,s,"step"),s.staged){await On(n,e,o,i,s);continue}await Ct(n,e,o,i,s)}},Bn=async(n,t,e)=>{const i={uniqueKeyMissing:[],unmappedSkipped:0};await Lt(n,t,e);for(const[o,s,a]of nt(t)){const f=await vt(n,e,s,o,a,"drain");i.unmappedSkipped+=f.unmappedSkipped,f.uniqueKeyMissing&&i.uniqueKeyMissing.push(R(o,a));let c=!1;for(;!c;)c=await Ct(n,e,s,o,a)}return i},Mt=async(n,t,e,i,o,s,a)=>{await I(s,t).purgeDocument(n,t,o,a,e);const c=(await P(n,t,e,[a])).get(a);c!==void 0&&await W(n,t,i,e,o,s,new Map([[a,{row:c}]]))},Dt=async(n,t,e,i,o,s,a)=>{const c=(await P(n,t,e,[a])).get(a);await(c===void 0?Mt(n,t,e,i,o,s,a):W(n,t,i,e,o,s,new Map([[a,{row:c}]])))},Wn=async(n,t,e)=>{const i=n.schema.tables[t];for(const o of i?.searchIndexes??[])await Dt(n.exec,n.dialect,t,i,R(t,o),o,e)},jn=n=>{const{dialect:t,exec:e,schema:i}=n;return async(o,s,a)=>{const f=i.tables[o],c=f?.searchIndexes;if(!(!f||!c||c.length===0))for(const[w,u]of c.entries()){const S=R(o,u);try{if(on(a?.previous,a?.document,u))continue;if(a){await W(e,t,f,o,S,u,new Map([[s,{document:a.document,row:{...a.written,id:s}}]]));continue}await Mt(e,t,o,f,S,u,s)}catch(E){const m=async()=>{for(const $ of c.slice(w))await Dt(e,t,o,f,R(o,$),$,s)};throw jt(E)?.then(m,m).catch(()=>{}),E}}}};export{Dn as A,Un as C,kn as R,bn as T,Wn as a,Bn as b,jn as c,Hn as d,Fn as e,Pn as r,st as u,qn as x};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{bigintSqlKey as a}from"@lunora/shard-engine";import{B as t,c as n,U as o,d as r,e as d,i as E,r as c,s as N,a as U,t as _}from"./value-codec-CbyTgWR3.mjs";export{t as BIGINT_KEY_LENGTH,n as UNTYPED_NUMBER_PREFIX,o as UNTYPED_WIRE_PREFIX,a as bigintSqlKey,r as decodeBigint,d as effectiveColumnKind,E as isUntypedColumnKind,c as rewriteLegacyUntypedNumber,N as sqliteDecode,U as sqliteEncode,_ as tryJsonParse};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{LunoraError as O}from"@lunora/errors";import{aggregateTableName as V,rankTableName as Q,sortColumnName as N,bigintSqlKey as z}from"@lunora/shard-engine";import{sql as t}from"drizzle-orm";import{b as Z,e as g,B as b,r as J,i as nn,U as en,c as tn}from"./value-codec-CbyTgWR3.mjs";import{O as S,t as on,c as d,q as $,M as q,e as y,j as m,z as rn,s as sn,y as an}from"./sql-exec-enIOMsv0.mjs";const ln=new Set(["any","null"]),k=(e,n)=>{const i=n.kindOf(e);return i!==void 0&&ln.has(i)||n.nullableOf(e)?!0:i==="union"&&(n.membersOf(e)??[]).some(o=>k(o,n))},R=e=>{const n=e._meta?.inner;return e.kind==="optional"&&n?R(n):e},I=e=>k(e,{kindOf:Z,membersOf:n=>R(n)._meta?.members,nullableOf:n=>R(n)._meta?.column?.notNull===!1}),x=(e,n,i=!1)=>n.columnType(g(e),{unique:i||e._meta?.column?.unique===!0}),M=e=>{const n=new Set;for(const i of e.indexes)i.unique===!0&&i.fields.length===1&&n.add(i.fields[0]);return n},un=(e,n,i)=>{if(i.indexKeyPrefix!==void 0)for(const o of n.indexes){if(o.unique!==!0||o.fields.length<=1)continue;const r=o.fields.filter(s=>{const a=n.shape[s];return a!==void 0&&i.indexKeyPrefix?.(g(a))!==void 0});if(r.length>0)throw new Error(`${e}.${o.name}: a composite unique index cannot cover ${r.join(", ")} in full on this engine (its key limit forces a prefix, which would constrain the prefix rather than the value). Split it into single-column unique indexes, or store those fields as a bounded type.`)}},cn=e=>e._meta?.column?.notNull===!0&&e.kind!=="optional"&&!I(e),fn=(e,n,i)=>{const o=[],r=M(n);for(const[u,c]of Object.entries(n.shape)){if(!c._meta?.column)continue;const f=cn(c)?" NOT NULL":"";o.push(t`${t.identifier(u)} ${t.raw(`${x(c,i,r.has(u))}${f}`)}`)}const s=[...i.frameworkColumns().map(u=>t`${t.identifier(u.name)} ${t.raw(u.type)}`),t`${t.identifier(S)} ${t.raw(i.companionTypes.integer)}`],a=s.length+o.length,l=i.maxTableColumns;if(l!==void 0&&a>l){const u=a-1===l,c="Move one or more fields into a single object field, or split the table — either way the existing rows need a data migration (`defineMigration` + `lunora migrate up`); there is no in-place path.";throw new O("VALIDATION_ERROR",`@lunora/sql-store: global table "${e}" needs ${String(a)} columns, over this engine's ${String(l)}-column limit. ${u?`One of them is "${S}", the row version every guarded write reads, which caps declared fields at ${String(l-s.length)}. A table provisioned at ${String(l)} columns before that column existed cannot be widened to hold it. `:""}${c}`)}return t.join([...s,...o],t`, `)},B=e=>{if(e.indexKeyPrefix?.("string")===void 0)return t`${m("_creationTime")}, ${m("id")}`},D=new Set,F=async(e,n,i,o)=>{const r=t.join(i.refs.map(a=>t`${a} IS NOT NULL`),t` AND `);if((await $(e,n,t`SELECT ${i.columns} FROM ${t.identifier(i.table)} WHERE ${r} GROUP BY ${i.columns} HAVING COUNT(*) > 1 LIMIT 1`)).length>0){const a=`unique index "${i.name}" on "${i.table}" ${o}: existing rows are duplicates under it. De-duplicate the table with a data migration first.`;throw D.has(a)||(D.add(a),console.error(`[@lunora/sql-store] ${a}`)),new O("UNIQUE_INDEX_DUPLICATES",a)}},dn=async(e,n,i)=>{if(!i.unique){await y(e,n,i);return}try{await y(e,n,i)}catch(o){throw n.isUniqueViolation(o)&&await F(e,n,i,"cannot be created"),o}},P=e=>{const n=e.indexOf("(");return n===-1?void 0:e.slice(n,e.lastIndexOf(")")+1)},mn=(e,n)=>{const i=n.unique?t`UNIQUE `:t``;return P(e.render(t`CREATE ${i}INDEX ${t.identifier(n.name)} ON ${t.identifier(n.table)} (${n.columns})`).sql)},$n=(e,n,i)=>{const o=mn(e,i);return o!==void 0&&o!==P(n)},j=async(e,n,i)=>{if(n.name!=="sqlite")return;const r=(await $(e,n,t`SELECT sql FROM sqlite_master WHERE type = 'index' AND name = ${i.name} COLLATE NOCASE AND tbl_name = ${i.table} COLLATE NOCASE`))[0]?.sql;typeof r=="string"&&$n(n,r,i)&&(i.unique&&await F(e,n,i,"cannot be re-created with its new column list; the previous index is left in place"),await d(e,n,t`DROP INDEX IF EXISTS ${t.identifier(i.name)}`))},En=(e,n,i)=>{un(e,n,i);const o=M(n),r=l=>{const u=m(l),c=n.shape[l],f=c&&i.indexKeyPrefix&&c._meta?.column?.unique!==!0&&!o.has(l)?i.indexKeyPrefix(g(c)):void 0;return f===void 0?u:t`${u}(${t.raw(String(f))})`},s=B(i),a=[];for(const l of n.indexes){const u=l.fields.map(E=>r(E)),c=t.join(u,t`, `),f=l.unique??!1;a.push({columns:f||s===void 0?c:t`${c}, ${s}`,kind:"declared",name:`${e}_${l.name}`,refs:u,table:e,unique:f})}s!==void 0&&a.push({columns:s,kind:"default-order",name:`${e}__by_creation`,refs:[],table:e,unique:!1});for(const[l,u]of on(n)){if(!u.unique)continue;const c=r(l);a.push({columns:c,kind:"unique-column",name:`${e}_unique_${l}`,refs:[c],table:e,unique:!0})}return a},gn=/^\s*create\s+unique\s/iu,p="__lunora_framework_indexes",wn=()=>t`CREATE TABLE IF NOT EXISTS ${t.identifier(p)} (name TEXT PRIMARY KEY COLLATE NOCASE, table_name TEXT NOT NULL)`,K=(e,n)=>t`INSERT OR IGNORE INTO ${t.identifier(p)} (name, table_name) VALUES (${e}, ${n})`,h=e=>e.replaceAll(/[A-Z]/gu,n=>n.toLowerCase()),hn=async(e,n,i)=>{if(n.name!=="sqlite"||(await $(e,n,t`SELECT 1 AS present FROM sqlite_master WHERE type = 'table' AND name = ${p} COLLATE NOCASE`)).length>0)return;await d(e,n,wn());const r=B(n),s=r===void 0?void 0:`, ${n.render(r).sql})`;for(const a of i){const l=`${h(a)}_`,u=await $(e,n,t`SELECT name, sql FROM sqlite_master WHERE type = 'index' AND tbl_name = ${a} COLLATE NOCASE AND sql IS NOT NULL`);for(const c of u){const f=String(c.name),E=String(c.sql);h(f).startsWith(l)&&h(f)!==h(`${a}__by_creation`)&&(gn.test(E)||s!==void 0&&E.trimEnd().endsWith(s))&&await d(e,n,K(f,a))}}},pn=(e,n,i)=>{if(e.name!=="sqlite")return[];const o=new Set(n.map(r=>h(r.name)));return i.filter(r=>!o.has(h(r)))},_n=async(e,n,i,o)=>{if(o.name!=="sqlite")return;const r=await $(e,o,t`SELECT "l"."name" FROM ${t.identifier(p)} AS "l" WHERE "l"."table_name" = ${n} COLLATE NOCASE`);for(const s of pn(o,i,r.map(a=>String(a.name))))await d(e,o,t`DROP INDEX IF EXISTS ${t.identifier(s)}`),await d(e,o,t`DELETE FROM ${t.identifier(p)} WHERE ${t.identifier(p)}."name" = ${s}`)},Tn=async(e,n,i,o)=>{const r=En(n,i,o);for(const s of r){if(s.kind==="default-order"){await y(e,o,s);continue}s.kind==="declared"&&await j(e,o,s),await dn(e,o,s),o.name==="sqlite"&&await d(e,o,K(s.name,s.table))}await _n(e,n,r,o)},C="__lunora_migration_state",yn=async(e,n)=>{await d(e,n,t`CREATE TABLE IF NOT EXISTS ${t.identifier(C)} (${t.identifier("name")} ${t.raw(n.companionTypes.key)} PRIMARY KEY)`)},Ln=async(e,n,i)=>(await $(e,n,t`SELECT ${t.identifier("name")} FROM ${t.identifier(C)} WHERE ${t.identifier("name")} = ${i}`)).length>0,An=async(e,n,i,o,r,s)=>{r>0&&s!==void 0&&console.warn(`[@lunora/sql-store] storage migration "${i}" on "${o}": ${String(r)} row(s) ${s} and were left as stored — range filters and ORDER BY over them stay wrong until they are corrected by hand.`);try{await d(e,n,t`INSERT INTO ${t.identifier(C)} (${t.identifier("name")}) VALUES (${i})`)}catch(a){if(!n.isUniqueViolation(a))throw a}},Sn=100,Rn=(e,n)=>{const i=[],o=[];for(const r of n.fields){const s=e[r],a=n.convert(s);a!==void 0&&(i.push(t`${m(r)} = ${a}`),o.push(t`${m(r)} = ${s}`))}return{assignments:i,guards:o}},On=e=>t.join(e.fields.map(n=>e.probe(n)),t` OR `),G=async(e,n,i,o)=>{if(o.fields.length===0||(await yn(e,i),await Ln(e,i,o.marker)))return;const r=On(o),s=t.join([m("id"),...o.fields.map(u=>m(u))],t`, `);let a="",l=0;for(;;){const u=await $(e,i,t`SELECT ${s} FROM ${t.identifier(n)} WHERE (${r}) AND ${m("id")} > ${a} ORDER BY ${m("id")} LIMIT ${t.raw(String(Sn))}`);if(u.length===0){await An(e,i,o.marker,n,l,o.describeUnconvertible);return}const c=[];for(const E of u){const{id:w}=E,{assignments:_,guards:T}=typeof w=="string"?Rn(E,o):{assignments:[],guards:[]};if(_.length===0){l+=1;continue}c.push(t`UPDATE ${t.identifier(n)} SET ${t.join(_,t`, `)} WHERE ${m("id")} = ${w} AND ${t.join(T,t` AND `)}`)}await an(e,i,c);const f=u.at(-1)?.id;if(typeof f!="string")return;a=f}},U=e=>`'${e}%'`,Nn=e=>Object.entries(e.shape).filter(([,n])=>n._meta?.column!==void 0&&g(n)==="bigint").map(([n])=>n),In=e=>Object.entries(e.shape).filter(([,n])=>n._meta?.column!==void 0&&nn(g(n))).map(([n])=>n),H=(e,n)=>({convert:i=>{if(!(typeof i!="string"||i.length===b))try{return z(BigInt(i))}catch{return}},describeUnconvertible:"hold a value the order-preserving key cannot represent (non-numeric text, or a magnitude past 39 digits)",fields:Nn(n),marker:`bigint-key:${e}`,probe:i=>t`(${m(i)} IS NOT NULL AND LENGTH(${m(i)}) <> ${b})`}),Cn=async(e,n,i,o)=>G(e,n,o,H(n,i)),W=(e,n)=>({convert:J,fields:In(n),marker:`untyped-number-key:${e}`,probe:i=>t`(${m(i)} LIKE ${t.raw(U(en))} AND ${m(i)} NOT LIKE ${t.raw(U(tn))})`}),bn=async(e,n,i,o)=>G(e,n,o,W(n,i)),v=new Set,L=(e,n)=>{v.has(e)||(v.add(e),console.warn(`[@lunora/sql-store] ${n}`))},qn=e=>{const n=e._meta?.column;return n?.defaultFn?n.defaultFn():n&&"defaultValue"in n?n.defaultValue:void 0},Dn=(e,n,i)=>i._meta?.column?.unique===!0||e.indexes.some(o=>o.unique===!0&&o.fields.includes(n)),Un=async(e,n,i,o,r,s)=>{if(s.kind==="optional"||I(s))return;const a=Dn(i,r,s),l=a?void 0:qn(s),u=`UPDATE "${n}" SET "${r}" = … WHERE "${r}" IS NULL`;if(l===void 0){const c=a?"is unique, so one default cannot be written to every row":"has no default";L(`backfill:${n}.${r}`,`"${n}.${r}" was added as a required field that ${c}, so rows written before it read NULL. Backfill it with a migration (${u}).`);return}try{await d(e,o,t`UPDATE ${t.identifier(n)} SET ${t.identifier(r)} = ${sn(i,r,l)} WHERE ${t.identifier(r)} IS NULL`)}catch(c){L(`backfill:${n}.${r}`,`could not backfill "${n}.${r}" from its default (${c instanceof Error?c.message:String(c)}); rows written before it read NULL. Run ${u}.`)}},vn=(e,n)=>[[S,n.companionTypes.integer],...Object.entries(e.shape).filter(([,i])=>i._meta?.column!==void 0).map(([i,o])=>[i,x(o,n),o])],kn=async(e,n,i,o)=>{const r=vn(i,o),s="t",a=async l=>{try{return await $(e,o,t`SELECT ${t.join(l.map(u=>rn(s,u)),t`, `)} FROM ${t.identifier(n)} AS ${t.identifier(s)} LIMIT 0`),!0}catch{return!1}};if(!await a(r.map(([l])=>l)))for(const[l,u,c]of r)await a([l])||(await d(e,o,t`ALTER TABLE ${t.identifier(n)} ADD COLUMN ${t.identifier(l)} ${t.raw(u)}`),c!==void 0&&await Un(e,n,i,o,l,c))},xn=(e,n,i)=>{const o=typeof i.charset=="string"?` CHARACTER SET ${i.charset} COLLATE ${String(i.collation)}`:"";return`ALTER TABLE \`${e}\` MODIFY COLUMN \`${n}\` ${String(i.type)}${o} NULL`},Mn=async(e,n,i,o)=>{if(o.name==="sqlite")return;const r=Object.keys(i.shape).filter(s=>{const a=i.shape[s];return a._meta?.column?.notNull===!0&&a.kind!=="optional"&&I(a)});if(r.length!==0)try{const s=o.name==="postgres"?t`column_name AS ${t.identifier("name")}`:t`column_name AS ${t.identifier("name")}, column_type AS ${t.identifier("type")}, character_set_name AS ${t.identifier("charset")}, collation_name AS ${t.identifier("collation")}`,a=o.name==="postgres"?t`table_schema = ANY (current_schemas(false))`:t`table_schema = DATABASE()`,l=await $(e,o,t`SELECT ${s} FROM information_schema.columns WHERE ${a} AND table_name = ${n} AND is_nullable = 'NO' AND column_name IN (${t.join(r.map(u=>t`${u}`),t`, `)})`);for(const u of l){const c=String(u.name);if(o.name==="postgres"){await d(e,o,t`ALTER TABLE ${t.identifier(n)} ALTER COLUMN ${t.identifier(c)} DROP NOT NULL`);continue}L(`${n}.${c}`,`"${n}"."${c}" accepts null in the schema but its column is NOT NULL, so writing null there fails. Relaxing it on MySQL can rebuild the table, so it is not done at startup; run this once, in a maintenance window: ${xn(n,c,u)};`)}}catch(s){L(`${n}:relax-failed`,`could not relax NOT NULL on the null-accepting columns of "${n}" (${r.join(", ")}): ${s instanceof Error?s.message:String(s)}. Writing null to them fails until the constraint is dropped by hand.`)}},Bn=async(e,n,i,o)=>{const r=fn(n,i,o);await d(e,o,t`CREATE TABLE IF NOT EXISTS ${t.identifier(n)} (${r})`),await kn(e,n,i,o),await Mn(e,n,i,o),await Tn(e,n,i,o),await Cn(e,n,i,o),await bn(e,n,i,o)},Qn=(e,n)=>[H(e,n),W(e,n)].filter(i=>i.fields.length>0),zn=async(e,n,i,o)=>{let r=!1;for(const[s,a]of Object.entries(n.tables))a.shardMode?.kind!=="global"||o!==void 0&&!o.has(s)||(r||(r=!0,await hn(e,i,Object.entries(n.tables).filter(([,l])=>l.shardMode?.kind==="global").map(([l])=>l))),await Bn(e,s,a,i))},X=e=>e.shardMode===void 0||e.shardMode.kind==="global",Zn=async(e,n,i)=>{const{integer:o,key:r,real:s}=i.companionTypes;for(const[a,l]of Object.entries(n.tables)){const u=l.aggregateIndexes;if(!(!u||u.length===0||!X(l)))for(const c of u){const f=V(a,c.name);await d(e,i,t`CREATE TABLE IF NOT EXISTS ${t.identifier(f)} (${t.identifier("__key__")} ${t.raw(r)} PRIMARY KEY, ${t.identifier("__value__")} ${t.raw(s)}, ${t.identifier("__count__")} ${t.raw(o)} NOT NULL DEFAULT 0)`),i.name==="sqlite"&&((await $(e,i,t`PRAGMA table_info(${t.identifier(f)})`)).some(w=>w.name==="__count__")||await d(e,i,t`ALTER TABLE ${t.identifier(f)} ADD COLUMN ${t.identifier("__count__")} ${t.raw(o)} NOT NULL DEFAULT 0`))}}},A=(e,n,i,o)=>{const r=e.name==="mysql"&&o?t`${t.identifier(n)}(191)`:t`${t.identifier(n)}`;return t`${r} ${t.raw(i)}`},Fn=(e,n,i)=>{const o=[A(e,"__partition__","ASC",!0)];for(const[r,s]of n.sortBy.entries()){const a=i.shape[s.field],l=a!==void 0&&e.indexKeyPrefix?.(g(a))!==void 0;o.push(A(e,N(r),s.direction==="desc"?"DESC":"ASC",l))}return o.push(A(e,"__id__","ASC",!0)),o},Pn=(e,n,i)=>n.sortBy.map((o,r)=>{const s=i.shape[o.field],a=e.columnType(s?g(s):void 0);return t`${t.identifier(N(r))} ${t.raw(a)}`}),jn=/__sort_k\d+__/gu,Kn=async(e,n,i,o)=>{if(n.name!=="sqlite")return;const s=(await $(e,n,t`SELECT sql FROM sqlite_master WHERE type = 'table' AND name = ${i} COLLATE NOCASE`))[0]?.sql;if(typeof s!="string")return;const a=s.match(jn)??[];(a.length!==o.length||a.some((l,u)=>l!==o[u]))&&await d(e,n,t`DROP TABLE ${t.identifier(i)}`)},Jn=async(e,n,i)=>{const{key:o}=i.companionTypes;for(const[r,s]of Object.entries(n.tables)){const a=s.rankIndexes;if(!(!a||a.length===0||!X(s)))for(const l of a){const u=q-4;if(l.sortBy.length>u)throw new O("BAD_REQUEST",`rank index "${l.name}" on ${r} has ${String(l.sortBy.length)} sort keys; at most ${String(u)} fit the ${String(q)} parameters one statement binds`);const c=Q(r,l.name),f=Pn(i,l,s);await Kn(e,i,c,l.sortBy.map((Gn,Y)=>N(Y)));const E=f.length>0?t`, ${t.join(f,t`, `)}`:t``;await d(e,i,t`CREATE TABLE IF NOT EXISTS ${t.identifier(c)} (${t.identifier("__id__")} ${t.raw(o)} PRIMARY KEY, ${t.identifier("__partition__")} ${t.raw(o)} NOT NULL${E})`);const w=Fn(i,l,s),_=`${r}__rank_${l.name}__btree`,T={columns:t.join(w,t`, `),name:_,refs:[],table:c,unique:!1};await j(e,i,T),await y(e,i,T)}}};export{p as INDEX_LEDGER_TABLE,C as MIGRATION_STATE_TABLE,mn as declaredIndexColumnList,h as foldIdentifier,fn as globalTableColumnsDdl,En as globalTableIndexSpecs,P as indexColumnList,wn as indexLedgerDdl,$n as indexShapeChanged,Qn as legacyRewrites,On as legacyRowPredicate,Bn as provisionGlobalTable,zn as provisionGlobalTablesSequentially,K as recordIndexStatement,Zn as runSqlAggregateMigrations,Jn as runSqlRankMigrations,pn as undeclaredFrameworkIndexes,vn as wantedGlobalColumns};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{sql as a}from"drizzle-orm";import{provisionGlobalTablesSequentially as m,foldIdentifier as c,globalTableColumnsDdl as A,globalTableIndexSpecs as L,legacyRewrites as O,indexLedgerDdl as R,wantedGlobalColumns as k,undeclaredFrameworkIndexes as y,indexShapeChanged as $,INDEX_LEDGER_TABLE as T,MIGRATION_STATE_TABLE as E,recordIndexStatement as M,legacyRowPredicate as C}from"./runSqlAggregateMigrations-D5_8KDaC.mjs";import{a as q,q as g}from"./sql-exec-enIOMsv0.mjs";const v=50,h=new Map([["'","'"],["[","]"],["`","`"],['"','"']]),N=/^[\w$]+/u,b=(e,s)=>{const n=h.get(e[s]);let t=s+1;for(;t<e.length;)if(e[t]!==n)t+=1;else if(n!=="]"&&e[t+1]===n)t+=2;else return t+1;return t},_=e=>{const s=e.trim(),n=h.get(s[0]??"");if(n===void 0)return N.exec(s)?.[0];const t=b(s,0),r=s.slice(1,s[t-1]===n?t-1:t);return n==="]"?r:r.replaceAll(`${n}${n}`,n)},B=e=>{const s=new Set,n=i=>{const d=_(i);d!==void 0&&s.add(d)};let t=0,r=0,o=0;for(;o<e.length;){const i=e[o];if(h.has(i)){o=b(e,o);continue}if(i==="(")t+=1,r=t===1?o+1:r;else if(i===")"){if(t-=1,t===0)return n(e.slice(r,o)),s}else i===","&&t===1&&(n(e.slice(r,o)),r=o+1);o+=1}return s},F=async(e,s,n)=>{const t=new Set,r=new Map,o=n.has(c(T)),i=[];if(n.has(c(E))&&i.push(a`SELECT 'marker' AS kind, name, NULL AS owner FROM ${a.identifier(E)}`),o&&i.push(a`SELECT 'index' AS kind, "l"."name" AS name, "l"."table_name" AS owner FROM ${a.identifier(T)} AS "l"`),i.length===0)return{hasLedger:o,markers:t,owned:r};for(const d of await g(e,s,a.join(i,a` UNION ALL `)))if(d.kind==="marker")t.add(String(d.name));else{const f=c(String(d.owner));r.set(f,[...r.get(f)??[],String(d.name)])}return{hasLedger:o,markers:t,owned:r}},D=async(e,s)=>{try{const n=await g(e,s,a`SELECT type, name, tbl_name, sql FROM sqlite_master WHERE type IN ('table', 'index')`),t=new Set,r=new Map,o=new Map;for(const l of n){const u=String(l.name);if(u.startsWith("sqlite_"))continue;const S=typeof l.sql=="string"?l.sql:void 0;l.type==="table"?(t.add(c(u)),r.set(c(u),new Set([...S===void 0?[]:B(S)].map(I=>c(I))))):o.set(c(u),S)}const{hasLedger:i,markers:d,owned:f}=await F(e,s,t);return{columns:r,hasLedger:i,indexes:o,markers:d,owned:f,tables:t}}catch{return}},w=e=>e.kind==="default-order"?[]:[M(e.name,e.table)],p=e=>{const s=e.unique?a`UNIQUE `:a``;return a`CREATE ${s}INDEX IF NOT EXISTS ${a.identifier(e.name)} ON ${a.identifier(e.table)} (${e.columns})`},x=(e,s,n)=>n.length===0?[]:[a`CREATE TABLE IF NOT EXISTS ${a.identifier(E)} (${a.identifier("name")} ${a.raw(e.companionTypes.key)} PRIMARY KEY)`,...n.map(t=>a`INSERT OR IGNORE INTO ${a.identifier(E)} (${a.identifier("name")}) SELECT ${t.marker} WHERE NOT EXISTS (SELECT 1 FROM ${a.identifier(s)} WHERE ${C(t)})`)],G=(e,s,n,t)=>{const r=A(e,s,n),o=L(e,s,n),i=O(e,s);if(!t.tables.has(c(e)))return[...t.hasLedger?[]:[R()],a`CREATE TABLE IF NOT EXISTS ${a.identifier(e)} (${r})`,...o.flatMap(l=>[p(l),...w(l)]),...x(n,e,i)];const d=t.columns.get(c(e))??new Set;if(k(s,n).some(([l])=>!d.has(c(l)))||i.some(l=>!t.markers.has(l.marker))||y(n,o,t.owned.get(c(e))??[]).length>0)return;const f=[];for(const l of o){if(!t.indexes.has(c(l.name))){f.push(p(l),...w(l));continue}const u=t.indexes.get(c(l.name));if(l.kind==="declared"&&typeof u=="string"&&$(n,u,l))return}return f},X=e=>{const s=[];let n=[],t=0;for(const r of e)n.length>0&&t+r.statements.length>v&&(s.push(n),n=[],t=0),n.push(r),t+=r.statements.length;return n.length>0&&s.push(n),s},U=(e,s)=>!s.hasLedger&&Object.entries(e.tables).some(([n,t])=>t.shardMode?.kind==="global"&&s.tables.has(c(n))),Q=async(e,s,n)=>{if(!e.batch||n.name!=="sqlite"){await m(e,s,n);return}const t=await D(e,n);if(t===void 0){await m(e,s,n);return}if(U(s,t)){await m(e,s,n);return}const r=[],o=new Set;for(const[i,d]of Object.entries(s.tables)){if(d.shardMode?.kind!=="global")continue;const f=G(i,d,n,t);f===void 0?o.add(i):f.length>0&&r.push({statements:f,table:i})}for(const i of X(r))try{await q(e,n,i.flatMap(d=>d.statements))}catch{for(const d of i)o.add(d.table)}await m(e,s,n,o)};export{B as columnNamesOfCreateTable,Q as runSqlGlobalTableMigrations};
|