@cap-js/sqlite 0.2.0 → 1.0.1

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.
@@ -1,175 +0,0 @@
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
- // REVISIT: Timestamp should not loos precision
100
- Date: e => `strftime('%Y-%m-%d',${e})`,
101
- Time: e => `strftime('%H:%M:%S',${e})`,
102
- DateTime: e => `strftime('%Y-%m-%dT%H:%M:%SZ',${e})`,
103
- Timestamp: e => `strftime('%Y-%m-%dT%H:%M:%fZ',${e})`,
104
- }
105
-
106
- // Used for SQL function expressions
107
- static Functions = { ...super.Functions }
108
-
109
- // Used for CREATE TABLE statements
110
- static TypeMap = { ...super.TypeMap,
111
- Binary: e => `BINARY_BLOB(${e.length || 5000})`,
112
- Date: () => 'DATE_TEXT',
113
- Time: () => 'TIME_TEXT',
114
- DateTime: () => 'TIMESTAMP_TEXT',
115
- Timestamp: () => 'TIMESTAMP_TEXT'
116
- }
117
-
118
- static ReservedWords = { ...super.ReservedWords, ...require("./ReservedWords.json") }
119
- }
120
-
121
-
122
- // REALLY REVISIT: Here we are doing error handling which we probably never should have started.
123
- // And worst of all, we handed out this as APIs without documenting it, so stakeholder tests rely
124
- // on that? -> we urgently need to review these stakeholder tests.
125
- // And we'd also need this to be implemented by each db service, and therefore documented, correct?
126
- async onINSERT(req) {
127
- try {
128
- return await super.onINSERT(req)
129
- } catch (err) {
130
- throw _not_unique(err,'ENTITY_ALREADY_EXISTS')
131
- || err
132
- }
133
- }
134
-
135
- async onUPDATE(req) {
136
- try {
137
- return await super.onUPDATE(req)
138
- } catch (err) {
139
- throw _not_unique(err,'UNIQUE_CONSTRAINT_VIOLATION')
140
- || err
141
- }
142
- }
143
-
144
- // SQLite doesn't support streaming, the whole data is read from the database
145
- async onStream(query) {
146
- delete query._streaming
147
- const result = await super.onSELECT({query, data: {}})
148
- if (result == null || result.length === 0) return
149
- let val = Array.isArray(result) ? Object.values(result[0])[0] : Object.values(result)[0]
150
- if (val === null) return null
151
- const stream_ = new Readable()
152
- stream_.push(Buffer.from(val, 'base64'))
153
- stream_.push(null)
154
- return stream_
155
- }
156
-
157
- }
158
-
159
- // function _not_null (err) {
160
- // if (err.code === "SQLITE_CONSTRAINT_NOTNULL") return Object.assign ({
161
- // code: 'MUST_NOT_BE_NULL',
162
- // target: /\.(.*?)$/.exec(err.message)[1], // here we are even constructing OData responses, with .target
163
- // message: 'Value is required',
164
- // })
165
- // }
166
-
167
- function _not_unique (err, code) {
168
- if (err.message.match(/unique constraint/i)) return Object.assign ({
169
- originalMessage: err.message, // FIXME: required because of next line
170
- message: code, // FIXME: misusing message as code
171
- code: 400, // FIXME: misusing code as (http) status
172
- })
173
- }
174
-
175
- module.exports = SQLiteService