on-zero 0.6.11 → 0.6.13
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/dist/cjs/createZeroSQLiteServer.cjs +319 -0
- package/dist/cjs/createZeroSQLiteServer.native.js +440 -0
- package/dist/cjs/createZeroSQLiteServer.native.js.map +1 -0
- package/dist/cjs/createZeroSQLiteServer.test.cjs +429 -0
- package/dist/cjs/createZeroSQLiteServer.test.native.js +466 -0
- package/dist/cjs/createZeroSQLiteServer.test.native.js.map +1 -0
- package/dist/cjs/createZeroServer.cjs +20 -234
- package/dist/cjs/createZeroServer.native.js +24 -250
- package/dist/cjs/createZeroServer.native.js.map +1 -1
- package/dist/cjs/createZeroServer.test.cjs +35 -1
- package/dist/cjs/createZeroServer.test.native.js +38 -1
- package/dist/cjs/createZeroServer.test.native.js.map +1 -1
- package/dist/cjs/createZeroServerCore.cjs +362 -0
- package/dist/cjs/createZeroServerCore.native.js +389 -0
- package/dist/cjs/createZeroServerCore.native.js.map +1 -0
- package/dist/cjs/generate-lite.cjs +1 -0
- package/dist/cjs/generate-lite.native.js +1 -0
- package/dist/cjs/generate-lite.native.js.map +1 -1
- package/dist/cjs/generate-lite.test.cjs +5 -1
- package/dist/cjs/generate-lite.test.native.js +5 -1
- package/dist/cjs/generate-lite.test.native.js.map +1 -1
- package/dist/cjs/generate.cjs +20 -11
- package/dist/cjs/generate.native.js +29 -21
- package/dist/cjs/generate.native.js.map +1 -1
- package/dist/cjs/generate.test.cjs +110 -0
- package/dist/cjs/generate.test.native.js +110 -0
- package/dist/cjs/generate.test.native.js.map +1 -1
- package/dist/cjs/httpPull/transport.test.cjs +44 -0
- package/dist/cjs/httpPull/transport.test.native.js +53 -0
- package/dist/cjs/httpPull/transport.test.native.js.map +1 -1
- package/dist/cjs/httpPullTransport.cjs +4 -1
- package/dist/cjs/httpPullTransport.native.js +5 -2
- package/dist/cjs/httpPullTransport.native.js.map +1 -1
- package/dist/cjs/server.cjs +2 -1
- package/dist/cjs/syncHost.cjs +164 -0
- package/dist/cjs/syncHost.native.js +371 -0
- package/dist/cjs/syncHost.native.js.map +1 -0
- package/dist/cjs/syncHost.test.cjs +229 -0
- package/dist/cjs/syncHost.test.native.js +278 -0
- package/dist/cjs/syncHost.test.native.js.map +1 -0
- package/dist/esm/createZeroSQLiteServer.mjs +293 -0
- package/dist/esm/createZeroSQLiteServer.mjs.map +1 -0
- package/dist/esm/createZeroSQLiteServer.native.js +411 -0
- package/dist/esm/createZeroSQLiteServer.native.js.map +1 -0
- package/dist/esm/createZeroSQLiteServer.test.mjs +430 -0
- package/dist/esm/createZeroSQLiteServer.test.mjs.map +1 -0
- package/dist/esm/createZeroSQLiteServer.test.native.js +464 -0
- package/dist/esm/createZeroSQLiteServer.test.native.js.map +1 -0
- package/dist/esm/createZeroServer.mjs +17 -231
- package/dist/esm/createZeroServer.mjs.map +1 -1
- package/dist/esm/createZeroServer.native.js +21 -247
- package/dist/esm/createZeroServer.native.js.map +1 -1
- package/dist/esm/createZeroServer.test.mjs +35 -1
- package/dist/esm/createZeroServer.test.mjs.map +1 -1
- package/dist/esm/createZeroServer.test.native.js +38 -1
- package/dist/esm/createZeroServer.test.native.js.map +1 -1
- package/dist/esm/createZeroServerCore.mjs +336 -0
- package/dist/esm/createZeroServerCore.mjs.map +1 -0
- package/dist/esm/createZeroServerCore.native.js +360 -0
- package/dist/esm/createZeroServerCore.native.js.map +1 -0
- package/dist/esm/generate-lite.mjs +1 -0
- package/dist/esm/generate-lite.mjs.map +1 -1
- package/dist/esm/generate-lite.native.js +1 -0
- package/dist/esm/generate-lite.native.js.map +1 -1
- package/dist/esm/generate-lite.test.mjs +5 -1
- package/dist/esm/generate-lite.test.mjs.map +1 -1
- package/dist/esm/generate-lite.test.native.js +5 -1
- package/dist/esm/generate-lite.test.native.js.map +1 -1
- package/dist/esm/generate.mjs +20 -11
- package/dist/esm/generate.mjs.map +1 -1
- package/dist/esm/generate.native.js +29 -21
- package/dist/esm/generate.native.js.map +1 -1
- package/dist/esm/generate.test.mjs +87 -1
- package/dist/esm/generate.test.mjs.map +1 -1
- package/dist/esm/generate.test.native.js +87 -1
- package/dist/esm/generate.test.native.js.map +1 -1
- package/dist/esm/httpPull/transport.test.mjs +44 -0
- package/dist/esm/httpPull/transport.test.mjs.map +1 -1
- package/dist/esm/httpPull/transport.test.native.js +53 -0
- package/dist/esm/httpPull/transport.test.native.js.map +1 -1
- package/dist/esm/httpPullTransport.mjs +4 -1
- package/dist/esm/httpPullTransport.mjs.map +1 -1
- package/dist/esm/httpPullTransport.native.js +5 -2
- package/dist/esm/httpPullTransport.native.js.map +1 -1
- package/dist/esm/server.mjs +1 -0
- package/dist/esm/server.mjs.map +1 -1
- package/dist/esm/syncHost.mjs +138 -0
- package/dist/esm/syncHost.mjs.map +1 -0
- package/dist/esm/syncHost.native.js +342 -0
- package/dist/esm/syncHost.native.js.map +1 -0
- package/dist/esm/syncHost.test.mjs +206 -0
- package/dist/esm/syncHost.test.mjs.map +1 -0
- package/dist/esm/syncHost.test.native.js +252 -0
- package/dist/esm/syncHost.test.native.js.map +1 -0
- package/package.json +19 -3
- package/readme.md +26 -0
- package/src/createZeroSQLiteServer.test.ts +461 -0
- package/src/createZeroSQLiteServer.ts +523 -0
- package/src/createZeroServer.test.ts +39 -1
- package/src/createZeroServer.ts +35 -428
- package/src/createZeroServerCore.ts +557 -0
- package/src/generate-lite.test.ts +4 -0
- package/src/generate-lite.ts +1 -0
- package/src/generate.test.ts +87 -1
- package/src/generate.ts +29 -20
- package/src/httpPull/transport.test.ts +47 -0
- package/src/httpPullTransport.ts +15 -1
- package/src/server.ts +1 -0
- package/src/syncHost.test.ts +216 -0
- package/src/syncHost.ts +255 -0
- package/test-fixtures/server-return-types.ts +50 -0
- package/test-fixtures/tsconfig.json +13 -0
- package/types/createZeroSQLiteServer.d.ts +37 -0
- package/types/createZeroSQLiteServer.d.ts.map +1 -0
- package/types/createZeroSQLiteServer.test.d.ts +2 -0
- package/types/createZeroSQLiteServer.test.d.ts.map +1 -0
- package/types/createZeroServer.d.ts +11 -293
- package/types/createZeroServer.d.ts.map +1 -1
- package/types/createZeroServerCore.d.ts +310 -0
- package/types/createZeroServerCore.d.ts.map +1 -0
- package/types/generate-lite.d.ts.map +1 -1
- package/types/generate.d.ts +2 -1
- package/types/generate.d.ts.map +1 -1
- package/types/httpPullTransport.d.ts +2 -0
- package/types/httpPullTransport.d.ts.map +1 -1
- package/types/server.d.ts +1 -0
- package/types/server.d.ts.map +1 -1
- package/types/syncHost.d.ts +51 -0
- package/types/syncHost.d.ts.map +1 -0
- package/types/syncHost.test.d.ts +2 -0
- package/types/syncHost.test.d.ts.map +1 -0
|
@@ -0,0 +1,523 @@
|
|
|
1
|
+
import { createBuilder } from '@rocicorp/zero'
|
|
2
|
+
import { asQueryInternals } from '@rocicorp/zero/bindings'
|
|
3
|
+
|
|
4
|
+
import {
|
|
5
|
+
createZeroServerCore,
|
|
6
|
+
type PersistAlreadyProcessedArgs,
|
|
7
|
+
type ZeroServer,
|
|
8
|
+
type ZeroServerCommonOptions,
|
|
9
|
+
type ZeroServerDatabase,
|
|
10
|
+
} from './createZeroServerCore'
|
|
11
|
+
|
|
12
|
+
import type { GenericModels, Transaction } from './types'
|
|
13
|
+
import type { AST, Schema as ZeroSchema } from '@rocicorp/zero'
|
|
14
|
+
import type {
|
|
15
|
+
TransactionProviderHooks,
|
|
16
|
+
TransactionProviderInput,
|
|
17
|
+
} from '@rocicorp/zero/server'
|
|
18
|
+
|
|
19
|
+
export type SQLiteTransactionExecutor = {
|
|
20
|
+
exec(sql: string, params?: readonly unknown[]): void | Promise<void>
|
|
21
|
+
query<Row extends Record<string, unknown> = Record<string, unknown>>(
|
|
22
|
+
sql: string,
|
|
23
|
+
params?: readonly unknown[],
|
|
24
|
+
): Row[] | Promise<Row[]>
|
|
25
|
+
queryAst<Result = unknown>(
|
|
26
|
+
ast: AST,
|
|
27
|
+
format: SQLiteQueryFormat,
|
|
28
|
+
queryName?: string,
|
|
29
|
+
): Result | Promise<Result>
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
export type SQLiteQueryFormat = {
|
|
33
|
+
relationships: Record<string, SQLiteQueryFormat>
|
|
34
|
+
singular: boolean
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
export type SQLiteTransactionProvider = <R>(
|
|
38
|
+
callback: (tx: SQLiteTransactionExecutor) => Promise<R>,
|
|
39
|
+
) => Promise<R>
|
|
40
|
+
|
|
41
|
+
type SQLiteColumn = ZeroSchema['tables'][string]['columns'][string]
|
|
42
|
+
|
|
43
|
+
export type SQLiteValueContext = {
|
|
44
|
+
column: SQLiteColumn
|
|
45
|
+
columnName: string
|
|
46
|
+
tableName: string
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
export type ZeroSQLiteTransactionOptions<Schema extends ZeroSchema> = {
|
|
50
|
+
schema: Schema
|
|
51
|
+
encodeValue?: (value: unknown, context: SQLiteValueContext) => unknown
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
export type SQLiteLedgerTables = {
|
|
55
|
+
clients: string
|
|
56
|
+
mutations: string
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
export type CreateZeroSQLiteServerOptions<
|
|
60
|
+
Schema extends ZeroSchema,
|
|
61
|
+
Models extends GenericModels,
|
|
62
|
+
ServerActions extends Record<string, unknown>,
|
|
63
|
+
> = ZeroServerCommonOptions<Schema, Models, ServerActions> & {
|
|
64
|
+
transactionProvider: SQLiteTransactionProvider
|
|
65
|
+
ledgerTables?: (upstreamSchema: string) => SQLiteLedgerTables
|
|
66
|
+
encodeValue?: (value: unknown, context: SQLiteValueContext) => unknown
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
export function createZeroSQLiteServer<
|
|
70
|
+
Schema extends ZeroSchema,
|
|
71
|
+
Models extends GenericModels,
|
|
72
|
+
ServerActions extends Record<string, unknown>,
|
|
73
|
+
>({
|
|
74
|
+
encodeValue = encodeSQLiteValue,
|
|
75
|
+
ledgerTables = defaultLedgerTables,
|
|
76
|
+
transactionProvider,
|
|
77
|
+
...options
|
|
78
|
+
}: CreateZeroSQLiteServerOptions<Schema, Models, ServerActions>): ZeroServer<
|
|
79
|
+
Schema,
|
|
80
|
+
Models,
|
|
81
|
+
ServerActions
|
|
82
|
+
> {
|
|
83
|
+
const databaseOptions = {
|
|
84
|
+
encodeValue,
|
|
85
|
+
initializedLedgers: new Set<string>(),
|
|
86
|
+
ledgerTables,
|
|
87
|
+
schema: options.schema,
|
|
88
|
+
transactionProvider,
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
return createZeroServerCore({
|
|
92
|
+
...options,
|
|
93
|
+
createDatabase: () => createSQLiteDatabase(databaseOptions),
|
|
94
|
+
persistAlreadyProcessed: (args) =>
|
|
95
|
+
persistAlreadyProcessedMutationResults(databaseOptions, args),
|
|
96
|
+
})
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
type SQLiteTransactionOptions<Schema extends ZeroSchema> = {
|
|
100
|
+
encodeValue: (value: unknown, context: SQLiteValueContext) => unknown
|
|
101
|
+
schema: Schema
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
type SQLiteDatabaseOptions<Schema extends ZeroSchema> =
|
|
105
|
+
SQLiteTransactionOptions<Schema> & {
|
|
106
|
+
initializedLedgers: Set<string>
|
|
107
|
+
ledgerTables: (upstreamSchema: string) => SQLiteLedgerTables
|
|
108
|
+
transactionProvider: SQLiteTransactionProvider
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
function createSQLiteDatabase<Schema extends ZeroSchema>(
|
|
112
|
+
options: SQLiteDatabaseOptions<Schema>,
|
|
113
|
+
): ZeroServerDatabase {
|
|
114
|
+
return {
|
|
115
|
+
async transaction<R>(
|
|
116
|
+
callback: (
|
|
117
|
+
tx: Transaction,
|
|
118
|
+
transactionHooks: TransactionProviderHooks,
|
|
119
|
+
) => R | Promise<R>,
|
|
120
|
+
input?: TransactionProviderInput,
|
|
121
|
+
) {
|
|
122
|
+
let committedLedgers = new Set<string>()
|
|
123
|
+
const value = await options.transactionProvider(async (executor) => {
|
|
124
|
+
const attemptLedgers = new Set<string>()
|
|
125
|
+
const ensureLedger = async (upstreamSchema: string) => {
|
|
126
|
+
const tables = options.ledgerTables(upstreamSchema)
|
|
127
|
+
const key = ledgerKey(tables)
|
|
128
|
+
if (options.initializedLedgers.has(key) || attemptLedgers.has(key)) {
|
|
129
|
+
return
|
|
130
|
+
}
|
|
131
|
+
await createLedgerTables(executor, tables)
|
|
132
|
+
attemptLedgers.add(key)
|
|
133
|
+
}
|
|
134
|
+
const transaction = createZeroSQLiteTransaction(options, executor, input)
|
|
135
|
+
const result = await callback(
|
|
136
|
+
transaction,
|
|
137
|
+
createLedgerHooks(options, executor, ensureLedger, input),
|
|
138
|
+
)
|
|
139
|
+
committedLedgers = attemptLedgers
|
|
140
|
+
return result
|
|
141
|
+
})
|
|
142
|
+
for (const key of committedLedgers) options.initializedLedgers.add(key)
|
|
143
|
+
return value
|
|
144
|
+
},
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
export function createZeroSQLiteTransaction<Schema extends ZeroSchema>(
|
|
149
|
+
options: ZeroSQLiteTransactionOptions<Schema>,
|
|
150
|
+
executor: SQLiteTransactionExecutor,
|
|
151
|
+
input?: TransactionProviderInput,
|
|
152
|
+
): Transaction {
|
|
153
|
+
const transactionOptions = {
|
|
154
|
+
encodeValue: options.encodeValue ?? encodeSQLiteValue,
|
|
155
|
+
schema: options.schema,
|
|
156
|
+
}
|
|
157
|
+
const clientID = input?.clientID ?? ''
|
|
158
|
+
const mutationID = input?.mutationID ?? 0
|
|
159
|
+
const mutate = new Proxy(
|
|
160
|
+
{},
|
|
161
|
+
{
|
|
162
|
+
get(_target, tableKey) {
|
|
163
|
+
const tableName = String(tableKey)
|
|
164
|
+
if (!options.schema.tables[tableName]) {
|
|
165
|
+
throw new Error(`unknown SQLite mutation table ${tableName}`)
|
|
166
|
+
}
|
|
167
|
+
return new Proxy(
|
|
168
|
+
{},
|
|
169
|
+
{
|
|
170
|
+
get(_innerTarget, kindKey) {
|
|
171
|
+
const kind = String(kindKey)
|
|
172
|
+
if (!isCrudKind(kind)) return
|
|
173
|
+
return (value: unknown) =>
|
|
174
|
+
executeCrud(transactionOptions, executor, tableName, kind, value)
|
|
175
|
+
},
|
|
176
|
+
},
|
|
177
|
+
)
|
|
178
|
+
},
|
|
179
|
+
},
|
|
180
|
+
)
|
|
181
|
+
|
|
182
|
+
const runQuery = (
|
|
183
|
+
ast: AST,
|
|
184
|
+
format: SQLiteQueryFormat,
|
|
185
|
+
queryName?: string,
|
|
186
|
+
): Promise<unknown> => Promise.resolve(executor.queryAst(ast, format, queryName))
|
|
187
|
+
const dbTransaction = {
|
|
188
|
+
wrappedTransaction: executor,
|
|
189
|
+
query: (sql: string, args: unknown[]) => executor.query(sql, args),
|
|
190
|
+
runQuery,
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
return {
|
|
194
|
+
clientID,
|
|
195
|
+
dbTransaction,
|
|
196
|
+
location: 'server',
|
|
197
|
+
mutate,
|
|
198
|
+
mutationID,
|
|
199
|
+
query: transactionOptions.schema.enableLegacyQueries
|
|
200
|
+
? createLegacyQueryBuilder(transactionOptions.schema, (query) => {
|
|
201
|
+
const internals = asQueryInternals(query as never)
|
|
202
|
+
return runQuery(internals.ast, internals.format, internals.customQueryID?.name)
|
|
203
|
+
})
|
|
204
|
+
: undefined,
|
|
205
|
+
reason: 'authoritative',
|
|
206
|
+
async run(query: unknown) {
|
|
207
|
+
const internals = asQueryInternals(query as never)
|
|
208
|
+
return runQuery(internals.ast, internals.format, internals.customQueryID?.name)
|
|
209
|
+
},
|
|
210
|
+
} as unknown as Transaction
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
type CrudKind = 'delete' | 'insert' | 'update' | 'upsert'
|
|
214
|
+
|
|
215
|
+
function isCrudKind(value: string): value is CrudKind {
|
|
216
|
+
return (
|
|
217
|
+
value === 'delete' || value === 'insert' || value === 'update' || value === 'upsert'
|
|
218
|
+
)
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
async function executeCrud<Schema extends ZeroSchema>(
|
|
222
|
+
options: SQLiteTransactionOptions<Schema>,
|
|
223
|
+
executor: SQLiteTransactionExecutor,
|
|
224
|
+
tableName: string,
|
|
225
|
+
kind: CrudKind,
|
|
226
|
+
raw: unknown,
|
|
227
|
+
) {
|
|
228
|
+
if (!raw || typeof raw !== 'object' || Array.isArray(raw)) {
|
|
229
|
+
throw new Error(`${tableName}.${kind} expects an object`)
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
const table = options.schema.tables[tableName]!
|
|
233
|
+
const values = Object.fromEntries(
|
|
234
|
+
Object.entries(raw as Record<string, unknown>).filter(
|
|
235
|
+
([, value]) => value !== undefined,
|
|
236
|
+
),
|
|
237
|
+
)
|
|
238
|
+
for (const columnName of Object.keys(values)) {
|
|
239
|
+
if (!table.columns[columnName]) {
|
|
240
|
+
throw new Error(`unknown SQLite column ${tableName}.${columnName}`)
|
|
241
|
+
}
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
const primaryValues = table.primaryKey.map((columnName) => {
|
|
245
|
+
if (!(columnName in values)) {
|
|
246
|
+
throw new Error(`${tableName}.${kind} is missing primary key ${columnName}`)
|
|
247
|
+
}
|
|
248
|
+
return encodeColumn(options, tableName, columnName, values[columnName])
|
|
249
|
+
})
|
|
250
|
+
const primaryWhere = table.primaryKey
|
|
251
|
+
.map((columnName) => `${quoteSQLiteIdentifier(serverColumn(table, columnName))} = ?`)
|
|
252
|
+
.join(' AND ')
|
|
253
|
+
const serverTableName = quoteSQLiteIdentifier(table.serverName ?? table.name)
|
|
254
|
+
|
|
255
|
+
if (kind === 'delete') {
|
|
256
|
+
await executor.exec(
|
|
257
|
+
`DELETE FROM ${serverTableName} WHERE ${primaryWhere}`,
|
|
258
|
+
primaryValues,
|
|
259
|
+
)
|
|
260
|
+
return
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
const columnNames = Object.keys(values)
|
|
264
|
+
if (columnNames.length === 0) {
|
|
265
|
+
throw new Error(`${tableName}.${kind} has no values`)
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
const serverColumns = columnNames.map((columnName) =>
|
|
269
|
+
quoteSQLiteIdentifier(serverColumn(table, columnName)),
|
|
270
|
+
)
|
|
271
|
+
const params = columnNames.map((columnName) =>
|
|
272
|
+
encodeColumn(options, tableName, columnName, values[columnName]),
|
|
273
|
+
)
|
|
274
|
+
const insert = `INSERT INTO ${serverTableName} (${serverColumns.join(
|
|
275
|
+
', ',
|
|
276
|
+
)}) VALUES (${columnNames.map(() => '?').join(', ')})`
|
|
277
|
+
|
|
278
|
+
if (kind === 'insert') {
|
|
279
|
+
await executor.exec(insert, params)
|
|
280
|
+
return
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
if (kind === 'upsert') {
|
|
284
|
+
const mutableColumns = columnNames.filter(
|
|
285
|
+
(columnName) => !table.primaryKey.includes(columnName),
|
|
286
|
+
)
|
|
287
|
+
const conflictColumns = table.primaryKey
|
|
288
|
+
.map((columnName) => quoteSQLiteIdentifier(serverColumn(table, columnName)))
|
|
289
|
+
.join(', ')
|
|
290
|
+
const conflictAction =
|
|
291
|
+
mutableColumns.length === 0
|
|
292
|
+
? 'DO NOTHING'
|
|
293
|
+
: `DO UPDATE SET ${mutableColumns
|
|
294
|
+
.map((columnName) => {
|
|
295
|
+
const column = quoteSQLiteIdentifier(serverColumn(table, columnName))
|
|
296
|
+
return `${column} = excluded.${column}`
|
|
297
|
+
})
|
|
298
|
+
.join(', ')}`
|
|
299
|
+
await executor.exec(
|
|
300
|
+
`${insert} ON CONFLICT (${conflictColumns}) ${conflictAction}`,
|
|
301
|
+
params,
|
|
302
|
+
)
|
|
303
|
+
return
|
|
304
|
+
}
|
|
305
|
+
|
|
306
|
+
const mutableColumns = columnNames.filter(
|
|
307
|
+
(columnName) => !table.primaryKey.includes(columnName),
|
|
308
|
+
)
|
|
309
|
+
if (mutableColumns.length === 0) return
|
|
310
|
+
await executor.exec(
|
|
311
|
+
`UPDATE ${serverTableName} SET ${mutableColumns
|
|
312
|
+
.map(
|
|
313
|
+
(columnName) => `${quoteSQLiteIdentifier(serverColumn(table, columnName))} = ?`,
|
|
314
|
+
)
|
|
315
|
+
.join(', ')} WHERE ${primaryWhere}`,
|
|
316
|
+
[
|
|
317
|
+
...mutableColumns.map((columnName) =>
|
|
318
|
+
encodeColumn(options, tableName, columnName, values[columnName]),
|
|
319
|
+
),
|
|
320
|
+
...primaryValues,
|
|
321
|
+
],
|
|
322
|
+
)
|
|
323
|
+
}
|
|
324
|
+
|
|
325
|
+
function serverColumn(table: ZeroSchema['tables'][string], columnName: string) {
|
|
326
|
+
const column = table.columns[columnName]
|
|
327
|
+
if (!column) throw new Error(`unknown SQLite column ${table.name}.${columnName}`)
|
|
328
|
+
return column.serverName ?? columnName
|
|
329
|
+
}
|
|
330
|
+
|
|
331
|
+
function encodeColumn<Schema extends ZeroSchema>(
|
|
332
|
+
options: SQLiteTransactionOptions<Schema>,
|
|
333
|
+
tableName: string,
|
|
334
|
+
columnName: string,
|
|
335
|
+
value: unknown,
|
|
336
|
+
) {
|
|
337
|
+
return options.encodeValue(value, {
|
|
338
|
+
column: options.schema.tables[tableName]!.columns[columnName]!,
|
|
339
|
+
columnName,
|
|
340
|
+
tableName,
|
|
341
|
+
})
|
|
342
|
+
}
|
|
343
|
+
|
|
344
|
+
function createLegacyQueryBuilder<Schema extends ZeroSchema>(
|
|
345
|
+
schema: Schema,
|
|
346
|
+
run: (query: unknown) => Promise<unknown>,
|
|
347
|
+
) {
|
|
348
|
+
const builder = createBuilder(schema)
|
|
349
|
+
return new Proxy(builder, {
|
|
350
|
+
get(target, property) {
|
|
351
|
+
return makeRunnableQuery(Reflect.get(target, property, target), run)
|
|
352
|
+
},
|
|
353
|
+
})
|
|
354
|
+
}
|
|
355
|
+
|
|
356
|
+
function makeRunnableQuery(
|
|
357
|
+
query: unknown,
|
|
358
|
+
run: (query: unknown) => Promise<unknown>,
|
|
359
|
+
): unknown {
|
|
360
|
+
if (!isQueryBuilder(query)) return query
|
|
361
|
+
return new Proxy(query as object, {
|
|
362
|
+
get(target, property) {
|
|
363
|
+
if (property === 'run') return () => run(target)
|
|
364
|
+
if (property === 'materialize' || property === 'preload') {
|
|
365
|
+
return () => {
|
|
366
|
+
throw new Error(`${String(property)}() is not supported in server transactions`)
|
|
367
|
+
}
|
|
368
|
+
}
|
|
369
|
+
const value = Reflect.get(target, property, target)
|
|
370
|
+
if (typeof value !== 'function') return value
|
|
371
|
+
return (...args: unknown[]) =>
|
|
372
|
+
makeRunnableQuery(Reflect.apply(value, target, args), run)
|
|
373
|
+
},
|
|
374
|
+
})
|
|
375
|
+
}
|
|
376
|
+
|
|
377
|
+
function isQueryBuilder(value: unknown) {
|
|
378
|
+
if (!value || typeof value !== 'object') return false
|
|
379
|
+
try {
|
|
380
|
+
asQueryInternals(value as never)
|
|
381
|
+
return true
|
|
382
|
+
} catch {
|
|
383
|
+
return false
|
|
384
|
+
}
|
|
385
|
+
}
|
|
386
|
+
|
|
387
|
+
function createLedgerHooks<Schema extends ZeroSchema>(
|
|
388
|
+
options: SQLiteDatabaseOptions<Schema>,
|
|
389
|
+
executor: SQLiteTransactionExecutor,
|
|
390
|
+
ensureLedger: (upstreamSchema: string) => Promise<void>,
|
|
391
|
+
input?: TransactionProviderInput,
|
|
392
|
+
): TransactionProviderHooks {
|
|
393
|
+
const upstreamSchema = input?.upstreamSchema ?? ''
|
|
394
|
+
const clientGroupID = input?.clientGroupID ?? ''
|
|
395
|
+
const clientID = input?.clientID ?? ''
|
|
396
|
+
const tables = options.ledgerTables(upstreamSchema)
|
|
397
|
+
const clientsTable = quoteSQLiteIdentifier(tables.clients)
|
|
398
|
+
const mutationsTable = quoteSQLiteIdentifier(tables.mutations)
|
|
399
|
+
|
|
400
|
+
return {
|
|
401
|
+
async updateClientMutationID() {
|
|
402
|
+
await ensureLedger(upstreamSchema)
|
|
403
|
+
const rows = await executor.query<{ lastMutationID: number | bigint }>(
|
|
404
|
+
`INSERT INTO ${clientsTable}
|
|
405
|
+
(clientGroupID, clientID, lastMutationID)
|
|
406
|
+
VALUES (?, ?, 1)
|
|
407
|
+
ON CONFLICT (clientGroupID, clientID)
|
|
408
|
+
DO UPDATE SET lastMutationID = lastMutationID + 1
|
|
409
|
+
RETURNING lastMutationID`,
|
|
410
|
+
[clientGroupID, clientID],
|
|
411
|
+
)
|
|
412
|
+
const lastMutationID = rows[0]?.lastMutationID
|
|
413
|
+
if (typeof lastMutationID !== 'number' && typeof lastMutationID !== 'bigint') {
|
|
414
|
+
throw new Error('SQLite mutation ledger returned no lastMutationID')
|
|
415
|
+
}
|
|
416
|
+
return { lastMutationID }
|
|
417
|
+
},
|
|
418
|
+
async writeMutationResult(result) {
|
|
419
|
+
await ensureLedger(upstreamSchema)
|
|
420
|
+
await executor.exec(
|
|
421
|
+
`INSERT INTO ${mutationsTable}
|
|
422
|
+
(clientGroupID, clientID, mutationID, result)
|
|
423
|
+
VALUES (?, ?, ?, ?)`,
|
|
424
|
+
[clientGroupID, result.id.clientID, result.id.id, JSON.stringify(result.result)],
|
|
425
|
+
)
|
|
426
|
+
},
|
|
427
|
+
async deleteMutationResults(args) {
|
|
428
|
+
await ensureLedger(upstreamSchema)
|
|
429
|
+
if ('type' in args && args.type === 'bulk') {
|
|
430
|
+
if (args.clientIDs.length === 0) return
|
|
431
|
+
await executor.exec(
|
|
432
|
+
`DELETE FROM ${mutationsTable}
|
|
433
|
+
WHERE clientGroupID = ?
|
|
434
|
+
AND clientID IN (${args.clientIDs.map(() => '?').join(', ')})`,
|
|
435
|
+
[args.clientGroupID, ...args.clientIDs],
|
|
436
|
+
)
|
|
437
|
+
return
|
|
438
|
+
}
|
|
439
|
+
await executor.exec(
|
|
440
|
+
`DELETE FROM ${mutationsTable}
|
|
441
|
+
WHERE clientGroupID = ?
|
|
442
|
+
AND clientID = ?
|
|
443
|
+
AND mutationID <= ?`,
|
|
444
|
+
[args.clientGroupID, args.clientID, args.upToMutationID],
|
|
445
|
+
)
|
|
446
|
+
},
|
|
447
|
+
}
|
|
448
|
+
}
|
|
449
|
+
|
|
450
|
+
async function persistAlreadyProcessedMutationResults<Schema extends ZeroSchema>(
|
|
451
|
+
options: SQLiteDatabaseOptions<Schema>,
|
|
452
|
+
{ clientGroupID, mutations, upstreamSchema }: PersistAlreadyProcessedArgs,
|
|
453
|
+
) {
|
|
454
|
+
const tables = options.ledgerTables(upstreamSchema)
|
|
455
|
+
const table = quoteSQLiteIdentifier(tables.mutations)
|
|
456
|
+
const key = ledgerKey(tables)
|
|
457
|
+
await options.transactionProvider(async (executor) => {
|
|
458
|
+
if (!options.initializedLedgers.has(key)) {
|
|
459
|
+
await createLedgerTables(executor, tables)
|
|
460
|
+
}
|
|
461
|
+
for (const mutation of mutations) {
|
|
462
|
+
await executor.exec(
|
|
463
|
+
`INSERT INTO ${table}
|
|
464
|
+
(clientGroupID, clientID, mutationID, result)
|
|
465
|
+
VALUES (?, ?, ?, ?)
|
|
466
|
+
ON CONFLICT (clientGroupID, clientID, mutationID) DO NOTHING`,
|
|
467
|
+
[
|
|
468
|
+
clientGroupID,
|
|
469
|
+
mutation.id.clientID,
|
|
470
|
+
mutation.id.id,
|
|
471
|
+
JSON.stringify(mutation.result),
|
|
472
|
+
],
|
|
473
|
+
)
|
|
474
|
+
}
|
|
475
|
+
})
|
|
476
|
+
options.initializedLedgers.add(key)
|
|
477
|
+
}
|
|
478
|
+
|
|
479
|
+
async function createLedgerTables(
|
|
480
|
+
executor: SQLiteTransactionExecutor,
|
|
481
|
+
tables: SQLiteLedgerTables,
|
|
482
|
+
) {
|
|
483
|
+
await executor.exec(
|
|
484
|
+
`CREATE TABLE IF NOT EXISTS ${quoteSQLiteIdentifier(tables.clients)} (
|
|
485
|
+
clientGroupID TEXT NOT NULL,
|
|
486
|
+
clientID TEXT NOT NULL,
|
|
487
|
+
lastMutationID INTEGER NOT NULL,
|
|
488
|
+
PRIMARY KEY (clientGroupID, clientID)
|
|
489
|
+
)`,
|
|
490
|
+
)
|
|
491
|
+
await executor.exec(
|
|
492
|
+
`CREATE TABLE IF NOT EXISTS ${quoteSQLiteIdentifier(tables.mutations)} (
|
|
493
|
+
clientGroupID TEXT NOT NULL,
|
|
494
|
+
clientID TEXT NOT NULL,
|
|
495
|
+
mutationID INTEGER NOT NULL,
|
|
496
|
+
result TEXT NOT NULL,
|
|
497
|
+
PRIMARY KEY (clientGroupID, clientID, mutationID)
|
|
498
|
+
)`,
|
|
499
|
+
)
|
|
500
|
+
}
|
|
501
|
+
|
|
502
|
+
function ledgerKey(tables: SQLiteLedgerTables) {
|
|
503
|
+
return `${tables.clients}\0${tables.mutations}`
|
|
504
|
+
}
|
|
505
|
+
|
|
506
|
+
function defaultLedgerTables(upstreamSchema: string): SQLiteLedgerTables {
|
|
507
|
+
const prefix = upstreamSchema ? `${upstreamSchema}_` : ''
|
|
508
|
+
return {
|
|
509
|
+
clients: `${prefix}clients`,
|
|
510
|
+
mutations: `${prefix}mutations`,
|
|
511
|
+
}
|
|
512
|
+
}
|
|
513
|
+
|
|
514
|
+
function encodeSQLiteValue(value: unknown, { column }: SQLiteValueContext) {
|
|
515
|
+
if (value === null) return null
|
|
516
|
+
if (column.type === 'boolean') return value ? 1 : 0
|
|
517
|
+
if (column.type === 'json') return JSON.stringify(value)
|
|
518
|
+
return value
|
|
519
|
+
}
|
|
520
|
+
|
|
521
|
+
function quoteSQLiteIdentifier(value: string) {
|
|
522
|
+
return `"${value.replaceAll('"', '""')}"`
|
|
523
|
+
}
|
|
@@ -43,7 +43,10 @@ class FakePgClient {
|
|
|
43
43
|
}
|
|
44
44
|
}
|
|
45
45
|
|
|
46
|
-
if (
|
|
46
|
+
if (
|
|
47
|
+
sql.includes('INSERT INTO "zero_0"."mutations"') ||
|
|
48
|
+
sql.includes('INSERT INTO "zero_0".mutations')
|
|
49
|
+
) {
|
|
47
50
|
this.mutationResultInserts.push(params)
|
|
48
51
|
return { rows: [] }
|
|
49
52
|
}
|
|
@@ -91,6 +94,41 @@ function pushRequest(mutationIDs: number | number[]) {
|
|
|
91
94
|
}
|
|
92
95
|
|
|
93
96
|
describe('createZeroServer mutation recovery', () => {
|
|
97
|
+
test('discards async tasks from a rolled-back PostgreSQL mutation', async () => {
|
|
98
|
+
const pg = new FakePgClient()
|
|
99
|
+
let effectRuns = 0
|
|
100
|
+
const zeroServer = createZeroServer({
|
|
101
|
+
schema: zeroHttpFixtureSchema,
|
|
102
|
+
models: {
|
|
103
|
+
project: {
|
|
104
|
+
mutate: {
|
|
105
|
+
touch: async ({ server }) => {
|
|
106
|
+
server?.asyncTasks.push(async () => {
|
|
107
|
+
effectRuns++
|
|
108
|
+
})
|
|
109
|
+
throw new Error('rejected')
|
|
110
|
+
},
|
|
111
|
+
},
|
|
112
|
+
},
|
|
113
|
+
},
|
|
114
|
+
createServerActions: () => ({}),
|
|
115
|
+
pool: pg as any,
|
|
116
|
+
})
|
|
117
|
+
|
|
118
|
+
const result = await zeroServer.handleMutationRequest({
|
|
119
|
+
authData: null,
|
|
120
|
+
request: pushRequest(1),
|
|
121
|
+
skipAsyncTasks: true,
|
|
122
|
+
})
|
|
123
|
+
|
|
124
|
+
expect((result.response as any).mutations[0].result).toMatchObject({
|
|
125
|
+
error: 'app',
|
|
126
|
+
message: 'rejected',
|
|
127
|
+
})
|
|
128
|
+
expect(result.asyncTasks).toEqual([])
|
|
129
|
+
expect(effectRuns).toBe(0)
|
|
130
|
+
})
|
|
131
|
+
|
|
94
132
|
test('persists alreadyProcessed duplicate results for zero-cache recovery rows', async () => {
|
|
95
133
|
const pg = new FakePgClient()
|
|
96
134
|
const zeroServer = createZeroServer({
|