@cap-js/db-service 1.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +9 -0
- package/LICENSE +201 -0
- package/README.md +5 -0
- package/index.js +4 -0
- package/lib/InsertResults.js +95 -0
- package/lib/SQLService.js +288 -0
- package/lib/common/DatabaseService.js +144 -0
- package/lib/cql-functions.js +148 -0
- package/lib/cqn2sql.js +605 -0
- package/lib/cqn4sql.js +1846 -0
- package/lib/deep-queries.js +244 -0
- package/lib/fill-in-keys.js +65 -0
- package/lib/infer/index.js +922 -0
- package/lib/infer/join-tree.js +188 -0
- package/lib/infer/pseudos.js +23 -0
- package/package.json +30 -0
package/CHANGELOG.md
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
# Change Log
|
|
2
|
+
|
|
3
|
+
- All notable changes to this project are documented in this file.
|
|
4
|
+
- The format is based on [Keep a Changelog](http://keepachangelog.com/).
|
|
5
|
+
- This project adheres to [Semantic Versioning](http://semver.org/).
|
|
6
|
+
|
|
7
|
+
## Version 1.0.0 - 2023-06-23
|
|
8
|
+
|
|
9
|
+
- Initial Release
|
package/LICENSE
ADDED
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for reasonable and customary use in describing the
|
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
|
177
|
+
|
|
178
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
179
|
+
|
|
180
|
+
To apply the Apache License to your work, attach the following
|
|
181
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
182
|
+
replaced with your own identifying information. (Don't include
|
|
183
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
184
|
+
comment syntax for the file format. We also recommend that a
|
|
185
|
+
file or class name and description of purpose be included on the
|
|
186
|
+
same "printed page" as the copyright notice for easier
|
|
187
|
+
identification within third-party archives.
|
|
188
|
+
|
|
189
|
+
Copyright [yyyy] [name of copyright owner]
|
|
190
|
+
|
|
191
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
192
|
+
you may not use this file except in compliance with the License.
|
|
193
|
+
You may obtain a copy of the License at
|
|
194
|
+
|
|
195
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
196
|
+
|
|
197
|
+
Unless required by applicable law or agreed to in writing, software
|
|
198
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
199
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
200
|
+
See the License for the specific language governing permissions and
|
|
201
|
+
limitations under the License.
|
package/README.md
ADDED
package/index.js
ADDED
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
const iterator = Symbol.iterator
|
|
2
|
+
|
|
3
|
+
// eslint-disable-next-line no-unused-vars
|
|
4
|
+
const USAGE_SAMPLE = async () => {
|
|
5
|
+
// from https://cap.cloud.sap/docs/node.js/services?q=Emily#srv-run
|
|
6
|
+
const { Authors, Books } = {}
|
|
7
|
+
const [Emily, Charlotte] = await INSERT.into(Authors, [{ name: 'Emily Brontëe' }, { name: 'Charlotte Brontëe' }])
|
|
8
|
+
await INSERT.into(Books, [
|
|
9
|
+
{ title: 'Wuthering Heights', author: Emily },
|
|
10
|
+
{ title: 'Jane Eyre', author: Charlotte },
|
|
11
|
+
])
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
module.exports = class InsertResult {
|
|
15
|
+
constructor(query, results) {
|
|
16
|
+
this.query = query
|
|
17
|
+
this.results = results
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
/*
|
|
21
|
+
* Lazy access to auto-generated keys.
|
|
22
|
+
*/
|
|
23
|
+
get [iterator]() {
|
|
24
|
+
// For INSERT.as(SELECT.from(...)) return a dummy iterator with correct length
|
|
25
|
+
const { INSERT } = this.query
|
|
26
|
+
if (INSERT.as) {
|
|
27
|
+
return (super[iterator] = function* () {
|
|
28
|
+
for (let i = 0; i < this.affectedRows; i++) yield {}
|
|
29
|
+
})
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
const { target } = this.query
|
|
33
|
+
if (!target?.keys) return (super[iterator] = this.results[iterator])
|
|
34
|
+
const keys = Object.keys(target.keys),
|
|
35
|
+
[k1] = keys
|
|
36
|
+
|
|
37
|
+
// For INSERT.entries() with generated keys in there return these keys
|
|
38
|
+
const { entries } = INSERT
|
|
39
|
+
if (entries && k1 in entries[0]) {
|
|
40
|
+
return (super[iterator] = function* () {
|
|
41
|
+
for (const each of entries)
|
|
42
|
+
yield keys.reduce((p, k) => {
|
|
43
|
+
p[k] = each[k]
|
|
44
|
+
return p
|
|
45
|
+
}, {})
|
|
46
|
+
})
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
// For INSERT.rows/values() with generated keys in there return these keys
|
|
50
|
+
const { columns } = INSERT
|
|
51
|
+
if (columns && columns.includes(k1)) {
|
|
52
|
+
return (super[iterator] = function* () {
|
|
53
|
+
const indices = keys.reduce((p, k) => {
|
|
54
|
+
let i = columns.indexOf(k)
|
|
55
|
+
if (i >= 0) p[k] = i
|
|
56
|
+
return p
|
|
57
|
+
}, {})
|
|
58
|
+
for (const each of INSERT.rows || [INSERT.values])
|
|
59
|
+
yield keys.reduce((p, k) => {
|
|
60
|
+
p[k] = each[indices[k]]
|
|
61
|
+
return p
|
|
62
|
+
}, {})
|
|
63
|
+
})
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
// If no generated keys in entries/rows/values we might have database-generated keys
|
|
67
|
+
const rows = this.results.slice(0, this.affectedRows) // only up to # of root entries
|
|
68
|
+
return (super[iterator] = function* () {
|
|
69
|
+
for (const each of rows) yield { [k1]: this.insertedRowId4(each) } // REVISIT: sqlite only returns a single lastID per row -> how is that with others?
|
|
70
|
+
})
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/*
|
|
74
|
+
* the number of inserted (root) entries or the number of affectedRows in case of INSERT into SELECT
|
|
75
|
+
*/
|
|
76
|
+
get affectedRows() {
|
|
77
|
+
const { INSERT: _ } = this.query
|
|
78
|
+
if (_.as) return (super.affectedRows = this.affectedRows4(this.results[0] || this.results))
|
|
79
|
+
else return (super.affectedRows = _.entries?.length || _.rows?.length || this.results.length || 1)
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/*
|
|
83
|
+
* for checks such as res > 2
|
|
84
|
+
*/
|
|
85
|
+
valueOf() {
|
|
86
|
+
return this.affectedRows
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
insertedRowId4(result) {
|
|
90
|
+
return result.lastID
|
|
91
|
+
}
|
|
92
|
+
affectedRows4(result) {
|
|
93
|
+
return result.changes
|
|
94
|
+
}
|
|
95
|
+
}
|
|
@@ -0,0 +1,288 @@
|
|
|
1
|
+
const cds = require('@sap/cds/lib'),
|
|
2
|
+
DEBUG = cds.debug('sql|db')
|
|
3
|
+
const { resolveView } = require('@sap/cds/libx/_runtime/common/utils/resolveView')
|
|
4
|
+
const DatabaseService = require('./common/DatabaseService')
|
|
5
|
+
const cqn4sql = require('./cqn4sql')
|
|
6
|
+
|
|
7
|
+
class SQLService extends DatabaseService {
|
|
8
|
+
init() {
|
|
9
|
+
this.on(['SELECT'], this.transformStreamFromCQN)
|
|
10
|
+
this.on(['UPDATE'], this.transformStreamIntoCQN)
|
|
11
|
+
this.on(['INSERT', 'UPSERT', 'UPDATE', 'DELETE'], require('./fill-in-keys')) // REVISIT should be replaced by correct input processing eventually
|
|
12
|
+
this.on(['INSERT', 'UPSERT', 'UPDATE', 'DELETE'], require('./deep-queries').onDeep)
|
|
13
|
+
this.on(['SELECT'], this.onSELECT)
|
|
14
|
+
this.on(['INSERT'], this.onINSERT)
|
|
15
|
+
this.on(['UPSERT'], this.onUPSERT)
|
|
16
|
+
this.on(['UPDATE'], this.onUPDATE)
|
|
17
|
+
this.on(['DELETE', 'CREATE ENTITY', 'DROP ENTITY'], this.onSIMPLE)
|
|
18
|
+
this.on(['BEGIN', 'COMMIT', 'ROLLBACK'], this.onEVENT)
|
|
19
|
+
this.on(['STREAM'], this.onSTREAM)
|
|
20
|
+
this.on(['*'], this.onPlainSQL)
|
|
21
|
+
return super.init()
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
async transformStreamFromCQN({ query }, next) {
|
|
25
|
+
if (!query._streaming) return next()
|
|
26
|
+
const cqn = STREAM.from(query.SELECT.from).column(query.SELECT.columns[0].ref[0])
|
|
27
|
+
if (query.SELECT.where) cqn.STREAM.where = query.SELECT.where
|
|
28
|
+
const stream = await this.run(cqn)
|
|
29
|
+
return stream && { value: stream }
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
async transformStreamIntoCQN({ query, data, target }, next) {
|
|
33
|
+
let col, type, etag
|
|
34
|
+
const elements = query._target?.elements || target?.elements
|
|
35
|
+
if (!elements) next()
|
|
36
|
+
for (const key in elements) {
|
|
37
|
+
const element = elements[key]
|
|
38
|
+
if (element['@Core.MediaType'] && data[key]?.pipe) col = key
|
|
39
|
+
if (element['@Core.IsMediaType'] && data[key]) type = key
|
|
40
|
+
if (element['@odata.etag'] && data[key]) etag = key
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
if (!col) return next()
|
|
44
|
+
|
|
45
|
+
const cqn = STREAM.into(query.UPDATE.entity).column(col).data(data[col])
|
|
46
|
+
if (query.UPDATE.where) cqn.STREAM.where = query.UPDATE.where
|
|
47
|
+
const result = await this.run(cqn)
|
|
48
|
+
if (type || etag) {
|
|
49
|
+
const d = { ...data }
|
|
50
|
+
delete d[col]
|
|
51
|
+
const cqn = UPDATE.entity(query.UPDATE.entity).with(d)
|
|
52
|
+
if (query.UPDATE.where) cqn.UPDATE.where = query.UPDATE.where
|
|
53
|
+
await this.run(cqn)
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
return result
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/** Handler for SELECT */
|
|
60
|
+
async onSELECT({ query, data }) {
|
|
61
|
+
// REVISIT: disable this for queries like (SELECT 1)
|
|
62
|
+
// Will return multiple rows with objects inside
|
|
63
|
+
query.SELECT.expand = 'root'
|
|
64
|
+
const { sql, values, cqn } = this.cqn2sql(query, data)
|
|
65
|
+
let ps = await this.prepare(sql)
|
|
66
|
+
let rows = await ps.all(values)
|
|
67
|
+
if (rows.length)
|
|
68
|
+
if (cqn.SELECT.expand) rows = rows.map(r => (typeof r._json_ === 'string' ? JSON.parse(r._json_) : r._json_ || r))
|
|
69
|
+
if (cqn.SELECT.count) rows.$count = await this.count(query, rows)
|
|
70
|
+
return cqn.SELECT.one || query.SELECT.from.ref?.[0].cardinality?.max === 1 ? rows[0] : rows
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
async onINSERT({ query, data }) {
|
|
74
|
+
const { sql, entries, cqn } = this.cqn2sql(query, data)
|
|
75
|
+
if (!sql) return // Do nothing when there is nothing to be done
|
|
76
|
+
const ps = await this.prepare(sql)
|
|
77
|
+
const results = entries ? await Promise.all(entries.map(e => ps.run(e))) : await ps.run()
|
|
78
|
+
return new this.class.InsertResults(cqn, results)
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
async onUPSERT({ query, data }) {
|
|
82
|
+
const { sql, entries } = this.cqn2sql(query, data)
|
|
83
|
+
if (!sql) return // Do nothing when there is nothing to be done
|
|
84
|
+
const ps = await this.prepare(sql)
|
|
85
|
+
const results = entries ? await Promise.all(entries.map(e => ps.run(e))) : await ps.run()
|
|
86
|
+
return results.reduce((lastValue, currentValue) => (lastValue += currentValue.changes), 0)
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/** Handler for UPDATE */
|
|
90
|
+
async onUPDATE(req) {
|
|
91
|
+
if (!req.query.UPDATE.data && !req.query.UPDATE.with) return 0
|
|
92
|
+
return this.onSIMPLE(req)
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/** Handler for Stream */
|
|
96
|
+
async onSTREAM(req) {
|
|
97
|
+
const { sql, values, entries } = this.cqn2sql(req.query)
|
|
98
|
+
// writing stream
|
|
99
|
+
if (req.query.STREAM.into) {
|
|
100
|
+
const stream = entries[0]
|
|
101
|
+
stream.on('error', () => stream.removeAllListeners('error'))
|
|
102
|
+
values.unshift(stream)
|
|
103
|
+
const ps = await this.prepare(sql)
|
|
104
|
+
return (await ps.run(values)).changes
|
|
105
|
+
}
|
|
106
|
+
// reading stream
|
|
107
|
+
const ps = await this.prepare(sql)
|
|
108
|
+
let result = await ps.all(values)
|
|
109
|
+
if (result.length === 0) return
|
|
110
|
+
|
|
111
|
+
return Object.values(result[0])[0]
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/** Handler for CREATE, DROP, UPDATE, DELETE, with simple CQN */
|
|
115
|
+
async onSIMPLE({ query, data }) {
|
|
116
|
+
const { sql, values } = this.cqn2sql(query, data)
|
|
117
|
+
let ps = await this.prepare(sql)
|
|
118
|
+
return (await ps.run(values)).changes
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
/** Handler for BEGIN, COMMIT, ROLLBACK, which don't have any CQN */
|
|
122
|
+
async onEVENT({ event }) {
|
|
123
|
+
DEBUG?.(event) // in the other cases above DEBUG happens in cqn2sql
|
|
124
|
+
return await this.exec(event)
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
/** Handler for SQL statements which don't have any CQN */
|
|
128
|
+
async onPlainSQL({ query, data }, next) {
|
|
129
|
+
if (typeof query === 'string') {
|
|
130
|
+
DEBUG?.(query)
|
|
131
|
+
const ps = await this.prepare(query)
|
|
132
|
+
const exec = this.hasResults(query) ? d => ps.all(d) : d => ps.run(d)
|
|
133
|
+
if (Array.isArray(data) && typeof data[0] === 'object') return await Promise.all(data.map(exec))
|
|
134
|
+
else return exec(data)
|
|
135
|
+
} else return next()
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
/** Override in subclasses to detect more statements to be called with ps.all() */
|
|
139
|
+
hasResults(sql) {
|
|
140
|
+
return /^(SELECT|WITH|CALL|PRAGMA table_info)/.test(sql)
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
/** Derives and executes a query to fill in `$count` for given query */
|
|
144
|
+
async count(query, ret) {
|
|
145
|
+
if (ret) {
|
|
146
|
+
const { one, limit: _ } = query.SELECT,
|
|
147
|
+
n = ret.length
|
|
148
|
+
const [max, offset = 0] = one ? [1] : _ ? [_.rows?.val, _.offset?.val] : []
|
|
149
|
+
if (max === undefined || (n < max && (n || !offset))) return n + offset
|
|
150
|
+
}
|
|
151
|
+
const cq = cds.ql.clone(query, {
|
|
152
|
+
columns: [{ func: 'count' }],
|
|
153
|
+
localized: false,
|
|
154
|
+
expand: false,
|
|
155
|
+
limit: 0,
|
|
156
|
+
orderBy: 0,
|
|
157
|
+
})
|
|
158
|
+
const { sql, values } = this.cqn2sql(cq)
|
|
159
|
+
const ps = await this.prepare(sql)
|
|
160
|
+
const { count } = await ps.get(values)
|
|
161
|
+
return count
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
static InsertResults = require('./InsertResults')
|
|
165
|
+
|
|
166
|
+
/**
|
|
167
|
+
* Helper class implementing {@link SQLService#cqn2sql}.
|
|
168
|
+
* Subclasses commonly override this.
|
|
169
|
+
*/
|
|
170
|
+
static CQN2SQL = require('./cqn2sql').class
|
|
171
|
+
constructor() {
|
|
172
|
+
super(...arguments)
|
|
173
|
+
this.class = new.target // for IntelliSense
|
|
174
|
+
}
|
|
175
|
+
cqn2sql(q, values) {
|
|
176
|
+
const cqn = this.cqn4sql(q)
|
|
177
|
+
|
|
178
|
+
const cmd = cqn.cmd || Object.keys(cqn)[0]
|
|
179
|
+
if (cmd in { INSERT: 1, DELETE: 1, UPSERT: 1, UPDATE: 1 }) {
|
|
180
|
+
let resolvedCqn = resolveView(cqn, this.model, this)
|
|
181
|
+
if (resolvedCqn && resolvedCqn[cmd]._transitions?.[0].target) {
|
|
182
|
+
resolvedCqn = resolvedCqn || cqn
|
|
183
|
+
resolvedCqn.target = resolvedCqn?.[cmd]._transitions[0].target || cqn.target
|
|
184
|
+
}
|
|
185
|
+
return new this.class.CQN2SQL(this.context).render(resolvedCqn, values)
|
|
186
|
+
}
|
|
187
|
+
return new this.class.CQN2SQL(this.context).render(cqn, values)
|
|
188
|
+
}
|
|
189
|
+
cqn4sql(q) {
|
|
190
|
+
// REVISIT: move this check to cqn4sql?
|
|
191
|
+
if (!q.SELECT?.from?.join && !this.model?.definitions[_target_name4(q)]) return _unquirked(q)
|
|
192
|
+
return cqn4sql(q, this.model)
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
/**
|
|
196
|
+
* Returns a Promise which resolves to a prepared statement object with
|
|
197
|
+
* `{run,get,all}` signature as specified in {@link PreparedStatement}.
|
|
198
|
+
* @returns {PreparedStatement}
|
|
199
|
+
*/
|
|
200
|
+
// eslint-disable-next-line no-unused-vars
|
|
201
|
+
async prepare(/*sql*/) {
|
|
202
|
+
throw '2b overridden by subclass'
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
/**
|
|
206
|
+
* Used to execute simple SQL statement like BEGIN, COMMIT, ROLLBACK
|
|
207
|
+
*/
|
|
208
|
+
// eslint-disable-next-line no-unused-vars
|
|
209
|
+
async exec(sql) {
|
|
210
|
+
throw '2b overridden by subclass'
|
|
211
|
+
}
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
/** Interface of prepared statement objects as returned by {@link SQLService#prepare} */
|
|
215
|
+
class PreparedStatement {
|
|
216
|
+
// eslint-disable-line no-unused-vars
|
|
217
|
+
/**
|
|
218
|
+
* Executes a prepared DML query, i.e., INSERT, UPDATE, DELETE, CREATE, DROP
|
|
219
|
+
* @param {[]|{}} binding_params
|
|
220
|
+
*/
|
|
221
|
+
async run(/*binding_params*/) {} // eslint-disable-line no-unused-vars
|
|
222
|
+
/**
|
|
223
|
+
* Executes a prepared SELECT query and returns a single/first row only
|
|
224
|
+
* @param {[]|{}} binding_params
|
|
225
|
+
*/
|
|
226
|
+
async get(/*binding_params*/) {
|
|
227
|
+
return {}
|
|
228
|
+
} // eslint-disable-line no-unused-vars
|
|
229
|
+
/**
|
|
230
|
+
* Executes a prepared SELECT query and returns an array of all rows
|
|
231
|
+
* @param {[]|{}} binding_params
|
|
232
|
+
*/
|
|
233
|
+
async all(/*binding_params*/) {
|
|
234
|
+
return [{}]
|
|
235
|
+
} // eslint-disable-line no-unused-vars
|
|
236
|
+
}
|
|
237
|
+
SQLService.prototype.PreparedStatement = PreparedStatement
|
|
238
|
+
|
|
239
|
+
const _target_name4 = q => {
|
|
240
|
+
const target =
|
|
241
|
+
q.SELECT?.from ||
|
|
242
|
+
q.INSERT?.into ||
|
|
243
|
+
q.UPSERT?.into ||
|
|
244
|
+
q.UPDATE?.entity ||
|
|
245
|
+
q.DELETE?.from ||
|
|
246
|
+
q.CREATE?.entity ||
|
|
247
|
+
q.DROP?.entity ||
|
|
248
|
+
q.STREAM?.from ||
|
|
249
|
+
q.STREAM?.into ||
|
|
250
|
+
undefined
|
|
251
|
+
if (target?.SET?.op === 'union') throw new cds.error('”UNION” based queries are not supported')
|
|
252
|
+
if (!target?.ref) return target
|
|
253
|
+
const [first] = target.ref
|
|
254
|
+
return first.id || first
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
const _unquirked = q => {
|
|
258
|
+
if (typeof q.INSERT?.into === 'string') q.INSERT.into = { ref: [q.INSERT.into] }
|
|
259
|
+
if (typeof q.UPSERT?.into === 'string') q.UPSERT.into = { ref: [q.UPSERT.into] }
|
|
260
|
+
if (typeof q.UPDATE?.entity === 'string') q.UPDATE.entity = { ref: [q.UPDATE.entity] }
|
|
261
|
+
if (typeof q.DELETE?.from === 'string') q.DELETE.from = { ref: [q.DELETE.from] }
|
|
262
|
+
if (typeof q.CREATE?.entity === 'string') q.CREATE.entity = { ref: [q.CREATE.entity] }
|
|
263
|
+
if (typeof q.DROP?.entity === 'string') q.DROP.entity = { ref: [q.DROP.entity] }
|
|
264
|
+
return q
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
const sqls = new (class extends SQLService {
|
|
268
|
+
get factory() {
|
|
269
|
+
return null
|
|
270
|
+
}
|
|
271
|
+
})()
|
|
272
|
+
cds.extend(cds.ql.Query).with(
|
|
273
|
+
class {
|
|
274
|
+
forSQL() {
|
|
275
|
+
let cqn = (cds.db || sqls).cqn4sql(this)
|
|
276
|
+
return this.flat(cqn)
|
|
277
|
+
}
|
|
278
|
+
toSQL() {
|
|
279
|
+
let { sql, values } = (cds.db || sqls).cqn2sql(this)
|
|
280
|
+
return { sql, values } // skipping .cqn property
|
|
281
|
+
}
|
|
282
|
+
toSql() {
|
|
283
|
+
return this.toSQL().sql
|
|
284
|
+
}
|
|
285
|
+
},
|
|
286
|
+
)
|
|
287
|
+
|
|
288
|
+
module.exports = Object.assign(SQLService, { _target_name4 })
|