@jcbuisson/express-x-drizzle 1.0.5 → 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 +88 -124
|
@@ -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,24 +1,33 @@
|
|
|
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
27
|
|
|
28
|
+
// DOIT FAIRE UN ROLLBACK EN CAS D'ERREUR SERVEUR (EX: ERREUR SÉMANTIQUE TYPE PB CLÉ ÉTRANGÈRE OU AUTRE)
|
|
29
|
+
|
|
30
|
+
|
|
22
31
|
////////////////////////// DRIZZLE OFFLINE PLUGIN //////////////////////////
|
|
23
32
|
|
|
24
33
|
export function drizzleOfflinePlugin(app, db, metadata, models) {
|
|
@@ -39,154 +48,109 @@ export function drizzleOfflinePlugin(app, db, metadata, models) {
|
|
|
39
48
|
},
|
|
40
49
|
|
|
41
50
|
createWithMeta: async (uid, data, created_at) => {
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
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();
|
|
45
69
|
return [value, meta]
|
|
46
70
|
})
|
|
47
71
|
},
|
|
48
|
-
|
|
72
|
+
|
|
49
73
|
updateWithMeta: async (uid, data, updated_at) => {
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
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();
|
|
53
83
|
return [value, meta]
|
|
54
84
|
})
|
|
55
85
|
},
|
|
56
|
-
|
|
86
|
+
|
|
57
87
|
deleteWithMeta: async (uid, deleted_at) => {
|
|
58
|
-
db.transaction(async (tx) => {
|
|
59
|
-
const value = await tx.delete(model).where(eq(model.uid, uid)).returning();
|
|
60
|
-
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();
|
|
61
91
|
return [value, meta]
|
|
62
92
|
})
|
|
63
93
|
},
|
|
64
94
|
})
|
|
65
95
|
}
|
|
66
96
|
|
|
67
|
-
const
|
|
97
|
+
const syncMutexes = new Map()
|
|
68
98
|
|
|
69
99
|
// add a synchronization service
|
|
70
100
|
app.createService('sync', {
|
|
71
101
|
|
|
72
|
-
//
|
|
102
|
+
// CUTOFFDATE INUTILE ?
|
|
73
103
|
go: async (modelName, where, cutoffDate, clientMetadataDict) => {
|
|
74
|
-
|
|
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
|
+
|
|
75
111
|
try {
|
|
76
112
|
console.log('>>>>> SYNC', modelName, where, cutoffDate)
|
|
77
113
|
const databaseService = app.service(modelName)
|
|
78
114
|
|
|
79
|
-
//
|
|
115
|
+
// STEP1: get existing database `where` values and build a dictionary
|
|
80
116
|
const databaseValues = await databaseService.findMany(where)
|
|
81
|
-
|
|
82
117
|
const databaseValuesDict = databaseValues.reduce((accu, value) => {
|
|
83
118
|
accu[value.uid] = value
|
|
84
119
|
return accu
|
|
85
120
|
}, {})
|
|
86
|
-
|
|
87
|
-
//
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
const databaseAndClientIds = new Set()
|
|
93
|
-
|
|
94
|
-
for (const uid in databaseValuesDict) {
|
|
95
|
-
if (uid in clientMetadataDict) {
|
|
96
|
-
databaseAndClientIds.add(uid)
|
|
97
|
-
} else {
|
|
98
|
-
onlyDatabaseIds.add(uid)
|
|
99
|
-
}
|
|
100
|
-
}
|
|
101
|
-
|
|
102
|
-
for (const uid in clientMetadataDict) {
|
|
103
|
-
if (uid in databaseValuesDict) {
|
|
104
|
-
databaseAndClientIds.add(uid)
|
|
105
|
-
} else {
|
|
106
|
-
onlyClientIds.add(uid)
|
|
107
|
-
}
|
|
108
|
-
}
|
|
109
|
-
// console.log('onlyDatabaseIds', onlyDatabaseIds)
|
|
110
|
-
// console.log('onlyClientIds', onlyClientIds)
|
|
111
|
-
// console.log('databaseAndClientIds', databaseAndClientIds)
|
|
112
|
-
|
|
113
|
-
// STEP 3: build add/update/delete sets
|
|
114
|
-
const addDatabase = []
|
|
115
|
-
const updateDatabase = []
|
|
116
|
-
const deleteDatabase = []
|
|
117
|
-
|
|
118
|
-
const addClient = []
|
|
119
|
-
const updateClient = []
|
|
120
|
-
const deleteClient = []
|
|
121
|
-
|
|
122
|
-
for (const uid of onlyDatabaseIds) {
|
|
123
|
-
const databaseValue = databaseValuesDict[uid]
|
|
124
|
-
const databaseMetaData = (await db.select().from(metadata).where(eq(metadata.uid, uid)))[0]
|
|
125
|
-
|| { uid, created_at: new Date() } // should not happen
|
|
126
|
-
addClient.push([databaseValue, databaseMetaData])
|
|
127
|
-
}
|
|
128
|
-
|
|
129
|
-
for (const uid of onlyClientIds) {
|
|
130
|
-
const clientMetaData = clientMetadataDict[uid]
|
|
131
|
-
if (clientMetaData.deleted_at) {
|
|
132
|
-
deleteClient.push([uid, clientMetaData.deleted_at])
|
|
133
|
-
} else if (new Date(clientMetaData.created_at) > cutoffDate) {
|
|
134
|
-
addDatabase.push(clientMetaData)
|
|
135
|
-
} else {
|
|
136
|
-
// ???
|
|
137
|
-
}
|
|
138
|
-
}
|
|
139
|
-
|
|
140
|
-
for (const uid of databaseAndClientIds) {
|
|
141
|
-
const databaseValue = databaseValuesDict[uid]
|
|
142
|
-
const clientMetaData = clientMetadataDict[uid]
|
|
143
|
-
|| { uid, created_at: new Date() } // should not happen
|
|
144
|
-
if (clientMetaData.deleted_at) {
|
|
145
|
-
deleteDatabase.push(uid)
|
|
146
|
-
deleteClient.push([uid, clientMetaData.deleted_at])
|
|
147
|
-
} else {
|
|
148
|
-
const databaseMetaData = (await db.select().from(metadata).where(eq(metadata.uid, uid)))[0]
|
|
149
|
-
|| { uid, created_at: new Date() } // should not happen
|
|
150
|
-
const clientUpdatedAt = new Date(clientMetaData.updated_at || clientMetaData.created_at)
|
|
151
|
-
const databaseUpdatedAt = new Date(databaseMetaData.updated_at || databaseMetaData.created_at)
|
|
152
|
-
const dateDifference = clientUpdatedAt - databaseUpdatedAt
|
|
153
|
-
// console.log('databaseMetaData', databaseMetaData, 'clientMetaData', clientMetaData, 'dateDifference', dateDifference)
|
|
154
|
-
if (dateDifference > 0) {
|
|
155
|
-
updateDatabase.push(clientMetaData)
|
|
156
|
-
} else if (dateDifference < 0) {
|
|
157
|
-
updateClient.push(databaseValue)
|
|
158
|
-
}
|
|
159
|
-
}
|
|
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
|
|
160
127
|
}
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
// STEP4: execute database deletions
|
|
170
|
-
for (const uid of deleteDatabase) {
|
|
171
|
-
const clientMetaData = clientMetadataDict[uid]
|
|
172
|
-
// console.log('---delete', uid, clientMetaData)
|
|
173
|
-
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)
|
|
174
135
|
}
|
|
175
|
-
|
|
176
|
-
// STEP5: return to client the changes to perform on its cache, and create/update to perform on database with full data
|
|
177
|
-
// Database creations & updates are done later by the client with complete data (this function only has client values's meta-data)
|
|
178
|
-
return {
|
|
179
|
-
toAdd: addClient,
|
|
180
|
-
toUpdate: updateClient,
|
|
181
|
-
toDelete: deleteClient,
|
|
182
136
|
|
|
183
|
-
|
|
184
|
-
|
|
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,
|
|
185
149
|
}
|
|
186
150
|
} catch(err) {
|
|
187
151
|
console.log('*** err sync', err)
|
|
188
152
|
} finally {
|
|
189
|
-
|
|
153
|
+
syncMutexes.get(mutexKey).release()
|
|
190
154
|
}
|
|
191
155
|
},
|
|
192
156
|
})
|