-
Notifications
You must be signed in to change notification settings - Fork 25
Expand file tree
/
Copy pathSQLiteService.js
More file actions
322 lines (284 loc) · 10.6 KB
/
SQLiteService.js
File metadata and controls
322 lines (284 loc) · 10.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
const { SQLService } = require('@cap-js/db-service')
const cds = require('@sap/cds/lib')
let sqlite // sqlite driver is loaded on connect
const $session = Symbol('dbc.session')
const sessionVariableMap = require('./session.json') // Adjust the path as necessary for your project
const convStrm = require('stream/consumers')
const { Readable } = require('stream')
const keywords = cds.compiler.to.sql.sqlite.keywords
// keywords come as array
const sqliteKeywords = keywords.reduce((prev, curr) => {
prev[curr] = 1
return prev
}, {})
// 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
}
class SQLiteService extends SQLService {
get factory() {
return {
options: this.options.pool || {},
create: async tenant => {
if (!sqlite) loadSQLite(this.options.driver || this.options.credentials?.driver)
const database = this.url4(tenant)
const dbc = new sqlite(database, this.options.client || {})
await dbc.ready
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())
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 (database !== ':memory:') dbc.pragma?.('journal_mode = WAL') || dbc.exec('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')
// Enrich provided session context with aliases
for (const alias in sessionVariableMap) {
const name = sessionVariableMap[alias]
if (variables[name]) variables[alias] = variables[name]
}
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._allStream(stmt, ..._),
}
} catch (e) {
e.message += ' in:\n' + (e.query = 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 *_iteratorRaw(rs, one) {
const pageSize = (1 << 16)
// 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
}
let buffer = '[' + first.value[0]
// Print first value as stand alone to prevent comma check inside the loop
for (const row of rs) {
buffer += `,${row[0]}`
if (buffer.length > pageSize) {
yield buffer
buffer = ''
}
}
buffer += ']'
yield buffer
}
async *_iteratorObjectMode(rs) {
for (const row of rs) {
yield JSON.parse(row[0])
}
}
async _allStream(stmt, binding_params, one, objectMode) {
stmt = stmt.iterate ? stmt : stmt.__proto__
stmt.raw?.(true)
const rs = stmt.iterate(binding_params)
const stream = Readable.from(objectMode ? this._iteratorObjectMode(rs) : this._iteratorRaw(rs, one), { objectMode })
const close = () => rs.return() // finish result set when closed early
stream.on('error', close)
stream.on('close', close)
return stream
}
pragma(pragma, options) {
if (!this.dbc) return this.begin('pragma').then(tx => {
try { return tx.pragma(pragma, options) }
finally { tx.release() }
})
return this.dbc.pragma(pragma, options)
}
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 (typeof v.val === 'boolean') v.val = v.val ? 1 : 0
else 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)
}
forUpdate() {
return ''
}
forShareLock() {
return ''
}
// 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 => e === '?' ? e : `strftime('%Y-%m-%d',${e})`,
Time: e => e === '?' ? 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 => e === '?' ? e : `ISO(${e})`,
Timestamp: e => e === '?' ? 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:
cds.env.features.sql_simple_queries === 2
? undefined
: 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: cds.env.features.ieee754compatible ? expr => `CAST(${expr} as TEXT)` : undefined,
// REVISIT: always cast to string in next major
// Reading decimal as string to not loose precision
Decimal: cds.env.features.ieee754compatible ? (expr, elem) => elem?.scale
? `CASE WHEN ${expr} IS NULL THEN NULL ELSE format('%.${elem.scale}f', ${expr}) END`
: `CAST(${expr} as TEXT)`
: undefined,
// Binary is not allowed in json objects
Binary: expr => `${expr} || ''`,
}
// Used for SQL function expressions
static Functions = { ...super.Functions, ...require('./cql-functions') }
// 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',
Map: () => 'JSON_TEXT'
}
get is_distinct_from_() {
return 'is not'
}
get is_not_distinct_from_() {
return 'is'
}
static ReservedWords = { ...super.ReservedWords, ...sqliteKeywords }
}
}
function loadSQLite(driver) {
const drivers = {
node: './node-sqlite.js',
'better-sqlite3': 'better-sqlite3',
'sql.js': './sql.js.js',
}
if (driver) {
sqlite = require(drivers[driver])
return
}
try {
sqlite = require(drivers['better-sqlite3'])
} catch {
try {
sqlite = require(drivers.node)
} catch {
// When failing to load better-sqlite3 it fallsback to sql.js (wasm version of sqlite)
sqlite = require(drivers['sql.js'])
}
}
}
module.exports = SQLiteService