@workbasehq/core 0.2.4 → 0.2.5
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/package.json +1 -1
- package/src/config.ts +1 -1
- package/src/console-model.ts +7 -1
- package/src/query/compiler.ts +25 -5
- package/src/query/display-parts.ts +53 -0
- package/src/query/executor.ts +15 -2
- package/src/query/expressions.ts +12 -7
package/package.json
CHANGED
package/src/config.ts
CHANGED
|
@@ -18,7 +18,7 @@ export { Q, Cond }
|
|
|
18
18
|
/** SQLite date formatting with column operands; values use the library wire encoding. */
|
|
19
19
|
export const Fn = { ...LibraryFn, strftime: (format: string, date: string) => Q.expr(`FN(${JSON.stringify(['STRFTIME', Q.value(format).serialize(), Q.expr(date).serialize()])})`) }
|
|
20
20
|
|
|
21
|
-
export const CORE_VERSION = '0.2.
|
|
21
|
+
export const CORE_VERSION = '0.2.5'
|
|
22
22
|
const navigationIconSchema = z.enum(['LayoutDashboard', 'Users', 'MapPin', 'Coins', 'Wallet', 'ArrowLeftRight', 'Settings', 'Building2', 'Activity', 'Workflow', 'Database', 'Folder'])
|
|
23
23
|
const identifier = z.string().regex(/^[a-z][a-z0-9_]*$/)
|
|
24
24
|
export const serializedExpressionSchema = z.union([z.string().min(1).max(32000), z.record(z.string(), z.unknown()).transform(value => JSON.stringify(value))])
|
package/src/console-model.ts
CHANGED
|
@@ -85,7 +85,8 @@ export function consoleModel(kernel: KernelRegistry, scope: Scope): ConsoleModel
|
|
|
85
85
|
instance: config.id, revision: config.revision,
|
|
86
86
|
...(config.displayName ? { displayName: config.displayName } : {}),
|
|
87
87
|
locale: config.locale, timeZone: config.timeZone,
|
|
88
|
-
...(config.enumLabels ? { enumLabels: Object.fromEntries(Object.
|
|
88
|
+
...(config.enumLabels || Object.values(config.entities).some(entity => entity.displayExpression) ? { enumLabels: Object.fromEntries([...new Set(['en', 'cs', ...Object.keys(config.enumLabels ?? {})])].flatMap(language => {
|
|
89
|
+
const labels = config.enumLabels?.[language] ?? {}
|
|
89
90
|
// Catalogs use language -> translation key, matching query search and i18next.
|
|
90
91
|
const keys = new Set(Object.entries(config.entities).flatMap(([name, entity]) => Object.entries(entity.fields)
|
|
91
92
|
.filter(([field]) => authority.literals(name, field)).flatMap(([, field]) => {
|
|
@@ -97,6 +98,11 @@ export function consoleModel(kernel: KernelRegistry, scope: Scope): ConsoleModel
|
|
|
97
98
|
for (const field of Object.keys(entity.fields)) if (authority.literals(name, field)) keys.add(`field_${field}_${name}`)
|
|
98
99
|
}
|
|
99
100
|
const dictionary = Object.fromEntries(Object.entries(labels).filter(([key]) => keys.has(key)))
|
|
101
|
+
for (const [name, entity] of Object.entries(config.entities)) if (entity.displayExpression && entity.displayField && authority.read(name, entity.displayField)) {
|
|
102
|
+
const title = labels[`entitySingular_${name}`] ?? labels[`entity_${name}`] ?? name.replaceAll('_', ' ').replace(/^./, first => first.toUpperCase())
|
|
103
|
+
dictionary[`field_${entity.displayField}_${name}`] = title
|
|
104
|
+
dictionary[`listField_${entity.displayField}_${name}`] = title
|
|
105
|
+
}
|
|
100
106
|
return Object.keys(dictionary).length ? [[language, dictionary]] : []
|
|
101
107
|
})) } : {}),
|
|
102
108
|
...(config.ui ? { ui: presentation.modelUI(config.ui) } : {}),
|
package/src/query/compiler.ts
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { DisplayPartsExpression, needsDisplayParts, partsAlias } from './display-parts'
|
|
1
2
|
import { expressionInfo, readableComputed, rebindExpression, type ExpressionInfo } from './expressions'
|
|
2
3
|
import { ApiError } from '../errors'
|
|
3
4
|
import { Q, Fn, Cond, Condition, toSQLWithBindings, type ISQLFlavor, type SelectQuery, type ISequelizable } from '@jakub.knejzlik/ts-query'
|
|
@@ -207,13 +208,14 @@ export function renderStatement(kernel: KernelRegistry, scope: Scope, ast: Selec
|
|
|
207
208
|
}
|
|
208
209
|
const computed = new Map<string, Condition>()
|
|
209
210
|
const computing = new Set<string>()
|
|
211
|
+
const presentation = new Map<string, Condition>()
|
|
210
212
|
function computedValue(field: string): Condition {
|
|
211
213
|
const previous = computed.get(field); if (previous) return previous
|
|
212
214
|
if (computing.has(field)) throw new QueryError('query_invalid')
|
|
213
215
|
if (!readableComputed(kernel, scope, entity, field)) return new DisplayExpression(Q.value(null), new Map(), [])
|
|
214
216
|
computing.add(field)
|
|
215
217
|
const info = expressionInfo(kernel.config, entity, field, definition.fields[field].computed!)
|
|
216
|
-
const columns = new Map<string, string | Condition>(); const visible: Condition[] = []
|
|
218
|
+
const columns = new Map<string, string | Condition>(); const visible: Condition[] = []; const nested = new Map<string, ISequelizable>()
|
|
217
219
|
const paths = new Map<string, string>()
|
|
218
220
|
const demands = new Map<string, Set<string>>()
|
|
219
221
|
for (const dependency of info.dependencies) {
|
|
@@ -252,7 +254,18 @@ export function renderStatement(kernel: KernelRegistry, scope: Scope, ast: Selec
|
|
|
252
254
|
if (kernel.config.entities[dependency.entity].fields[dependency.field]?.computed) visible.push(Cond.isNotNull(col(parent, dependency.field)))
|
|
253
255
|
}
|
|
254
256
|
}
|
|
255
|
-
|
|
257
|
+
const source = (target: string) => scopedTable(target, undefined, true, true, info.tables.get(target) ?? new Set())
|
|
258
|
+
if (needsDisplayParts(kernel.config, entity, field)) {
|
|
259
|
+
for (const dep of info.dependencies) if ((!dep.qualifier || dep.qualifier === 'self') && needsDisplayParts(kernel.config, dep.entity, dep.field)) {
|
|
260
|
+
if (!dep.hops.length) { computedValue(dep.field); nested.set(dep.column, presentation.get(dep.field)!) }
|
|
261
|
+
else {
|
|
262
|
+
const parent = paths.get(dep.hops.map(hop => `/${hop.field}`).join(''))!
|
|
263
|
+
nested.set(dep.column, Q.expr(col(parent, partsAlias(dep.field))))
|
|
264
|
+
}
|
|
265
|
+
}
|
|
266
|
+
presentation.set(field, new DisplayPartsExpression(info.parts!, columns, nested, source))
|
|
267
|
+
}
|
|
268
|
+
let result: Condition = new ComputedExpression(info, columns, visible, source)
|
|
256
269
|
if (definition.fields[field].type === 'ref') {
|
|
257
270
|
const operand = result
|
|
258
271
|
const allowed = Cond.exists(scopedTable(definition.fields[field].entity!, child => Cond.equal(col(child, 'id'), operand), false))
|
|
@@ -313,6 +326,9 @@ export function renderStatement(kernel: KernelRegistry, scope: Scope, ast: Selec
|
|
|
313
326
|
if (definition?.computed) {
|
|
314
327
|
const projected = !computedDemand || computedDemand.has(field) ? computedValue(field) : Q.raw('NULL')
|
|
315
328
|
query = query.field(projected, field)
|
|
329
|
+
if (maskForeignKeys && (!computedDemand || computedDemand.has(field)) && needsDisplayParts(kernel.config, entity, field)) {
|
|
330
|
+
query = query.field(presentation.get(field) ?? Q.raw('NULL'), partsAlias(field))
|
|
331
|
+
}
|
|
316
332
|
} else if (kernel.config.entities[entity].label && field === kernel.config.entities[entity].displayField) {
|
|
317
333
|
query = query.field(label, field)
|
|
318
334
|
} else if (maskForeignKeys && definition?.type === 'ref') {
|
|
@@ -369,6 +385,8 @@ export function buildSelect(kernel: KernelRegistry, scope: Scope, entity: string
|
|
|
369
385
|
let aliases = 0
|
|
370
386
|
let ast = Q.select().from(entity, 'row')
|
|
371
387
|
for (const field of executionFields(kernel, scope, entity, node, [...extras, ...((node as QueryInput).search?.fields ?? []).filter(key => !labelPath(kernel.config, entity, key))])) ast = ast.field(col('row', field))
|
|
388
|
+
const display = kernel.config.entities[entity].displayField
|
|
389
|
+
if (display && selectedFields(kernel, scope, entity, node).includes(display) && needsDisplayParts(kernel.config, entity, display)) ast = ast.field(col('row', partsAlias(display)))
|
|
372
390
|
if (node.where) ast = ast.where(filterCondition(kernel, entity, 'row', node.where, () => `rel_${++aliases}`))
|
|
373
391
|
return ast
|
|
374
392
|
}
|
|
@@ -384,11 +402,11 @@ export function compileAggregate(kernel: KernelRegistry, scope: Scope, query: Qu
|
|
|
384
402
|
}
|
|
385
403
|
/** All values come from scoped joined tables; a missing/denied target has one safe marker. */
|
|
386
404
|
class LabelObject extends Condition {
|
|
387
|
-
constructor(private entity: string, private alias: string, private display?: string) { super() }
|
|
405
|
+
constructor(private entity: string, private alias: string, private display?: string, private parts = false) { super() }
|
|
388
406
|
toSQL(flavor: ISQLFlavor) {
|
|
389
407
|
const id = flavor.escapeColumn(col(this.alias, 'id'))
|
|
390
408
|
const display = this.display ? value(this.display).toSQL(flavor) : 'NULL'
|
|
391
|
-
const row = this.display ? `json_object('id', ${id}, ${display}, ${flavor.escapeColumn(col(this.alias, this.display))})` : `json_object('id', ${id})`
|
|
409
|
+
const row = this.display ? `json_object('id', ${id}, ${display}, ${flavor.escapeColumn(col(this.alias, this.display))}${this.parts ? `, '__display', json(${flavor.escapeColumn(col(this.alias, partsAlias(this.display)))})` : ''})` : `json_object('id', ${id})`
|
|
392
410
|
return `CASE WHEN ${id} IS NULL THEN json_object('status', 'unavailable') ELSE json_object('status', 'ok', 'entity', ${value(this.entity).toSQL(flavor)}, 'display', ${display}, 'row', ${row}) END`
|
|
393
411
|
}
|
|
394
412
|
}
|
|
@@ -414,7 +432,7 @@ export function compileRoot(kernel: KernelRegistry, scope: Scope, query: QueryIn
|
|
|
414
432
|
}
|
|
415
433
|
parent = alias
|
|
416
434
|
}
|
|
417
|
-
expression = new LabelObject(plan.entity, parent, plan.display)
|
|
435
|
+
expression = new LabelObject(plan.entity, parent, plan.display, !!plan.display && needsDisplayParts(kernel.config, plan.entity, plan.display))
|
|
418
436
|
}
|
|
419
437
|
source = source.field(expression, labelAlias(key))
|
|
420
438
|
}
|
|
@@ -470,6 +488,8 @@ export function compileInclude(kernel: KernelRegistry, scope: Scope, entity: str
|
|
|
470
488
|
child = child.field(Q.raw(`ROW_NUMBER() OVER (PARTITION BY ${quote('row')}.${quote(parentField)} ORDER BY ${sort})`), '__row_number')
|
|
471
489
|
let outer = Q.select().from(child, 'ranked')
|
|
472
490
|
for (const field of fields) outer = outer.field(col('ranked', field))
|
|
491
|
+
const display = kernel.config.entities[entity].displayField
|
|
492
|
+
if (display && selectedFields(kernel, scope, entity, node).includes(display) && needsDisplayParts(kernel.config, entity, display)) outer = outer.field(col('ranked', partsAlias(display)))
|
|
473
493
|
outer = outer.where(Cond.lessThanOrEqual('ranked.__row_number', value(node.limit ?? L.children)))
|
|
474
494
|
.orderBy('ranked.__row_number').orderBy(col('ranked', parentField))
|
|
475
495
|
return renderStatement(kernel, scope, outer, cost, requiredDisplayEntities(kernel, scope, entity, node).required)
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
import { Condition, Q, type ISequelizable, type ISQLFlavor, type SelectQuery } from '@jakub.knejzlik/ts-query'
|
|
2
|
+
import { expressionInfo, rebindExpression, type DisplayParts } from './expressions'
|
|
3
|
+
import type { InstanceConfig } from '../config'
|
|
4
|
+
|
|
5
|
+
/** Presentation is additive: raw SQL values still own search, ordering and cursors.
|
|
6
|
+
* JSON arrays preserve typed date operands without interpreting an expression in JS.
|
|
7
|
+
* Locale and timezone belong to the browser's ordinary field formatter.
|
|
8
|
+
*/
|
|
9
|
+
export const partsAlias = (field: string) => `__parts_${field}`
|
|
10
|
+
const needsCache = new WeakMap<object, Map<string, boolean>>()
|
|
11
|
+
export function needsDisplayParts(config: Pick<InstanceConfig, 'entities'>, entity: string, field: string): boolean {
|
|
12
|
+
let cache = needsCache.get(config); if (!cache) { cache = new Map(); needsCache.set(config, cache) }
|
|
13
|
+
const key = `${entity}.${field}`; const known = cache.get(key); if (known !== undefined) return known
|
|
14
|
+
const wire = config.entities[entity].fields[field]?.computed
|
|
15
|
+
if (!wire) { cache.set(key, false); return false }
|
|
16
|
+
const info = expressionInfo(config, entity, field, wire)
|
|
17
|
+
const containsDate = (parts: DisplayParts): boolean => 'concat' in parts ? parts.concat.some(containsDate)
|
|
18
|
+
: 'condition' in parts ? containsDate(parts.yes) || containsDate(parts.no)
|
|
19
|
+
: 'coalesce' in parts ? parts.coalesce.some(item => containsDate(item.parts))
|
|
20
|
+
: parts.type === 'datetime' || parts.type === 'date'
|
|
21
|
+
const result = containsDate(info.parts!) || info.dependencies.some(dep => needsDisplayParts(config, dep.entity, dep.field))
|
|
22
|
+
cache.set(key, result); return result
|
|
23
|
+
}
|
|
24
|
+
export class DisplayPartsExpression extends Condition {
|
|
25
|
+
constructor(private parts: DisplayParts, private columns: Map<string, string | ISequelizable>, private nested: Map<string, ISequelizable>, private source: (entity: string) => SelectQuery) { super() }
|
|
26
|
+
toSQL(flavor: ISQLFlavor) {
|
|
27
|
+
const raw = (wire: string) => {
|
|
28
|
+
const query = wire.startsWith('{') && JSON.parse(wire).type === 'SelectQuery'
|
|
29
|
+
const ast = query ? Q.deserialize(wire, { allowRaw: false }) : Q.expr(wire)
|
|
30
|
+
const sql = rebindExpression(ast, this.columns).toSQL(flavor, { transformTable: this.source })
|
|
31
|
+
return query ? `(${sql})` : sql
|
|
32
|
+
}
|
|
33
|
+
const render = (parts: DisplayParts): string => {
|
|
34
|
+
if ('concat' in parts) return `json_array(${parts.concat.map(child => `json(${render(child)})`).join(', ')})`
|
|
35
|
+
if ('condition' in parts) return `CASE WHEN ${raw(parts.condition)} THEN ${render(parts.yes)} ELSE ${render(parts.no)} END`
|
|
36
|
+
if ('coalesce' in parts) return `CASE ${parts.coalesce.map(item => `WHEN ${raw(item.wire)} IS NOT NULL THEN ${render(item.parts)}`).join(' ')} ELSE json_array(NULL) END`
|
|
37
|
+
const nested = this.nested.get(parts.wire.match(/^#([^#]+)#$/)?.[1] ?? parts.wire)
|
|
38
|
+
if (nested) return nested.toSQL(flavor)
|
|
39
|
+
const sql = raw(parts.wire)
|
|
40
|
+
return parts.type === 'datetime' || parts.type === 'date' ? `json_array(json_object('type', '${parts.type}', 'value', ${sql}))` : `json_array(CAST(${sql} AS TEXT))`
|
|
41
|
+
}
|
|
42
|
+
return render(this.parts)
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
/** Flatten SQL's nested concat arrays once, before sending the typed wire value. */
|
|
46
|
+
export function parseDisplayParts(value: string | unknown[]): unknown[] {
|
|
47
|
+
return (typeof value === 'string' ? JSON.parse(value) as unknown[] : value).flat(Infinity).map(part => {
|
|
48
|
+
// SQLite DATETIME/DATEADD return UTC timestamps without an offset. Qualify
|
|
49
|
+
// only presentation values; raw SQL text still owns search and ordering.
|
|
50
|
+
if (part && typeof part === 'object' && 'type' in part && part.type === 'datetime' && 'value' in part && typeof part.value === 'string' && /^\d{4}-\d{2}-\d{2}[ T]\d{2}:\d{2}(?::\d{2}(?:\.\d+)?)?$/.test(part.value)) return { ...part, value: `${part.value.replace(' ', 'T')}Z` }
|
|
51
|
+
return part == null ? '' : part
|
|
52
|
+
})
|
|
53
|
+
}
|
package/src/query/executor.ts
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { needsDisplayParts, parseDisplayParts, partsAlias } from './display-parts'
|
|
1
2
|
import { ApiError } from '../errors'
|
|
2
3
|
import type { KernelRegistry } from '../kernel/registry'
|
|
3
4
|
import type { Scope } from '../types'
|
|
@@ -10,14 +11,26 @@ import { validateQuery, type QueryInput, type Scalar, type Selection } from './s
|
|
|
10
11
|
export type Row = Record<string, any>
|
|
11
12
|
/** Shared projection for entity reads and server-configured dashboard queries. */
|
|
12
13
|
export function projectQueryRow(kernel: KernelRegistry, scope: Scope, entity: string, node: Selection, row: Row): Row {
|
|
13
|
-
|
|
14
|
+
const result = Object.fromEntries(selectedFields(kernel, scope, entity, node).map(field => [field,
|
|
14
15
|
kernel.config.entities[entity].fields[field]?.type === 'bool' && row[field] !== null ? Boolean(row[field]) : row[field]]))
|
|
16
|
+
const display = kernel.config.entities[entity].displayField
|
|
17
|
+
if (display && result[display] != null && needsDisplayParts(kernel.config, entity, display) && row[partsAlias(display)]) result.__display = parseDisplayParts(row[partsAlias(display)])
|
|
18
|
+
return result
|
|
15
19
|
}
|
|
16
20
|
export function projectRootRow(kernel: KernelRegistry, scope: Scope, query: QueryInput, row: Row): Row {
|
|
17
21
|
return { ...projectQueryRow(kernel, scope, query.entity, query, row), ...(query.labels ? {
|
|
18
|
-
__labels: Object.fromEntries(query.labels.map(key => [key,
|
|
22
|
+
__labels: Object.fromEntries(query.labels.map(key => [key, projectLabel(row[labelAlias(key)])])),
|
|
19
23
|
} : {}) }
|
|
20
24
|
}
|
|
25
|
+
function projectLabel(value: string | null) {
|
|
26
|
+
if (!value) return null
|
|
27
|
+
const label = JSON.parse(value)
|
|
28
|
+
if (label.row?.__display) {
|
|
29
|
+
if (label.row[label.display] == null) delete label.row.__display
|
|
30
|
+
else label.row.__display = parseDisplayParts(label.row.__display)
|
|
31
|
+
}
|
|
32
|
+
return label
|
|
33
|
+
}
|
|
21
34
|
export interface QueryResult { data: Row[]; next_cursor: string | null }
|
|
22
35
|
export type { QueryLog } from './observability'
|
|
23
36
|
import { emptyQueryLog, recordQuery, type QueryLog } from './observability'
|
package/src/query/expressions.ts
CHANGED
|
@@ -9,7 +9,8 @@ export const isExpression = (value: string) => !/^[a-z][a-z0-9_]*$/.test(value)
|
|
|
9
9
|
type Config = Pick<InstanceConfig, 'entities'>
|
|
10
10
|
type Kind = 'string' | 'number' | 'bool' | 'datetime' | 'null'
|
|
11
11
|
export interface Dependency { column: string; entity: string; field: string; hops: { source: string; field: string; target: string }[]; qualifier?: string; sourcePath?: string }
|
|
12
|
-
|
|
12
|
+
export type DisplayParts = { wire: string; type: Kind | 'date' } | { concat: DisplayParts[] } | { condition: string; yes: DisplayParts; no: DisplayParts } | { coalesce: { wire: string; parts: DisplayParts }[] }
|
|
13
|
+
interface ValueInfo { type: Kind; dateOnly: boolean; calendarDate?: boolean; textDependencies?: Dependency[]; parts?: DisplayParts }
|
|
13
14
|
export interface ExpressionInfo extends ValueInfo { sources: string[]; nodes: number; ast: ISequelizable; scalarQuery: boolean; dependencies: Dependency[]; tables: Map<string, Set<string>> }
|
|
14
15
|
export interface ExpressionIssue { code: 'invalid_expression'; entity: string; field: string; message: string; suggestedFix: string }
|
|
15
16
|
export class ExpressionError extends Error {
|
|
@@ -100,6 +101,10 @@ export function expressionInfo(config: Config, entity: string, field: string, wi
|
|
|
100
101
|
return fieldKind(config, source, name)
|
|
101
102
|
}
|
|
102
103
|
function scalar(node: unknown, context: Context, depth: number): ValueInfo {
|
|
104
|
+
const result = scalarValue(node, context, depth)
|
|
105
|
+
return { ...result, parts: result.parts ?? { wire: typeof node === 'string' ? node : Q.value(node as number | boolean).serialize(), type: result.calendarDate ? 'date' : result.type } }
|
|
106
|
+
}
|
|
107
|
+
function scalarValue(node: unknown, context: Context, depth: number): ValueInfo {
|
|
103
108
|
if (++nodes > 512 || depth > 32) fail('Expression exceeds the complexity budget', 'Use fewer functions or subqueries.')
|
|
104
109
|
if (typeof node === 'number') return { type: 'number', dateOnly: false }
|
|
105
110
|
if (typeof node === 'boolean') return { type: 'bool', dateOnly: false }
|
|
@@ -156,11 +161,11 @@ export function expressionInfo(config: Config, entity: string, field: string, wi
|
|
|
156
161
|
} else operands(all.slice(start + 1), ['string'], "Use literal SQLite date modifier strings, for example Q.value('start of month').")
|
|
157
162
|
}
|
|
158
163
|
if (node.startsWith('OP(')) { if (values.length < 2 || values.some(value => !['number', 'null'].includes(value.type))) fail('Arithmetic type mismatch', 'Use numeric fields and Q.value(number).'); return { type: 'number', dateOnly: false } }
|
|
159
|
-
if (fn === 'IF') { if (values.length !== 3 || values[0].type !== 'bool') fail('IF needs a condition and two values'); if (values[1].type !== values[2].type && !values.slice(1).some(value => value.type === 'null')) fail('IF branch type mismatch'); return { type: values[1].type === 'null' ? values[2].type : values[1].type, dateOnly: values.slice(1).every(value => value.dateOnly), textDependencies: values.slice(1).flatMap(value => value.textDependencies ?? []) } }
|
|
160
|
-
if (['IFNULL','COALESCE','NULLIF','MIN','MAX'].includes(fn)) { const nonnull = values.filter(value => value.type !== 'null'); if (new Set(nonnull.map(value => value.type)).size > 1) fail(`${fn} argument type mismatch`); return { type: nonnull[0]?.type ?? 'null', dateOnly: nonnull.every(value => value.dateOnly), textDependencies: fn === 'NULLIF' ? values[0].textDependencies : textDependencies } }
|
|
164
|
+
if (fn === 'IF') { if (values.length !== 3 || values[0].type !== 'bool') fail('IF needs a condition and two values'); if (values[1].type !== values[2].type && !values.slice(1).some(value => value.type === 'null')) fail('IF branch type mismatch'); return { type: values[1].type === 'null' ? values[2].type : values[1].type, dateOnly: values.slice(1).every(value => value.dateOnly), calendarDate: values.slice(1).filter(value => value.type !== 'null').every(value => value.calendarDate), textDependencies: values.slice(1).flatMap(value => value.textDependencies ?? []), parts: { condition: typeof args[0] === 'string' ? args[0] : Q.value(args[0] as boolean).serialize(), yes: values[1].parts!, no: values[2].parts! } } }
|
|
165
|
+
if (['IFNULL','COALESCE','NULLIF','MIN','MAX'].includes(fn)) { const nonnull = values.filter(value => value.type !== 'null'); if (new Set(nonnull.map(value => value.type)).size > 1) fail(`${fn} argument type mismatch`); return { type: nonnull[0]?.type ?? 'null', dateOnly: nonnull.every(value => value.dateOnly), calendarDate: (fn === 'NULLIF' ? [values[0]] : nonnull).every(value => value.calendarDate), textDependencies: fn === 'NULLIF' ? values[0].textDependencies : textDependencies, ...(['IFNULL', 'COALESCE'].includes(fn) ? { parts: { coalesce: values.map((value, i) => ({ wire: typeof args[i] === 'string' ? args[i] : Q.value(args[i] as number | boolean).serialize(), parts: value.parts! })) } } : {}) } }
|
|
161
166
|
if (['COUNT','SUM','AVG','ABS','ROUND','LENGTH','JULIANDAY','UNIXEPOCH','YEAR','MONTH','DATEDIFF'].includes(fn)) return { type: 'number', dateOnly: false }
|
|
162
|
-
if (['STRFTIME','DATE','DATETIME','TIME','DATEADD'].includes(fn)) return { type: fn === 'STRFTIME' ? 'string' : 'datetime', dateOnly: true }
|
|
163
|
-
return { type: 'string', dateOnly: fn === 'CONCAT' && values.every(value => value.dateOnly || value.type === 'null'), textDependencies }
|
|
167
|
+
if (['STRFTIME','DATE','DATETIME','TIME','DATEADD'].includes(fn)) return { type: fn === 'STRFTIME' ? 'string' : 'datetime', dateOnly: true, calendarDate: fn === 'DATE' }
|
|
168
|
+
return { type: 'string', dateOnly: fn === 'CONCAT' && values.every(value => value.dateOnly || value.type === 'null'), textDependencies, ...(fn === 'CONCAT' ? { parts: { concat: values.map(value => value.parts!) } } : {}) }
|
|
164
169
|
}
|
|
165
170
|
if (node.startsWith('{')) return object(JSON.parse(node), context, depth + 1)
|
|
166
171
|
if (/^[+-]?\d+(?:\.\d+)?$/.test(node)) return { type: 'number', dateOnly: false }
|
|
@@ -233,7 +238,7 @@ export function expressionInfo(config: Config, entity: string, field: string, wi
|
|
|
233
238
|
while (changed) { changed = false; for (const [from, to] of edges) if (connected.has(from) && !connected.has(to)) { connected.add(to); changed = true } }
|
|
234
239
|
if (local.some((alias: string) => !connected.has(alias))) fail(correlated ? 'Nested correlated expression sources require a mandatory equality on id or a stored ref field' : 'Cartesian expression sources require an equality on id or a stored ref field', "Join each additional source or correlate it in WHERE, for example Cond.columnEqual('p2.id', 'p.id'); a LEFT JOIN ON only bounds its right-hand source.")
|
|
235
240
|
if (node.limit !== 1 && !aggregates.found) fail('Scalar subquery needs LIMIT 1 or an aggregate', 'Add .limit(1), or select a single aggregate such as Fn.count; multi-argument MIN/MAX are scalar functions.')
|
|
236
|
-
return result
|
|
241
|
+
return { ...result, parts: { wire: JSON.stringify(node), type: result.calendarDate ? 'date' : result.type } }
|
|
237
242
|
}
|
|
238
243
|
const expr = (value: unknown) => scalar(value, { ...parent, rawRefs: true }, depth + 1)
|
|
239
244
|
// Value slots use deserializeValue: plain strings are literal data, even
|
|
@@ -297,7 +302,7 @@ export function expressionInfo(config: Config, entity: string, field: string, wi
|
|
|
297
302
|
const query = Q.deserialize(wrapper, { allowRaw: false, functions, maxDepth: 4 }) as SelectQuery
|
|
298
303
|
// COUNT(1)/COUNT(*) depend on scoped source rows without naming a column.
|
|
299
304
|
if (!dependencies.length && !hasSourceAggregate) fail('Expression must reference at least one schema field', 'Add a field operand such as title or customer.name.')
|
|
300
|
-
const info = { sources, nodes, ast: scalarQuery ? query : query.getFields()[0].name as ISequelizable, scalarQuery, dependencies, ...result, tables }
|
|
305
|
+
const info = { sources, nodes, ast: scalarQuery ? query : query.getFields()[0].name as ISequelizable, scalarQuery, dependencies, ...result, parts: result.parts ?? { wire, type: result.calendarDate ? 'date' : result.type }, tables }
|
|
301
306
|
entries.set(key, info); return info
|
|
302
307
|
} catch (error) { if (error instanceof ExpressionError) throw error; return fail(`Raw SQL or invalid serialized node: ${error instanceof Error ? error.message : String(error)}`) }
|
|
303
308
|
}
|