-
Notifications
You must be signed in to change notification settings - Fork 14
/
Copy pathSQLiteService.js
279 lines (242 loc) · 9.23 KB
/
SQLiteService.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
const { SQLService } = require('@cap-js/db-service')
const cds = require('@sap/cds/lib')
const sqlite = require('better-sqlite3')
const $session = Symbol('dbc.session')
const convStrm = require('stream/consumers')
const { Readable } = require('stream')
class SQLiteService extends SQLService {
init() {
return super.init(...arguments)
}
get factory() {
return {
options: { max: 1, ...this.options.pool },
create: tenant => {
const database = this.url4(tenant)
const dbc = new sqlite(database)
const deterministic = { deterministic: true }
dbc.function('session_context', key => dbc[$session][key])
dbc.function('regexp', deterministic, (re, x) => (RegExp(re).test(x) ? 1 : 0))
dbc.function('ISO', deterministic, d => d && new Date(d).toISOString())
// define date and time functions in js to allow for throwing errors
const isTime = /^\d{1,2}:\d{1,2}:\d{1,2}$/
const hasTimezone = /([+-]\d{1,2}:?\d{0,2}|Z)$/
const toDate = (d, allowTime = false) => {
const date = new Date(allowTime && isTime.test(d) ? `1970-01-01T${d}Z` : hasTimezone.test(d) ? d : d + 'Z')
if (Number.isNaN(date.getTime())) throw new Error(`Value does not contain a valid ${allowTime ? 'time' : 'date'} "${d}"`)
return date
}
dbc.function('year', deterministic, d => d === null ? null : toDate(d).getUTCFullYear())
dbc.function('month', deterministic, d => d === null ? null : toDate(d).getUTCMonth() + 1)
dbc.function('day', deterministic, d => d === null ? null : toDate(d).getUTCDate())
dbc.function('hour', deterministic, d => d === null ? null : toDate(d, true).getUTCHours())
dbc.function('minute', deterministic, d => d === null ? null : toDate(d, true).getUTCMinutes())
dbc.function('second', deterministic, d => d === null ? null : toDate(d, true).getUTCSeconds())
if (!dbc.memory) dbc.pragma('journal_mode = WAL')
return dbc
},
destroy: dbc => dbc.close(),
validate: dbc => dbc.open,
}
}
url4(tenant) {
let { url, database: db = url } = this.options.credentials || this.options || {}
if (!db || db === ':memory:') return ':memory:'
if (tenant) db = db.replace(/\.(db|sqlite)$/, `-${tenant}.$1`)
return cds.utils.path.resolve(cds.root, db)
}
set(variables) {
const dbc = this.dbc || cds.error('Cannot set session context: No database connection')
if (!dbc[$session]) dbc[$session] = variables
else Object.assign(dbc[$session], variables)
}
release() {
this.dbc[$session] = undefined
return super.release()
}
prepare(sql) {
try {
const stmt = this.dbc.prepare(sql)
return {
run: (..._) => this._run(stmt, ..._),
get: (..._) => stmt.get(..._),
all: (..._) => stmt.all(..._),
stream: (..._) => this._stream(stmt, ..._),
}
} catch (e) {
e.message += ' in:\n' + (e.sql = sql)
throw e
}
}
async _run(stmt, binding_params) {
for (let i = 0; i < binding_params.length; i++) {
const val = binding_params[i]
if (val instanceof Readable) {
binding_params[i] = await convStrm[val.type === 'json' ? 'text' : 'buffer'](val)
}
if (Buffer.isBuffer(val)) {
binding_params[i] = Buffer.from(val.toString('base64'))
}
}
return stmt.run(binding_params)
}
async *_iterator(rs, one) {
// Allow for both array and iterator result sets
const first = Array.isArray(rs) ? { done: !rs[0], value: rs[0] } : rs.next()
if (first.done) return
if (one) {
yield first.value[0]
// Close result set to release database connection
rs.return()
return
}
yield '['
// Print first value as stand alone to prevent comma check inside the loop
yield first.value[0]
for (const row of rs) {
yield `,${row[0]}`
}
yield ']'
}
exec(sql) {
return this.dbc.exec(sql)
}
_prepareStreams(values) {
let any
values.forEach((v, i) => {
if (v instanceof Readable) {
any = values[i] = convStrm.buffer(v)
}
})
return any ? Promise.all(values) : values
}
async onSIMPLE({ query, data }) {
const { sql, values } = this.cqn2sql(query, data)
let ps = await this.prepare(sql)
const vals = await this._prepareStreams(values)
return (await ps.run(vals)).changes
}
onPlainSQL({ query, data }, next) {
if (typeof query === 'string') {
// REVISIT: this is a hack the target of $now might not be a timestamp or date time
// Add input converter to CURRENT_TIMESTAMP inside views using $now
if (/^CREATE VIEW.* CURRENT_TIMESTAMP[( ]/is.test(query)) {
query = query.replace(/CURRENT_TIMESTAMP/gi, "STRFTIME('%Y-%m-%dT%H:%M:%fZ','NOW')")
}
}
return super.onPlainSQL({ query, data }, next)
}
static CQN2SQL = class CQN2SQLite extends SQLService.CQN2SQL {
column_alias4(x, q) {
let alias = super.column_alias4(x, q)
if (alias) return alias
if (x.ref) {
let obm = q._orderByMap
if (!obm) {
Object.defineProperty(q, '_orderByMap', { value: (obm = {}) })
q.SELECT?.orderBy?.forEach(o => {
if (o.ref?.length === 1) obm[o.ref[0]] = o.ref[0]
})
}
return obm[x.ref.at(-1)]
}
}
val(v) {
if (Buffer.isBuffer(v.val)) v.val = v.val.toString('base64')
// intercept DateTime values and convert to Date objects to compare ISO Strings
else if (/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(.\d{1,9})?(Z|[+-]\d{2}(:?\d{2})?)$/.test(v.val)) {
const date = new Date(v.val)
if (!Number.isNaN(date.getTime())) {
v.val = date
}
}
return super.val(v)
}
// Used for INSERT statements
static InputConverters = {
...super.InputConverters,
// The following allows passing in ISO strings with non-zulu
// timezones and converts them into zulu dates and times
Date: e => `strftime('%Y-%m-%d',${e})`,
Time: e => `strftime('%H:%M:%S',${e})`,
// Both, DateTimes and Timestamps are canonicalized to ISO strings with
// ms precision to allow safe comparisons, also to query {val}s in where clauses
DateTime: e => `ISO(${e})`,
Timestamp: e => `ISO(${e})`,
}
static OutputConverters = {
...super.OutputConverters,
// Structs and arrays are stored as JSON strings; the ->'$' unwraps them.
// Otherwise they would be added as strings to json_objects.
Association: expr => `${expr}->'$'`,
struct: expr => `${expr}->'$'`,
array: expr => `${expr}->'$'`,
// SQLite has no booleans so we need to convert 0 and 1
boolean: expr => `CASE ${expr} when 1 then 'true' when 0 then 'false' END ->'$'`,
// DateTimes are returned without ms added by InputConverters
DateTime: e => `substr(${e},0,20)||'Z'`,
// Timestamps are returned with ms, as written by InputConverters.
// And as cds.builtin.classes.Timestamp inherits from DateTime we need
// to override the DateTime converter above
Timestamp: undefined,
// int64 is stored as native int64 for best comparison
// Reading int64 as string to not loose precision
Int64: expr => `CAST(${expr} as TEXT)`,
// Binary is not allowed in json objects
Binary: expr => `${expr} || ''`,
}
// Used for SQL function expressions
static Functions = { ...super.Functions, ...require('./func') }
// Used for CREATE TABLE statements
static TypeMap = {
...super.TypeMap,
Binary: e => `BINARY_BLOB(${e.length || 5000})`,
Date: () => 'DATE_TEXT',
Time: () => 'TIME_TEXT',
DateTime: () => 'DATETIME_TEXT',
Timestamp: () => 'TIMESTAMP_TEXT',
}
get is_distinct_from_() {
return 'is not'
}
get is_not_distinct_from_() {
return 'is'
}
static ReservedWords = { ...super.ReservedWords, ...require('./ReservedWords.json') }
}
// REALLY REVISIT: Here we are doing error handling which we probably never should have started.
// And worst of all, we handed out this as APIs without documenting it, so stakeholder tests rely
// on that? -> we urgently need to review these stakeholder tests.
// And we'd also need this to be implemented by each db service, and therefore documented, correct?
async onINSERT(req) {
try {
return await super.onINSERT(req)
} catch (err) {
throw _not_unique(err, 'ENTITY_ALREADY_EXISTS')
}
}
async onUPDATE(req) {
try {
return await super.onUPDATE(req)
} catch (err) {
throw _not_unique(err, 'UNIQUE_CONSTRAINT_VIOLATION')
}
}
}
// function _not_null (err) {
// if (err.code === "SQLITE_CONSTRAINT_NOTNULL") return Object.assign (err, {
// code: 'MUST_NOT_BE_NULL',
// target: /\.(.*?)$/.exec(err.message)[1], // here we are even constructing OData responses, with .target
// message: 'Value is required',
// })
// }
function _not_unique(err, code) {
if (err.message.match(/unique constraint/i))
return Object.assign(err, {
originalMessage: err.message, // FIXME: required because of next line
message: code, // FIXME: misusing message as code
code: 400, // FIXME: misusing code as (http) status
})
return err
}
module.exports = SQLiteService