@oino-ts/db-mssql 0.0.16

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,395 @@
1
+ /*
2
+ * This Source Code Form is subject to the terms of the Mozilla Public
3
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
4
+ * file, You can obtain one at https://mozilla.org/MPL/2.0/.
5
+ */
6
+
7
+ import { OINODb, OINODbParams, OINODbDataSet, OINODbApi, OINOBooleanDataField, OINONumberDataField, OINOStringDataField, OINODbDataFieldParams, OINO_ERROR_PREFIX, OINODataRow, OINODataCell, OINOBenchmark, OINODatetimeDataField, OINOBlobDataField, OINO_INFO_PREFIX, OINODB_EMPTY_ROW, OINODB_EMPTY_ROWS, OINOLog } from "@oino-ts/db";
8
+
9
+ import {ConnectionPool, config} from "mssql";
10
+
11
+ /**
12
+ * Implmentation of OINODbDataSet for MariaDb.
13
+ *
14
+ */
15
+ class OINOMsSqlData extends OINODbDataSet {
16
+ private _recordsets:OINODataRow[][] = [OINODB_EMPTY_ROWS]
17
+ private _rows:OINODataRow[] = OINODB_EMPTY_ROWS
18
+
19
+ private _currentRecordset: number
20
+ private _currentRow: number
21
+ private _eof: boolean
22
+
23
+ /**
24
+ * OINOMsSqlData constructor
25
+ * @param params database parameters
26
+ */
27
+ constructor(data: any, messages:string[]=[]) {
28
+ super(data, messages)
29
+ if (data == null) {
30
+ this.messages.push(OINO_INFO_PREFIX + "SQL result is empty")
31
+
32
+ } else if (!(Array.isArray(data) && (data.length>0) && Array.isArray(data[0]))) {
33
+ throw new Error(OINO_ERROR_PREFIX + ": OINOMsSqlData constructor: invalid data!")
34
+
35
+ } else {
36
+ this._recordsets = data as OINODataRow[][]
37
+ this._rows = this._recordsets[0]
38
+ }
39
+ // OINOLog.debug("OINOMsSqlData.constructor", {_rows:this._rows})
40
+ if (this.isEmpty()) {
41
+ this._currentRecordset = -1
42
+ this._currentRow = -1
43
+ this._eof = true
44
+ } else {
45
+ this._currentRecordset = 0
46
+ this._currentRow = 0
47
+ this._eof = false
48
+ }
49
+ }
50
+
51
+ /**
52
+ * Is data set empty.
53
+ *
54
+ */
55
+ isEmpty():boolean {
56
+ return (this._rows.length == 0)
57
+ }
58
+
59
+ /**
60
+ * Is there no more content, i.e. either dataset is empty or we have moved beyond last line
61
+ *
62
+ */
63
+ isEof():boolean {
64
+ return (this._eof)
65
+ }
66
+
67
+ /**
68
+ * Attempts to moves dataset to the next row, possibly waiting for more data to become available. Returns !isEof().
69
+ *
70
+ */
71
+ async next():Promise<boolean> {
72
+ // OINOLog.debug("OINODbDataSet.next", {currentRow:this._currentRow, length:this.sqlResult.data.length})
73
+ if (this._currentRow < this._rows.length-1) {
74
+ this._currentRow = this._currentRow + 1
75
+
76
+ } else if (this._currentRecordset < this._recordsets.length-1) {
77
+ this._currentRecordset = this._currentRecordset + 1
78
+ this._rows = this._recordsets[this._currentRecordset]
79
+ this._currentRow = 0
80
+
81
+ } else {
82
+ this._eof = true
83
+ }
84
+ return Promise.resolve(!this._eof)
85
+ }
86
+
87
+ /**
88
+ * Gets current row of data.
89
+ *
90
+ */
91
+ getRow(): OINODataRow {
92
+ if ((this._currentRow >=0) && (this._currentRow < this._rows.length)) {
93
+ return this._rows[this._currentRow]
94
+ } else {
95
+ return OINODB_EMPTY_ROW
96
+ }
97
+ }
98
+ }
99
+
100
+ /**
101
+ * Implementation of MariaDb/MySql-database.
102
+ *
103
+ */
104
+ export class OINODbMsSql extends OINODb {
105
+
106
+ private _pool:ConnectionPool
107
+
108
+ /**
109
+ * Constructor of `OINODbMsSql`
110
+ * @param params database parameters
111
+ */
112
+ constructor(params:OINODbParams) {
113
+ super(params)
114
+
115
+ // OINOLog.debug("OINODbMsSql.constructor", {params:params})
116
+ if (this._params.type !== "OINODbMsSql") {
117
+ throw new Error(OINO_ERROR_PREFIX + ": Not OINODbMsSql-type: " + this._params.type)
118
+ }
119
+ this._pool = new ConnectionPool({
120
+ user: params.user,
121
+ password: params.password,
122
+ server: params.url,
123
+ port: params.port,
124
+ database: params.database,
125
+ arrayRowMode:true,
126
+ options: {
127
+ encrypt: true, // Use encryption for Azure SQL Database
128
+ rowCollectionOnRequestCompletion:false,
129
+ rowCollectionOnDone:false,
130
+ trustServerCertificate: true // Change to false for production
131
+ }
132
+ })
133
+ //this._pool = new ConnectionPool({connectionString: "Server=localhost,1433;Database=database;User Id=username;Password=" + params.password + ";Encrypt=true"})
134
+
135
+ this._pool.on("error", (conn:any) => {
136
+ // console.log("OINODbMsSql error", conn)
137
+ })
138
+ this._pool.on("debug", (event:any) => {
139
+ // console.log("OINODbMsSql debug",event)
140
+ })
141
+ }
142
+
143
+ private async _query(sql:string):Promise<OINOMsSqlData> {
144
+ // OINOLog.debug("OINODbMsSql._query", {sql:sql})
145
+ try {
146
+ const sql_res = await this._pool.request().query(sql);
147
+ // console.log("OINODbMsSql._query result:" + JSON.stringify(sql_res.recordsets))
148
+ const result:OINOMsSqlData = new OINOMsSqlData(sql_res.recordsets)
149
+ return Promise.resolve(result)
150
+
151
+ } catch (err) {
152
+ OINOLog.error("OINODbMsSql._query exception", {err:err})
153
+ throw err;
154
+
155
+ } finally {
156
+ // console.log("OINODbMsSql._query finally");
157
+ }
158
+ // OINOLog.debug("OINODbMsSql._query", {result:query_result})
159
+ }
160
+
161
+ private async _exec(sql:string):Promise<OINOMsSqlData> {
162
+ // OINOLog.debug("OINODbMsSql._exec", {sql:sql})
163
+ try {
164
+ const sql_res = await this._pool.request().query(sql);
165
+ // console.log("OINODbMsSql._exec result", sql_res);
166
+ return Promise.resolve(new OINOMsSqlData([[]]))
167
+
168
+ } catch (err) {
169
+ OINOLog.error("OINODbMsSql._exec exception", {err:err})
170
+ throw err;
171
+ } finally {
172
+ }
173
+ // OINOLog.debug("OINODbMsSql._exec", {result:query_result})
174
+ }
175
+
176
+ /**
177
+ * Print a table name using database specific SQL escaping.
178
+ *
179
+ * @param sqlTable name of the table
180
+ *
181
+ */
182
+ printSqlTablename(sqlTable:string): string {
183
+ return "["+sqlTable+"]"
184
+ }
185
+
186
+ /**
187
+ * Print a column name with correct SQL escaping.
188
+ *
189
+ * @param sqlColumn name of the column
190
+ *
191
+ */
192
+ printSqlColumnname(sqlColumn:string): string {
193
+ return "["+sqlColumn+"]"
194
+ }
195
+
196
+
197
+ /**
198
+ * Print a single data value from serialization using the context of the native data
199
+ * type with the correct SQL escaping.
200
+ *
201
+ * @param cellValue data from sql results
202
+ * @param sqlType native type name for table column
203
+ *
204
+ */
205
+ printCellAsSqlValue(cellValue:OINODataCell, sqlType: string): string {
206
+ // OINOLog.debug("OINODbMsSql.printCellAsSqlValue", {cellValue:cellValue, sqlType:sqlType})
207
+ if (cellValue === null) {
208
+ return "NULL"
209
+
210
+ } else if (cellValue === undefined) {
211
+ return "UNDEFINED"
212
+
213
+ } else if ((sqlType == "int") || (sqlType == "smallint") || (sqlType == "float")) {
214
+ return cellValue.toString()
215
+
216
+ } else if ((sqlType == "longblob") || (sqlType == "binary") || (sqlType == "varbinary")) {
217
+ if (cellValue instanceof Buffer) {
218
+ return "0x" + (cellValue as Buffer).toString("hex") + ""
219
+ } else if (cellValue instanceof Uint8Array) {
220
+ return "0x" + Buffer.from(cellValue as Uint8Array).toString("hex") + ""
221
+ } else {
222
+ return "'" + cellValue?.toString() + "'"
223
+ }
224
+
225
+ } else if (((sqlType == "date") || (sqlType == "datetime") || (sqlType == "timestamp")) && (cellValue instanceof Date)) {
226
+ return "'" + cellValue.toISOString().substring(0, 23) + "'"
227
+
228
+ } else {
229
+ // return "'" + cellValue?.toString().replaceAll("\\", "\\\\").replaceAll("\'", "''").replaceAll("\r", "\\r").replaceAll("\n", "\\n").replaceAll("\t", "\\t") + "'"
230
+ return "'" + cellValue?.toString().replaceAll("\'", "''") + "'"
231
+ }
232
+ }
233
+
234
+ /**
235
+ * Parse a single SQL result value for serialization using the context of the native data
236
+ * type.
237
+ *
238
+ * @param sqlValue data from serialization
239
+ * @param sqlType native type name for table column
240
+ *
241
+ */
242
+ parseSqlValueAsCell(sqlValue:OINODataCell, sqlType: string): OINODataCell {
243
+ // OINOLog.debug("OINODbMsSql.parseSqlValueAsCell", {sqlValue:sqlValue, sqlType:sqlType})
244
+ if ((sqlValue === null) || (sqlValue == "NULL")) {
245
+ return null
246
+
247
+ } else if (sqlValue === undefined) {
248
+ return undefined
249
+
250
+ } else if (((sqlType == "date")) && (typeof(sqlValue) == "string")) {
251
+ return new Date(sqlValue)
252
+
253
+ } else {
254
+ return sqlValue
255
+ }
256
+
257
+ }
258
+
259
+ /**
260
+ * Connect to database.
261
+ *
262
+ */
263
+ async connect(): Promise<boolean> {
264
+ try {
265
+ // make sure that any items are correctly URL encoded in the connection string
266
+ await this._pool.connect()
267
+ // OINOLog.info("OINODbMsSql.connect: Connected to database server.")
268
+ await this._pool.request().query("SELECT 1 as test")
269
+ return Promise.resolve(true)
270
+ } catch (err) {
271
+ // ... error checks
272
+ throw new Error(OINO_ERROR_PREFIX + ": Error connecting to OINODbMsSql server: " + err)
273
+ }
274
+ }
275
+
276
+ /**
277
+ * Execute a select operation.
278
+ *
279
+ * @param sql SQL statement.
280
+ *
281
+ */
282
+ async sqlSelect(sql:string): Promise<OINODbDataSet> {
283
+ OINOBenchmark.start("OINODb", "sqlSelect")
284
+ let result:OINODbDataSet
285
+ try {
286
+ // OINOLog.debug("OINODbMsSql.sqlSelect", {sql_rows:sql_rows})
287
+ result = await this._query(sql)
288
+
289
+ } catch (e:any) {
290
+ result = new OINOMsSqlData([[]], [OINO_ERROR_PREFIX + " (sqlSelect): OINODbMsSql.sqlSelect exception in _db.query: " + e.message])
291
+ }
292
+ OINOBenchmark.end("OINODb", "sqlSelect")
293
+ return result
294
+ }
295
+
296
+ /**
297
+ * Execute other sql operations.
298
+ *
299
+ * @param sql SQL statement.
300
+ *
301
+ */
302
+ async sqlExec(sql:string): Promise<OINODbDataSet> {
303
+ OINOBenchmark.start("OINODb", "sqlExec")
304
+ let result:OINODbDataSet
305
+ try {
306
+ result = await this._exec(sql)
307
+
308
+ } catch (e:any) {
309
+ result = new OINOMsSqlData([[]], [OINO_ERROR_PREFIX + " (sqlExec): exception in _db.exec [" + e.message + "]"])
310
+ }
311
+ OINOBenchmark.end("OINODb", "sqlExec")
312
+ return result
313
+ }
314
+
315
+ private _getSchemaSql(dbName:string, tableName:string):string {
316
+ const sql =
317
+ // 0 1 2 3 4 5 6 7 8
318
+ `SELECT C.COLUMN_NAME, C.IS_NULLABLE, C.DATA_TYPE, C.CHARACTER_MAXIMUM_LENGTH, C.NUMERIC_PRECISION, C.NUMERIC_PRECISION_RADIX, CONST.CONSTRAINT_TYPES, COLUMNPROPERTY(OBJECT_ID(C.TABLE_SCHEMA + '.' + C.TABLE_NAME), C.COLUMN_NAME, 'IsIdentity') AS IS_AUTO_INCREMENT, COLUMNPROPERTY(OBJECT_ID(C.TABLE_SCHEMA + '.' + C.TABLE_NAME), C.COLUMN_NAME, 'IsComputed') AS IS_COMPUTED
319
+ FROM
320
+ INFORMATION_SCHEMA.COLUMNS as C LEFT JOIN
321
+ (
322
+ SELECT TC.TABLE_NAME, KU.COLUMN_NAME, STRING_AGG(TC.CONSTRAINT_TYPE, ', ') as CONSTRAINT_TYPES
323
+ FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS AS TC
324
+ INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE AS KU ON TC.CONSTRAINT_NAME = KU.CONSTRAINT_NAME
325
+ GROUP BY TC.TABLE_NAME, KU.COLUMN_NAME
326
+ ) as CONST
327
+ ON C.TABLE_NAME = CONST.TABLE_NAME AND C.COLUMN_NAME = CONST.COLUMN_NAME
328
+ WHERE C.TABLE_CATALOG = '${dbName}' AND C.TABLE_NAME = '${tableName}';`
329
+ return sql
330
+ }
331
+ /**
332
+ * Initialize a data model by getting the SQL schema and populating OINODbDataFields of
333
+ * the model.
334
+ *
335
+ * @param api api which data model to initialize.
336
+ *
337
+ */
338
+ async initializeApiDatamodel(api:OINODbApi): Promise<void> {
339
+
340
+ //"SELECT COLUMN_NAME, IS_NULLABLE, DATA_TYPE, CHARACTER_MAXIMUM_LENGTH, NUMERIC_PRECISION, NUMERIC_PRECISION_RADIX
341
+ const res:OINODbDataSet = await this.sqlSelect(this._getSchemaSql(this._params.database, api.params.tableName))
342
+ while (!res.isEof()) {
343
+ const row:OINODataRow = res.getRow()
344
+ // OINOLog.debug("OINODbMsSql.initializeApiDatamodel", { description:row })
345
+ const field_name:string = row[0]?.toString() || ""
346
+ const sql_type:string = row[2] as string || ""
347
+ const char_field_length:number = row[3] as number || 0
348
+ const numeric_field_length1:number = row[4] as number || 0
349
+ const numeric_field_length2:number = row[5] as number || 0
350
+ const constraint_types:string = row[6] as string || ""
351
+ const field_params:OINODbDataFieldParams = {
352
+ isPrimaryKey: constraint_types.indexOf("PRIMARY KEY") >= 0,
353
+ isAutoInc: row[7] == 1,
354
+ isNotNull: row[1] == "NO"
355
+ }
356
+ if (((api.params.excludeFieldPrefix) && field_name.startsWith(api.params.excludeFieldPrefix)) || ((api.params.excludeFields) && (api.params.excludeFields.indexOf(field_name) < 0))) {
357
+ OINOLog.info("OINODbMsSql.initializeApiDatamodel: field excluded in API parameters.", {field:field_name})
358
+ } else {
359
+ // OINOLog.debug("OINODbMsSql.initializeApiDatamodel: next field ", {field_name: field_name, sql_type:sql_type, char_field_length:char_field_length, numeric_field_length1:numeric_field_length1, numeric_field_length2:numeric_field_length2, field_params:field_params })
360
+ if ((sql_type == "tinyint") || (sql_type == "smallint") || (sql_type == "int") || (sql_type == "bigint") || (sql_type == "float") || (sql_type == "real")) {
361
+ api.datamodel.addField(new OINONumberDataField(this, field_name, sql_type, field_params ))
362
+
363
+ } else if ((sql_type == "date") || (sql_type == "datetime") || (sql_type == "datetime2")) {
364
+ if (api.params.useDatesAsString) {
365
+ api.datamodel.addField(new OINOStringDataField(this, field_name, sql_type, field_params, 0))
366
+ } else {
367
+ api.datamodel.addField(new OINODatetimeDataField(this, field_name, sql_type, field_params))
368
+ }
369
+
370
+ } else if ((sql_type == "ntext") || (sql_type == "nchar") || (sql_type == "nvarchar") || (sql_type == "text") || (sql_type == "char") || (sql_type == "varchar")) {
371
+ api.datamodel.addField(new OINOStringDataField(this, field_name, sql_type, field_params, char_field_length))
372
+
373
+ } else if ((sql_type == "binary") || (sql_type == "varbinary") || (sql_type == "image")) {
374
+ api.datamodel.addField(new OINOBlobDataField(this, field_name, sql_type, field_params, char_field_length))
375
+
376
+ } else if ((sql_type == "numeric") || (sql_type == "decimal") || (sql_type == "money")) {
377
+ api.datamodel.addField(new OINOStringDataField(this, field_name, sql_type, field_params, numeric_field_length1 + numeric_field_length2 + 1))
378
+
379
+ } else if ((sql_type == "bit")) {
380
+ api.datamodel.addField(new OINOBooleanDataField(this, field_name, sql_type, field_params))
381
+
382
+ } else {
383
+ OINOLog.info("OINODbMsSql.initializeApiDatamodel: unrecognized field type treated as string", {field_name: field_name, sql_type:sql_type, char_length: char_field_length, numeric_field_length1:numeric_field_length1, numeric_field_length2:numeric_field_length2, field_params:field_params })
384
+ api.datamodel.addField(new OINOStringDataField(this, field_name, sql_type, field_params, 0))
385
+ }
386
+ }
387
+ await res.next()
388
+ }
389
+ OINOLog.debug("OINODbMsSql.initializeDatasetModel:\n" + api.datamodel.printDebug("\n"))
390
+ return Promise.resolve()
391
+ }
392
+ }
393
+
394
+
395
+
package/src/index.ts ADDED
@@ -0,0 +1 @@
1
+ export { OINODbMsSql } from "./OINODbMsSql.js"