ramdb2-cli 0.0.0-stage → 2.0.0-alpha.0
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 +21 -0
- package/README.md +369 -2
- package/package.json +33 -4
- package/src/cli.js +124 -0
- package/src/convert.js +90 -0
- package/src/directives.js +42 -0
- package/src/generate/classes.js +292 -0
- package/src/generate/client.js +146 -0
- package/src/generate/invalidation.js +102 -0
- package/src/generate/operations.js +98 -0
- package/src/generate/typeDefs.js +39 -0
- package/src/generate.js +51 -0
- package/src/index.js +8 -0
- package/src/model.js +420 -0
- package/src/new.js +619 -0
- package/src/plantuml.js +71 -0
- package/src/query.js +159 -0
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
// Declarations of the directives of the preTypeDefs (D17). They live here, not in the projects:
|
|
2
|
+
// ramdb2-cli adds them before reading a schema, so graphql-js checks every use (name, place, arguments).
|
|
3
|
+
|
|
4
|
+
export const DIRECTIVES = `
|
|
5
|
+
"A type stored in a ramdb2 table. Its fields are persistent unless @transient or @computed."
|
|
6
|
+
directive @persistent on OBJECT
|
|
7
|
+
|
|
8
|
+
"Group of the type in the PlantUML diagram."
|
|
9
|
+
directive @group(name: String!) on OBJECT
|
|
10
|
+
|
|
11
|
+
"On a field: index on it. On a type: index on several fields (MultiMap). unique: no two objects with the same values (MAP only)."
|
|
12
|
+
directive @index(type: RamdbIndexType = MAP, fields: [String!], name: String, unique: Boolean = false) repeatable on OBJECT | FIELD_DEFINITION
|
|
13
|
+
|
|
14
|
+
enum RamdbIndexType { MAP BTREE FULLTEXT }
|
|
15
|
+
|
|
16
|
+
"On a list relation: the foreign key held by the other type."
|
|
17
|
+
directive @field(name: String!) on FIELD_DEFINITION
|
|
18
|
+
|
|
19
|
+
"On a list relation: what happens to its objects when this one is deleted."
|
|
20
|
+
directive @onDelete(action: RamdbOnDelete!) on FIELD_DEFINITION
|
|
21
|
+
|
|
22
|
+
enum RamdbOnDelete { CASCADE SET_ZERO RESTRICT NOTHING }
|
|
23
|
+
|
|
24
|
+
"Computed field, cached, with the paths of its dependencies through the relations."
|
|
25
|
+
directive @computed(depends: [String!]!) on FIELD_DEFINITION
|
|
26
|
+
|
|
27
|
+
"Validation rule: the value must match the regular expression."
|
|
28
|
+
directive @pattern(regex: String!, message: String) on FIELD_DEFINITION
|
|
29
|
+
|
|
30
|
+
"Field of a persistent type that is not stored: resolved elsewhere."
|
|
31
|
+
directive @transient on FIELD_DEFINITION
|
|
32
|
+
|
|
33
|
+
"Field stored and readable in code, but absent from the GraphQL API: neither read, written nor queried (D47)."
|
|
34
|
+
directive @private on FIELD_DEFINITION
|
|
35
|
+
|
|
36
|
+
"Value masked in the logs. Kept in the schema served by Apollo: ramdb2-server reads it."
|
|
37
|
+
directive @sensitive on FIELD_DEFINITION | INPUT_FIELD_DEFINITION | ARGUMENT_DEFINITION
|
|
38
|
+
`
|
|
39
|
+
|
|
40
|
+
/** Names of the directives above removed from the schema served by Apollo: all but @sensitive. */
|
|
41
|
+
export const DIRECTIVE_NAMES = new Set(['persistent', 'group', 'index', 'field', 'onDelete', 'computed', 'pattern', 'transient', 'private'])
|
|
42
|
+
export const INTERNAL_TYPES = new Set(['RamdbIndexType', 'RamdbOnDelete'])
|
|
@@ -0,0 +1,292 @@
|
|
|
1
|
+
import { upperFirst } from '../model.js'
|
|
2
|
+
import { invalidations } from './invalidation.js'
|
|
3
|
+
|
|
4
|
+
// The files of the database layer (spec section 12): a generated class per persistent type, rewritten
|
|
5
|
+
// at each generation, an extended class written once, and the index of the classes.
|
|
6
|
+
|
|
7
|
+
const HEADER = '// Generated by ramdb2-cli from the schema: do not edit, this file is rewritten at each generation.\n'
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* @param {import('../model.js').Model} model
|
|
11
|
+
* @returns {{path: string, content: string, overwrite: boolean}[]}
|
|
12
|
+
*/
|
|
13
|
+
export function classFiles(model) {
|
|
14
|
+
const codes = invalidations(model)
|
|
15
|
+
const files = []
|
|
16
|
+
for (const type of model.types) {
|
|
17
|
+
files.push({ path: `db/generated/${type.table}.js`, content: generatedClass(type, model, codes.get(type.name)), overwrite: true })
|
|
18
|
+
files.push({ path: `db/extended/${type.table}.js`, content: extendedClass(type), overwrite: false })
|
|
19
|
+
}
|
|
20
|
+
files.push({ path: 'db/index.js', content: indexFile(model), overwrite: true })
|
|
21
|
+
return files
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
function generatedClass(type, model, code) {
|
|
25
|
+
const lines = []
|
|
26
|
+
const rules = generatedRules(type)
|
|
27
|
+
const helpers = ['required', 'pattern', 'oneOf'].filter(helper => rules.some(([, list]) => list.some(rule => rule.startsWith(helper + '('))))
|
|
28
|
+
lines.push(HEADER + `import { DbObject, store${helpers.map(h => ', ' + h).join('')} } from 'ramdb2-core'`)
|
|
29
|
+
lines.push('')
|
|
30
|
+
lines.push(jsdoc(type.description, '', [`Table ${type.table}${type.group ? `, group ${type.group}` : ''}.`]))
|
|
31
|
+
lines.push(`export default class ${type.name}Base extends DbObject {`)
|
|
32
|
+
lines.push('')
|
|
33
|
+
lines.push(` static table = '${type.table}'`)
|
|
34
|
+
lines.push('')
|
|
35
|
+
lines.push(` static fields = [${['id', ...type.parents.map(p => p.fk), ...type.fields.map(f => f.name)].map(quote).join(', ')}]`)
|
|
36
|
+
|
|
37
|
+
const privateFields = type.fields.filter(f => f.private).map(f => f.name)
|
|
38
|
+
if (privateFields.length > 0) {
|
|
39
|
+
lines.push('')
|
|
40
|
+
lines.push(' // @private: never read, written nor queried through the GraphQL API')
|
|
41
|
+
lines.push(` static privateFields = [${privateFields.map(quote).join(', ')}]`)
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
const foreignKeys = type.parents.map(parent => [parent, onDeleteOf(parent, type, model)])
|
|
45
|
+
if (foreignKeys.length > 0) {
|
|
46
|
+
lines.push('')
|
|
47
|
+
lines.push(' static foreignKeys = {')
|
|
48
|
+
for (const [parent, onDelete] of foreignKeys) {
|
|
49
|
+
const target = model.byName.get(parent.target).table
|
|
50
|
+
lines.push(` ${parent.fk}: { table: '${target}', required: ${parent.required}, onDelete: '${onDelete}' },`)
|
|
51
|
+
}
|
|
52
|
+
lines.push(' }')
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
if (type.indexes.length > 0) {
|
|
56
|
+
lines.push('')
|
|
57
|
+
lines.push(' static indexes = [')
|
|
58
|
+
for (const index of type.indexes) {
|
|
59
|
+
const kind = index.type === 'map' ? '' : `, type: '${index.type}'`
|
|
60
|
+
const unique = index.unique ? ', unique: true' : ''
|
|
61
|
+
lines.push(` { name: '${index.name}', fields: [${index.fields.map(quote).join(', ')}]${kind}${unique} },`)
|
|
62
|
+
}
|
|
63
|
+
lines.push(' ]')
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
if (rules.length > 0) {
|
|
67
|
+
lines.push('')
|
|
68
|
+
lines.push(' static generatedRules = {')
|
|
69
|
+
for (const [field, list] of rules) lines.push(` ${field}: [${list.join(', ')}],`)
|
|
70
|
+
lines.push(' }')
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
// Constructor: the default values
|
|
74
|
+
const defaults = ['id: 0', ...type.parents.map(p => `${p.fk}: 0`), ...type.fields.map(f => `${f.name}: ${f.defaultValue}`)]
|
|
75
|
+
lines.push('')
|
|
76
|
+
lines.push(' constructor() {')
|
|
77
|
+
lines.push(' super()')
|
|
78
|
+
lines.push(` this._f = { ${defaults.join(', ')} }`)
|
|
79
|
+
lines.push(' }')
|
|
80
|
+
|
|
81
|
+
// Getters and setters of the stored values
|
|
82
|
+
const accessors = [
|
|
83
|
+
...type.parents.map(p => ({ name: p.fk, jsType: 'number', description: `Foreign key of ${p.name} (0: no object).` })),
|
|
84
|
+
...type.fields,
|
|
85
|
+
]
|
|
86
|
+
for (const field of accessors) {
|
|
87
|
+
lines.push('')
|
|
88
|
+
lines.push(jsdoc(field.description, ' ', [`@returns {${field.jsType}}`]))
|
|
89
|
+
lines.push(` get ${field.name}() { return this._f.${field.name} }`)
|
|
90
|
+
lines.push(` /** @param {${field.jsType}} value */`)
|
|
91
|
+
lines.push(` set ${field.name}(value) {`)
|
|
92
|
+
lines.push(` if (this._f.${field.name} === value) return`)
|
|
93
|
+
lines.push(` this._change('${field.name}', value)`)
|
|
94
|
+
lines.push(' }')
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
// Relations
|
|
98
|
+
for (const parent of type.parents) {
|
|
99
|
+
const target = model.byName.get(parent.target)
|
|
100
|
+
lines.push('')
|
|
101
|
+
lines.push(jsdoc(parent.description, ' ', [`@returns {import('../extended/${target.table}.js').default | null}`]))
|
|
102
|
+
lines.push(` get ${parent.name}() { return this._f.${parent.fk} === 0 ? null : store.get('${target.table}', this._f.${parent.fk}) ?? null }`)
|
|
103
|
+
}
|
|
104
|
+
for (const child of type.children) {
|
|
105
|
+
const target = model.byName.get(child.target)
|
|
106
|
+
lines.push('')
|
|
107
|
+
lines.push(jsdoc(child.description, ' ', [`@returns {import('ramdb2-core').BucketView<import('../extended/${target.table}.js').default>}`]))
|
|
108
|
+
lines.push(` get ${child.name}() { return store.index('${target.table}', '${child.fk}').get(this._f.id) }`)
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
// Computed fields
|
|
112
|
+
for (const computed of type.computed) {
|
|
113
|
+
lines.push('')
|
|
114
|
+
lines.push(jsdoc(computed.description, ' ', [`Computed, depends on ${computed.depends.join(', ')}.`, `@returns {${computed.jsType}}`]))
|
|
115
|
+
lines.push(` get ${computed.name}() {`)
|
|
116
|
+
lines.push(` const value = this._c?.${computed.name}`)
|
|
117
|
+
lines.push(` return value !== undefined ? value : this._cache('${computed.name}', this.compute${upperFirst(computed.name)}())`)
|
|
118
|
+
lines.push(' }')
|
|
119
|
+
lines.push('')
|
|
120
|
+
lines.push(` /** @returns {${computed.jsType}} written in the extended class */`)
|
|
121
|
+
lines.push(` compute${upperFirst(computed.name)}() {`)
|
|
122
|
+
lines.push(` throw new Error(\`\${this.constructor.name} must implement compute${upperFirst(computed.name)}()\`)`)
|
|
123
|
+
lines.push(' }')
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
// Finders
|
|
127
|
+
for (const finder of finders(type)) {
|
|
128
|
+
lines.push('')
|
|
129
|
+
lines.push(...finder.map(line => ' ' + line))
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
// Invalidation of the computed fields
|
|
133
|
+
if (code.cases.size > 0) {
|
|
134
|
+
lines.push('')
|
|
135
|
+
lines.push(' _invalidateDependents(field, oldValue) {')
|
|
136
|
+
lines.push(' switch (field) {')
|
|
137
|
+
for (const [field, body] of code.cases) {
|
|
138
|
+
lines.push(` case '${field}':`)
|
|
139
|
+
for (const line of body) lines.push(' ' + line)
|
|
140
|
+
lines.push(' break')
|
|
141
|
+
}
|
|
142
|
+
lines.push(' }')
|
|
143
|
+
lines.push(' }')
|
|
144
|
+
}
|
|
145
|
+
if (code.links.length > 0) {
|
|
146
|
+
lines.push('')
|
|
147
|
+
lines.push(' _invalidateLinks() {')
|
|
148
|
+
for (const line of code.links) lines.push(' ' + line)
|
|
149
|
+
lines.push(' }')
|
|
150
|
+
}
|
|
151
|
+
lines.push('}')
|
|
152
|
+
return lines.join('\n') + '\n'
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
// The policy of a foreign key: the @onDelete of the list relation pointing back, or the v1 default
|
|
156
|
+
// (CASCADE when the key is required, SET_ZERO otherwise). Without a list relation, NOTHING, as in the v1.
|
|
157
|
+
export function onDeleteOf(parent, type, model) {
|
|
158
|
+
const child = model.byName.get(parent.target).children.find(c => c.fk === parent.fk && c.target === type.name)
|
|
159
|
+
if (child === undefined) return 'NOTHING'
|
|
160
|
+
return child.onDelete ?? (parent.required ? 'CASCADE' : 'SET_ZERO')
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
/** @returns {[string, string[]][]} field -> code of its rules */
|
|
164
|
+
export function generatedRules(type) {
|
|
165
|
+
const rules = []
|
|
166
|
+
for (const field of type.fields) {
|
|
167
|
+
const list = []
|
|
168
|
+
if (field.nonNull && (field.gqlType === 'String' || field.gqlType === 'ID' || field.defaultValue === 'null')) {
|
|
169
|
+
list.push(`required('${field.name}')`)
|
|
170
|
+
}
|
|
171
|
+
if (field.pattern !== undefined) {
|
|
172
|
+
const message = field.pattern.message === undefined ? '' : `, ${JSON.stringify(field.pattern.message)}`
|
|
173
|
+
list.push(`pattern('${field.name}', new RegExp(${JSON.stringify(field.pattern.regex)})${message})`)
|
|
174
|
+
}
|
|
175
|
+
if (field.enumValues !== undefined) {
|
|
176
|
+
const allowed = [...field.enumValues.map(quote), ...(field.nonNull ? [] : ['null'])]
|
|
177
|
+
list.push(`oneOf('${field.name}', [${allowed.join(', ')}])`)
|
|
178
|
+
}
|
|
179
|
+
if (list.length > 0) rules.push([field.name, list])
|
|
180
|
+
}
|
|
181
|
+
return rules
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
function finders(type) {
|
|
185
|
+
const result = []
|
|
186
|
+
const typeOf = name => type.fields.find(f => f.name === name)?.jsType ?? 'number'
|
|
187
|
+
const view = `import('ramdb2-core').BucketView<import('../extended/${type.table}.js').default>`
|
|
188
|
+
const lookup = (name, fields, index) => {
|
|
189
|
+
const params = fields.map(field => `@param {${typeOf(field)}} ${field}`)
|
|
190
|
+
if (fields.length === 1) {
|
|
191
|
+
return [
|
|
192
|
+
`/**`, ` * ${params[0]}`, ` * @returns {${view}}`, ` */`,
|
|
193
|
+
`static ${name}(${fields[0]}) {`,
|
|
194
|
+
` return store.index('${type.table}', '${index}').get(${fields[0]})`,
|
|
195
|
+
`}`,
|
|
196
|
+
]
|
|
197
|
+
}
|
|
198
|
+
return [
|
|
199
|
+
`/**`,
|
|
200
|
+
` * The last values can be left out, to search on a prefix of the fields.`,
|
|
201
|
+
...params.map((param, i) => ` * ${i === 0 ? param : param.replace(/ (\w+)$/, ' [$1]')}`),
|
|
202
|
+
` * @returns {${view}}`,
|
|
203
|
+
` */`,
|
|
204
|
+
`static ${name}(${fields.join(', ')}) {`,
|
|
205
|
+
` return store.index('${type.table}', '${index}').get(...[${fields.join(', ')}].slice(0, arguments.length))`,
|
|
206
|
+
`}`,
|
|
207
|
+
]
|
|
208
|
+
}
|
|
209
|
+
const finderName = (index, fields) => index.name === fields.join('_')
|
|
210
|
+
? 'findBy' + fields.map(upperFirst).join('And')
|
|
211
|
+
: 'findBy' + upperFirst(index.name)
|
|
212
|
+
|
|
213
|
+
// The inverse indexes of the foreign keys, automatic in ramdb2
|
|
214
|
+
for (const parent of type.parents) {
|
|
215
|
+
if (!type.indexes.some(index => index.name === parent.fk)) result.push(lookup('findBy' + upperFirst(parent.fk), [parent.fk], parent.fk))
|
|
216
|
+
}
|
|
217
|
+
for (const index of type.indexes) {
|
|
218
|
+
if (index.type === 'fulltext') {
|
|
219
|
+
result.push([
|
|
220
|
+
`/**`,
|
|
221
|
+
` * Full-text search on ${index.fields.join(', ')}, best matches first.`,
|
|
222
|
+
` * @param {string} text`,
|
|
223
|
+
` * @param {{fields?: string[]}} [options]`,
|
|
224
|
+
` * @returns {{obj: import('../extended/${type.table}.js').default, score: number}[]}`,
|
|
225
|
+
` */`,
|
|
226
|
+
`static search(text, options) {`,
|
|
227
|
+
` return store.index('${type.table}', '${index.name}').search(text, options)`,
|
|
228
|
+
`}`,
|
|
229
|
+
])
|
|
230
|
+
continue
|
|
231
|
+
}
|
|
232
|
+
const name = finderName(index, index.fields)
|
|
233
|
+
result.push(lookup(name, index.fields, index.name))
|
|
234
|
+
if (index.type === 'btree') {
|
|
235
|
+
const field = index.fields[0]
|
|
236
|
+
result.push([
|
|
237
|
+
`/**`,
|
|
238
|
+
` * The objects in the order of ${field}, between optional bounds.`,
|
|
239
|
+
` * @param {{gt?: ${typeOf(field)}, gte?: ${typeOf(field)}, lt?: ${typeOf(field)}, lte?: ${typeOf(field)}}} [bounds]`,
|
|
240
|
+
` * @param {{reverse?: boolean}} [options]`,
|
|
241
|
+
` * @returns {Generator<import('../extended/${type.table}.js').default>}`,
|
|
242
|
+
` */`,
|
|
243
|
+
`static rangeOf${upperFirst(index.name === field ? field : index.name)}(bounds, options) {`,
|
|
244
|
+
` return store.index('${type.table}', '${index.name}').range(bounds, options)`,
|
|
245
|
+
`}`,
|
|
246
|
+
])
|
|
247
|
+
}
|
|
248
|
+
}
|
|
249
|
+
return result
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
function extendedClass(type) {
|
|
253
|
+
const lines = [`import ${type.name}Base from '../generated/${type.table}.js'`, '']
|
|
254
|
+
lines.push(`/** Written by hand: business rules, computed fields and methods. Created once by ramdb2-cli, never rewritten. */`)
|
|
255
|
+
lines.push(`export default class ${type.name} extends ${type.name}Base {`)
|
|
256
|
+
lines.push('')
|
|
257
|
+
lines.push(' // Validation rules per field, run at commit after the generated ones: (values, obj) => "" | message')
|
|
258
|
+
lines.push(' static rules = {}')
|
|
259
|
+
lines.push('')
|
|
260
|
+
lines.push(' // Integrity rules checked by delete(): (values, obj) => "" | message')
|
|
261
|
+
lines.push(' static deleteRules = []')
|
|
262
|
+
for (const computed of type.computed) {
|
|
263
|
+
lines.push('')
|
|
264
|
+
lines.push(` /** @returns {${computed.jsType}} depends on ${computed.depends.join(', ')} */`)
|
|
265
|
+
lines.push(` compute${upperFirst(computed.name)}() {`)
|
|
266
|
+
lines.push(` throw new Error('${type.name}.compute${upperFirst(computed.name)}() is not written yet')`)
|
|
267
|
+
lines.push(' }')
|
|
268
|
+
}
|
|
269
|
+
lines.push('}')
|
|
270
|
+
return lines.join('\n') + '\n'
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
function indexFile(model) {
|
|
274
|
+
const lines = [HEADER]
|
|
275
|
+
for (const type of model.types) lines.push(`import ${type.name} from './extended/${type.table}.js'`)
|
|
276
|
+
lines.push('')
|
|
277
|
+
lines.push(`export { ${model.types.map(type => type.name).join(', ')} }`)
|
|
278
|
+
lines.push('')
|
|
279
|
+
lines.push('/** Every persistent class, for store.register(...classes). */')
|
|
280
|
+
lines.push(`export const classes = [${model.types.map(type => type.name).join(', ')}]`)
|
|
281
|
+
return lines.join('\n') + '\n'
|
|
282
|
+
}
|
|
283
|
+
|
|
284
|
+
export function jsdoc(description, indent, extra = []) {
|
|
285
|
+
const text = [...(description === undefined ? [] : description.trim().split('\n')), ...extra]
|
|
286
|
+
if (text.length === 1) return `${indent}/** ${text[0]} */`
|
|
287
|
+
return [`${indent}/**`, ...text.map(line => `${indent} * ${line.trim()}`.trimEnd()), `${indent} */`].join('\n')
|
|
288
|
+
}
|
|
289
|
+
|
|
290
|
+
export function quote(string) {
|
|
291
|
+
return `'${string}'`
|
|
292
|
+
}
|
|
@@ -0,0 +1,146 @@
|
|
|
1
|
+
import { generatedRules, jsdoc, quote } from './classes.js'
|
|
2
|
+
import { operationNames } from './operations.js'
|
|
3
|
+
|
|
4
|
+
// The classes of a ramdb2-client application (spec section 12, D49): a generated class per persistent type,
|
|
5
|
+
// rewritten at each generation, an extended class written once, and the index of the classes.
|
|
6
|
+
// Instances are read-only (getters only) and never use # private fields, which break the reactive proxy of Vue.
|
|
7
|
+
|
|
8
|
+
const HEADER = '// Generated by ramdb2-cli from the schema: do not edit, this file is rewritten at each generation.\n'
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* @param {import('../model.js').Model} model
|
|
12
|
+
* @returns {{files: {path: string, content: string, overwrite: boolean}[], warnings: string[]}}
|
|
13
|
+
*/
|
|
14
|
+
export function clientFiles(model) {
|
|
15
|
+
const files = []
|
|
16
|
+
const warnings = []
|
|
17
|
+
for (const type of model.types) {
|
|
18
|
+
for (const field of type.transient) {
|
|
19
|
+
if (!field.scalar) warnings.push(`${type.name}.${field.name}: @transient of an object type, not loaded by the client`)
|
|
20
|
+
else if (field.requiredArgs.length > 0) {
|
|
21
|
+
warnings.push(`${type.name}.${field.name}: @transient with required arguments (${field.requiredArgs.join(', ')}), not loaded by the client`)
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
files.push({ path: `generated/${type.table}.js`, content: generatedClass(type, model), overwrite: true })
|
|
25
|
+
files.push({ path: `extended/${type.table}.js`, content: extendedClass(type), overwrite: false })
|
|
26
|
+
}
|
|
27
|
+
files.push({ path: 'index.js', content: indexFile(model), overwrite: true })
|
|
28
|
+
return { files, warnings }
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
// The @transient fields the client loads with the object: a scalar type, no required argument (D49)
|
|
32
|
+
const loadedTransient = type => type.transient.filter(field => field.scalar && field.requiredArgs.length === 0)
|
|
33
|
+
|
|
34
|
+
function generatedClass(type, model) {
|
|
35
|
+
const fields = type.fields.filter(f => !f.private)
|
|
36
|
+
const privateFields = type.fields.filter(f => f.private).map(f => f.name)
|
|
37
|
+
const rules = [
|
|
38
|
+
...type.parents.filter(p => p.required).map(p => [p.fk, [`requiredKey('${p.fk}')`]]),
|
|
39
|
+
...generatedRules({ ...type, fields }),
|
|
40
|
+
]
|
|
41
|
+
const helpers = ['required', 'requiredKey', 'pattern', 'oneOf'].filter(helper => rules.some(([, list]) => list.some(rule => rule.startsWith(helper + '('))))
|
|
42
|
+
const names = operationNames(type.name)
|
|
43
|
+
const transient = loadedTransient(type)
|
|
44
|
+
// The fields of the FULLTEXT index, for a search with $text (a @private field is refused there by readSchema)
|
|
45
|
+
const fullText = type.indexes.filter(index => index.type === 'fulltext').flatMap(index => index.fields)
|
|
46
|
+
.filter(name => !privateFields.includes(name))
|
|
47
|
+
|
|
48
|
+
const lines = []
|
|
49
|
+
lines.push(HEADER + `import { ClientObject${helpers.map(h => ', ' + h).join('')} } from 'ramdb2-client'`)
|
|
50
|
+
lines.push('')
|
|
51
|
+
// Always on several lines, even without a description: the place to add one is visible
|
|
52
|
+
const doc = [...(type.description?.trim().split('\n') ?? []), `Type ${type.name}.`]
|
|
53
|
+
lines.push(['/**', ...doc.map(line => ` * ${line.trim()}`.trimEnd()), ' */'].join('\n'))
|
|
54
|
+
lines.push(`export default class ${type.name}Base extends ClientObject {`)
|
|
55
|
+
lines.push('')
|
|
56
|
+
lines.push(` static typeName = '${type.name}'`)
|
|
57
|
+
lines.push('')
|
|
58
|
+
lines.push(' static operations = {')
|
|
59
|
+
lines.push(` list: '${names.list}', byId: '${names.byId}', dataCheck: '${names.dataCheck}', default: '${names.default}',`)
|
|
60
|
+
lines.push(` create: '${names.create}', update: '${names.update}', delete: '${names.delete}', argument: '${names.argument}',`)
|
|
61
|
+
lines.push(' }')
|
|
62
|
+
lines.push('')
|
|
63
|
+
if (privateFields.length > 0) {
|
|
64
|
+
const verb = privateFields.length === 1 ? 'is' : 'are'
|
|
65
|
+
lines.push(` // ${privateFields.join(', ')} ${verb} @private (D47 of ramdb2): absent from the API, so absent here`)
|
|
66
|
+
}
|
|
67
|
+
lines.push(` static fields = [${['id', ...type.parents.map(p => p.fk), ...fields.map(f => f.name)].map(quote).join(', ')}]`)
|
|
68
|
+
lines.push('')
|
|
69
|
+
lines.push(` static computed = [${type.computed.map(c => quote(c.name)).join(', ')}]`)
|
|
70
|
+
lines.push('')
|
|
71
|
+
lines.push(` static transient = [${transient.map(t => quote(t.name)).join(', ')}]`)
|
|
72
|
+
lines.push('')
|
|
73
|
+
lines.push(` static fullText = [${fullText.map(quote).join(', ')}]`)
|
|
74
|
+
lines.push('')
|
|
75
|
+
const relations = [
|
|
76
|
+
...type.parents.map(p => ` ${p.name}: { type: '${p.target}', key: '${p.fk}' },`),
|
|
77
|
+
...type.children.map(c => ` ${c.name}: { type: '${c.target}', key: '${c.fk}', list: true },`),
|
|
78
|
+
]
|
|
79
|
+
if (relations.length === 0) lines.push(' static relations = {}')
|
|
80
|
+
else lines.push(' static relations = {', ...relations, ' }')
|
|
81
|
+
lines.push('')
|
|
82
|
+
const defaults = ['id: 0', ...type.parents.map(p => `${p.fk}: 0`), ...fields.map(f => `${f.name}: ${f.defaultValue}`)]
|
|
83
|
+
lines.push(` static defaults = { ${defaults.join(', ')} }`)
|
|
84
|
+
lines.push('')
|
|
85
|
+
if (rules.length === 0) lines.push(' static generatedRules = {}')
|
|
86
|
+
else {
|
|
87
|
+
lines.push(' static generatedRules = {')
|
|
88
|
+
for (const [field, list] of rules) lines.push(` ${field}: [${list.join(', ')}],`)
|
|
89
|
+
lines.push(' }')
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
for (const parent of type.parents) {
|
|
93
|
+
lines.push('')
|
|
94
|
+
lines.push(` /** @returns {number} foreign key of ${parent.name}, 0 = none */`)
|
|
95
|
+
lines.push(` get ${parent.fk}() { return this._f.${parent.fk} }`)
|
|
96
|
+
}
|
|
97
|
+
for (const field of fields) {
|
|
98
|
+
lines.push('')
|
|
99
|
+
lines.push(jsdoc(field.description, ' ', [`@returns {${field.jsType}}`]))
|
|
100
|
+
lines.push(` get ${field.name}() { return this._f.${field.name} }`)
|
|
101
|
+
}
|
|
102
|
+
for (const relation of [...type.parents, ...type.children]) {
|
|
103
|
+
const target = model.byName.get(relation.target)
|
|
104
|
+
const list = type.children.includes(relation) ? '[]' : ''
|
|
105
|
+
lines.push('')
|
|
106
|
+
lines.push(jsdoc(relation.description, ' ', [
|
|
107
|
+
`Loaded with include: ['${relation.name}'].`,
|
|
108
|
+
`@returns {import('../extended/${target.table}.js').default${list}}`,
|
|
109
|
+
]))
|
|
110
|
+
lines.push(` get ${relation.name}() { return this._relation('${relation.name}') }`)
|
|
111
|
+
}
|
|
112
|
+
for (const computed of type.computed) {
|
|
113
|
+
lines.push('')
|
|
114
|
+
lines.push(jsdoc(computed.description, ' ', ['Computed by the server.', `@returns {${computed.jsType}}`]))
|
|
115
|
+
lines.push(` get ${computed.name}() { return this._c.${computed.name} }`)
|
|
116
|
+
}
|
|
117
|
+
for (const field of transient) {
|
|
118
|
+
lines.push('')
|
|
119
|
+
lines.push(jsdoc(field.description, ' ', ['Resolved by the project on the server.', `@returns {${field.jsType}}`]))
|
|
120
|
+
lines.push(` get ${field.name}() { return this._c.${field.name} }`)
|
|
121
|
+
}
|
|
122
|
+
lines.push('}')
|
|
123
|
+
return lines.join('\n') + '\n'
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
function extendedClass(type) {
|
|
127
|
+
return [
|
|
128
|
+
`// Created by ramdb2-cli, never rewritten: the code of the project for ${type.name} goes here.`,
|
|
129
|
+
`import ${type.name}Base from '../generated/${type.table}.js'`,
|
|
130
|
+
'',
|
|
131
|
+
`export default class ${type.name} extends ${type.name}Base {`,
|
|
132
|
+
'}',
|
|
133
|
+
].join('\n') + '\n'
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
function indexFile(model) {
|
|
137
|
+
const names = model.types.map(type => type.name)
|
|
138
|
+
return [
|
|
139
|
+
HEADER + model.types.map(type => `import ${type.name} from './extended/${type.table}.js'`).join('\n'),
|
|
140
|
+
'',
|
|
141
|
+
`export { ${names.join(', ')} }`,
|
|
142
|
+
'',
|
|
143
|
+
'/** For configure({ classes }) of ramdb2-client. */',
|
|
144
|
+
`export const classes = [${names.join(', ')}]`,
|
|
145
|
+
].join('\n') + '\n'
|
|
146
|
+
}
|
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
import { resolvePath } from '../model.js'
|
|
2
|
+
|
|
3
|
+
// Inverts the dependency paths of the computed fields (D12, D36) into the code of the generated methods
|
|
4
|
+
// _invalidateDependents(field, oldValue) and _invalidateLinks(), for every type a path goes through.
|
|
5
|
+
//
|
|
6
|
+
// A path from type T0 goes through relations r0..rk-1 to Tk, then ends on a field f of Tk:
|
|
7
|
+
// - f changes on a Tk object: invalidate the T0 objects that reach it;
|
|
8
|
+
// - the foreign key of a relation ri changes: the T0 objects reaching the object that changed;
|
|
9
|
+
// for a list relation, those reaching the old parent and those reaching the new one;
|
|
10
|
+
// - an object of T1..Tk is inserted or deleted: the T0 objects that reach it.
|
|
11
|
+
// Going back over a relation: an object relation (the object holds idX) is inverted by the inverse
|
|
12
|
+
// index of idX (several objects); a list relation (the other object holds the key) by store.get (one object).
|
|
13
|
+
|
|
14
|
+
/**
|
|
15
|
+
* @param {import('../model.js').Model} model
|
|
16
|
+
* @returns {Map<string, {cases: Map<string, string[]>, links: string[]}>} code per type name
|
|
17
|
+
*/
|
|
18
|
+
export function invalidations(model) {
|
|
19
|
+
const result = new Map(model.types.map(type => [type.name, { cases: new Map(), links: [] }]))
|
|
20
|
+
// Deduplicated by whole block: two blocks may share lines ('{', '}'...) without being the same
|
|
21
|
+
const blocks = new Map()
|
|
22
|
+
const add = (key, block) => {
|
|
23
|
+
if (!blocks.has(key)) blocks.set(key, new Set())
|
|
24
|
+
blocks.get(key).add(block.join('\n'))
|
|
25
|
+
}
|
|
26
|
+
const addCase = (type, field, ...list) => {
|
|
27
|
+
for (const block of list) add(`${type.name}\0case\0${field}`, block)
|
|
28
|
+
}
|
|
29
|
+
const addLinks = (type, block) => add(`${type.name}\0links`, block)
|
|
30
|
+
|
|
31
|
+
for (const type of model.types) {
|
|
32
|
+
for (const computed of type.computed) {
|
|
33
|
+
for (const path of computed.depends) {
|
|
34
|
+
const { steps, end, last } = resolvePath(type, path.split('.'), model.byName)
|
|
35
|
+
const k = steps.length
|
|
36
|
+
const back = i => steps.slice(0, i).reverse() // the relations to go back from position i to 0
|
|
37
|
+
const target = computed.name
|
|
38
|
+
|
|
39
|
+
// The field at the end of the path
|
|
40
|
+
if (last !== undefined) addCase(end, last, code('this', back(k), target))
|
|
41
|
+
|
|
42
|
+
for (let i = 0; i < k; i++) {
|
|
43
|
+
const { relation, kind, from, to } = steps[i]
|
|
44
|
+
if (kind === 'parent') {
|
|
45
|
+
// The object at position i points to another object
|
|
46
|
+
addCase(from, relation.fk, code('this', back(i), target))
|
|
47
|
+
} else {
|
|
48
|
+
// The object at position i + 1 moves from a parent to another
|
|
49
|
+
const parentTable = from.table
|
|
50
|
+
addCase(to, relation.fk,
|
|
51
|
+
code(`store.get('${parentTable}', oldValue)`, back(i), target),
|
|
52
|
+
code(`store.get('${parentTable}', this._f.${relation.fk})`, back(i), target))
|
|
53
|
+
}
|
|
54
|
+
// The object at position i + 1 appears or disappears
|
|
55
|
+
addLinks(to, code('this', back(i + 1), target))
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
for (const [key, set] of blocks) {
|
|
61
|
+
const [typeName, kind, field] = key.split('\0')
|
|
62
|
+
const lines = [...set].flatMap(block => block.split('\n'))
|
|
63
|
+
if (kind === 'links') result.get(typeName).links = lines
|
|
64
|
+
else result.get(typeName).cases.set(field, lines)
|
|
65
|
+
}
|
|
66
|
+
return result
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/**
|
|
70
|
+
* Lines that invalidate `target` on every object reached from `start` by going back over `steps`.
|
|
71
|
+
* `start` may evaluate to undefined, except 'this'.
|
|
72
|
+
*/
|
|
73
|
+
function code(start, steps, target, depth = 1) {
|
|
74
|
+
// `this` and the loop variables are never undefined
|
|
75
|
+
if (steps.length === 0) return [`${start}${start === 'this' || /^o\d+$/.test(start) ? '' : '?'}.invalidate('${target}')`]
|
|
76
|
+
const [step, ...rest] = steps
|
|
77
|
+
const from = step.from
|
|
78
|
+
const fk = step.relation.fk
|
|
79
|
+
if (step.kind === 'child') {
|
|
80
|
+
// `start` holds the foreign key towards its parent
|
|
81
|
+
const access = start === 'this' ? `this._f.${fk}` : `${start}?._f.${fk}`
|
|
82
|
+
return code(`store.get('${from.table}', ${access})`, rest, target, depth)
|
|
83
|
+
}
|
|
84
|
+
// Every object of `from` whose foreign key designates `start`
|
|
85
|
+
const variable = `o${depth}`
|
|
86
|
+
const loop = source => [
|
|
87
|
+
`for (const ${variable} of store.index('${from.table}', '${fk}').get(${source}._f.id)) {`,
|
|
88
|
+
...code(variable, rest, target, depth + 1).map(line => ' ' + line),
|
|
89
|
+
'}',
|
|
90
|
+
]
|
|
91
|
+
if (start === 'this' || /^o\d+$/.test(start)) return loop(start)
|
|
92
|
+
// In a block: the same case may hold several of them
|
|
93
|
+
const holder = `p${depth}`
|
|
94
|
+
return [
|
|
95
|
+
'{',
|
|
96
|
+
` const ${holder} = ${start}`,
|
|
97
|
+
` if (${holder} !== undefined) {`,
|
|
98
|
+
...loop(holder).map(line => ' ' + line),
|
|
99
|
+
' }',
|
|
100
|
+
'}',
|
|
101
|
+
]
|
|
102
|
+
}
|