ramdb2-cli 0.0.0-stage → 2.0.0-alpha.1
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/CHANGELOG.md +7 -0
- package/LICENSE +21 -0
- package/README.md +428 -2
- package/package.json +34 -4
- package/src/cli.js +139 -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 +10 -0
- package/src/infra/build.js +372 -0
- package/src/infra/config.js +165 -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
package/src/convert.js
ADDED
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
import { Kind, parse } from 'graphql'
|
|
2
|
+
|
|
3
|
+
// Converts a v1 preTypeDefs (annotations in the descriptions) into a v2 one (directives), D17.
|
|
4
|
+
// The text is edited in place: comments, order and formatting are kept.
|
|
5
|
+
// type: [PERSISTENT] -> @persistent, [GROUP=X] -> @group(name: "X")
|
|
6
|
+
// field of a persistent type: [PERSISTENT] -> nothing (persistent by default), [FIELD=x] -> @field(name: "x"),
|
|
7
|
+
// no [PERSISTENT] -> @transient
|
|
8
|
+
// The deletion policies of extIndexConfig are JavaScript: they are not converted (see the warnings).
|
|
9
|
+
|
|
10
|
+
const PERSISTENT = /^\s*\[PERSISTENT\]\s*$/
|
|
11
|
+
const GROUP = /^\s*\[GROUP=([A-Za-z0-9_]+)\]\s*$/
|
|
12
|
+
const FIELD = /^\s*\[FIELD=([A-Za-z0-9_]+)\]\s*$/
|
|
13
|
+
|
|
14
|
+
/**
|
|
15
|
+
* @param {string} source v1 preTypeDefs
|
|
16
|
+
* @returns {{source: string, types: number, warnings: string[]}}
|
|
17
|
+
*/
|
|
18
|
+
export function convert(source) {
|
|
19
|
+
const document = parse(source)
|
|
20
|
+
const edits = []
|
|
21
|
+
const warnings = []
|
|
22
|
+
let types = 0
|
|
23
|
+
|
|
24
|
+
for (const definition of document.definitions) {
|
|
25
|
+
if (definition.kind !== Kind.OBJECT_TYPE_DEFINITION) continue
|
|
26
|
+
const typeAnnotations = annotations(definition.description)
|
|
27
|
+
if (!typeAnnotations.persistent) continue
|
|
28
|
+
types++
|
|
29
|
+
const directives = [' @persistent']
|
|
30
|
+
if (typeAnnotations.group !== undefined) directives.push(` @group(name: "${typeAnnotations.group}")`)
|
|
31
|
+
edits.push({ start: definition.name.loc.end, end: definition.name.loc.end, text: directives.join('') })
|
|
32
|
+
// The location of a definition starts at its description: the keyword comes after it
|
|
33
|
+
const keyword = source.indexOf('type', definition.description.loc.end)
|
|
34
|
+
cleanDescription(source, definition.description, keyword, typeAnnotations.rest, edits)
|
|
35
|
+
|
|
36
|
+
for (const field of definition.fields ?? []) {
|
|
37
|
+
const fieldAnnotations = annotations(field.description)
|
|
38
|
+
const added = []
|
|
39
|
+
if (!fieldAnnotations.persistent) added.push(' @transient')
|
|
40
|
+
if (fieldAnnotations.field !== undefined) added.push(` @field(name: "${fieldAnnotations.field}")`)
|
|
41
|
+
if (fieldAnnotations.persistent && fieldAnnotations.field !== undefined) {
|
|
42
|
+
warnings.push(`${definition.name.value}.${field.name.value}: check its deletion policy in extIndexConfig, ` +
|
|
43
|
+
'and write it with @onDelete(action:) if it is not the default (CASCADE for a required key, SET_ZERO otherwise)')
|
|
44
|
+
}
|
|
45
|
+
if (added.length > 0) edits.push({ start: field.type.loc.end, end: field.type.loc.end, text: added.join('') })
|
|
46
|
+
if (field.description !== undefined) {
|
|
47
|
+
cleanDescription(source, field.description, field.name.loc.start, fieldAnnotations.rest, edits)
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
let result = source
|
|
53
|
+
for (const edit of edits.sort((a, b) => b.start - a.start)) {
|
|
54
|
+
result = result.slice(0, edit.start) + edit.text + result.slice(edit.end)
|
|
55
|
+
}
|
|
56
|
+
return { source: result, types, warnings }
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
function annotations(description) {
|
|
60
|
+
const found = { persistent: false, group: undefined, field: undefined, rest: [] }
|
|
61
|
+
if (description === undefined) return found
|
|
62
|
+
for (const line of description.value.split('\n')) {
|
|
63
|
+
let match
|
|
64
|
+
if (PERSISTENT.test(line)) found.persistent = true
|
|
65
|
+
else if ((match = GROUP.exec(line)) !== null) found.group = match[1]
|
|
66
|
+
else if ((match = FIELD.exec(line)) !== null) found.field = match[1]
|
|
67
|
+
else found.rest.push(line)
|
|
68
|
+
}
|
|
69
|
+
while (found.rest.length > 0 && found.rest[0].trim() === '') found.rest.shift()
|
|
70
|
+
while (found.rest.length > 0 && found.rest.at(-1).trim() === '') found.rest.pop()
|
|
71
|
+
return found
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
// Rewrites a description without its annotations, or removes it when nothing else is left
|
|
75
|
+
function cleanDescription(source, description, nextStart, rest, edits) {
|
|
76
|
+
if (description === undefined) return
|
|
77
|
+
const { start, end } = description.loc
|
|
78
|
+
if (rest.length === 0) {
|
|
79
|
+
// Up to the next token: the indentation of the line before the description stays in place
|
|
80
|
+
const lineStart = source.lastIndexOf('\n', start) + 1
|
|
81
|
+
const indent = source.slice(lineStart, start)
|
|
82
|
+
edits.push({ start: lineStart, end: nextStart, text: indent })
|
|
83
|
+
return
|
|
84
|
+
}
|
|
85
|
+
const indent = source.slice(source.lastIndexOf('\n', start) + 1, start)
|
|
86
|
+
const text = rest.length === 1 && !rest[0].includes('"')
|
|
87
|
+
? `"${rest[0].trim()}"`
|
|
88
|
+
: ['"""', ...rest.map(line => indent + line.trim()), indent + '"""'].join('\n')
|
|
89
|
+
edits.push({ start, end, text })
|
|
90
|
+
}
|
|
@@ -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
|
+
}
|