@cap-js/sqlite 0.1.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 +189 -0
- package/cds.js +39 -0
- package/index.js +1 -0
- package/lib/db/DatabaseService.js +101 -0
- package/lib/db/sql/InsertResults.js +87 -0
- package/lib/db/sql/SQLService.js +223 -0
- package/lib/db/sql/copy.js +17 -0
- package/lib/db/sql/cqn2sql.js +515 -0
- package/lib/db/sql/cqn4sql.js +1461 -0
- package/lib/db/sql/deep.js +233 -0
- package/lib/db/sql/func.js +146 -0
- package/lib/db/sql/structuralComparisonOps.js +16 -0
- package/lib/db/sql/utils.js +22 -0
- package/lib/db/sql/workarounds.js +73 -0
- package/lib/db/sqlite/ReservedWords.json +149 -0
- package/lib/db/sqlite/SQLiteService.js +170 -0
- package/lib/ql/cds.infer.js +786 -0
- package/lib/ql/join-tree.js +167 -0
- package/lib/ql/pseudos.js +23 -0
- package/package.json +52 -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 0.1.0 - 2023-04-04
|
|
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
|
@@ -0,0 +1,189 @@
|
|
|
1
|
+
# CDS database service for SQLite
|
|
2
|
+
|
|
3
|
+
Welcome to the new SQLite database service for [SAP Cloud Application Programming Model](https://cap.cloud.sap) Node.js, based on new, streamlined database architecture and [*better-sqlite* driver](https://www.npmjs.com/package/better-sqlite3) .
|
|
4
|
+
|
|
5
|
+
> ⚠️ _**WARNING:** This package is in a beta state._ ⚠️
|
|
6
|
+
>
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
## Installing
|
|
10
|
+
|
|
11
|
+
### Add `@cap-js/sqlite` as package dependency
|
|
12
|
+
|
|
13
|
+
As SQLite is commonly used during development or tests only, add it as a dev dependency like so:
|
|
14
|
+
|
|
15
|
+
```sh
|
|
16
|
+
npm add @cap-js/sqlite -D
|
|
17
|
+
```
|
|
18
|
+
|
|
19
|
+
> **Note:** There's no need to add the [*better-sqlite*](https://www.npmjs.com/package/better-sqlite3) driver, and it's also not recommended anymore to do so, as that is done transiently.
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
### Remove `sqlite3` package dependency
|
|
23
|
+
|
|
24
|
+
If migrating an existing project you may want to remove the old [*sqlite3* driver](https://www.npmjs.com/package/sqlite3) :
|
|
25
|
+
|
|
26
|
+
```sh
|
|
27
|
+
npm rm sqlite3
|
|
28
|
+
```
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
## Usage
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
### Via `@cap-js/sqlite` in package dependencies
|
|
35
|
+
|
|
36
|
+
Adding `@cap-js/sqlite` to your package dependencies as described above is all you need to do. We'll automatically use the new service if that dependency is there in
|
|
37
|
+
`dependencies` or in `devDependencies`. Your configuration can stay as is, e.g.:
|
|
38
|
+
|
|
39
|
+
```jsonc
|
|
40
|
+
{ ...,
|
|
41
|
+
"cds": {
|
|
42
|
+
"requires": {
|
|
43
|
+
"db": "sql"
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
```
|
|
48
|
+
|
|
49
|
+
> **Note:** This automatically also enables the new, lean draft implementation that's required for the new database services, i.e., `cds.fiori.lean_draft` will be automatically set to `true`.
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
### Via `better-sqlite` config profile
|
|
53
|
+
|
|
54
|
+
Alternatively, if you don't have `@cap-js/sqlite` in your package dependencies, but installed in an outer monorepo like in *[cap/samples](https://github.com/sap-samples/cloud-cap-samples)*, you can occasionally run or test your apps with the `better-sqlite` profile using one of these options to specify the profile:
|
|
55
|
+
|
|
56
|
+
```sh
|
|
57
|
+
cds watch bookshop --profile better-sqlite
|
|
58
|
+
```
|
|
59
|
+
```sh
|
|
60
|
+
CDS_ENV=better-sqlite cds watch bookshop
|
|
61
|
+
```
|
|
62
|
+
```sh
|
|
63
|
+
CDS_ENV=better-sqlite jest --silent
|
|
64
|
+
```
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
## New Features & Improvements
|
|
69
|
+
|
|
70
|
+
### Full Support for Path Expressions
|
|
71
|
+
|
|
72
|
+
The new SQLite service provides full support for all kinds of [path expressions](https://cap.cloud.sap/docs/cds/cql#path-expressions), including [infix filters](https://cap.cloud.sap/docs/cds/cql#with-infix-filters), and [exists predicates](https://cap.cloud.sap/docs/cds/cql#exists-predicate). For example, you can try this out with *[cap/samples](https://github.com/sap-samples/cloud-cap-samples)* as follows:
|
|
73
|
+
|
|
74
|
+
```sh
|
|
75
|
+
cds repl --profile better-sqlite
|
|
76
|
+
var { server } = await cds.test('bookshop')
|
|
77
|
+
var { Books, Authors } = cds.entities
|
|
78
|
+
await INSERT.into (Books) .entries ({ title: 'Unwritten Book' })
|
|
79
|
+
await INSERT.into (Authors) .entries ({ name: 'Upcomming Author' })
|
|
80
|
+
await SELECT `from ${Books} { title as book, author.name as author, genre.name as genre }`
|
|
81
|
+
await SELECT `from ${Authors} { books.title as book, name as author, books.genre.name as genre }`
|
|
82
|
+
await SELECT `from ${Books} { title as book, author[ID<170].name as author, genre.name as genre }`
|
|
83
|
+
await SELECT `from ${Books} { title as book, author.name as author, genre.name as genre }` .where ({'author.name':{like:'Ed%'},or:{'author.ID':170}})
|
|
84
|
+
await SELECT `from ${Books} { title as book, author.name as author, genre.name as genre } where author.name like 'Ed%' or author.ID=170`
|
|
85
|
+
await SELECT `from ${Books}:author[name like 'Ed%' or ID=170] { books.title as book, name as author, books.genre.name as genre }`
|
|
86
|
+
await SELECT `from ${Books}:author[150] { books.title as book, name as author, books.genre.name as genre }`
|
|
87
|
+
await SELECT `from ${Authors} { ID, name, books { ID, title }}`
|
|
88
|
+
await SELECT `from ${Authors} { ID, name, books { ID, title, genre { ID, name }}}`
|
|
89
|
+
await SELECT `from ${Authors} { ID, name, books.genre { ID, name }}`
|
|
90
|
+
await SELECT `from ${Authors} { ID, name, books as some_books { ID, title, genre.name as genre }}`
|
|
91
|
+
await SELECT `from ${Authors} { ID, name, books[genre.ID=11] as dramatic_books { ID, title, genre.name as genre }}`
|
|
92
|
+
await SELECT `from ${Authors} { ID, name, books.genre[name!='Drama'] as no_drama_books_count { count(*) as sum }}`
|
|
93
|
+
await SELECT `from ${Authors} { books.genre.ID }`
|
|
94
|
+
await SELECT `from ${Authors} { books.genre }`
|
|
95
|
+
await SELECT `from ${Authors} { books.genre.name }`
|
|
96
|
+
|
|
97
|
+
```
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
### Specified Standard Functions
|
|
102
|
+
|
|
103
|
+
A specified set of standard functions is now supported and translated to database-specific variants. These functions are by and large the same as specified in OData:
|
|
104
|
+
|
|
105
|
+
* `concat`, `indexof`, `length`
|
|
106
|
+
* `contains`, `startswith`, `endswith`, `substring`, `matchesPattern`
|
|
107
|
+
* `tolower`, `toupper`
|
|
108
|
+
* `ceiling`
|
|
109
|
+
* `year`, `month`, `day`, `hour`, `minute`, `second`
|
|
110
|
+
|
|
111
|
+
The db service implementation translates these to the best-possible native SQL functions, thus enhancing the extend of **portable** queries.
|
|
112
|
+
|
|
113
|
+
> **Note** that usage is **case-sensitive**, which means you have to write these functions exactly as given above; all-uppercase usages are not supported.
|
|
114
|
+
|
|
115
|
+
### Support for Common HANA Functions
|
|
116
|
+
|
|
117
|
+
In addition to the standard functions, which all new database services will support, the new SQLite service also supports these common HANA functions, to further increase the scope for portable testing:
|
|
118
|
+
|
|
119
|
+
- `years_between`
|
|
120
|
+
- `months_between`
|
|
121
|
+
- `days_between`
|
|
122
|
+
- `seconds_between`
|
|
123
|
+
- `nano100_between`
|
|
124
|
+
|
|
125
|
+
> Both usages are allowed here: all-lowercase as given above, as well as all-uppercase.
|
|
126
|
+
|
|
127
|
+
### Support for Session Context Variables
|
|
128
|
+
|
|
129
|
+
The new SQLite service can leverage [*better-sqlite*](https://www.npmjs.com/package/better-sqlite3)'s user-defined functions to support *session context* variables. In particular, the pseudo variables `$user.id`, `$user.locale`, `$valid.from`, and `$valid.to` are available in native SQL queries like so:
|
|
130
|
+
|
|
131
|
+
```sql
|
|
132
|
+
SELECT session_context('$user.id')
|
|
133
|
+
SELECT session_context('$user.locale')
|
|
134
|
+
SELECT session_context('$valid.from')
|
|
135
|
+
SELECT session_context('$valid.to')
|
|
136
|
+
```
|
|
137
|
+
|
|
138
|
+
Amongst other, this allows us to get rid of static helper views for localized data like `localized_de_sap_capire_Books`.
|
|
139
|
+
|
|
140
|
+
### Deep Reads via Single Queries
|
|
141
|
+
|
|
142
|
+
The old database service implementation(s) translated deep reads, i.e., SELECTs with expands, into several database queries and collected the individual results into deep result structures. The new service uses `json_object` functions and alike to instead do that in one single query, with sub selects, which greatly improves performance.
|
|
143
|
+
|
|
144
|
+
### New `SELECT.localized` Queries
|
|
145
|
+
|
|
146
|
+
With the old implementation when running queries like `SELECT.from(Books)` would always return localized data, without being able to easily read the non-localized data. The new service does only what you asked for, offering new `SELECT.localized` options:
|
|
147
|
+
|
|
148
|
+
```js
|
|
149
|
+
let books = await SELECT.from(Books) //> non-localized data
|
|
150
|
+
let lbooks = await SELECT.localized(Books) //> localized data
|
|
151
|
+
```
|
|
152
|
+
|
|
153
|
+
Usage variants include:
|
|
154
|
+
|
|
155
|
+
```js
|
|
156
|
+
SELECT.localized(Books)
|
|
157
|
+
SELECT.from.localized(Books)
|
|
158
|
+
SELECT.one.localized(Books)
|
|
159
|
+
```
|
|
160
|
+
|
|
161
|
+
> **Note:** Queries executed through generic application service handlers continue to serve localized data as before.
|
|
162
|
+
|
|
163
|
+
### Using Lean Draft Implementation
|
|
164
|
+
|
|
165
|
+
The old implementation was overly polluted with draft handling. But as draft is actually a Fiori UI concept, that should not be the case. Hence, we eliminated all draft handling from the new database service implementations, and implemented draft in a modular, non-intrusive way — called *'Lean Draft'*. The most important change is that we don't do expensive UNIONs anymore but work with single cheap selects.
|
|
166
|
+
|
|
167
|
+
When using the new SQLite service the new `cds.fiori.lean_draft` mode is automatically switched on. You may additionally switch on `cds.fiori_draft_compat` in case you run into problems.
|
|
168
|
+
|
|
169
|
+
More detailed documentation for that will follow soon.
|
|
170
|
+
|
|
171
|
+
### Performance Improvements
|
|
172
|
+
|
|
173
|
+
The combination of the above-mentioned improvements commonly leads to significant performance improvements. For example displaying the list page of Travels in [cap/sflight](https://github.com/SAP-samples/cap-sflight) took **>250ms** in the past, and **~15ms** now.
|
|
174
|
+
|
|
175
|
+
## Known Limitations & Changes
|
|
176
|
+
|
|
177
|
+
- Node v14 is no longer supported → will be dropped anyways with upcomming cds7.
|
|
178
|
+
- JOINs and UNIONs by CQN are no longer supported → use plain SQL instead.
|
|
179
|
+
* CQNs with subqueries require table aliases to refer to elements of outer queries.
|
|
180
|
+
* CQNs with an empty columns array now throws an error.
|
|
181
|
+
* Search: only single values are allowed as search expression.
|
|
182
|
+
* CSV input: column names like `author.ID` are disallowed → use `author_ID` instead.
|
|
183
|
+
* No `default` values are returned anymore for `virtual` elements.
|
|
184
|
+
* `SELECT.from(...)` queries on database level don't return localized data anymore → use `SELECT.localized(...)`
|
|
185
|
+
* Standard functions in CQN are case-sensitive → don't uppercase them.
|
|
186
|
+
* For `@cds.on.insert/update`annotations only `$now` and `$user.id` are supported.
|
|
187
|
+
* The `cds/db.stream()` methods are not implemented yet → will come soon.
|
|
188
|
+
|
|
189
|
+
_The list of important changes is not final and will be constantly updated._
|
package/cds.js
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
const cds = module.exports = require('@sap/cds/lib')
|
|
2
|
+
const { extend, lazified } = cds
|
|
3
|
+
|
|
4
|
+
extend(cds).with(lazified({
|
|
5
|
+
inferred: lazy => require('./lib/ql/cds.infer'),
|
|
6
|
+
cqn2sql: lazy => require('./lib/db/sql/cqn2sql'),
|
|
7
|
+
cqn4sql: lazy => require('./lib/db/sql/cqn4sql'),
|
|
8
|
+
}))
|
|
9
|
+
|
|
10
|
+
extend (cds.ql.Query) .with (class {
|
|
11
|
+
forSQL (db = cds.db || cds) { return this.flat(db.cqn4sql(this)) }
|
|
12
|
+
toSQL (db = cds.db || cds) { return _2sql(db.cqn2sql(this)) }
|
|
13
|
+
toSql (db = cds.db || cds) { return this.toSQL(db).sql }
|
|
14
|
+
})
|
|
15
|
+
|
|
16
|
+
// Monkey-patch req.event to be undefined for plain sql query strings -> remove when @sap/cds 6.6 is released
|
|
17
|
+
const $super = Reflect.getOwnPropertyDescriptor(cds.Request.prototype,'event')
|
|
18
|
+
Reflect.defineProperty (cds.Request.prototype,'event', {...$super, get(){
|
|
19
|
+
if (typeof this.query === 'string') return this._set ('event', undefined)
|
|
20
|
+
else return $super.get.call(this)
|
|
21
|
+
}})
|
|
22
|
+
|
|
23
|
+
// skip .cqn property when in repl
|
|
24
|
+
const _2sql = cds.repl ? ({sql,values}) => ({sql,values}) : x => x
|
|
25
|
+
|
|
26
|
+
cds.ApplicationService // FIXME: somehow we need to invoke the getter, must be removed in the future
|
|
27
|
+
|
|
28
|
+
// cds.requires.kinds.postgres = {
|
|
29
|
+
// kind: 'postgres',
|
|
30
|
+
// dialect: 'plain',
|
|
31
|
+
// credentials: {
|
|
32
|
+
// "host": "localhost",
|
|
33
|
+
// "port": "5432",
|
|
34
|
+
// "database": "beershop", //> override per test
|
|
35
|
+
// "username": "postgres",
|
|
36
|
+
// "password": "postgres"
|
|
37
|
+
// },
|
|
38
|
+
// impl: __dirname + '/lib/db/pg'
|
|
39
|
+
// }
|
package/index.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
module.exports = require('./lib/db/sqlite/SQLiteService.js')
|
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
const cds = require('../../cds')
|
|
2
|
+
|
|
3
|
+
function Pool (factory, tenant) { return createPool (
|
|
4
|
+
{ __proto__:factory, create: factory.create.bind(undefined,tenant) },
|
|
5
|
+
factory.options
|
|
6
|
+
)}
|
|
7
|
+
const { createPool } = require('@sap/cds-foss').pool
|
|
8
|
+
|
|
9
|
+
class DatabaseService extends cds.Service {
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* Return a pool factory + options property as expected by
|
|
13
|
+
* https://github.com/coopernurse/node-pool#createpool.
|
|
14
|
+
*/
|
|
15
|
+
get factory(){ throw '2b overriden in subclass' }
|
|
16
|
+
pools = { _factory: this.factory }
|
|
17
|
+
|
|
18
|
+
get isMultitenant() { return (
|
|
19
|
+
'multiTenant' in this.options ? this.options.multiTenant
|
|
20
|
+
: cds.env.requires.multitenancy
|
|
21
|
+
)}
|
|
22
|
+
|
|
23
|
+
/**
|
|
24
|
+
* Set one or more session context variables like so:
|
|
25
|
+
* ```js
|
|
26
|
+
* const tx = cds.db.tx()
|
|
27
|
+
* tx.set({
|
|
28
|
+
* '$user.name': 'Alice',
|
|
29
|
+
* '$user.role': 'admin'
|
|
30
|
+
* })
|
|
31
|
+
* ```
|
|
32
|
+
*/
|
|
33
|
+
// eslint-disable-next-line no-unused-vars
|
|
34
|
+
set (variables) { throw '2b overridden by subclass' }
|
|
35
|
+
|
|
36
|
+
infer (q, m = this.model) {
|
|
37
|
+
return cds.inferred(q,m)
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
async begin() {
|
|
41
|
+
const ctx = this.context; if (!ctx) return this.tx().begin()
|
|
42
|
+
const tenant = this.isMultitenant && ctx.tenant
|
|
43
|
+
const pool = this.pools[tenant] ??= new Pool (this.pools._factory, tenant)
|
|
44
|
+
const dbc = this.dbc = await pool.acquire()
|
|
45
|
+
this._release = (dbc) => pool.release(dbc)
|
|
46
|
+
// Setting session context variables
|
|
47
|
+
await this.set({
|
|
48
|
+
get '$user.id'(){ return _set (this, '$user.id', ctx.user?.id || 'anonymous') },
|
|
49
|
+
get '$user.locale'(){ return _set (this, '$user.locale', ctx.locale || cds.env.i18n.default_language) },
|
|
50
|
+
get '$valid.from'(){ return _set (this, '$valid.from', ctx._?.['VALID-FROM'] || ctx._?.['VALID-AT'] || '1970-01-01T00:00:00Z') },
|
|
51
|
+
get '$valid.to'(){ return _set (this, '$valid.to', ctx._?.['VALID-TO'] || _validTo4(ctx._?.['VALID-AT']) || '9999-11-11T22:22:22Z') },
|
|
52
|
+
})
|
|
53
|
+
// Run BEGIN
|
|
54
|
+
try { await this.send('BEGIN') }
|
|
55
|
+
catch (e) { this._release(dbc); throw e }
|
|
56
|
+
return this
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
async commit() {
|
|
60
|
+
const dbc = this.dbc; if (!dbc) return
|
|
61
|
+
await this.send('COMMIT')
|
|
62
|
+
this._release(dbc) // only release on successful commit as otherwise released on rollback
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
async rollback() {
|
|
66
|
+
const dbc = this.dbc; if (!dbc) return
|
|
67
|
+
try { await this.send('ROLLBACK') }
|
|
68
|
+
finally { this._release(dbc) }
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
// REVISIT: should happen automatically after a configurable time
|
|
72
|
+
async disconnect (tenant) {
|
|
73
|
+
const pool = this.pools[tenant]
|
|
74
|
+
if (pool) delete this.pools[tenant]; else return
|
|
75
|
+
await pool.drain()
|
|
76
|
+
await pool.clear()
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
run (query, data, ...etc) {
|
|
80
|
+
// Allow db.run('...',1,2,3,4)
|
|
81
|
+
if (data !== undefined && typeof query === 'string' && typeof data !== 'object') data = [ data, ...etc ]
|
|
82
|
+
return super.run (query, data)
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
url4 (tenant) { // eslint-disable-line no-unused-vars
|
|
86
|
+
let { url } = this.options?.credentials || this.options || {}
|
|
87
|
+
return url
|
|
88
|
+
}
|
|
89
|
+
getDbUrl (tenant) { return this.url4 (tenant) } // REVISIT: Remove after cds v6.7
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
const _set = (context, variable, value) => {
|
|
93
|
+
Object.defineProperty (context, variable, { value, configurable:true })
|
|
94
|
+
return value
|
|
95
|
+
}
|
|
96
|
+
const _validTo4 = validAt => {
|
|
97
|
+
return validAt?.replace(/(\dZ?)$/,d=>parseInt(d[0])+1+d[1]||'')
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
DatabaseService.prototype.isDatabaseService = true
|
|
101
|
+
module.exports = DatabaseService
|
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
const iterator = Symbol.iterator
|
|
2
|
+
|
|
3
|
+
// eslint-disable-next-line no-unused-vars
|
|
4
|
+
const USAGE_SAMPLE = async ()=>{ // from https://pages.github.tools.sap/cap/docs/node.js/services?q=Emily#srvrun--query--results
|
|
5
|
+
const { Authors, Books } = {}
|
|
6
|
+
const [ Emily, Charlotte ] = await INSERT.into (Authors, [
|
|
7
|
+
{ name: 'Emily Brontëe' },
|
|
8
|
+
{ name: 'Charlotte Brontëe' },
|
|
9
|
+
])
|
|
10
|
+
await INSERT.into (Books, [
|
|
11
|
+
{ title: 'Wuthering Heights', author: Emily },
|
|
12
|
+
{ title: 'Jane Eyre', author: Charlotte },
|
|
13
|
+
])
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
module.exports = class InsertResult {
|
|
18
|
+
|
|
19
|
+
constructor (query, results) {
|
|
20
|
+
this.query = query
|
|
21
|
+
this.results = results
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/*
|
|
25
|
+
* Lazy access to auto-generated keys.
|
|
26
|
+
*/
|
|
27
|
+
get [iterator]() {
|
|
28
|
+
|
|
29
|
+
// For INSERT.as(SELECT.from(...)) return a dummy iterator with correct length
|
|
30
|
+
const { INSERT } = this.query
|
|
31
|
+
if (INSERT.as) {
|
|
32
|
+
return super[iterator] = function*(){
|
|
33
|
+
for (let i = 0; i < this.affectedRows; i++) yield {}
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
const { target } = this.query; if (!target?.keys) return (super[iterator] = this.results[iterator])
|
|
38
|
+
const keys = Object.keys(target.keys), [k1] = keys
|
|
39
|
+
|
|
40
|
+
// For INSERT.entries() with generated keys in there return these keys
|
|
41
|
+
const { entries } = INSERT; if (entries && k1 in entries[0]) {
|
|
42
|
+
return super[iterator] = function*(){
|
|
43
|
+
for (const each of entries)
|
|
44
|
+
yield keys.reduce ((p,k) => { p[k] = each[k]; return p },{})
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
// For INSERT.rows/values() with generated keys in there return these keys
|
|
49
|
+
const { columns } = INSERT; if (columns && columns.includes(k1)) {
|
|
50
|
+
return super[iterator] = function*(){
|
|
51
|
+
const indices = keys.reduce ((p,k) => {
|
|
52
|
+
let i = columns.indexOf(k); if (i >= 0) p[k] = i
|
|
53
|
+
return p
|
|
54
|
+
},{})
|
|
55
|
+
for (const each of INSERT.rows || [INSERT.values])
|
|
56
|
+
yield keys.reduce ((p,k) => { p[k] = each[indices[k]]; return p },{})
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
// If no generated keys in entries/rows/values we might have database-generated keys
|
|
61
|
+
const rows = this.results.slice(0, this.affectedRows) // only up to # of root entries
|
|
62
|
+
return super[iterator] = function*(){
|
|
63
|
+
for (const each of rows)
|
|
64
|
+
yield { [k1]: this.insertedRowId4(each) } // REVISIT: sqlite only returns a single lastID per row -> how is that with others?
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/*
|
|
69
|
+
* the number of inserted (root) entries or the number of affectedRows in case of INSERT into SELECT
|
|
70
|
+
*/
|
|
71
|
+
get affectedRows() {
|
|
72
|
+
const { INSERT:_ } = this.query
|
|
73
|
+
if (_.as) return super.affectedRows = this.affectedRows4(this.results[0]|| this.results)
|
|
74
|
+
else return super.affectedRows = _.entries?.length || _.rows?.length || this.results.length || 1
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/*
|
|
78
|
+
* for checks such as res > 2
|
|
79
|
+
*/
|
|
80
|
+
valueOf() {
|
|
81
|
+
return this.affectedRows
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
insertedRowId4 (result) { return result.lastID }
|
|
85
|
+
affectedRows4 (result) { return result.changes }
|
|
86
|
+
|
|
87
|
+
}
|