@jcbuisson/express-x-drizzle 1.0.4 → 1.0.7
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/.claude/settings.local.json +14 -0
- package/package.json +18 -8
- package/src/drizzle-plugins.mjs +86 -156
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
{
|
|
2
|
+
"permissions": {
|
|
3
|
+
"allow": [
|
|
4
|
+
"Bash(npm test *)",
|
|
5
|
+
"Bash(node -e \"require\\('tsx'\\)\")",
|
|
6
|
+
"Bash(npm install *)",
|
|
7
|
+
"Bash(node --test test/sync.test.mjs)",
|
|
8
|
+
"Bash(tee /tmp/test-output.txt)",
|
|
9
|
+
"Bash(tee /tmp/test-output2.txt)",
|
|
10
|
+
"Bash(node --help)",
|
|
11
|
+
"Bash(node --import tsx/esm --import /tmp/preload.mjs --test --test-force-exit test/round-trip.test.mjs)"
|
|
12
|
+
]
|
|
13
|
+
}
|
|
14
|
+
}
|
package/package.json
CHANGED
|
@@ -1,17 +1,20 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@jcbuisson/express-x-drizzle",
|
|
3
|
-
"version": "1.0.
|
|
4
|
-
"description": "",
|
|
3
|
+
"version": "1.0.7",
|
|
4
|
+
"description": "Drizzle ORM plugins for express-x framework",
|
|
5
5
|
"main": "src/drizzle-plugins.mjs",
|
|
6
6
|
"type": "module",
|
|
7
7
|
"private": false,
|
|
8
|
-
"publishConfig": {
|
|
9
|
-
"access": "public"
|
|
8
|
+
"publishConfig": {
|
|
9
|
+
"access": "public"
|
|
10
10
|
},
|
|
11
11
|
"engines": {
|
|
12
12
|
"node": ">= 14.0.0",
|
|
13
13
|
"npm": ">= 6.0.0"
|
|
14
14
|
},
|
|
15
|
+
"imports": {
|
|
16
|
+
"#root/*": "./*"
|
|
17
|
+
},
|
|
15
18
|
"homepage": "",
|
|
16
19
|
"repository": {
|
|
17
20
|
"type": "git",
|
|
@@ -22,13 +25,20 @@
|
|
|
22
25
|
"bugs": "",
|
|
23
26
|
"keywords": [],
|
|
24
27
|
"scripts": {
|
|
25
|
-
"dev": "",
|
|
26
|
-
"test": ""
|
|
27
28
|
},
|
|
28
29
|
"dependencies": {
|
|
29
|
-
"@jcbuisson/express-x": "^3.0.
|
|
30
|
+
"@jcbuisson/express-x": "^3.0.4",
|
|
31
|
+
"@jcbuisson/express-x-client": "^3.0.5",
|
|
32
|
+
"@vueuse/core": "^14.3.0",
|
|
33
|
+
"dexie": "^4.4.2",
|
|
34
|
+
"drizzle-orm": "^0.45.2",
|
|
35
|
+
"fake-indexeddb": "^6.2.5",
|
|
36
|
+
"rxjs": "^7.8.2",
|
|
37
|
+
"socket.io-client": "^4.8.3",
|
|
38
|
+
"uuid": "^14.0.0"
|
|
30
39
|
},
|
|
31
40
|
"devDependencies": {
|
|
32
|
-
|
|
41
|
+
"@electric-sql/pglite": "^0.4.5",
|
|
42
|
+
"tsx": "^4.22.1"
|
|
33
43
|
}
|
|
34
44
|
}
|
package/src/drizzle-plugins.mjs
CHANGED
|
@@ -1,56 +1,31 @@
|
|
|
1
|
-
import
|
|
2
|
-
import { createServer } from "http"
|
|
3
|
-
import { Server } from "socket.io"
|
|
4
|
-
import bcrypt from 'bcryptjs'
|
|
1
|
+
import { and, eq, gt, gte, lt, lte, isNull, getTableName } from "drizzle-orm";
|
|
5
2
|
|
|
6
|
-
import {
|
|
7
|
-
|
|
8
|
-
import { metadata } from '#root/src/db/schema.js';
|
|
9
|
-
import { Mutex, truncateString } from '@jcbuisson/express-x'
|
|
3
|
+
import { Mutex, truncateString, computeSyncResult } from '@jcbuisson/express-x'
|
|
10
4
|
|
|
11
5
|
|
|
12
6
|
////////////////////////// UTILITIES //////////////////////////
|
|
13
7
|
|
|
14
|
-
function whereToDrizzleFilters(table,
|
|
15
|
-
const conditions = Object.entries(
|
|
8
|
+
function whereToDrizzleFilters(table, where) {
|
|
9
|
+
const conditions = Object.entries(where)
|
|
16
10
|
.filter(([_, value]) => value !== undefined)
|
|
17
|
-
.map(([key, value]) =>
|
|
11
|
+
.map(([key, value]) => {
|
|
12
|
+
if (value === null) return isNull(table[key])
|
|
13
|
+
if (typeof value === 'object') {
|
|
14
|
+
// Collect ALL range bounds — a compound { gte:1, lte:10 } needs both
|
|
15
|
+
const bounds = []
|
|
16
|
+
if ('gte' in value) bounds.push(gte(table[key], value.gte))
|
|
17
|
+
if ('gt' in value) bounds.push(gt(table[key], value.gt))
|
|
18
|
+
if ('lte' in value) bounds.push(lte(table[key], value.lte))
|
|
19
|
+
if ('lt' in value) bounds.push(lt(table[key], value.lt))
|
|
20
|
+
if (bounds.length > 0) return and(...bounds)
|
|
21
|
+
}
|
|
22
|
+
return eq(table[key], value)
|
|
23
|
+
})
|
|
18
24
|
return conditions.length ? and(...conditions) : undefined;
|
|
19
25
|
}
|
|
20
26
|
|
|
21
|
-
// ////////////////////////// DRIZZLE CRUD DATABSE PLUGIN //////////////////////////
|
|
22
|
-
|
|
23
|
-
// export function drizzleDatabasePlugin(app, db, models) {
|
|
24
|
-
|
|
25
|
-
// // add a database service for each model
|
|
26
|
-
// for (const model of models) {
|
|
27
|
-
// const modelName = getTableName(model)
|
|
28
|
-
|
|
29
|
-
// app.createService(modelName, {
|
|
30
|
-
|
|
31
|
-
// findUnique: async (where) => {
|
|
32
|
-
// const rows = await db.select().from(model).where(whereToDrizzleFilters(model, where));
|
|
33
|
-
// return rows[0] ?? null;
|
|
34
|
-
// },
|
|
35
|
-
|
|
36
|
-
// findMany: async (where) => {
|
|
37
|
-
// return await db.select().from(model).where(whereToDrizzleFilters(model, where));
|
|
38
|
-
// },
|
|
39
|
-
|
|
40
|
-
// create: async (data) => {
|
|
41
|
-
// return await db.insert(model).values(data).returning();
|
|
42
|
-
// },
|
|
43
|
-
|
|
44
|
-
// update: async (uid, data) => {
|
|
45
|
-
// return await db.update(model).where(eq(model.uid, uid)).values(data).returning();
|
|
46
|
-
// },
|
|
47
27
|
|
|
48
|
-
//
|
|
49
|
-
// return await db.delete(model).where(eq(model.uid, uid)).returning();
|
|
50
|
-
// }
|
|
51
|
-
// })
|
|
52
|
-
// }
|
|
53
|
-
// }
|
|
28
|
+
// DOIT FAIRE UN ROLLBACK EN CAS D'ERREUR SERVEUR (EX: ERREUR SÉMANTIQUE TYPE PB CLÉ ÉTRANGÈRE OU AUTRE)
|
|
54
29
|
|
|
55
30
|
|
|
56
31
|
////////////////////////// DRIZZLE OFFLINE PLUGIN //////////////////////////
|
|
@@ -73,154 +48,109 @@ export function drizzleOfflinePlugin(app, db, metadata, models) {
|
|
|
73
48
|
},
|
|
74
49
|
|
|
75
50
|
createWithMeta: async (uid, data, created_at) => {
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
51
|
+
const ts = new Date(created_at)
|
|
52
|
+
return await db.transaction(async (tx) => {
|
|
53
|
+
// Upsert: if the model row already exists (e.g. a concurrent createWithMeta
|
|
54
|
+
// from the direct create() path landed before the sync's addDatabase step),
|
|
55
|
+
// update it instead of throwing a PK conflict that would rollback the
|
|
56
|
+
// client's Dexie record.
|
|
57
|
+
const [value] = await tx.insert(model)
|
|
58
|
+
.values({ uid, ...data })
|
|
59
|
+
.onConflictDoUpdate({ target: model.uid, set: data })
|
|
60
|
+
.returning();
|
|
61
|
+
// Upsert metadata: handles re-creation after a prior deleteWithMeta.
|
|
62
|
+
const [meta] = await tx.insert(metadata)
|
|
63
|
+
.values({ uid, created_at: ts })
|
|
64
|
+
.onConflictDoUpdate({
|
|
65
|
+
target: metadata.uid,
|
|
66
|
+
set: { created_at: ts, deleted_at: null, updated_at: null },
|
|
67
|
+
})
|
|
68
|
+
.returning();
|
|
79
69
|
return [value, meta]
|
|
80
70
|
})
|
|
81
71
|
},
|
|
82
|
-
|
|
72
|
+
|
|
83
73
|
updateWithMeta: async (uid, data, updated_at) => {
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
const
|
|
74
|
+
const ts = updated_at ? new Date(updated_at) : null
|
|
75
|
+
return await db.transaction(async (tx) => {
|
|
76
|
+
const [value] = await tx.update(model).set(data).where(eq(model.uid, uid)).returning();
|
|
77
|
+
// Upsert metadata: if the row is missing (data-integrity gap where the
|
|
78
|
+
// model row exists but no metadata row), create it so the loop stops.
|
|
79
|
+
const [meta] = await tx.insert(metadata)
|
|
80
|
+
.values({ uid, updated_at: ts })
|
|
81
|
+
.onConflictDoUpdate({ target: metadata.uid, set: { updated_at: ts } })
|
|
82
|
+
.returning();
|
|
87
83
|
return [value, meta]
|
|
88
84
|
})
|
|
89
85
|
},
|
|
90
|
-
|
|
86
|
+
|
|
91
87
|
deleteWithMeta: async (uid, deleted_at) => {
|
|
92
|
-
db.transaction(async (tx) => {
|
|
93
|
-
const value = await tx.delete(model).where(eq(model.uid, uid)).returning();
|
|
94
|
-
const meta = await tx.update(metadata).set({ deleted_at }).where(eq(metadata.uid, uid)).returning();
|
|
88
|
+
return await db.transaction(async (tx) => {
|
|
89
|
+
const [value] = await tx.delete(model).where(eq(model.uid, uid)).returning();
|
|
90
|
+
const [meta] = await tx.update(metadata).set({ deleted_at: new Date(deleted_at) }).where(eq(metadata.uid, uid)).returning();
|
|
95
91
|
return [value, meta]
|
|
96
92
|
})
|
|
97
93
|
},
|
|
98
94
|
})
|
|
99
95
|
}
|
|
100
96
|
|
|
101
|
-
const
|
|
97
|
+
const syncMutexes = new Map()
|
|
102
98
|
|
|
103
99
|
// add a synchronization service
|
|
104
100
|
app.createService('sync', {
|
|
105
101
|
|
|
106
|
-
//
|
|
102
|
+
// CUTOFFDATE INUTILE ?
|
|
107
103
|
go: async (modelName, where, cutoffDate, clientMetadataDict) => {
|
|
108
|
-
|
|
104
|
+
|
|
105
|
+
// get or create a mutex specific to modelName + where
|
|
106
|
+
const mutexKey = `${modelName}:${JSON.stringify(Object.fromEntries(Object.entries(where).sort()))}`
|
|
107
|
+
if (!syncMutexes.has(mutexKey)) syncMutexes.set(mutexKey, new Mutex())
|
|
108
|
+
// acquire it: no other sync operation from another client on this model+where can occur in parallel
|
|
109
|
+
await syncMutexes.get(mutexKey).acquire()
|
|
110
|
+
|
|
109
111
|
try {
|
|
110
112
|
console.log('>>>>> SYNC', modelName, where, cutoffDate)
|
|
111
113
|
const databaseService = app.service(modelName)
|
|
112
114
|
|
|
113
|
-
//
|
|
115
|
+
// STEP1: get existing database `where` values and build a dictionary
|
|
114
116
|
const databaseValues = await databaseService.findMany(where)
|
|
115
|
-
|
|
116
117
|
const databaseValuesDict = databaseValues.reduce((accu, value) => {
|
|
117
118
|
accu[value.uid] = value
|
|
118
119
|
return accu
|
|
119
120
|
}, {})
|
|
120
|
-
|
|
121
|
-
//
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
const databaseAndClientIds = new Set()
|
|
127
|
-
|
|
128
|
-
for (const uid in databaseValuesDict) {
|
|
129
|
-
if (uid in clientMetadataDict) {
|
|
130
|
-
databaseAndClientIds.add(uid)
|
|
131
|
-
} else {
|
|
132
|
-
onlyDatabaseIds.add(uid)
|
|
133
|
-
}
|
|
134
|
-
}
|
|
135
|
-
|
|
136
|
-
for (const uid in clientMetadataDict) {
|
|
137
|
-
if (uid in databaseValuesDict) {
|
|
138
|
-
databaseAndClientIds.add(uid)
|
|
139
|
-
} else {
|
|
140
|
-
onlyClientIds.add(uid)
|
|
141
|
-
}
|
|
142
|
-
}
|
|
143
|
-
// console.log('onlyDatabaseIds', onlyDatabaseIds)
|
|
144
|
-
// console.log('onlyClientIds', onlyClientIds)
|
|
145
|
-
// console.log('databaseAndClientIds', databaseAndClientIds)
|
|
146
|
-
|
|
147
|
-
// STEP 3: build add/update/delete sets
|
|
148
|
-
const addDatabase = []
|
|
149
|
-
const updateDatabase = []
|
|
150
|
-
const deleteDatabase = []
|
|
151
|
-
|
|
152
|
-
const addClient = []
|
|
153
|
-
const updateClient = []
|
|
154
|
-
const deleteClient = []
|
|
155
|
-
|
|
156
|
-
for (const uid of onlyDatabaseIds) {
|
|
157
|
-
const databaseValue = databaseValuesDict[uid]
|
|
158
|
-
const databaseMetaData = (await db.select().from(metadata).where(eq(metadata.uid, uid)))[0]
|
|
159
|
-
|| { uid, created_at: new Date() } // should not happen
|
|
160
|
-
addClient.push([databaseValue, databaseMetaData])
|
|
161
|
-
}
|
|
162
|
-
|
|
163
|
-
for (const uid of onlyClientIds) {
|
|
164
|
-
const clientMetaData = clientMetadataDict[uid]
|
|
165
|
-
if (clientMetaData.deleted_at) {
|
|
166
|
-
deleteClient.push([uid, clientMetaData.deleted_at])
|
|
167
|
-
} else if (new Date(clientMetaData.created_at) > cutoffDate) {
|
|
168
|
-
addDatabase.push(clientMetaData)
|
|
169
|
-
} else {
|
|
170
|
-
// ???
|
|
171
|
-
}
|
|
172
|
-
}
|
|
173
|
-
|
|
174
|
-
for (const uid of databaseAndClientIds) {
|
|
175
|
-
const databaseValue = databaseValuesDict[uid]
|
|
176
|
-
const clientMetaData = clientMetadataDict[uid]
|
|
177
|
-
|| { uid, created_at: new Date() } // should not happen
|
|
178
|
-
if (clientMetaData.deleted_at) {
|
|
179
|
-
deleteDatabase.push(uid)
|
|
180
|
-
deleteClient.push([uid, clientMetaData.deleted_at])
|
|
181
|
-
} else {
|
|
182
|
-
const databaseMetaData = (await db.select().from(metadata).where(eq(metadata.uid, uid)))[0]
|
|
183
|
-
|| { uid, created_at: new Date() } // should not happen
|
|
184
|
-
const clientUpdatedAt = new Date(clientMetaData.updated_at || clientMetaData.created_at)
|
|
185
|
-
const databaseUpdatedAt = new Date(databaseMetaData.updated_at || databaseMetaData.created_at)
|
|
186
|
-
const dateDifference = clientUpdatedAt - databaseUpdatedAt
|
|
187
|
-
// console.log('databaseMetaData', databaseMetaData, 'clientMetaData', clientMetaData, 'dateDifference', dateDifference)
|
|
188
|
-
if (dateDifference > 0) {
|
|
189
|
-
updateDatabase.push(clientMetaData)
|
|
190
|
-
} else if (dateDifference < 0) {
|
|
191
|
-
updateClient.push(databaseValue)
|
|
192
|
-
}
|
|
193
|
-
}
|
|
121
|
+
|
|
122
|
+
// STEP 2: fetch metadata for each database record
|
|
123
|
+
const databaseMetadataDict = {}
|
|
124
|
+
for (const uid of Object.keys(databaseValuesDict)) {
|
|
125
|
+
const meta = (await db.select().from(metadata).where(eq(metadata.uid, uid)))[0] ?? null
|
|
126
|
+
if (meta) databaseMetadataDict[uid] = meta
|
|
194
127
|
}
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
// STEP4: execute database deletions
|
|
204
|
-
for (const uid of deleteDatabase) {
|
|
205
|
-
const clientMetaData = clientMetadataDict[uid]
|
|
206
|
-
// console.log('---delete', uid, clientMetaData)
|
|
207
|
-
await databaseService.deleteWithMeta(uid, clientMetaData.deleted_at)
|
|
128
|
+
|
|
129
|
+
// STEP 3: compute sync result
|
|
130
|
+
const result = computeSyncResult(databaseValuesDict, clientMetadataDict, databaseMetadataDict)
|
|
131
|
+
|
|
132
|
+
// STEP 4: execute server-side deletions
|
|
133
|
+
for (const uid of result.deleteDatabase) {
|
|
134
|
+
await databaseService.deleteWithMeta(uid, clientMetadataDict[uid].deleted_at)
|
|
208
135
|
}
|
|
209
|
-
|
|
210
|
-
// STEP5: return to client the changes to perform on its cache, and create/update to perform on database with full data
|
|
211
|
-
// Database creations & updates are done later by the client with complete data (this function only has client values's meta-data)
|
|
212
|
-
return {
|
|
213
|
-
toAdd: addClient,
|
|
214
|
-
toUpdate: updateClient,
|
|
215
|
-
toDelete: deleteClient,
|
|
216
136
|
|
|
217
|
-
|
|
218
|
-
|
|
137
|
+
console.log('addDatabase', truncateString(JSON.stringify(result.addDatabase)))
|
|
138
|
+
console.log('updateDatabase', truncateString(JSON.stringify(result.updateDatabase)))
|
|
139
|
+
console.log('addClient', truncateString(JSON.stringify(result.addClient)))
|
|
140
|
+
console.log('deleteClient', truncateString(JSON.stringify(result.deleteClient)))
|
|
141
|
+
console.log('updateClient', truncateString(JSON.stringify(result.updateClient)))
|
|
142
|
+
|
|
143
|
+
return {
|
|
144
|
+
addClient: result.addClient,
|
|
145
|
+
updateClient: result.updateClient,
|
|
146
|
+
deleteClient: result.deleteClient,
|
|
147
|
+
addDatabase: result.addDatabase,
|
|
148
|
+
updateDatabase: result.updateDatabase,
|
|
219
149
|
}
|
|
220
150
|
} catch(err) {
|
|
221
151
|
console.log('*** err sync', err)
|
|
222
152
|
} finally {
|
|
223
|
-
|
|
153
|
+
syncMutexes.get(mutexKey).release()
|
|
224
154
|
}
|
|
225
155
|
},
|
|
226
156
|
})
|