@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.
@@ -0,0 +1,170 @@
1
+ const SQLService = require('../sql/SQLService')
2
+ const sqlite = require('better-sqlite3')
3
+ const cds = require ('@sap/cds/lib')
4
+ const $session = Symbol('dbc.session')
5
+ const { Readable } = require('stream')
6
+
7
+ class SQLiteService extends SQLService {
8
+
9
+ get factory() { return {
10
+ options: { max:1, ...this.options.pool },
11
+ create: tenant => {
12
+ const database = this.url4(tenant)
13
+ const dbc = new sqlite (database)
14
+ dbc.function('SESSION_CONTEXT', key => dbc[$session][key])
15
+ dbc.function('REGEXP', { deterministic: true }, (re, x) => (RegExp(re).test(x) ? 1 : 0))
16
+ if (!dbc.memory) dbc.pragma('journal_mode = WAL')
17
+ return dbc
18
+ },
19
+ destroy: dbc => dbc.close(),
20
+ validate: dbc => dbc.open,
21
+ }}
22
+
23
+ url4 (tenant) {
24
+ let { url, database:db = url } = this.options.credentials || this.options || {}
25
+ if (!db || db === ':memory:') return ':memory:'
26
+ if (tenant) db = db.replace(/\.(db|sqlite)$/, `-${tenant}.$1`)
27
+ return cds.utils.path.resolve (cds.root, db)
28
+ }
29
+
30
+
31
+ set (variables) {
32
+ const dbc = this.dbc || cds.error ('Cannot set session context: No database connection')
33
+ if (!dbc[$session]) {
34
+ dbc[$session] = variables // initial call from within this.begin()
35
+ const $super = this._release; this._release = function (dbc) { // reset session on release
36
+ delete dbc[$session]
37
+ return $super.call(this,dbc)
38
+ }
39
+ }
40
+ else Object.assign (dbc[$session], variables) // subsequent uses from custom code
41
+ }
42
+
43
+ prepare (sql) {
44
+ try {
45
+ return this.dbc.prepare(sql)
46
+ } catch (e) {
47
+ e.message += ' in:\n'+ (e.sql = sql)
48
+ throw e
49
+ }
50
+ }
51
+
52
+ exec (sql) {
53
+ return this.dbc.exec(sql)
54
+ }
55
+
56
+ static CQN2SQL = class CQN2SQLite extends SQLService.CQN2SQL {
57
+
58
+ SELECT_columns({SELECT}) {
59
+ if (!SELECT.columns) return '*'
60
+ const { orderBy } = SELECT
61
+ const orderByMap = {}
62
+ // Collect all orderBy columns that should be taken from the SELECT.columns
63
+ if(Array.isArray(orderBy)) orderBy?.forEach(o => {
64
+ if(o.ref?.length === 1) {
65
+ orderByMap[o.ref[0]] = true
66
+ }
67
+ })
68
+ return SELECT.columns.map(x => {
69
+ const alias = this.column_name(x)
70
+ // Check whether the column alias should be added
71
+ const xpr = this.column_expr(x)
72
+ const needsAlias = (typeof x.as === 'string' && x.as) || orderByMap[alias]
73
+ return `${xpr}${needsAlias ? ` as ${this.quote(alias)}` : ''}`
74
+ })
75
+ }
76
+
77
+ operator (x,i,xpr) {
78
+ if (x === '=' && xpr[i+1]?.val === null) return 'is'
79
+ if (x === '!=') return 'is not'
80
+ else return x
81
+ }
82
+
83
+ // Used for INSERT statements
84
+ static InputConverters = { ...super.InputConverters,
85
+ Date: e => `strftime('%Y-%m-%d',${e})`,
86
+ Time: e => `strftime('%H:%M:%S',${e})`,
87
+ DateTime: e => `strftime('%Y-%m-%dT%H:%M:%SZ',${e})`,
88
+ Timestamp: e => `strftime('%Y-%m-%dT%H:%M:%fZ',${e})`,
89
+ }
90
+
91
+ static OutputConverters = { ...super.OutputConverters,
92
+ boolean: expr => `CASE ${expr} when 1 then 'true' when 0 then 'false' END ->'$'`, // REVIEW: ist that correct?
93
+ Int64: expr => `CAST(${expr} as TEXT)`, // REVISIT: As discussed: please put that on a list of things to revisit later on
94
+ Decimal: expr => `nullif(quote(${expr}),'NULL')->'$'`, // REVISIT: what is that ->'$' doing?
95
+ Float: expr => `nullif(quote(${expr}),'NULL')->'$'`,
96
+ Double: expr => `nullif(quote(${expr}),'NULL')->'$'`,
97
+ struct: expr => `${expr}->'$'`, // Association + Composition inherits from struct
98
+ array: expr => `${expr}->'$'`,
99
+ }
100
+
101
+ // Used for SQL function expressions
102
+ static Functions = { ...super.Functions }
103
+
104
+ // Used for CREATE TABLE statements
105
+ static TypeMap = { ...super.TypeMap,
106
+ Binary: e => `BINARY_BLOB(${e.length || 5000})`,
107
+ Date: () => 'DATE_TEXT',
108
+ Time: () => 'TIME_TEXT',
109
+ DateTime: () => 'TIMESTAMP_TEXT',
110
+ Timestamp: () => 'TIMESTAMP_TEXT'
111
+ }
112
+
113
+ static ReservedWords = { ...super.ReservedWords, ...require("./ReservedWords.json") }
114
+ }
115
+
116
+
117
+ // REALLY REVISIT: Here we are doing error handling which we probably never should have started.
118
+ // And worst of all, we handed out this as APIs without documenting it, so stakeholder tests rely
119
+ // on that? -> we urgently need to review these stakeholder tests.
120
+ // And we'd also need this to be implemented by each db service, and therefore documented, correct?
121
+ async onINSERT(req) {
122
+ try {
123
+ return await super.onINSERT(req)
124
+ } catch (err) {
125
+ throw _not_unique(err,'ENTITY_ALREADY_EXISTS')
126
+ || err
127
+ }
128
+ }
129
+
130
+ async onUPDATE(req) {
131
+ try {
132
+ return await super.onUPDATE(req)
133
+ } catch (err) {
134
+ throw _not_unique(err,'UNIQUE_CONSTRAINT_VIOLATION')
135
+ || err
136
+ }
137
+ }
138
+
139
+ // SQLite doesn't support streaming, the whole data is read from the database
140
+ async onStream(query) {
141
+ delete query._streaming
142
+ const result = await super.onSELECT({query, data: {}})
143
+ if (result == null || result.length === 0) return
144
+ let val = Array.isArray(result) ? Object.values(result[0])[0] : Object.values(result)[0]
145
+ if (val === null) return null
146
+ const stream_ = new Readable()
147
+ stream_.push(Buffer.from(val, 'base64'))
148
+ stream_.push(null)
149
+ return stream_
150
+ }
151
+
152
+ }
153
+
154
+ // function _not_null (err) {
155
+ // if (err.code === "SQLITE_CONSTRAINT_NOTNULL") return Object.assign ({
156
+ // code: 'MUST_NOT_BE_NULL',
157
+ // target: /\.(.*?)$/.exec(err.message)[1], // here we are even constructing OData responses, with .target
158
+ // message: 'Value is required',
159
+ // })
160
+ // }
161
+
162
+ function _not_unique (err, code) {
163
+ if (err.message.match(/unique constraint/i)) return Object.assign ({
164
+ originalMessage: err.message, // FIXME: required because of next line
165
+ message: code, // FIXME: misusing message as code
166
+ code: 400, // FIXME: misusing code as (http) status
167
+ })
168
+ }
169
+
170
+ module.exports = SQLiteService