-
Notifications
You must be signed in to change notification settings - Fork 15
/
Copy pathHANAService.js
1476 lines (1328 loc) · 54 KB
/
HANAService.js
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 fs = require('fs')
const path = require('path')
const { Readable } = require('stream')
const { SQLService } = require('@cap-js/db-service')
const drivers = require('./drivers')
const cds = require('@sap/cds')
const collations = require('./collations.json')
const keywords = cds.compiler.to.hdi.keywords
// keywords come as array
const hanaKeywords = keywords.reduce((prev, curr) => {
prev[curr] = 1
return prev
}, {})
const DEBUG = cds.debug('sql|db')
let HANAVERSION = 0
const SANITIZE_VALUES = process.env.NODE_ENV === 'production' && cds.env.log.sanitize_values !== false
/**
* @implements SQLService
*/
class HANAService extends SQLService {
init() {
// When hdi is enabled it defines the deploy function
// REVISIT: refactor together with cds-deploy.js
if (this.options.hdi) {
super.deploy = this.hdiDeploy
}
this.on(['BEGIN'], this.onBEGIN)
this.on(['COMMIT'], this.onCOMMIT)
this.on(['ROLLBACK'], this.onROLLBACK)
this.on(['SELECT', 'INSERT', 'UPSERT', 'UPDATE', 'DELETE'], this.onNOTFOUND)
return super.init()
}
// REVISIT: Add multi tenant factory when clarified
get factory() {
const driver = drivers[this.options.driver || this.options.credentials?.driver]?.driver || drivers.default.driver
const service = this
const { credentials, kind } = service.options
if (!credentials) {
throw new Error(`Database kind "${kind}" configured, but no HDI container or Service Manager instance bound to application.`)
}
const isMultitenant = !!service.options.credentials.sm_url || ('multiTenant' in this.options ? this.options.multiTenant : cds.env.requires.multitenancy)
const acquireTimeoutMillis = this.options.pool?.acquireTimeoutMillis || (cds.env.profiles.includes('production') ? 1000 : 10000)
return {
options: {
min: 0,
max: 10,
acquireTimeoutMillis,
idleTimeoutMillis: 60000,
evictionRunIntervalMillis: 100000,
numTestsPerEvictionRun: Math.ceil((this.options.pool?.max || 10) - (this.options.pool?.min || 0) / 3),
...(this.options.pool || {}),
testOnBorrow: true,
fifo: false
},
create: async function (tenant) {
try {
const { credentials } = isMultitenant
? await require('@sap/cds-mtxs/lib').xt.serviceManager.get(tenant, { disableCache: false })
: service.options
const dbc = new driver(credentials)
await dbc.connect()
HANAVERSION = dbc.server.major
return dbc
} catch (err) {
if (isMultitenant) {
// REVISIT: throw the error and break retry loop
// Stop trying when the tenant does not exist or is rate limited
if (err.status == 404 || err.status == 429)
return new Promise(function (_, reject) {
setTimeout(() => reject(err), acquireTimeoutMillis)
})
} else if (err.code !== 10) throw err
await require('@sap/cds-mtxs/lib').xt.serviceManager.get(tenant, { disableCache: true })
return this.create(tenant)
}
},
error: (err /*, tenant*/) => {
// Check whether the connection error was an authentication error
if (err.code === 10) {
// REVISIT: Refresh the credentials when possible
cds.exit(1)
}
// REVISIT: Add additional connection error scenarios
try {
cds.error(err)
} finally {
cds.exit(1)
}
},
destroy: dbc => dbc.disconnect(),
validate: (dbc) => dbc.validate(),
}
}
// REVISIT: Add multi tenant credential look up when clarified
url4(tenant) {
tenant
let { host, port, driver } = this.options?.credentials || this.options || {}
return `hana@${host}:${port}${driver ? `(${driver})` : ''}`
}
ensureDBC() {
return this.dbc || cds.error`Database connection is ${this._done || 'disconnected'}`
}
async set(variables) {
// REVISIT: required to be compatible with generated views
if (variables['$valid.from']) variables['VALID-FROM'] = variables['$valid.from']
if (variables['$valid.to']) variables['VALID-TO'] = variables['$valid.to']
if (variables['$user.id']) variables['APPLICATIONUSER'] = variables['$user.id']
if (variables['$user.locale']) variables['LOCALE'] = variables['$user.locale']
this.ensureDBC().set(variables)
}
async onSELECT(req) {
const { query, data } = req
if (!query.target || query.target._unresolved) {
try { this.infer(query) } catch { /**/ }
}
if (!query.target || query.target._unresolved) {
return super.onSELECT(req)
}
const isLockQuery = query.SELECT.forUpdate || query.SELECT.forShareLock
if (!isLockQuery) {
// REVISIT: disable this for queries like (SELECT 1)
// Will return multiple rows with objects inside
query.SELECT.expand = 'root'
}
const { cqn, sql, temporary, blobs, withclause, values } = this.cqn2sql(query, data)
delete query.SELECT.expand
const isSimple = temporary.length + blobs.length + withclause.length === 0
// REVISIT: add prepare options when param:true is used
let sqlScript = isLockQuery || isSimple ? sql : this.wrapTemporary(temporary, withclause, blobs)
const { hints } = query.SELECT
if (hints) sqlScript += ` WITH HINT (${hints.join(',')})`
let rows
if (values?.length || blobs.length > 0) {
const ps = await this.prepare(sqlScript, blobs.length)
rows = this.ensureDBC() && await ps.all(values || [])
} else {
rows = await this.exec(sqlScript)
}
if (isLockQuery) {
// Fetch actual locked results
const resultQuery = query.clone()
resultQuery.SELECT.forUpdate = undefined
resultQuery.SELECT.forShareLock = undefined
return this.onSELECT({ query: resultQuery, __proto__: req })
}
if (rows.length && !isSimple) {
rows = this.parseRows(rows)
}
if (cqn.SELECT.count) {
// REVISIT: the runtime always expects that the count is preserved with .map, required for renaming in mocks
return HANAService._arrayWithCount(rows, await this.count(query, rows))
}
return cqn.SELECT.one || query.SELECT.from.ref?.[0].cardinality?.max === 1 ? rows[0] : rows
}
async onINSERT({ query, data }) {
try {
const { sql, entries, cqn } = this.cqn2sql(query, data)
if (!sql) return // Do nothing when there is nothing to be done
const ps = await this.prepare(sql)
// HANA driver supports batch execution
const results = await (entries
? HANAVERSION <= 2
? entries.reduce((l, c) => l.then(() => this.ensureDBC() && ps.run(c)), Promise.resolve(0))
: entries.length > 1 ? this.ensureDBC() && await ps.runBatch(entries) : this.ensureDBC() && await ps.run(entries[0])
: this.ensureDBC() && ps.run())
return new this.class.InsertResults(cqn, results)
} catch (err) {
throw _not_unique(err, 'ENTITY_ALREADY_EXISTS', data)
}
}
async onUPDATE(req) {
try {
return await super.onUPDATE(req)
} catch (err) {
throw _not_unique(err, 'UNIQUE_CONSTRAINT_VIOLATION') || err
}
}
async onNOTFOUND(req, next) {
try {
return await next()
} catch (err) {
// Ensure that the known entity still exists
if (!this.context.tenant && err.code === 259 && typeof req.query !== 'string') {
// Clear current tenant connection pool
this.disconnect(this.context.tenant)
}
throw err
}
}
// Allow for running complex expand queries in a single statement
wrapTemporary(temporary, withclauses, blobs) {
const blobColumn = b => `"${b.replace(/"/g, '""')}"`
const values = temporary
.map(t => {
const blobColumns = blobs.map(b => (b in t.blobs) ? blobColumn(b) : `NULL AS ${blobColumn(b)}`)
return blobColumns.length
? `SELECT "_path_","_blobs_","_expands_","_json_",${blobColumns} FROM (${t.select})`
: t.select
})
const withclause = withclauses.length ? `WITH ${withclauses} ` : ''
const pathOrder = ' ORDER BY "_path_" ASC'
const ret = withclause + (
values.length === 1
? values[0] + (values[0].indexOf(`SELECT '$[' as "_path_"`) < 0 ? pathOrder : '')
: 'SELECT * FROM ' + values.map(v => `(${v})`).join(' UNION ALL ') + pathOrder
)
DEBUG?.(ret)
return ret
}
// Structure flat rows into expands and include raw blobs as raw buffers
parseRows(rows) {
const ret = []
const levels = [
{
data: ret,
path: '$[',
expands: {},
},
]
for (let i = 0; i < rows.length; i++) {
const row = rows[i]
const expands = JSON.parse(row._expands_)
const blobs = JSON.parse(row._blobs_)
const data = Object.assign(JSON.parse(row._json_ || '{}'), expands, blobs)
Object.keys(blobs).forEach(k => (data[k] = row[k] || data[k]))
// REVISIT: try to unify with handleLevel from base driver used for streaming
while (levels.length) {
const level = levels[levels.length - 1]
// Check if the current row is a child of the current level
if (row._path_.indexOf(level.path) === 0) {
// Check if the current row is an expand of the current level
const property = row._path_.slice(level.path.length + 2, -7)
if (property in level.expands) {
if (level.expands[property]) {
level.data[property].push(data)
} else {
level.data[property] = data
}
levels.push({
data: data,
path: row._path_,
expands,
})
break
} else {
// REVISIT: identify why sometimes not all parent rows are returned
level.data.push?.(data)
if (row._path_ !== level.path) {
levels.push({
data: data,
path: row._path_,
expands,
})
}
break
}
} else {
// Step up if it is not a child of the current level
levels.pop()
}
}
}
return ret
}
// prepare and exec are both implemented inside the drivers
prepare(sql, hasBlobs) {
const stmt = this.ensureDBC().prepare(sql, hasBlobs)
// we store the statements, to release them on commit/rollback all at once
this.dbc.statements.push(stmt)
return stmt
}
exec(sql) {
return this.ensureDBC().exec(sql)
}
/**
* HDI specific deploy logic
* @param {import('@sap/cds/apis/csn').CSN} model The CSN model to be deployed
*/
async hdiDeploy(model) {
const fileGenerator = cds.compile.to.hdbtable(model)
const sql = fs.promises.readFile(path.resolve(__dirname, 'scripts/deploy.sql'), 'utf-8')
const hdiconfig = `${await fs.promises.readFile(path.resolve(__dirname, 'scripts/.hdiconfig'), 'utf-8')}`
let files = [{ path: '.hdiconfig', content: `${hdiconfig}` }]
for (let [src, { file }] of fileGenerator) {
files.push({ path: file, content: src })
}
const replaces = {
CONTAINER_GROUP: this.options.credentials.containerGroup,
CONTAINER_NAME: this.options.credentials.schema,
JSON_FILES: JSON.stringify(files).replace(/'/g, "''"),
}
const fullSQL = `${await sql}`.replace(/{{{([^}]*)}}}/g, (a, b) => replaces[b])
await this.tx(async tx => tx.run(fullSQL))
return true
}
static CQN2SQL = class CQN2HANA extends SQLService.CQN2SQL {
static _init() {
this._insertType = this._add_mixins(':insertType', this.InsertTypeMap)
return super._init()
}
SELECT(q) {
// Collect all queries and blob columns of all queries
this.blobs = this.blobs || []
this.withclause = this.withclause || []
this.temporary = this.temporary || []
this.temporaryValues = this.temporaryValues || []
if (q.SELECT.from?.join && !q.SELECT.columns) {
throw new Error('CQN query using joins must specify the selected columns.')
}
let { limit, one, distinct, from, orderBy, having, expand, columns = ['*'], localized, count, parent } = q.SELECT
// When one of these is defined wrap the query in a sub query
if (expand || (parent && (limit || one || orderBy))) {
const walkAlias = q => {
if (q.args) return q.as || walkAlias(q.args[0])
if (q.SELECT?.from) return walkAlias(q.SELECT?.from)
return q.as || cds.error`Missing alias for subquery`
}
const alias = q.as // Use query alias as path name
q.as = walkAlias(q) // Use from alias for query re use alias
q.alias = `${parent ? parent.alias + '.' : ''}${alias || q.as}`
const src = q
const { element, elements } = q
q = cds.ql.clone(q)
if (parent) {
q.SELECT.limit = undefined
q.SELECT.one = undefined
q.SELECT.orderBy = undefined
}
q.SELECT.expand = false
const outputColumns = [...columns.filter(c => c.as !== '_path_')]
if (parent) {
// Track parent _path_ for later concatination
if (!columns.find(c => this.column_name(c) === '_path_'))
columns.push({ ref: [parent.as, '_path_'], as: '_parent_path_' })
}
let orderByHasOutputColumnRef = false
if (orderBy) {
if (distinct) orderByHasOutputColumnRef = true
// Ensure that all columns used in the orderBy clause are exposed
orderBy = orderBy.map((c, i) => {
if (!c.ref) {
c.as = `$$ORDERBY_${i}$$`
columns.push(c)
return { __proto__: c, ref: [c.as], sort: c.sort }
}
if (c.ref?.length === 2) {
const ref = c.ref + ''
const match = columns.find(col => col.ref + '' === ref)
if (!match) {
c.as = `$$${c.ref.join('.')}$$`
columns.push(c)
}
return { __proto__: c, ref: [this.column_name(match || c)], sort: c.sort }
}
orderByHasOutputColumnRef = true
return c
})
}
let hasBooleans = false
let hasExpands = false
let hasStructures = false
const aliasedOutputColumns = outputColumns.map(c => {
if (c.element?.type === 'cds.Boolean') hasBooleans = true
if (c.elements && c.element?.isAssociation) hasExpands = true
if (c.element?.type in this.BINARY_TYPES || c.elements || c.element?.elements || c.element?.items) hasStructures = true
return c.elements ? c : { __proto__: c, ref: [this.column_name(c)] }
})
const isSimpleQuery = (
cds.env.features.sql_simple_queries &&
(cds.env.features.sql_simple_queries > 1 || !hasBooleans) &&
!hasStructures &&
!parent
)
const rowNumberRequired = parent // If this query has a parent it is an expand
|| (!isSimpleQuery && (orderBy || from.SELECT)) // If using JSON functions the _path_ is used for top level sorting
|| hasExpands // Expands depend on parent $$RN$$
if (rowNumberRequired) {
// Insert row number column for reducing or sorting the final result
const over = { xpr: [] }
// TODO: replace with full path partitioning
if (parent) over.xpr.push(`PARTITION BY ${this.ref({ ref: ['_parent_path_'] })}`)
if (orderBy?.length) over.xpr.push(` ORDER BY ${this.orderBy(orderBy, localized)}`)
const rn = { xpr: [{ func: 'ROW_NUMBER', args: [] }, 'OVER', over], as: '$$RN$$' }
q.as = q.SELECT.from.as
q = cds.ql.SELECT(['*', rn]).from(q)
q.as = q.SELECT.from.as
}
const outputAliasSimpleQueriesRequired = cds.env.features.sql_simple_queries
&& (orderByHasOutputColumnRef || having)
if (outputAliasSimpleQueriesRequired || rowNumberRequired || q.SELECT.columns.length !== aliasedOutputColumns.length) {
q = cds.ql.SELECT(aliasedOutputColumns).from(q)
q.as = q.SELECT.from.as
Object.defineProperty(q, 'elements', { value: elements })
Object.defineProperty(q, 'element', { value: element })
}
if (rowNumberRequired && !q.SELECT.columns.find(c => c.as === '_path_')) {
q.SELECT.columns.push({
xpr: [
{
func: 'concat',
args: parent
? [
{
func: 'concat',
args: [{ ref: ['_parent_path_'] }, { val: `].${alias}[`, param: false }],
},
{ func: 'lpad', args: [{ ref: ['$$RN$$'] }, { val: 6, param: false }, { val: '0', param: false }] },
]
: [{ val: '$[', param: false }, { func: 'lpad', args: [{ ref: ['$$RN$$'] }, { val: 6, param: false }, { val: '0', param: false }] }],
},
],
as: '_path_',
})
}
if (parent && (limit || one)) {
if (limit && limit.rows == null) {
// same error as in limit(), but for limits in expand
throw new Error('Rows parameter is missing in SELECT.limit(rows, offset)')
}
// Apply row number limits
q.where(
one
? [{ ref: ['$$RN$$'] }, '=', { val: 1, param: false }]
: limit.offset?.val
? [
{ ref: ['$$RN$$'] },
'>',
limit.offset,
'AND',
{ ref: ['$$RN$$'] },
'<=',
{ val: limit.rows.val + limit.offset.val },
]
: [{ ref: ['$$RN$$'] }, '<=', { val: limit.rows.val }],
)
}
// Pass along SELECT options
q.SELECT.expand = expand
q.SELECT._one = one
q.SELECT.count = count
q.src = src
}
super.SELECT(q)
// Set one and limit back to the query for onSELECT handler
q.SELECT.one = one
q.SELECT.limit = limit
if (expand === 'root' && this._outputColumns) {
this.cqn = q
const fromSQL = this.quote(this.name(q.src.alias))
this.withclause.unshift(`${fromSQL} as (${this.sql})`)
this.temporary.unshift({ blobs: this._blobs, select: `SELECT ${this._outputColumns} FROM ${fromSQL}` })
if (this.values) {
this.temporaryValues.unshift(this.values)
this.values = this.temporaryValues.flat()
}
}
return this.sql
}
SELECT_columns(q) {
const { SELECT, src } = q
if (!SELECT.columns) return '*'
const structures = []
const blobrefs = []
let expands = {}
let blobs = {}
let hasBooleans = false
let path
let sql = SELECT.columns
.map(
SELECT.expand === 'root'
? x => {
if (x === '*') return '*'
// means x is a sub select expand
if (x.elements && x.element?.isAssociation) {
expands[this.column_name(x)] = x.SELECT.one ? null : []
const parent = src
this.extractForeignKeys(x.SELECT.where, parent.as, []).forEach(ref => {
const columnName = this.column_name(ref)
if (!parent.SELECT.columns.find(c => this.column_name(c) === columnName)) {
parent.SELECT.columns.push(ref)
}
})
if (x.SELECT.from) {
x.SELECT.from = {
join: 'inner',
args: [x.SELECT.from, { ref: [parent.alias], as: parent.as }],
on: x.SELECT.where,
as: x.SELECT.from.as,
}
} else {
x.SELECT.from = { ref: [parent.alias], as: parent.as }
x.SELECT.columns.forEach(col => {
// if (col.ref?.length === 1) { col.ref.unshift(parent.as) }
if (col.ref?.length > 1) {
const colName = this.column_name(col)
if (!parent.SELECT.columns.some(c => !c.elements && this.column_name(c) === colName)) {
const isSource = from => {
if (from.as === col.ref[0]) return true
return from.args?.some(a => {
if (a.args) return isSource(a)
return a.as === col.ref[0]
})
}
// Inject foreign columns into parent selects (recursively)
const as = `$$${col.ref.join('.')}$$`
let rename = col.ref[0] !== parent.as
let curPar = parent
while (curPar) {
if (isSource(curPar.SELECT.from)) {
if (curPar.SELECT.columns.find(c => c.as === as)) {
rename = true
} else {
rename = rename || curPar === parent
curPar.SELECT.columns.push(rename ? { __proto__: col, ref: col.ref, as } : { __proto__: col, ref: [...col.ref] })
}
break
} else {
curPar.SELECT.columns.push({ __proto__: col, ref: [curPar.SELECT.parent.as, as], as })
curPar = curPar.SELECT.parent
}
}
if (rename) {
col.as = colName
col.ref = [parent.as, as]
} else {
col.ref = [parent.as, colName]
}
} else {
col.ref[1] = colName
}
}
})
}
x.SELECT.where = undefined
x.SELECT.expand = 'root'
x.SELECT.parent = parent
const values = this.values
this.values = []
parent.SELECT.expand = true
this.SELECT(x)
this.values = values
return false
}
if (x.element?.type in this.BINARY_TYPES) {
blobrefs.push(x)
blobs[this.column_name(x)] = null
return false
}
if (x.element?.elements || x.element?.items) {
// support for structured types and arrays
structures.push(x)
return false
}
const columnName = this.column_name(x)
if (columnName === '_path_') {
path = this.expr(x)
return false
}
if (x.element?.type === 'cds.Boolean') hasBooleans = true
const converter = x.element?.[this.class._convertOutput] || (e => e)
const sql = x.param !== true && typeof x.val === 'number' ? this.expr({ param: false, __proto__: x }) : this.expr(x)
return `${converter(sql, x.element)} as "${columnName.replace(/"/g, '""')}"`
}
: x => {
if (x === '*') return '*'
// means x is a sub select expand
if (x.elements && x.element?.isAssociation) return false
return this.column_expr(x)
},
)
.filter(a => a)
if (SELECT.expand === 'root') {
this._blobs = blobs
const blobColumns = Object.keys(blobs)
this.blobs.push(...blobColumns.filter(b => !this.blobs.includes(b)))
if (
cds.env.features.sql_simple_queries &&
(cds.env.features.sql_simple_queries > 1 || !hasBooleans) &&
structures.length + ObjectKeys(expands).length + ObjectKeys(blobs).length === 0 &&
!q?.src?.SELECT?.parent &&
this.temporary.length === 0
) {
return `${sql}`
}
expands = this.string(JSON.stringify(expands))
blobs = this.string(JSON.stringify(blobs))
// When using FOR JSON the whole dataset is put into a single blob
// To increase the potential maximum size of the result set every row is converted to a JSON
// Making each row a maximum size of 2gb instead of the whole result set to be 2gb
// Excluding binary columns as they are not supported by FOR JSON and themselves can be 2gb
const rawJsonColumn = sql.length
? `(SELECT ${path ? sql : sql.map(c => c.slice(c.lastIndexOf(' as "') + 4))} FROM JSON_TABLE('{}', '$' COLUMNS("'$$FaKeDuMmYCoLuMn$$'" FOR ORDINALITY)) FOR JSON ('format'='no', 'omitnull'='no', 'arraywrap'='no') RETURNS NVARCHAR(2147483647))`
: `'{}'`
let jsonColumn = rawJsonColumn
if (structures.length) {
// Appending the structured columns to prevent them from being quoted and escaped
// In case of the deep JSON select queries the deep columns depended on a REGEXP_REPLACE which will probably be slower
const structuresConcat = structures
.map((x, i) => {
const name = this.column_name(x)
return `'${i ? ',' : '{'}"${name}":' || COALESCE(${this.quote(name)},'null')`
})
.join(' || ')
jsonColumn = sql.length
? `${structuresConcat} || ',' || SUBSTRING(${rawJsonColumn}, 2)`
: `${structuresConcat} || '}'`
}
// Calculate final output columns once
let outputColumns = ''
outputColumns = `${path ? this.quote('_path_') : `'$['`} as "_path_",${blobs} as "_blobs_",${expands} as "_expands_",${jsonColumn} as "_json_"`
if (blobColumns.length)
outputColumns = `${outputColumns},${blobColumns.map(b => `${this.quote(b)} as "${b.replace(/"/g, '""')}"`)}`
this._outputColumns = outputColumns
if (path) {
sql = `*,${path} as ${this.quote('_path_')}`
} else {
structures.forEach(x => sql.push(this.column_expr(x)))
blobrefs.forEach(x => sql.push(this.column_expr(x)))
}
}
return sql
}
SELECT_expand(_, sql) {
return sql
}
from_dummy() {
return ' FROM DUMMY'
}
extractForeignKeys(xpr, alias, foreignKeys = []) {
// REVISIT: this is a quick method of extracting the foreign keys it could be nicer
// Find all foreign keys used in the expression so they can be exposed to the follow up expand queries
JSON.stringify(xpr, (key, val) => {
if (key === 'ref' && val.length === 2 && val[0] === alias && !foreignKeys.find(k => k.ref + '' === val + '')) {
foreignKeys.push({ ref: val })
return
}
return val
})
return foreignKeys
}
// REVISIT: Find a way to avoid overriding the whole function redundantly
INSERT_entries(q) {
this.values = undefined
const { INSERT } = q
// REVISIT: should @cds.persistence.name be considered ?
const entity = q.target?.['@cds.persistence.name'] || this.name(q.target?.name || INSERT.into.ref[0], q)
const elements = q.elements || q.target?.elements
if (!elements) {
return super.INSERT_entries(q)
}
const columns = elements
? ObjectKeys(elements).filter(c => c in elements && !elements[c].virtual && !elements[c].value && !elements[c].isAssociation)
: ObjectKeys(INSERT.entries[0])
this.columns = columns
const extractions = this.managed(columns.map(c => ({ name: c })), elements)
// REVISIT: @cds.extension required
const extraction = extractions.map(c => c.extract)
const converter = extractions.map(c => c.insert)
const _stream = entries => {
const stream = Readable.from(this.INSERT_entries_stream(entries, 'hex'), { objectMode: false })
stream.setEncoding('utf-8')
stream.type = 'json'
stream._raw = entries
return stream
}
// HANA Express does not process large JSON documents
// The limit is somewhere between 64KB and 128KB
if (HANAVERSION <= 2) {
this.entries = INSERT.entries.map(e => (e instanceof Readable
? [e]
: [_stream([e])]))
} else {
this.entries = [[
INSERT.entries[0] instanceof Readable
? INSERT.entries[0]
: _stream(INSERT.entries)
]]
}
// WITH SRC is used to force HANA to interpret the ? as a NCLOB allowing for streaming of the data
// Additionally for drivers that did allow for streaming of NVARCHAR they quickly reached size limits
// This should allow for 2GB of data to be inserted
// When using a buffer table it would be possible to stream indefinitely
// For the buffer table to work the data has to be sanitized by a complex regular expression
// Which in testing took up about a third of the total time processing time
// With the buffer table approach is also greatly reduces the required memory
// JSON_TABLE parses the whole JSON document at once meaning that the whole JSON document has to be in memory
// With the buffer table approach the data is processed in chunks of a configurable size
// Which allows even smaller HANA systems to process large datasets
// But the chunk size determines the maximum size of a single row
return (this.sql = `INSERT INTO ${this.quote(entity)} (${this.columns.map(c =>
this.quote(c),
)}) WITH SRC AS (SELECT ? AS JSON FROM DUMMY UNION ALL SELECT TO_NCLOB(NULL) AS JSON FROM DUMMY)
SELECT ${converter} FROM JSON_TABLE(SRC.JSON, '$' COLUMNS(${extraction}) ERROR ON ERROR) AS NEW`)
}
INSERT_rows(q) {
const { INSERT } = q
// Convert the rows into entries to simplify inserting
// Tested:
// - Array JSON INSERT (1.5x)
// - Simple INSERT with reuse onINSERT (2x)
// - Simple INSERT with batch onINSERT (1x)
// - Object JSON INSERT (1x)
// The problem with Simple INSERT is the type mismatch from csv files
// Recommendation is to always use entries
const elements = q.elements || q.target?.elements
if (!elements) {
return super.INSERT_rows(q)
}
const columns = INSERT.columns || []
for (const col of ObjectKeys(elements)) {
if (!columns.includes(col)) columns.push(col)
}
const entries = new Array(INSERT.rows.length)
const rows = INSERT.rows
for (let x = 0; x < rows.length; x++) {
const row = rows[x]
const entry = {}
for (let y = 0; y < columns.length; y++) {
entry[columns[y]] = row[y]
// Include explicit null values for managed fields
?? (elements[columns[y]]['@cds.on.insert'] && null)
}
entries[x] = entry
}
INSERT.entries = entries
return this.INSERT_entries(q)
}
UPSERT(q) {
const { UPSERT } = q
// REVISIT: should @cds.persistence.name be considered ?
const entity = q.target?.['@cds.persistence.name'] || this.name(q.target?.name || UPSERT.into.ref[0], q)
const elements = q.target?.elements || {}
const insert = this.INSERT({ __proto__: q, INSERT: UPSERT })
let keys = q.target?.keys
if (!keys) return insert
keys = Object.keys(keys).filter(k => !keys[k].isAssociation && !keys[k].virtual)
// temporal data
keys.push(...ObjectKeys(q.target.elements).filter(e => q.target.elements[e]['@cds.valid.from']))
const managed = this.managed(
this.columns.map(c => ({ name: c })),
elements
)
const keyCompare = managed
.filter(c => keys.includes(c.name))
.map(c => `${c.insert}=OLD.${this.quote(c.name)}`)
.join(' AND ')
const mixing = managed.map(c => c.upsert)
const extraction = managed.map(c => c.extract)
const sql = `WITH SRC AS (SELECT ? AS JSON FROM DUMMY UNION ALL SELECT TO_NCLOB(NULL) AS JSON FROM DUMMY)
SELECT ${mixing} FROM JSON_TABLE(SRC.JSON, '$' COLUMNS(${extraction})) AS NEW LEFT JOIN ${this.quote(entity)} AS OLD ON ${keyCompare}`
return (this.sql = `UPSERT ${this.quote(entity)} (${this.columns.map(c => this.quote(c))}) ${sql}`)
}
DROP(q) {
return (this.sql = super.DROP(q).replace('IF EXISTS', ''))
}
from_args(args) {
return `(${ObjectKeys(args).map(k => `${this.quote(k)} => ${this.expr(args[k])}`)})`
}
orderBy(orderBy, localized) {
return orderBy.map(
localized
? c =>
this.expr(c) +
(c.element?.[this.class._localized]
? ` COLLATE ${collations[this.context.locale] || collations[this.context.locale.split('_')[0]] || collations['']
}`
: '') +
(c.sort?.toLowerCase() === 'desc' || c.sort === -1 ? ' DESC' : ' ASC')
: c => this.expr(c) + (c.sort?.toLowerCase() === 'desc' || c.sort === -1 ? ' DESC' : ' ASC'),
)
}
limit({ rows, offset }) {
rows = { param: false, __proto__: rows }
return super.limit({ rows, offset })
}
where(xpr) {
xpr = { xpr, top: true }
const suffix = this.is_comparator(xpr)
return `${this.xpr(xpr, true)}${suffix ? '' : ` = ${this.val({ val: true })}`}`
}
having(xpr) {
return this.where(xpr)
}
xpr(_xpr, iscompare) {
let { xpr, top, _internal } = _xpr
// Maps the compare operators to what to return when both sides are null
const compareTranslations = {
'==': true,
'!=': false,
}
const expressionTranslations = { // These operators are not allowed in column expressions
'==': true,
'!=': false,
'=': null,
'>': null,
'<': null,
'<>': null,
'>=': null,
'<=': null,
'!<': null,
'!>': null,
}
if (!_internal) {
const iscompareStack = [iscompare]
for (let i = 0; i < xpr.length; i++) {
let x = xpr[i]
if (typeof x === 'string') {
// IS (NOT) NULL translation when required
if (x === '=' || x === '!=') {
const left = xpr[i - 1]
const right = xpr[i + 1]
const leftType = left?.element?.type
const rightType = right?.element?.type
// Prevent HANA from throwing and unify nonsense behavior
if (left?.val === null && rightType in lobTypes) {
left.param = false // Force null to be inlined
xpr[i + 1] = { param: false, val: null } // Remove illegal type ref for compare operator
}
if (right?.val === null) {
if (
!leftType || // Literal translation when left hand type is unknown
leftType in lobTypes
) {
xpr[i] = x = x === '=' ? 'IS' : 'IS NOT'
right.param = false // Force null to be inlined
} else {
x = x === '=' ? '==' : '!='
}
}
}
// const effective = x === '=' && xpr[i + 1]?.val === null ? '==' : x
// HANA does not support comparators in all clauses (e.g. SELECT 1>0 FROM DUMMY)
// HANA does not have an 'IS' or 'IS NOT' operator
if (iscompareStack.at(-1) ? x in compareTranslations : x in expressionTranslations) {
const left = xpr[i - 1]
const right = xpr[i + 1]
const ifNull = expressionTranslations[x]
x = x === '==' ? '=' : x
const compare = [left, x, right]
const expression = {
xpr: ['CASE', 'WHEN', ...compare, 'THEN', { val: true }, 'WHEN', 'NOT', ...compare, 'THEN', { val: false }],
_internal: true,
}
if (ifNull != null) {
// If at least one of the sides is NULL it will go into ELSE
// This case checks if both sides are NULL and return their result
expression.xpr.push('ELSE', {
xpr: [
'CASE',
'WHEN',
// coalesce is used to match the left and right hand types in case one is a placeholder
...[{ func: 'COALESCE', args: [left, right] }, 'IS', 'NULL'],
'THEN',
{ val: ifNull },
'ELSE',
{ val: !ifNull },
'END',
],
_internal: true,
})
}
expression.xpr.push('END')
xpr[i - 1] = ''
xpr[i] = expression
xpr[i + 1] = iscompareStack.at(-1) ? ' = TRUE' : ''
} else {
const up = x.toUpperCase()
if (up === 'CASE') iscompareStack.push(1)
if (up === 'END') iscompareStack.pop()
if (up in logicOperators && iscompareStack.length === 1) top = true
if (up in caseOperators) {
iscompareStack[iscompareStack.length - 1] = caseOperators[up]
}
}
}
}
}
const sql = []
const iscompareStack = [iscompare]
for (let i = 0; i < xpr.length; ++i) {
const x = xpr[i]
if (typeof x === 'string') {
const up = x.toUpperCase()
if (up === 'CASE') iscompareStack.push(1)
if (up === 'END') iscompareStack.pop()
if (up in caseOperators) {
iscompareStack[iscompareStack.length - 1] = caseOperators[up]
}
sql.push(this.operator(x, i, xpr, top || iscompareStack.length > 1))
} else if (x.xpr) sql.push(`(${this.xpr(x, iscompareStack.at(-1))})`)
// default
else sql.push(this.expr(x))
}
if (iscompare) {
const suffix = this.operator('OR', xpr.length, xpr).slice(0, -3)
if (suffix) {
sql.push(suffix)