-
Notifications
You must be signed in to change notification settings - Fork 33
Expand file tree
/
Copy pathcqn2sql.js
More file actions
1616 lines (1447 loc) · 57.9 KB
/
Copy pathcqn2sql.js
File metadata and controls
1616 lines (1447 loc) · 57.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
const cds = require('@sap/cds')
const cds_infer = require('./infer')
const cqn4sql = require('./cqn4sql')
const { resolveTable } = require('./utils')
const _simple_queries = cds.env.features.sql_simple_queries
const _strict_booleans = _simple_queries < 2
// REVISIT: make string the default in next major
const _count_as_string = cds.env.features.count_as_string
const _count = _count_as_string ? { func: 'count', cast: { type: 'cds.String' } } : { func: 'count' }
const { Readable } = require('stream')
const DEBUG = cds.log('sql|sqlite')
class CQN2SQLRenderer {
/**
* Creates a new CQN2SQL instance for processing a query
* @constructor
* @param {import('@sap/cds/apis/services').ContextProperties} context the cds.context of the request
*/
constructor(srv) {
this.srv = srv
this.context = srv?.context || cds.context // Using srv.context is required due to stakeholders doing unmanaged txs without cds.context being set
this.class = new.target // for IntelliSense
this.class._init() // is a noop for subsequent calls
this.model = srv?.model
// Overwrite smart quoting
if (cds.env.sql.names === 'quoted') {
this.class.prototype.name = (name, query) => {
const e = name.id || name
const entity = query?._target || this.model?.definitions[e]
return (!entity?.['@cds.persistence.skip'] && entity?.['@cds.persistence.name']) || e
}
this.class.prototype.quote = (s) => `"${String(s).replace(/"/g, '""')}"`
}
}
BINARY_TYPES = {
'cds.Binary': 1,
'cds.LargeBinary': 1,
'cds.hana.BINARY': 1,
}
static _add_mixins(aspect, mixins) {
const fqn = this.name + aspect
const types = cds.builtin.types
for (let each in mixins) {
const def = types[each]
if (!def) continue
const value = mixins[each]
if (value?.get) Object.defineProperty(def, fqn, { get: value.get })
else Object.defineProperty(def, fqn, { value })
}
return fqn
}
/**
* Initializes the class one first creation to link types to data converters
*/
static _init() {
this._localized = this._add_mixins(':localized', this.localized)
this._convertInput = this._add_mixins(':convertInput', this.InputConverters)
this._convertOutput = this._add_mixins(':convertOutput', this.OutputConverters)
this._sqlType = this._add_mixins(':sqlType', this.TypeMap)
// Have all-uppercase all-lowercase, and capitalized keywords to speed up lookups
for (let each in this.ReservedWords) {
// ORDER
this.ReservedWords[each[0] + each.slice(1).toLowerCase()] = 1 // Order
this.ReservedWords[each.toLowerCase()] = 1 // order
}
this._init = () => { } // makes this a noop for subsequent calls
}
/**
* Renders incoming query into SQL and generates binding values
* @param {import('./infer/cqn').Query} q CQN query to be rendered
* @param {unknown[]|undefined} vars Values to be used for params
* @returns {CQN2SQLRenderer|unknown}
*/
render(q, vars) {
const kind = q.kind || Object.keys(q)[0] // SELECT, INSERT, ...
if (q._with) this._with = q._with
/**
* @type {string} the rendered SQL string
*/
this.sql = '' // to have it as first property for debugging
/** @type {unknown[]} */
this.values = [] // prepare values, filled in by subroutines
this[kind]((this.cqn = q)) // actual sql rendering happens here
if (this._with?.length) {
this.render_with()
}
if (vars?.length && !this.values?.length) this.values = vars
if (vars && Object.keys(vars).length && !this.values?.length) this.values = vars
const sanitize_values = process.env.NODE_ENV === 'production' && cds.env.log.sanitize_values !== false
if (DEBUG._debug) {
let values = sanitize_values && (this.entries || this.values?.length > 0) ? ['***'] : this.entries || this.values || []
if (values && !Array.isArray(values)) {
values = [values]
}
DEBUG.debug(this.sql, values)
}
return this
}
render_with() {
const sql = this.sql
let recursive = false
const values = this.values
const prefix = this._with.map(q => {
const values = this.values = []
let sql
if ('SELECT' in q) sql = `${this.quote(q.as)} AS (${this.SELECT(q)})`
else if ('SET' in q) {
recursive = true
const { SET } = q
sql = `${this.quote(q.as)}(${SET.args[0].SELECT.columns?.map(c => this.quote(this.column_name(c))) || ''}) AS (${this.SELECT(SET.args[0])} ${SET.op?.toUpperCase() || 'UNION'} ${SET.all ? 'ALL' : ''} ${this.SELECT(SET.args[1])}${SET.orderBy ? ` ORDER BY ${this.orderBy(SET.orderBy)}` : ''})`
}
return { sql, values }
})
this.sql = `WITH${recursive ? ' RECURSIVE' : ''} ${prefix.map(p => p.sql)} ${sql}`
this.values = [...prefix.map(p => p.values).flat(), ...values]
}
/**
* Links the incoming query with the current service model
* @param {import('./infer/cqn').Query} q
* @returns {import('./infer/cqn').Query}
*/
infer(q) {
return q._target instanceof cds.entity ? q : cds_infer(q)
}
cqn4sql(q) {
return cqn4sql(q, this.model)
}
// CREATE Statements ------------------------------------------------
/**
* Renders a CREATE query into generic SQL
* @param {import('./infer/cqn').CREATE} q
*/
CREATE(q) {
let { _target: target } = q
let query = target?.query || q.CREATE.as
if (!target || target._unresolved) {
const entity = q.CREATE.entity
target = typeof entity === 'string' ? { name: entity } : q.CREATE.entity
}
const name = this.name(target.name, q)
// Don't allow place holders inside views
delete this.values
this.sql =
!query || target['@cds.persistence.table']
? `CREATE TABLE ${this.quote(name)} ( ${this.CREATE_elements(target.elements)} )`
: `CREATE VIEW ${this.quote(name)} AS ${this.SELECT(this.cqn4sql(query))}`
this.values = []
return
}
/**
* Renders a column clause for the given elements
* @param {import('./infer/cqn').elements} elements
* @returns {string} SQL
*/
CREATE_elements(elements) {
let sql = ''
let keys = ''
for (let e in elements) {
const definition = elements[e]
if (definition.isAssociation) continue
if (definition.key) keys = `${keys}, ${this.quote(definition.name)}`
const s = this.CREATE_element(definition)
if (s) sql += `, ${s}`
}
return `${sql.slice(2)}${keys && `, PRIMARY KEY(${keys.slice(2)})`}`
}
/**
* Renders a column definition for the given element
* @param {import('./infer/cqn').element} element
* @returns {string} SQL
*/
CREATE_element(element) {
const type = this.type4(element)
if (type) return this.quote(element.name) + ' ' + type
}
/**
* Renders the SQL type definition for the given element
* @param {import('./infer/cqn').element} element
* @returns {string}
*/
type4(element) {
if (!element._type) element = cds.builtin.types[element.type] || element
const fn = element[this.class._sqlType]
return (
fn?.(element) || element._type?.replace('cds.', '').toUpperCase() || cds.error`Unsupported type: ${element.type}`
)
}
/** @callback converter */
/** @type {Object<string,import('@sap/cds/apis/csn').Definition>} */
static TypeMap = {
// Utilizing cds.linked inheritance
UUID: () => `NVARCHAR(36)`,
String: e => `NVARCHAR(${e.length || 5000})`,
Binary: e => `VARBINARY(${e.length || 5000})`,
UInt8: () => 'TINYINT',
Int16: () => 'SMALLINT',
Int32: () => 'INT',
Int64: () => 'BIGINT',
Integer: () => 'INT',
Integer64: () => 'BIGINT',
LargeString: () => 'NCLOB',
LargeBinary: () => 'BLOB',
Association: () => false,
Composition: () => false,
array: () => 'NCLOB',
Map: () => 'NCLOB',
// HANA types
'cds.hana.TINYINT': () => 'TINYINT',
'cds.hana.REAL': () => 'REAL',
'cds.hana.CHAR': e => `CHAR(${e.length || 1})`,
'cds.hana.ST_POINT': () => 'ST_POINT',
'cds.hana.ST_GEOMETRY': () => 'ST_GEOMETRY',
}
// DROP Statements ------------------------------------------------
/**
* Renders a DROP query into generic SQL
* @param {import('./infer/cqn').DROP} q
*/
DROP(q) {
const { _target: target } = q
const isView = target?.query || target?.projection || q.DROP.view
const name = target?.name || q.DROP.table?.ref?.[0] || q.DROP.view?.ref?.[0]
return (this.sql = `DROP ${isView ? 'VIEW' : 'TABLE'} IF EXISTS ${this.quote(this.name(name, q))}`)
}
// SELECT Statements ------------------------------------------------
/**
* Renders a SELECT statement into generic SQL
* @param {import('./infer/cqn').SELECT} q
*/
SELECT(q) {
let { from, expand, where, groupBy, having, orderBy, limit, one, distinct, localized, forUpdate, forShareLock, recurse } =
q.SELECT
if (from?.join && !q.SELECT.columns) {
throw new Error('CQN query using joins must specify the selected columns.')
}
// REVISIT: When selecting from an entity that is not in the model the from.where are not normalized (as cqn4sql is skipped)
if (!where && from?.ref?.length === 1 && from.ref[0]?.where) where = from.ref[0]?.where
let sql = `SELECT`
if (distinct) sql += ` DISTINCT`
if (recurse) sql += this.SELECT_recurse(q)
else {
sql += ` ${this.SELECT_columns(q)}`
if (!_empty(from)) sql += ` FROM ${this.from(from, q)}`
else sql += this.from_dummy()
}
if (!recurse && !_empty(where)) sql += ` WHERE ${this.where(where)}`
if (!recurse && !_empty(groupBy)) sql += ` GROUP BY ${this.groupBy(groupBy)}`
if (!recurse && !_empty(having)) sql += ` HAVING ${this.having(having)}`
if (!recurse && !_empty(orderBy)) sql += ` ORDER BY ${this.orderBy(orderBy, localized)}`
if (one) limit = Object.assign({}, limit, { rows: { val: 1 } })
if (limit) sql += ` LIMIT ${this.limit(limit)}`
if (forUpdate) sql += ` ${this.forUpdate(forUpdate)}`
else if (forShareLock) sql += ` ${this.forShareLock(forShareLock)}`
// Expand cannot work without an inferred query
if (expand) {
if ('elements' in q) sql = this.SELECT_expand(q, sql)
else cds.error`Query was not inferred and includes expand. For which the metadata is missing.`
}
return (this.sql = sql)
}
SELECT_recurse(q) {
let { from, columns, where, orderBy, recurse, _internal } = q.SELECT
const _target = q._target
if (_target && where) {
const keys = []
for (const _key in _target.keys) {
const k = _target.keys[_key]
if (!k.virtual && !k.isAssociation && !k.value) {
keys.push({ ref: [_key] })
}
}
// `where` needs to be wrapped to also support `where == ['exists', { SELECT }]` which is not allowed in `START WHERE`
const clone = q.clone()
clone.SELECT.columns = keys
clone.SELECT.recurse = undefined
clone.SELECT.limit = undefined
clone.SELECT.expand = undefined // omits JSON
where = [{ list: keys }, 'in', clone]
}
const requiredComputedColumns = { PARENT_ID: true, NODE_ID: true }
if (!_internal) requiredComputedColumns.RANK = true
const addComputedColumn = (name) => {
if (requiredComputedColumns[name]) return
requiredComputedColumns[name] = true
}
// The hierarchy functions will output the following columns. Which might clash with the entity columns
const reservedColumnNames = {
PARENT_ID: 1, NODE_ID: 1,
HIERARCHY_RANK: 1, HIERARCHY_DISTANCE: 1, HIERARCHY_LEVEL: 1, HIERARCHY_TREE_SIZE: 1
}
const availableComputedColumns = {
// Input computed columns
PARENT_ID: false,
NODE_ID: false,
// Output computed columns
RANK: { xpr: [{ ref: ['HIERARCHY_RANK'] }, '-', { val: 1, param: false }], as: 'RANK' },
Distance: { func: where?.length ? 'min' : 'max', args: [{ ref: ['HIERARCHY_DISTANCE'] }], as: 'Distance' },
DistanceFromRoot: { xpr: [{ ref: ['HIERARCHY_LEVEL'] }, '-', { val: 1, param: false }], as: 'DistanceFromRoot' },
DrillState: false,
LimitedDescendantCount: { xpr: [{ ref: ['HIERARCHY_TREE_SIZE'] }, '-', { val: 1, param: false }], as: 'LimitedDescendantCount' },
LimitedRank: { xpr: [{ func: 'row_number', args: [] }, 'OVER', { xpr: ['ORDER', 'BY', { ref: ['HIERARCHY_RANK'] }, 'ASC'] }, '-', { val: 1, param: false }], as: 'LimitedRank' }
}
const columnsFiltered = columns
.filter(x => {
if (x.element?.isAssociation) return false
const name = this.column_name(x)
if (name === '$$RN$$') return false
// REVISIT: ensure that the selected column is one of the hierarchy computed columns by unifying their common definition
if (x.element?.['@Core.Computed'] && name in availableComputedColumns) {
addComputedColumn(name)
return false
}
return true
})
const columnsOut = []
const columnsIn = []
const target = q._target || q.target
for (const name in target.elements) {
const ref = { ref: [name] }
const element = target.elements[name]
if (element.virtual || element.isAssociation) continue
if (name in availableComputedColumns) continue
if (name.toUpperCase() in reservedColumnNames) ref.as = `$$${name}$$`
// This only supports calculated elements within the scope of the own entity
if ('value' in element) {
const requested = columnsFiltered.find(c => this.column_name(c) === element.name)
if (requested) columnsIn.push(requested)
else continue
}
else columnsIn.push(ref)
const foreignkey4 = element._foreignKey4
if (
from.args ||
columnsFiltered.find(c => this.column_name(c) === name) ||
// foreignkey needs to be included when the association is expanded
(foreignkey4 && q.SELECT.columns.some(c => c.element?.isAssociation && c.element.name === foreignkey4))
) {
columnsOut.push(ref.as ? { ref: [ref.as], as: name } : ref)
}
}
const nodeKeys = []
const parentKeys = []
const association = target.elements[recurse.ref[0]]
association._foreignKeys.forEach(fk => {
nodeKeys.push(fk.childElement.name)
parentKeys.push(fk.parentElement.name)
})
columnsIn.push(
nodeKeys.length === 1
? { ref: nodeKeys, as: 'NODE_ID' }
: { func: 'HIERARCHY_COMPOSITE_ID', args: nodeKeys.map(n => ({ ref: [n] })), as: 'NODE_ID' },
parentKeys.length === 1
? { ref: parentKeys, as: 'PARENT_ID' }
: { func: 'HIERARCHY_COMPOSITE_ID', args: parentKeys.map(n => ({ ref: [n] })), as: 'PARENT_ID' },
)
if (orderBy) {
orderBy = orderBy.filter(o => o.ref).map(r => {
let col = r.ref.at(-1)
if (col.toUpperCase() in reservedColumnNames) col = `$$${col}$$`
if (!columnsIn.find(c => this.column_name(c) === col)) {
columnsIn.push({ ref: [col] })
}
return { ...r, ref: [col] }
})
}
// In the case of join operations make sure to compute the hierarchy from the source table only
const stableFrom = getStableFrom(from)
const alias = stableFrom.as
const source = () => {
return ({
func: 'HIERARCHY',
args: [{ xpr: ['SOURCE', { SELECT: { columns: columnsIn, from: stableFrom } }, ...(orderBy ? ['SIBLING', 'ORDER', 'BY', `${this.orderBy(orderBy)}`] : [])] }],
as: alias
})
}
const expandedByNr = { list: [] } // DistanceTo(...,null)
const expandedByOne = { list: [] } // DistanceTo(...,1)
const expandedByZero = { list: [] } // not DistanceTo(...,null)
let expandedFilter = []
// If a root where exists it should always be DistanceFromRoot otherwise when a recurse.where exists with only DistanceTo() calls
let distanceType = 'DistanceFromRoot'
let distanceVal
if (recurse.where) {
distanceType = where?.length ? 'DistanceFromRoot' : 'Distance'
if (recurse.where[0] === 'and') recurse.where = recurse.where.slice(1)
expandedFilter = [...recurse.where]
collectDistanceTo(expandedFilter)
}
const direction = where?.length ? 'ANCESTORS' : 'DESCENDANTS'
// Ensure that the distance value is being computed
if (distanceType) addComputedColumn(distanceType)
let distanceClause = []
if (distanceType === 'Distance') {
const isOne = expandedByOne.list.length
distanceClause = ['DISTANCE', ...(
isOne
? [{ val: 1 }]
: ['FROM', { val: 1 }]
)]
where = [{ ref: ['NODE_ID'] }, 'IN', isOne ? expandedByOne : expandedByNr]
expandedFilter = []
}
availableComputedColumns.DrillState = {
xpr: [ // When the node doesn't have children make it a leaf
'CASE', 'WHEN', { ref: ['HIERARCHY_TREE_SIZE'] }, '=', { val: 1, param: false }, 'THEN', { val: 'leaf', param: false },
...(where?.length // When there is a where filter the final node will always be a leaf
? ['WHEN', { func: where?.length ? 'min' : 'max', args: [{ ref: ['HIERARCHY_DISTANCE'] }] }, '=', { val: 0, param: false }, 'THEN', { val: 'leaf', param: false }]
: []
), // When having expanded by 0 level nodes make sure they are collapsed
...(expandedByZero.list.length
? ['WHEN', { ref: ['NODE_ID'] }, 'IN', expandedByZero, 'THEN', { val: 'collapsed', param: false }]
: []
), // When having expanded by null or one nodes compute them as expanded
...(expandedByNr.list.length || expandedByOne.list.length
? ['WHEN', { ref: ['NODE_ID'] }, 'IN', { list: [...expandedByNr.list, ...expandedByOne.list] }, 'THEN', { val: 'expanded', param: false }]
: []
), // When having expanded by one level node make its children collapsed
...(expandedByOne.list.length
? ['WHEN', { ref: ['PARENT_ID'] }, 'IN', expandedByOne, 'THEN', { val: 'collapsed', param: false }]
: []
), // When using DistanceFromRoot compute all entries within the levels as expanded
...(distanceType === 'DistanceFromRoot' && distanceVal
? [
'WHEN', { ref: ['HIERARCHY_LEVEL'] }, '<>', { val: distanceVal.val + 1 },
'THEN', { val: 'expanded', param: false },
]
: []
), // Default to expanded when default filter behavior is truthy
'ELSE', { val: (recurse.where && !expandedByZero.list.length) && distanceType ? 'collapsed' : 'expanded', param: false },
'END',
],
as: 'DrillState'
}
for (const name in requiredComputedColumns) {
const def = availableComputedColumns[name]
if (def) columnsOut.push(def)
}
if (_internal) columnsOut.push({ ref: ['NODE_ID'] })
const graph = distanceType === 'DistanceFromRoot' && !where
? { SELECT: { columns: columnsOut, from: source(), where: expandedFilter } }
: {
SELECT: {
columns: columnsOut,
from: {
func: `HIERARCHY_${direction}`,
args: [{
xpr: [
'SOURCE', source(), 'AS', this.quote(alias),
'START', 'WHERE', {
xpr: where // Requires special where logic before being put into the args
? from.args
? [{ ref: ['NODE_ID'] }, 'IN', { SELECT: { columns: [columnsIn.find(c => c.as === 'NODE_ID')], from, where: where } }]
: this.is_comparator?.({ xpr: where }) ?? true ? where : [...where, '=', { val: true, param: false }]
: [{ ref: ['PARENT_ID'] }, '=', { val: null }]
},
...distanceClause
]
}]
},
where: expandedFilter.length ? expandedFilter : undefined,
orderBy: [{ ref: ['HIERARCHY_RANK'], sort: 'asc' }],
groupBy: [{ ref: ['NODE_ID'] }, { ref: ['PARENT_ID'] }, { ref: ['HIERARCHY_RANK'] }, { ref: ['HIERARCHY_LEVEL'] }, { ref: ['HIERARCHY_TREE_SIZE'] }, ...columnsOut.filter(c => c.ref)],
}
}
const columnsQuery = cds.ql(q).clone()
columnsQuery.SELECT.columns = columns.map(x => {
if (x.element && 'value' in x.element) return { element: x.element, ref: [this.column_name(x)] }
return x
})
const recurseColumns = this.SELECT_columns(columnsQuery)
// Only apply result join if the columns contain a references which doesn't start with the source alias
if (from.args && columns.find(c => c.ref?.[0] === alias)) {
graph.as = alias
return ` ${recurseColumns} FROM ${this.from(setStableFrom(from, graph))}`
}
return ` ${recurseColumns} FROM (${this.SELECT(graph)})${alias ? ` AS ${this.quote(alias)}` : ''} `
function collectDistanceTo(where, innot = false) {
for (let i = 0; i < where.length; i++) {
const c = where[i]
if (c === 'not') {
distanceType = 'DistanceFromRoot'
innot = true
}
else if (c.func === 'DistanceTo') {
const expr = c.args[0]
// { func: 'HIERARCHY_COMPOSITE_ID', args: nodeKeys.map(n => ({ val: cur[n] })) }
const to = c.args[1].val
const list = to === 1
? expandedByOne
: innot
? expandedByZero
: expandedByNr
if (!list._where) {
list._where = []
where.splice(i, 1,
...(to === 1
? [{ ref: ['PARENT_ID'] }, 'IN', list]
: [{ ref: ['NODE_ID'] }, 'IN', {
SELECT: {
_internal: true,
columns: [{ ref: ['NODE_ID'], element: { '@Core.Computed': true } }],
from: q.SELECT.from,
recurse: {
ref: recurse.ref,
where: list._where,
},
},
target,
}])
)
i += 2
} else {
// Remove current entry from where
if (where[i - 1] === 'not') {
where.splice(i - 2, 3)
i -= 3
} else {
where.splice(i - 1, 2)
i -= 2
}
}
list.list.push(expr)
list._where.push(c)
}
else if (c.ref?.[0] === 'DistanceFromRoot') {
distanceType = 'DistanceFromRoot'
where[i] = { ref: ['HIERARCHY_LEVEL'] }
i += 2
distanceVal = where[i]
where[i] = { val: where[i].val + 1 }
}
}
}
function getStableFrom(from) {
if (from.args) return getStableFrom(from.args[0])
return from
}
function setStableFrom(from, src) {
if (from.args) {
const ret = { ...from }
ret.args = [...ret.args]
ret.args[0] = setStableFrom(ret.args[0], src)
return ret
}
return src
}
}
/**
* Renders a column clause into generic SQL
* @param {import('./infer/cqn').SELECT} param0
* @returns {string} SQL
*/
SELECT_columns(q) {
const ret = []
const arr = q.SELECT.columns ?? ['*']
for (const x of arr) {
if (x.SELECT?.count) arr.push(this.SELECT_count(x))
ret.push(this.column_expr(x, q))
}
return ret
}
/**
* Renders a JSON select around the provided SQL statement
* @param {import('./infer/cqn').SELECT} param0
* @param {string} sql
* @returns {string} SQL
*/
SELECT_expand(q, sql) {
if (!('elements' in q)) return sql
const SELECT = q.SELECT
if (!SELECT.columns) return sql
const isRoot = SELECT.expand === 'root'
const isSimple = _simple_queries &&
isRoot && // Simple queries are only allowed to have a root
!ObjectKeys(q.elements).some(e =>
_strict_booleans && q.elements[e].type === 'cds.Boolean' || // REVISIT: Booleans require json for sqlite
q.elements[e].isAssociation || // Indicates columns contains an expand
q.elements[e].$assocExpand || // REVISIT: sometimes associations are structs
q.elements[e].items // Array types require to be inlined with a json result
)
let cols = SELECT.columns.map(isSimple
? x => {
const name = this.column_name(x)
const escaped = `${name.replace(/"/g, '""')}`
return `${this.output_converter4(x.element, this.quote(name))} AS "${escaped}"`
}
: x => {
const name = this.column_name(x)
return `${this.string(`$.${JSON.stringify(name)}`)},${this.output_converter4(x.element, this.quote(name))}`
}).flat()
if (isSimple) return `SELECT ${cols} FROM (${sql})`
// Prevent SQLite from hitting function argument limit of 100
let obj = "'{}'"
for (let i = 0; i < cols.length; i += 48) {
obj = `jsonb_insert(${obj},${cols.slice(i, i + 48)})`
}
return `SELECT ${isRoot || SELECT.one ? obj.replace('jsonb', 'json') : `jsonb_group_array(${obj})`} as _json_ FROM (${sql})`
}
SELECT_count(q) {
const countQuery = cds.ql.clone(q, {
columns: [_count],
one: 0, limit: 0, orderBy: 0, expand: 0, count: 0
})
countQuery.as = q.as + '@odata.count'
countQuery.elements = undefined
countQuery.element = cds.builtin.types.Int64
return countQuery
}
/**
* Renders a SELECT column expression into generic SQL
* @param {import('./infer/cqn').col} x
* @returns {string} SQL
*/
column_expr(x, q) {
if (x === '*') return '*'
let sql = x.param !== true && typeof x.val === 'number' ? this.expr({ param: false, __proto__: x }) : this.expr(x)
let alias = this.column_alias4(x, q)
if (alias) sql += ' as ' + this.quote(alias)
return sql
}
/**
* Extracts the column alias from a SELECT column expression
* @param {import('./infer/cqn').col} x
* @returns {string}
*/
column_alias4(x) {
return typeof x.as === 'string' ? x.as : x.func || x.val
}
/**
* Renders a FROM clause into generic SQL
* @param {import('./infer/cqn').source} from
* @returns {string} SQL
*/
from(from, q) {
const { ref, as } = from
const _aliased = as ? s => s + ` as ${this.quote(as)}` : s => s
if (ref) {
let z = ref[0]
if (z.args) {
return _aliased(`${this.quote(this.name(z, q))}${this.from_args(z.args)}`)
}
return _aliased(this.quote(this.name(z, q)))
}
if (from.SELECT) return _aliased(`(${this.SELECT(from)})`)
if (from.join) return `${this.from(from.args[0])} ${from.join} JOIN ${this.from(from.args[1])}${from.on ? ` ON ${this.where(from.on)}` : ''}`
if (from.func) return _aliased(this.func(from))
}
/**
* Renders a FROM clause into generic SQL
* @param {import('./infer/cqn').source} from
* @returns {string} SQL
*/
with(query) {
this._with ??= []
this._with.push(query)
return { ref: [query.as] }
}
/**
* Renders a FROM clause for when the query does not have a target
* @returns {string} SQL
*/
from_dummy() {
return ''
}
/**
* Renders a FROM clause into generic SQL
* @param {import('./infer/cqn').ref['ref'][0]['args']} args
* @returns {string} SQL
*/
from_args(args) {
args
cds.error`Parameterized views are not supported by ${this.constructor.name}`
}
/**
* Renders a WHERE clause into generic SQL
* @param {import('./infer/cqn').predicate} xpr
* @returns {string} SQL
*/
where(xpr) {
return this.xpr({ xpr })
}
/**
* Renders a transformed where clause that maps the query target view to the source table
* @param {import('./infer/cqn').source} alias
* @param {import('./infer/cqn').predicate} where
* @param {import('./infer/cqn').query} q
* @returns SQL
*/
where_resolved(alias, where, q) {
const transitions = this.srv.resolve.transitions(q)
if (transitions.target === transitions.queryTarget) return this.where(where)
// view and table column refs to be matched
const viewCols = []
const tableCols = []
// Only match key columns when possible
const elements = q._target.keys || q._target.elements
for (const c in elements) {
if (
c in elements
&& transitions.mapping.has(c)
&& this.physical_column(elements, c)
) {
viewCols.push({ ref: [c] })
tableCols.push(transitions.mapping.get(c))
}
}
return tableCols.length > 0
? this.where([{ list: tableCols }, 'in', SELECT.from(q._target).alias(alias).columns(viewCols).where(where)])
: this.where(where)
}
/**
* Renders a HAVING clause into generic SQL
* @param {import('./infer/cqn').predicate} xpr
* @returns {string} SQL
*/
having(xpr) {
return this.xpr({ xpr })
}
/**
* Renders a groupBy clause into generic SQL
* @param {import('./infer/cqn').expr[]} clause
* @returns {string[] | string} SQL
*/
groupBy(clause) {
return clause.map(c => this.expr(c))
}
/**
* Renders an orderBy clause into generic SQL
* @param {import('./infer/cqn').ordering_term[]} orderBy
* @param {boolean | undefined} localized
* @returns {string[] | string} SQL
*/
orderBy(orderBy, localized) {
return orderBy.map(c => {
const o = (localized && this.context.locale)
? this.expr(c) +
(c.element?.[this.class._localized] ? ' COLLATE NOCASE' : '') +
(c.sort?.toLowerCase() === 'desc' || c.sort === -1 ? ' DESC' : ' ASC')
: this.expr(c) + (c.sort?.toLowerCase() === 'desc' || c.sort === -1 ? ' DESC' : ' ASC')
if (c.nulls) return o + ' NULLS ' + (c.nulls.toLowerCase() === 'first' ? 'FIRST' : 'LAST')
return o
})
}
/**
* Renders an limit clause into generic SQL
* @param {import('./infer/cqn').limit} param0
* @returns {string} SQL
* @throws {Error} When no rows are defined
*/
limit({ rows, offset }) {
if (!rows) throw new Error('Rows parameter is missing in SELECT.limit(rows, offset)')
return !offset ? this.val(rows) : `${this.val(rows)} OFFSET ${this.val(offset)}`
}
/**
* Renders an forUpdate clause into generic SQL
* @param {import('./infer/cqn').SELECT["SELECT"]["forUpdate"]} update
* @returns {string} SQL
*/
forUpdate(update) {
const { wait, of, ignoreLocked } = update
let sql = 'FOR UPDATE'
if (!_empty(of)) sql += ` OF ${of.map(x => this.expr(x)).join(', ')}`
if (ignoreLocked) sql += ' IGNORE LOCKED'
if (typeof wait === 'number') sql += ` WAIT ${wait}`
return sql
}
/**
* Renders an forShareLock clause into generic SQL
* @param {import('./infer/cqn').SELECT["SELECT"]["forShareLock"]} update
* @returns {string} SQL
*/
forShareLock(lock) {
const { wait, of } = lock
let sql = 'FOR SHARE LOCK'
if (!_empty(of)) sql += ` OF ${of.map(x => this.expr(x)).join(', ')}`
if (typeof wait === 'number') sql += ` WAIT ${wait}`
return sql
}
// INSERT Statements ------------------------------------------------
/**
* Renders an INSERT query into generic SQL
* @param {import('./infer/cqn').INSERT} q
* @returns {string} SQL
*/
INSERT(q) {
const { INSERT } = q
return INSERT.entries
? this.INSERT_entries(q)
: INSERT.rows
? this.INSERT_rows(q)
: INSERT.values
? this.INSERT_values(q)
: INSERT.from || INSERT.as
? this.INSERT_select(q)
: cds.error`Missing .entries, .rows, or .values in ${q}`
}
/**
* Renders an INSERT query with entries property
* @param {import('./infer/cqn').INSERT} q
* @returns {string} SQL
*/
INSERT_entries(q) {
const { INSERT } = q
const elements = q.elements || q._target?.elements
if (!elements && !INSERT.entries?.length) {
return // REVISIT: mtx sends an insert statement without entries and no reference entity
}
const transitions = this.srv.resolve.transitions(q)
const columns = elements
? ObjectKeys(elements).filter(c => this.physical_column(elements, c)
&& (c = transitions.mapping.get(c)?.ref?.[0] || c)
&& c in transitions.target.elements
&& this.physical_column(transitions.target.elements, c)
)
: ObjectKeys(INSERT.entries[0])
/** @type {string[]} */
this.columns = columns
const alias = INSERT.into.as
const entity = q._target ? this.table_name(q) : INSERT.into.ref[0]
if (!elements) {
this.entries = INSERT.entries.map(e => columns.map(c => e[c]))
const param = this.param.bind(this, { ref: ['?'] })
return (this.sql = `INSERT INTO ${this.quote(entity)}${alias ? ' as ' + this.quote(alias) : ''} (${this.columns.map(c => this.quote(c))}) VALUES (${columns.map(param)})`)
}
// Include this.values for placeholders
/** @type {unknown[][]} */
this.entries = []
if (INSERT.entries[0] instanceof Readable && !INSERT.entries[0].readableObjectMode) {
INSERT.entries[0].type = 'json'
this.entries = [[...this.values, INSERT.entries[0]]]
} else {
const entries = INSERT.entries[0]?.[Symbol.iterator] || INSERT.entries[0]?.[Symbol.asyncIterator] || INSERT.entries[0] instanceof Readable ? INSERT.entries[0] : INSERT.entries
const stream = Readable.from(this.INSERT_entries_stream(entries), { objectMode: false })
stream.type = 'json'
stream._raw = entries
this.entries = [[...this.values, stream]]
}
const extractions = this._managed = this.managed(columns.map(c => ({ name: c })), elements)
return (this.sql = `INSERT INTO ${this.quote(entity)}${alias ? ' as ' + this.quote(alias) : ''} (${this.columns.map(c => this.quote(transitions.mapping.get(c)?.ref?.[0] || c))
}) SELECT ${extractions.slice(0, columns.length).map(c => c.insert)} FROM json_each(?)`)
}
async *INSERT_entries_stream(entries, binaryEncoding = 'base64') {
const elements = this.cqn._target?.elements || {}
const bufferLimit = 65536 // 1 << 16
let buffer = '['
let sep = ''
for await (const row of entries) {
buffer += `${sep}{`
if (!sep) sep = ','
let sepsub = ''
for (const key in row) {
let val = row[key]
if (val === undefined) continue
const keyJSON = `${sepsub}${JSON.stringify(key)}:`
if (!sepsub) sepsub = ','
if (val instanceof Readable) {
buffer += `${keyJSON}"`
// TODO: double check that it works
val.setEncoding(binaryEncoding)
for await (const chunk of val) {
buffer += chunk
if (buffer.length > bufferLimit) {
yield buffer
buffer = ''
}
}
buffer += '"'
} else {
if (val != null && elements[key]?.type in this.BINARY_TYPES) {
val = Buffer.from(val, 'base64').toString(binaryEncoding)
}
buffer += `${keyJSON}${JSON.stringify(val)}`
}
}
buffer += '}'
if (buffer.length > bufferLimit) {
yield buffer
buffer = ''
}
}
buffer += ']'
yield buffer
}
async *INSERT_rows_stream(entries, binaryEncoding = 'base64') {
const elements = this.cqn._target?.elements || {}
const bufferLimit = 65536 // 1 << 16
let buffer = '['
let sep = ''
for (const row of entries) {
buffer += `${sep}[`
if (!sep) sep = ','
let sepsub = ''
for (let key = 0; key < row.length; key++) {
let val = row[key]
if (val instanceof Readable) {
buffer += `${sepsub}"`
// TODO: double check that it works
val.setEncoding(binaryEncoding)
for await (const chunk of val) {
buffer += chunk
if (buffer.length > bufferLimit) {
yield buffer
buffer = ''
}
}