@cap-js/postgres 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 +10 -0
- package/LICENSE +201 -0
- package/README.md +5 -0
- package/cds-plugin.js +5 -0
- package/index.js +1 -0
- package/lib/PostgresService.js +404 -0
- package/lib/ReservedWords.json +4 -0
- package/lib/func.js +44 -0
- package/package.json +53 -0
package/CHANGELOG.md
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
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
|
+
|
|
8
|
+
## Version 1.0.0 - 2023-06-23
|
|
9
|
+
|
|
10
|
+
- 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,5 @@
|
|
|
1
|
+
# CDS database service for Postgres
|
|
2
|
+
|
|
3
|
+
Welcome to the new Postgres database service for [SAP Cloud Application Programming Model](https://cap.cloud.sap) Node.js, based on new, streamlined database architecture and [*pg* driver](https://www.npmjs.com/package/pg) .
|
|
4
|
+
|
|
5
|
+
Find documentation at https://cap.cloud.sap/docs/guides/databases-postgres.
|
package/cds-plugin.js
ADDED
package/index.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
module.exports = require('./lib/PostgresService.js')
|
|
@@ -0,0 +1,404 @@
|
|
|
1
|
+
const { SQLService } = require('@cap-js/db-service')
|
|
2
|
+
const { Client } = require('pg')
|
|
3
|
+
const cds = require('@sap/cds/lib')
|
|
4
|
+
const crypto = require('crypto')
|
|
5
|
+
|
|
6
|
+
class PostgresService extends SQLService {
|
|
7
|
+
init() {
|
|
8
|
+
if (!this.options.independentDeploy) {
|
|
9
|
+
// REVISIT: injects dialect into cds.deploy logic
|
|
10
|
+
cds.options = cds.options || {}
|
|
11
|
+
cds.options.dialect = 'postgres'
|
|
12
|
+
}
|
|
13
|
+
this.kind = 'postgres'
|
|
14
|
+
return super.init(...arguments)
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
get factory() {
|
|
18
|
+
return {
|
|
19
|
+
options: {
|
|
20
|
+
...this.options.pool,
|
|
21
|
+
min: 0,
|
|
22
|
+
testOnBorrow: true,
|
|
23
|
+
acquireTimeoutMillis: 1000,
|
|
24
|
+
destroyTimeoutMillis: 1000,
|
|
25
|
+
},
|
|
26
|
+
create: async () => {
|
|
27
|
+
const cr = this.options.credentials || {}
|
|
28
|
+
const credentials = {
|
|
29
|
+
// Cloud Foundry provides the user in the field username the pg npm module expects user
|
|
30
|
+
user: cr.username || cr.user,
|
|
31
|
+
password: cr.password,
|
|
32
|
+
// Special handling for:
|
|
33
|
+
// BTP - Cloud Foundry - PostgreSQL Hyperscaler Service
|
|
34
|
+
host: cr.hostname || cr.host,
|
|
35
|
+
port: cr.port || process.env.PGPORT || 5432,
|
|
36
|
+
database: cr.dbname || cr.database,
|
|
37
|
+
schema: cr.schema,
|
|
38
|
+
sslRequired: cr.sslrootcert && (cr.sslrootcert ?? true),
|
|
39
|
+
ssl: cr.sslrootcert && {
|
|
40
|
+
rejectUnauthorized: false,
|
|
41
|
+
ca: cr.sslrootcert,
|
|
42
|
+
},
|
|
43
|
+
}
|
|
44
|
+
const dbc = new Client(credentials)
|
|
45
|
+
await dbc.connect()
|
|
46
|
+
return dbc
|
|
47
|
+
},
|
|
48
|
+
destroy: dbc => dbc.end(),
|
|
49
|
+
validate: dbc => dbc.open,
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
url4() {
|
|
54
|
+
// TODO: Maybe log which database and which user? Be more robust against missing properties?
|
|
55
|
+
let { host, port } = this.options?.credentials || this.options || {}
|
|
56
|
+
return host + ':' + (port || 5432)
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
async set(variables) {
|
|
60
|
+
// REVISIT: remove when all environment variables are aligned
|
|
61
|
+
// RESTRICTIONS: 'Custom parameter names must be two or more simple identifiers separated by dots.'
|
|
62
|
+
const nameMap = {
|
|
63
|
+
'$user.id': 'CAP.APPLICATIONUSER',
|
|
64
|
+
'$user.locale': 'CAP.LOCALE',
|
|
65
|
+
'$valid.from': 'CAP.VALID_FROM',
|
|
66
|
+
'$valid.to': 'CAP.VALID_TO',
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
const env = {}
|
|
70
|
+
for (let name in variables) {
|
|
71
|
+
env[nameMap[name]] = variables[name]
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
return Promise.all([
|
|
75
|
+
(await this.prepare(`SELECT set_config(key::text,$1->>key,false) FROM json_each($1);`)).run([
|
|
76
|
+
JSON.stringify(env),
|
|
77
|
+
]),
|
|
78
|
+
...(this.options?.credentials?.schema
|
|
79
|
+
? [this.exec(`SET search_path TO "${this.options?.credentials?.schema}";`)]
|
|
80
|
+
: []),
|
|
81
|
+
|
|
82
|
+
...(!this._initalCollateCheck
|
|
83
|
+
? [
|
|
84
|
+
(await this.prepare(`SELECT collname FROM pg_collation WHERE collname = 'en_US' OR collname ='en-x-icu';`))
|
|
85
|
+
.all([])
|
|
86
|
+
.then(resp => {
|
|
87
|
+
this._initalCollateCheck = true
|
|
88
|
+
if (resp.find(row => row.collname === 'en_US')) return
|
|
89
|
+
if (resp.find(row => row.collname === 'en-x-icu'))
|
|
90
|
+
this.class.CQN2SQL.prototype.orderBy = this.class.CQN2SQL.prototype.orderByICU
|
|
91
|
+
// REVISIT throw error when there is no collated libary found
|
|
92
|
+
}),
|
|
93
|
+
]
|
|
94
|
+
: []),
|
|
95
|
+
])
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
prepare(sql) {
|
|
99
|
+
const query = {
|
|
100
|
+
text: sql,
|
|
101
|
+
// Track queries name for postgres referencing prepare statements
|
|
102
|
+
// sha1 as it needs to be less then 63 characters
|
|
103
|
+
name: crypto.createHash('sha1').update(sql).digest('hex'),
|
|
104
|
+
}
|
|
105
|
+
return {
|
|
106
|
+
run: async values => {
|
|
107
|
+
// REVISIT: SQLService provides empty values as {} for plain SQL statements - PostgreSQL driver expects array or nothing - see issue #78
|
|
108
|
+
const result = await this.dbc.query({ ...query, values: this._getValues(values) })
|
|
109
|
+
return { changes: result.rowCount }
|
|
110
|
+
},
|
|
111
|
+
get: async values => {
|
|
112
|
+
// REVISIT: SQLService provides empty values as {} for plain SQL statements - PostgreSQL driver expects array or nothing - see issue #78
|
|
113
|
+
const result = await this.dbc.query({ ...query, values: this._getValues(values) })
|
|
114
|
+
return result.rows[0]
|
|
115
|
+
},
|
|
116
|
+
all: async values => {
|
|
117
|
+
// REVISIT: SQLService provides empty values as {} for plain SQL statements - PostgreSQL driver expects array or nothing - see issue #78
|
|
118
|
+
try {
|
|
119
|
+
const result = await this.dbc.query({ ...query, values: this._getValues(values) })
|
|
120
|
+
return result.rows
|
|
121
|
+
} catch (e) {
|
|
122
|
+
throw Object.assign(e, { sql: sql + '\n' + new Array(e.position).fill(' ').join('') + '^' })
|
|
123
|
+
}
|
|
124
|
+
},
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
_getValues(values) {
|
|
129
|
+
// empty values
|
|
130
|
+
if (!values || Object.keys(values).length === 0) return null
|
|
131
|
+
// values are already in array form
|
|
132
|
+
if (Array.isArray(values)) return values
|
|
133
|
+
return values
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
async exec(sql) {
|
|
137
|
+
return this.dbc.query(sql)
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
onPlainSQL(req, next) {
|
|
141
|
+
const query = req.query
|
|
142
|
+
if (this.options.independentDeploy) {
|
|
143
|
+
// REVISIT: Should not be needed when deployment supports all types or sends CQNs
|
|
144
|
+
// Rewrite drop statements
|
|
145
|
+
if (/^DROP (TABLE|VIEW)/.test(query)) {
|
|
146
|
+
// Extracts the name from the incoming SQL statment
|
|
147
|
+
const name = query.match(/^DROP (TABLE|VIEW) IF EXISTS ("[^"]+"|[^\s;]+)/im)[2]
|
|
148
|
+
// Replaces all '_' with '.' from left to right
|
|
149
|
+
const split = name.split('_')
|
|
150
|
+
const options = split.map((_, i) => split.slice(0, i + 1).join('.') + '.' + split.slice(i + 1).join('_'))
|
|
151
|
+
// Finds the first match inside the model
|
|
152
|
+
const target = options.find(n => this.model.definitions[n])
|
|
153
|
+
// If the entity was found in the model it is dropped using CQN
|
|
154
|
+
return target && this.run(cds.ql.DROP(target))
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
// Rewrite create statements
|
|
158
|
+
if (/^CREATE (TABLE|VIEW)/.test(query)) {
|
|
159
|
+
// Extracts the name from the incoming SQL statment
|
|
160
|
+
const name = query.match(/^CREATE (TABLE|VIEW) ("[^"]+"|[^\s(]+)/im)[2]
|
|
161
|
+
// Replaces all '_' with '.' from left to right
|
|
162
|
+
const split = name.split('_')
|
|
163
|
+
const options = split.map((_, i) => split.slice(0, i + 1).join('.') + '.' + split.slice(i + 1).join('_'))
|
|
164
|
+
// Finds the first match inside the model
|
|
165
|
+
const target = options.find(n => this.model.definitions[n])
|
|
166
|
+
// If the entity was found in the model it is dropped using CQN
|
|
167
|
+
return target && this.run(cds.ql.CREATE(target))
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
// Look for ? placeholders outside of string and replace them with $n
|
|
171
|
+
if (/('|")(\1|[^\1]*?\1)|(\?)/.exec(query)?.[3]) {
|
|
172
|
+
let i = 1
|
|
173
|
+
// eslint-disable-next-line no-unused-vars
|
|
174
|
+
req.query = query.replace(/('|")(\1|[^\1]*?\1)|(\?)/g, (a, _b, _c, d, _e, _f, _g) => (d ? '$' + i++ : a))
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
return super.onPlainSQL(req, next)
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
static CQN2SQL = class CQN2Postgres extends SQLService.CQN2SQL {
|
|
181
|
+
orderBy(orderBy, localized) {
|
|
182
|
+
return orderBy.map(
|
|
183
|
+
localized
|
|
184
|
+
? c =>
|
|
185
|
+
this.expr(c) +
|
|
186
|
+
(c.element?.[this.class._localized] ? ` COLLATE "${this.context.locale}"` : '') +
|
|
187
|
+
(c.sort === 'desc' || c.sort === -1 ? ' DESC' : ' ASC')
|
|
188
|
+
: c => this.expr(c) + (c.sort === 'desc' || c.sort === -1 ? ' DESC' : ' ASC'),
|
|
189
|
+
)
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
orderByICU(orderBy, localized) {
|
|
193
|
+
return orderBy.map(
|
|
194
|
+
localized
|
|
195
|
+
? c =>
|
|
196
|
+
this.expr(c) +
|
|
197
|
+
(c.element?.[this.class._localized] ? ` COLLATE "${this.context.locale.replace('_', '-')}-x-icu"` : '') +
|
|
198
|
+
(c.sort === 'desc' || c.sort === -1 ? ' DESC' : ' ASC')
|
|
199
|
+
: c => this.expr(c) + (c.sort === 'desc' || c.sort === -1 ? ' DESC' : ' ASC'),
|
|
200
|
+
)
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
from(from) {
|
|
204
|
+
if (from.ref?.[0] === 'sqlite.schema') {
|
|
205
|
+
return '(SELECT table_name as name from information_schema.tables where table_schema = current_schema()) as schema'
|
|
206
|
+
}
|
|
207
|
+
// REVISIT: postgres always needs an alias for sub selects
|
|
208
|
+
if (from.SELECT && !from.as) from.as = from.SELECT.as || 'unknown'
|
|
209
|
+
return super.from(from)
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
// REVISIT: pg requires alias for {val}
|
|
213
|
+
SELECT_columns({ SELECT }) {
|
|
214
|
+
// REVISIT: Genres cqn has duplicate ID column
|
|
215
|
+
if (!SELECT.columns) return '*'
|
|
216
|
+
const unique = {}
|
|
217
|
+
return SELECT.columns
|
|
218
|
+
.map(x => `${this.column_expr(x)} as ${this.quote(this.column_name(x))}`)
|
|
219
|
+
.filter(x => {
|
|
220
|
+
if (unique[x]) return false
|
|
221
|
+
unique[x] = true
|
|
222
|
+
return true
|
|
223
|
+
})
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
SELECT_expand({ SELECT }, sql) {
|
|
227
|
+
if (!SELECT.columns) return sql
|
|
228
|
+
const queryAlias = this.quote(SELECT.from?.as || (SELECT.expand === 'root' && 'root'))
|
|
229
|
+
const cols = SELECT.columns.map(x => {
|
|
230
|
+
const name = this.column_name(x)
|
|
231
|
+
let col = `${this.string(name)},${this.output_converter4(x.element, queryAlias + '.' + this.quote(name))}`
|
|
232
|
+
|
|
233
|
+
if (x.SELECT?.count) {
|
|
234
|
+
// Return both the sub select and the count for @odata.count
|
|
235
|
+
const qc = cds.ql.clone(x, { columns: [{ func: 'count' }], one: 1, limit: 0, orderBy: 0 })
|
|
236
|
+
col += `, '${name}@odata.count',${this.expr(qc)}`
|
|
237
|
+
}
|
|
238
|
+
return col
|
|
239
|
+
})
|
|
240
|
+
let obj = `json_build_object(${cols})`
|
|
241
|
+
return `SELECT ${
|
|
242
|
+
SELECT.one || SELECT.expand === 'root' ? obj : `coalesce(json_agg(${obj}),'[]'::json)`
|
|
243
|
+
} as _json_ FROM (${sql}) as ${queryAlias}`
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
INSERT(q, isUpsert = false) {
|
|
247
|
+
super.INSERT(q, isUpsert)
|
|
248
|
+
|
|
249
|
+
// REVISIT: this should probably be made a bit easier to adopt
|
|
250
|
+
return (this.sql = this.sql
|
|
251
|
+
// Adjusts json path expressions to be postgres specific
|
|
252
|
+
.replace(/->>'\$(?:(?:\."(.*?)")|(?:\[(\d*)\]))'/g, (a, b, c) => (b ? `->>'${b}'` : `->>${c}`))
|
|
253
|
+
// Adjusts json function to be postgres specific
|
|
254
|
+
.replace('json_each(?)', 'json_array_elements($1)')
|
|
255
|
+
.replace(/json_type\((\w+),'\$\."(\w+)"'\)/g, (_a, b, c) => `json_typeof(${b}->'${c}')`))
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
val(val) {
|
|
259
|
+
const ret = super.val(val)
|
|
260
|
+
return ret === '?' ? `$${this.values.length}` : ret
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
operator(x) {
|
|
264
|
+
if (x === 'regexp') return '~'
|
|
265
|
+
if (x === '=') return 'is not distinct from'
|
|
266
|
+
if (x === '!=') return 'is distinct from'
|
|
267
|
+
else return x
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
defaultValue(defaultValue = this.context.timestamp.toISOString()) {
|
|
271
|
+
return this.string(`${defaultValue}`)
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
static Functions = { ...super.Functions, ...require('./func') }
|
|
275
|
+
|
|
276
|
+
static ReservedWords = { ...super.ReservedWords, ...require('./ReservedWords.json') }
|
|
277
|
+
|
|
278
|
+
static TypeMap = {
|
|
279
|
+
...super.TypeMap,
|
|
280
|
+
// REVISIT: check whether we should use native UUID support
|
|
281
|
+
UUID: () => `VARCHAR(36)`,
|
|
282
|
+
String: e => `VARCHAR(${e.length || 5000})`,
|
|
283
|
+
Binary: () => `BYTEA`,
|
|
284
|
+
Double: () => 'FLOAT8',
|
|
285
|
+
LargeString: () => 'TEXT',
|
|
286
|
+
LargeBinary: () => 'BYTEA',
|
|
287
|
+
array: () => 'TEXT',
|
|
288
|
+
Time: () => 'TIME',
|
|
289
|
+
DateTime: () => 'TIMESTAMP',
|
|
290
|
+
Timestamp: () => 'TIMESTAMP',
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
// Used for INSERT statements
|
|
294
|
+
static InputConverters = {
|
|
295
|
+
...super.InputConverters,
|
|
296
|
+
// UUID: (e) => `CAST(${e} as UUID)`, // UUID is strict in formatting sflight does not comply
|
|
297
|
+
boolean: e => `CASE ${e} WHEN 'true' THEN true WHEN 'false' THEN false END`,
|
|
298
|
+
Float: (e, t) => `CAST(${e} as decimal${t.precision && t.scale ? `(${t.precision},${t.scale})` : ''})`,
|
|
299
|
+
Decimal: (e, t) => `CAST(${e} as decimal${t.precision && t.scale ? `(${t.precision},${t.scale})` : ''})`,
|
|
300
|
+
Integer: e => `CAST(${e} as integer)`,
|
|
301
|
+
Int64: e => `CAST(${e} as bigint)`,
|
|
302
|
+
Date: e => `CAST(${e} as DATE)`,
|
|
303
|
+
Time: e => `CAST(${e} as TIME)`,
|
|
304
|
+
DateTime: e => `CAST(${e} as TIMESTAMP)`,
|
|
305
|
+
Timestamp: e => `CAST(${e} as TIMESTAMP)`,
|
|
306
|
+
// REVISIT: Remove that with upcomming fixes in cds.linked
|
|
307
|
+
Double: (e, t) => `CAST(${e} as decimal${t.precision && t.scale ? `(${t.precision},${t.scale})` : ''})`,
|
|
308
|
+
DecimalFloat: (e, t) => `CAST(${e} as decimal${t.precision && t.scale ? `(${t.precision},${t.scale})` : ''})`,
|
|
309
|
+
Binary: e => `CAST(${e} as bytea)`,
|
|
310
|
+
LargeBinary: e => `CAST(${e} as bytea)`,
|
|
311
|
+
}
|
|
312
|
+
|
|
313
|
+
static OutputConverters = {
|
|
314
|
+
...super.OutputConverters,
|
|
315
|
+
Binary: e => e,
|
|
316
|
+
LargeBinary: e => e,
|
|
317
|
+
Date: e => `to_char(${e}, 'YYYY-MM-DD')`,
|
|
318
|
+
Time: e => `to_char(${e}, 'HH24:MI:SS')`,
|
|
319
|
+
DateTime: e => `to_char(${e}, 'YYYY-MM-DD"T"HH24:MI:SS"Z"')`,
|
|
320
|
+
Timestamp: e => `to_char(${e}, 'YYYY-MM-DD"T"HH24:MI:SS.FF3"Z"')`,
|
|
321
|
+
UTCDateTime: e => `to_char(${e}, 'YYYY-MM-DD"T"HH24:MI:SS"Z"')`,
|
|
322
|
+
UTCTimestamp: e => `to_char(${e}, 'YYYY-MM-DD"T"HH24:MI:SS.FF3"Z"')`,
|
|
323
|
+
struct: e => `json(${e})`,
|
|
324
|
+
array: e => `json(${e})`,
|
|
325
|
+
}
|
|
326
|
+
}
|
|
327
|
+
|
|
328
|
+
// REVISIT: find good names database/tenant/schema/instance
|
|
329
|
+
async database({ database }) {
|
|
330
|
+
const creds = {
|
|
331
|
+
database: database,
|
|
332
|
+
usergroup: `${database}_USERS`,
|
|
333
|
+
user: `${database}_USER_MANAGER`,
|
|
334
|
+
}
|
|
335
|
+
creds.password = creds.user
|
|
336
|
+
|
|
337
|
+
const system = cds.requires.db.credentials
|
|
338
|
+
|
|
339
|
+
try {
|
|
340
|
+
const con = await this.factory.create(system)
|
|
341
|
+
this.dbc = con
|
|
342
|
+
const exists = await this.exec(`SELECT datname FROM pg_catalog.pg_database WHERE datname='${creds.database}'`)
|
|
343
|
+
|
|
344
|
+
if (exists.rowCount) return
|
|
345
|
+
// REVISIT: cleanup database for local development
|
|
346
|
+
if (!process._send) await this.exec(`DROP DATABASE IF EXISTS "${creds.database}"`)
|
|
347
|
+
await this.exec(`
|
|
348
|
+
DROP GROUP IF EXISTS "${creds.usergroup}";
|
|
349
|
+
DROP USER IF EXISTS "${creds.user}";
|
|
350
|
+
CREATE GROUP "${creds.usergroup}";
|
|
351
|
+
CREATE USER "${creds.user}" WITH CREATEROLE IN GROUP "${creds.usergroup}" PASSWORD '${creds.user}';
|
|
352
|
+
`)
|
|
353
|
+
await this.exec(`CREATE DATABASE "${creds.database}" OWNER="${creds.user}" TEMPLATE=template0`)
|
|
354
|
+
} catch (e) {
|
|
355
|
+
// Failed to reset database
|
|
356
|
+
} finally {
|
|
357
|
+
await this.dbc.end()
|
|
358
|
+
delete this.dbc
|
|
359
|
+
|
|
360
|
+
// Update credentials to new Database owner
|
|
361
|
+
await this.disconnect()
|
|
362
|
+
this.options.credentials = Object.assign({}, system, creds)
|
|
363
|
+
}
|
|
364
|
+
}
|
|
365
|
+
|
|
366
|
+
async tenant({ database, tenant }) {
|
|
367
|
+
const creds = {
|
|
368
|
+
database: database,
|
|
369
|
+
usergroup: `${database}_USERS`,
|
|
370
|
+
schema: tenant,
|
|
371
|
+
user: `${tenant}_USER`,
|
|
372
|
+
}
|
|
373
|
+
creds.password = creds.user
|
|
374
|
+
|
|
375
|
+
try {
|
|
376
|
+
await this.tx(async tx => {
|
|
377
|
+
// await tx.run(`DROP USER IF EXISTS "${creds.user}"`)
|
|
378
|
+
await tx
|
|
379
|
+
.run(`CREATE USER "${creds.user}" IN GROUP "${creds.usergroup}" PASSWORD '${creds.password}'`)
|
|
380
|
+
.catch(e => {
|
|
381
|
+
if (e.code === '42710') return
|
|
382
|
+
throw e
|
|
383
|
+
})
|
|
384
|
+
})
|
|
385
|
+
await this.tx(async tx => {
|
|
386
|
+
await tx.run(`GRANT CREATE, CONNECT ON DATABASE "${creds.database}" TO "${creds.user}";`)
|
|
387
|
+
})
|
|
388
|
+
|
|
389
|
+
// Update credentials to new Schema owner
|
|
390
|
+
await this.disconnect()
|
|
391
|
+
this.options.credentials = Object.assign({}, this.options.credentials, creds)
|
|
392
|
+
|
|
393
|
+
// Create new schema using schema owner
|
|
394
|
+
await this.tx(async tx => {
|
|
395
|
+
await tx.run(`DROP SCHEMA IF EXISTS "${creds.schema}" CASCADE`)
|
|
396
|
+
await tx.run(`CREATE SCHEMA "${creds.schema}" AUTHORIZATION "${creds.user}"`).catch(() => {})
|
|
397
|
+
})
|
|
398
|
+
} finally {
|
|
399
|
+
await this.disconnect()
|
|
400
|
+
}
|
|
401
|
+
}
|
|
402
|
+
}
|
|
403
|
+
|
|
404
|
+
module.exports = PostgresService
|
package/lib/func.js
ADDED
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
const StandardFunctions = {
|
|
2
|
+
countdistinct: x => `count(distinct ${x || '*'})`,
|
|
3
|
+
average: x => `avg(${x})`,
|
|
4
|
+
contains: (...args) => `(coalesce(strpos(${args}),0) > 0)`,
|
|
5
|
+
indexof: (x, y) => `strpos(${x},${y}) - 1`, // sqlite instr is 1 indexed
|
|
6
|
+
startswith: (x, y) => `strpos(${x},${y}) = 1`, // sqlite instr is 1 indexed
|
|
7
|
+
endswith: (x, y) => `substr(${x},length(${x}) + 1 - length(${y})) = ${y}`,
|
|
8
|
+
|
|
9
|
+
// Date and Time Functions
|
|
10
|
+
year: x => `date_part('year',(${x})::TIMESTAMP)`,
|
|
11
|
+
month: x => `date_part('month',(${x})::TIMESTAMP)`,
|
|
12
|
+
day: x => `date_part('day',(${x})::TIMESTAMP)`,
|
|
13
|
+
hour: x => `date_part('hour',(${x})::TIMESTAMP)`,
|
|
14
|
+
minute: x => `date_part('minute',(${x})::TIMESTAMP)`,
|
|
15
|
+
second: x => `date_part('second',(${x})::TIMESTAMP)`,
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
const HANAFunctions = {
|
|
19
|
+
// https://help.sap.com/docs/SAP_HANA_PLATFORM/4fe29514fd584807ac9f2a04f6754767/f12b86a6284c4aeeb449e57eb5dd3ebd.html
|
|
20
|
+
|
|
21
|
+
// Time functions
|
|
22
|
+
nano100_between: (x, y) => `EXTRACT(EPOCH FROM ${y} - ${x}) * 10000000`,
|
|
23
|
+
seconds_between: (x, y) => `EXTRACT(EPOCH FROM ${y} - ${x})`,
|
|
24
|
+
days_between: (x, y) => `EXTRACT(DAY FROM ${y} - ${x})`,
|
|
25
|
+
|
|
26
|
+
months_between: (x, y) => `((
|
|
27
|
+
(EXTRACT(YEAR FROM ${y}) - EXTRACT(YEAR FROM ${x})) * 12
|
|
28
|
+
)+(
|
|
29
|
+
EXTRACT(MONTH FROM ${y}) - EXTRACT(MONTH FROM ${x})
|
|
30
|
+
)+(
|
|
31
|
+
case when ( cast( to_char(${y},'YYYYMM') as Integer ) < cast( to_char(${x},'YYYYMM') as Integer ) ) then
|
|
32
|
+
cast((cast( to_char(${y},'DDHH24MISSFF3') as bigint ) > cast( to_char(${x},'DDHH24MISSFF3') as bigint )) as Integer)
|
|
33
|
+
else
|
|
34
|
+
cast((cast( to_char(${y},'DDHH24MISSFF3') as bigint ) < cast( to_char(${x},'DDHH24MISSFF3') as bigint )) as Integer) * -1
|
|
35
|
+
end
|
|
36
|
+
))`,
|
|
37
|
+
years_between(x, y) {
|
|
38
|
+
return `TRUNC(${this.months_between(x, y)} / 12,0)`
|
|
39
|
+
},
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
for (let each in HANAFunctions) HANAFunctions[each.toUpperCase()] = HANAFunctions[each]
|
|
43
|
+
|
|
44
|
+
module.exports = { ...StandardFunctions, ...HANAFunctions }
|
package/package.json
ADDED
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@cap-js/postgres",
|
|
3
|
+
"version": "1.0.0",
|
|
4
|
+
"description": "CDS database service for Postgres",
|
|
5
|
+
"homepage": "https://cap.cloud.sap/",
|
|
6
|
+
"keywords": [
|
|
7
|
+
"CAP",
|
|
8
|
+
"CDS",
|
|
9
|
+
"Postgres"
|
|
10
|
+
],
|
|
11
|
+
"author": "SAP SE (https://www.sap.com)",
|
|
12
|
+
"main": "index.js",
|
|
13
|
+
"files": [
|
|
14
|
+
"cds-plugin.js",
|
|
15
|
+
"lib",
|
|
16
|
+
"CHANGELOG.md"
|
|
17
|
+
],
|
|
18
|
+
"engines": {
|
|
19
|
+
"node": ">=16",
|
|
20
|
+
"npm": ">=8"
|
|
21
|
+
},
|
|
22
|
+
"scripts": {
|
|
23
|
+
"setup": "docker-compose -f pg-stack.yml up -d",
|
|
24
|
+
"test": "npm run setup && jest --silent"
|
|
25
|
+
},
|
|
26
|
+
"dependencies": {
|
|
27
|
+
"@cap-js/db-service": "^1",
|
|
28
|
+
"pg": "^8"
|
|
29
|
+
},
|
|
30
|
+
"peerDependencies": {
|
|
31
|
+
"@sap/cds": ">=7"
|
|
32
|
+
},
|
|
33
|
+
"cds": {
|
|
34
|
+
"requires": {
|
|
35
|
+
"kinds": {
|
|
36
|
+
"sql": {
|
|
37
|
+
"[production]": {
|
|
38
|
+
"kind": "postgres"
|
|
39
|
+
}
|
|
40
|
+
},
|
|
41
|
+
"postgres": {
|
|
42
|
+
"impl": "@cap-js/postgres",
|
|
43
|
+
"dialect": "postgres",
|
|
44
|
+
"vcap": {
|
|
45
|
+
"label": "postgresql-db"
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
},
|
|
49
|
+
"db": "sql"
|
|
50
|
+
}
|
|
51
|
+
},
|
|
52
|
+
"license": "SEE LICENSE"
|
|
53
|
+
}
|