forked from sapmentors/cds-pg
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
203 lines (176 loc) · 5.6 KB
/
index.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
const { Pool } = require('pg')
const dateTime = require('@sap/cds-runtime/lib/hana/dateTime.js')
const { managed, virtual, keys, rewrite } = require('@sap/cds-runtime/lib/db/generic')
/*eslint no-undef: "warn"*/
/*eslint no-unused-vars: "warn"*/
const cds = global.cds || require('@sap/cds/lib')
const { readHandler, createHandler, updateHandler, deleteHandler, sqlHandler, cqnHandler } = require('./lib/pg/query')
/*
* the service
*/ module.exports = class PostgresDatabase extends cds.DatabaseService {
constructor(...args) {
super(...args)
// Cloud Foundry provides the user in the field username the pg npm module expects user
if (this.options.credentials && this.options.credentials.username) {
this.options.credentials.user = this.options.credentials.username
}
this._pool = new Pool(this.options.credentials)
}
/**
* Convert the cds compile -to sql output to a PostgreSQL compatible format
* @see https://www.postgresql.org/docs/13/datatype.html
*
* NVARCHAR -> VARCHAR
* DOUBLE -> NUMERIC(15, 15)
* BLOB -> BYTEA
* NCLOB -> TEXT
*
* @param {String} SQL from cds compile -to sql
* @returns {String} postgresql sql compatible SQL
*/
cdssql2pgsql(cdssql) {
let pgsql = cdssql.replace(/NVARCHAR/g, 'VARCHAR')
pgsql = pgsql.replace(/DOUBLE/g, 'NUMERIC(30, 15)')
pgsql = pgsql.replace(/BLOB/g, 'BYTEA')
pgsql = pgsql.replace(/NCLOB/g, 'TEXT')
return pgsql
}
init() {
/*
* before
*/
// currently needed for transaction handling
this._ensureOpen && this.before('*', this._ensureOpen)
this._ensureModel && this.before('*', this._ensureModel)
// "flattens" the query
// and "redirects" modification statements (CUD) from view to actual table
this.before(['CREATE', 'UPDATE'], '*', dateTime) // > has to run before rewrite
this.before(['CREATE', 'UPDATE'], '*', keys)
this.before(['CREATE', 'UPDATE'], '*', managed)
this.before(['CREATE', 'UPDATE'], '*', virtual)
this.before(['CREATE', 'READ', 'UPDATE', 'DELETE'], '*', rewrite)
this.before(['CREATE', 'READ', 'UPDATE', 'DELETE'], '*', this.setModel)
/*
* on
*/
this.on('CREATE', '*', async function (req) {
return await createHandler(this.dbc, req.query)
})
this.on('READ', '*', async function (req) {
return await readHandler(this.dbc, req.query, req._model)
})
this.on('UPDATE', '*', async function (req) {
return await updateHandler(this.dbc, req.query)
})
this.on('DELETE', '*', async function (req) {
return await deleteHandler(this.dbc, req.query)
})
/*
* after
*/
// nothing
/*
* tx
*/
this.on('BEGIN', async function (req) {
this.dbc = await this.acquire(req)
await this.dbc.query(req.event)
// currently needed for continue with tx
this._state = req.event
return 'dummy'
})
this.on('COMMIT', async function (req) {
await this.dbc.query(req.event)
// currently needed for continue with tx
this._state = req.event
await this.release(this.dbc)
return 'dummy'
})
this.on('ROLLBACK', async function (req) {
try {
await this.dbc.query(req.event)
} finally {
await this.release(this.dbc)
}
// currently needed for continue with tx
this._state = req.event
return 'dummy'
})
/*
* "final on"
*/
this.on('*', function (req) {
if (typeof req.query === 'string') {
return sqlHandler(this.dbc, req.query || req.event, this.models)
} else {
return cqnHandler(this.dbc, req.query || req.event, this.models)
}
})
}
/**
* assign request metadata
* @param {Object} req currently served express http request, enhanced by cds
*/
setModel(req) {
this.models = req.context._model
}
/*
* connection
*/
async acquire(arg) {
// const tenant = (typeof arg === 'string' ? arg : arg.user.tenant) || 'anonymous'
const dbc = await this._pool.connect()
return dbc
}
/**
* release the query client back to the pool
* explicitly passing a truthy value
* see https://node-postgres.com/api/pool#releasecallback
*/
async release(dbc) {
await dbc.release(true)
return 'dummy'
}
// if needed
async disconnect(tenant = 'anonymous') {
// potential await custom_disconnect_function(tenant)
super.disconnect(tenant)
}
// REVISIT: Borrowed from SQLite service, but needs cleanup
async deploy(model, options = {}) {
let createEntities = cds.compile.to.sql(model)
if (!createEntities || createEntities.length === 0) return // > nothing to deploy
// Transform to PostgresSQL
createEntities = createEntities.map((e) => this.cdssql2pgsql(e))
const dropViews = []
const dropTables = []
for (let each of createEntities) {
const [, table, entity] = each.match(/^\s*CREATE (?:(TABLE)|VIEW)\s+"?([^\s(]+)"?/im) || []
if (table) dropTables.push({ DROP: { entity } })
else dropViews.push({ DROP: { view: entity } })
}
if (options.dry) {
const log = console.log // eslint-disable-line no-console
for (let {
DROP: { view },
} of dropViews) {
log('DROP VIEW IF EXISTS ' + view + ';')
}
log()
for (let {
DROP: { entity },
} of dropTables) {
log('DROP TABLE IF EXISTS ' + entity + ';')
}
log()
for (let each of createEntities) log(each + ';\n')
return
}
const tx = this.transaction()
await tx.run(dropViews)
await tx.run(dropTables)
await tx.run(createEntities)
await tx.commit()
return true
}
}