@oino-ts/db-bunsqlite 0.3.2 → 0.3.4

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.
package/package.json CHANGED
@@ -1,35 +1,35 @@
1
- {
2
- "name": "@oino-ts/db-bunsqlite",
3
- "version": "0.3.2",
4
- "description": "OINO TS package for using Bun Sqlite databases.",
5
- "author": "Matias Kiviniemi (pragmatta)",
6
- "license": "MPL-2.0",
7
- "repository": {
8
- "type": "git",
9
- "url": "https://github.com/pragmatta/oino-ts.git"
10
- },
11
- "keywords": [
12
- "sql",
13
- "database",
14
- "rest-api",
15
- "typescript",
16
- "library",
17
- "sqlite"
18
- ],
19
- "main": "./dist/cjs/index.js",
20
- "module": "./dist/esm/index.js",
21
- "types": "./dist/types/index.d.ts",
22
- "dependencies": {
23
- "@oino-ts/db": "^0.3.2"
24
- },
25
- "devDependencies": {
26
- "@types/node": "^20.12.7",
27
- "@types/bun": "latest"
28
- },
29
- "files": [
30
- "src/*.ts",
31
- "dist/cjs/*.js",
32
- "dist/esm/*.js",
33
- "dist/types/*.d.ts"
34
- ]
35
- }
1
+ {
2
+ "name": "@oino-ts/db-bunsqlite",
3
+ "version": "0.3.4",
4
+ "description": "OINO TS package for using Bun Sqlite databases.",
5
+ "author": "Matias Kiviniemi (pragmatta)",
6
+ "license": "MPL-2.0",
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "https://github.com/pragmatta/oino-ts.git"
10
+ },
11
+ "keywords": [
12
+ "sql",
13
+ "database",
14
+ "rest-api",
15
+ "typescript",
16
+ "library",
17
+ "sqlite"
18
+ ],
19
+ "main": "./dist/cjs/index.js",
20
+ "module": "./dist/esm/index.js",
21
+ "types": "./dist/types/index.d.ts",
22
+ "dependencies": {
23
+ "@oino-ts/db": "^0.3.4"
24
+ },
25
+ "devDependencies": {
26
+ "@types/node": "^20.12.7",
27
+ "@types/bun": "latest"
28
+ },
29
+ "files": [
30
+ "src/*.ts",
31
+ "dist/cjs/*.js",
32
+ "dist/esm/*.js",
33
+ "dist/types/*.d.ts"
34
+ ]
35
+ }
@@ -1,297 +1,297 @@
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, OINODbMemoryDataSet, OINODataCell, OINOBenchmark, OINOBlobDataField, OINODatetimeDataField, OINOStr, OINOLog } from "@oino-ts/db";
8
-
9
- import { Database as BunSqliteDb } from "bun:sqlite";
10
-
11
- /**
12
- * Implmentation of OINODbDataSet for BunSqlite.
13
- *
14
- */
15
- class OINOBunSqliteDataset extends OINODbMemoryDataSet {
16
- constructor(data: unknown, messages:string[]=[]) {
17
- super(data, messages)
18
- }
19
- }
20
-
21
- /**
22
- * Implementation of BunSqlite-database.
23
- *
24
- */
25
- export class OINODbBunSqlite extends OINODb {
26
- private static _tableDescriptionRegex = /^CREATE TABLE\s*[\"\[]?\w+[\"\]]?\s*\(\s*(.*)\s*\)\s*(WITHOUT ROWID)?$/msi
27
- private static _tablePrimarykeyRegex = /PRIMARY KEY \(([^\)]+)\)/i
28
- private static _tableForeignkeyRegex = /FOREIGN KEY \(\[([^\)]+)\]\)/i
29
- private static _tableFieldTypeRegex = /[\"\[\s]?(\w+)[\"\]\s]\s?(INTEGER|REAL|DOUBLE|NUMERIC|DECIMAL|TEXT|BLOB|VARCHAR|DATETIME|DATE|BOOLEAN)(\s?\((\d+)\s?\,?\s?(\d*)?\))?/i
30
-
31
- private _db:BunSqliteDb|null
32
-
33
- /**
34
- * OINODbBunSqlite constructor
35
- * @param params database parameters
36
- */
37
- constructor(params:OINODbParams) {
38
- super(params)
39
- this._db = null
40
- if (!this._params.url.startsWith("file://")) {
41
- throw new Error(OINO_ERROR_PREFIX + ": OINODbBunSqlite url must be a file://-url!")
42
- }
43
- // OINOLog.debug("OINODbBunSqlite.constructor", {params:params})
44
-
45
- if (this._params.type !== "OINODbBunSqlite") {
46
- throw new Error(OINO_ERROR_PREFIX + ": Not OINODbBunSqlite-type: " + this._params.type)
47
- }
48
- }
49
-
50
- private _parseDbFieldParams(fieldStr:string): OINODbDataFieldParams {
51
- const result:OINODbDataFieldParams = {
52
- isPrimaryKey: fieldStr.indexOf("PRIMARY KEY") >= 0,
53
- isForeignKey: false,
54
- isAutoInc: fieldStr.indexOf("AUTOINCREMENT") >= 0,
55
- isNotNull: fieldStr.indexOf("NOT NULL") >= 0
56
- }
57
- // OINOLog.debug("OINODbBunSqlite._parseDbFieldParams", {fieldStr:fieldStr, result:result})
58
- return result
59
- }
60
-
61
- /**
62
- * Print a table name using database specific SQL escaping.
63
- *
64
- * @param sqlTable name of the table
65
- *
66
- */
67
- printSqlTablename(sqlTable:string): string {
68
- return "["+sqlTable+"]"
69
- }
70
-
71
- /**
72
- * Print a column name with correct SQL escaping.
73
- *
74
- * @param sqlColumn name of the column
75
- *
76
- */
77
- printSqlColumnname(sqlColumn:string): string {
78
- return "\""+sqlColumn+"\""
79
- }
80
-
81
- /**
82
- * Print a single data value from serialization using the context of the native data
83
- * type with the correct SQL escaping.
84
- *
85
- * @param cellValue data from sql results
86
- * @param sqlType native type name for table column
87
- *
88
- */
89
- printCellAsSqlValue(cellValue:OINODataCell, sqlType: string): string {
90
- // OINOLog.debug("OINODbBunSqlite.printCellAsSqlValue", {cellValue:cellValue, sqlType:sqlType, type:typeof(cellValue)})
91
- if (cellValue === null) {
92
- return "NULL"
93
-
94
- } else if (cellValue === undefined) {
95
- return "UNDEFINED"
96
-
97
- } else if ((sqlType == "INTEGER") || (sqlType == "REAL") || (sqlType == "DOUBLE" || (sqlType == "NUMERIC") || (sqlType == "DECIMAL"))) {
98
- return cellValue.toString()
99
-
100
- } else if (sqlType == "BLOB") {
101
- if (cellValue instanceof Buffer) {
102
- return "X'" + (cellValue as Buffer).toString("hex") + "'"
103
- } else if (cellValue instanceof Uint8Array) {
104
- return "X'" + Buffer.from(cellValue as Uint8Array).toString("hex") + "'"
105
- } else {
106
- return "'" + cellValue?.toString() + "'"
107
- }
108
-
109
- } else if (((sqlType == "DATETIME") || (sqlType == "DATE")) && (cellValue instanceof Date)) {
110
- return "\'" + cellValue.toISOString() + "\'"
111
-
112
- } else {
113
- return "\"" + cellValue.toString().replaceAll("\"", "\"\"") + "\""
114
- }
115
- }
116
-
117
- /**
118
- * Parse a single SQL result value for serialization using the context of the native data
119
- * type.
120
- *
121
- * @param sqlValue data from serialization
122
- * @param sqlType native type name for table column
123
- *
124
- */
125
- parseSqlValueAsCell(sqlValue:OINODataCell, sqlType: string): OINODataCell {
126
- if ((sqlValue === null) || (sqlValue == "NULL")) {
127
- return null
128
-
129
- } else if (sqlValue === undefined) {
130
- return undefined
131
-
132
- } else if (((sqlType == "DATETIME") || (sqlType == "DATE")) && (typeof(sqlValue) == "string")) {
133
- return new Date(sqlValue)
134
-
135
- } else {
136
- return sqlValue
137
- }
138
-
139
- }
140
-
141
-
142
- /**
143
- * Connect to database.
144
- *
145
- */
146
- connect(): Promise<boolean> {
147
- const filepath:string = this._params.url.substring(7)
148
- try {
149
- // OINOLog.debug("OINODbBunSqlite.connect", {params:this._params})
150
- this._db = BunSqliteDb.open(filepath, { create: true, readonly: false, readwrite: true })
151
- // OINOLog.debug("OINODbBunSqlite.connect done")
152
- return Promise.resolve(true)
153
- } catch (err) {
154
- throw new Error(OINO_ERROR_PREFIX + ": Error connecting to Sqlite database ("+ filepath +"): " + err)
155
- }
156
- }
157
-
158
- /**
159
- * Execute a select operation.
160
- *
161
- * @param sql SQL statement.
162
- *
163
- */
164
- async sqlSelect(sql:string): Promise<OINODbDataSet> {
165
- OINOBenchmark.start("OINODb", "sqlSelect")
166
- let result:OINODbDataSet
167
- try {
168
- result = new OINOBunSqliteDataset(this._db?.query(sql).values(), [])
169
- // OINOLog.debug("OINODbBunSqlite.sqlSelect", {result:result})
170
-
171
- } catch (e:any) {
172
- result = new OINOBunSqliteDataset([[]], ["OINODbBunSqlite.sqlSelect exception in _db.query: " + e.message])
173
- }
174
- OINOBenchmark.end("OINODb", "sqlSelect")
175
- return Promise.resolve(result)
176
- }
177
-
178
- /**
179
- * Execute other sql operations.
180
- *
181
- * @param sql SQL statement.
182
- *
183
- */
184
- async sqlExec(sql:string): Promise<OINODbDataSet> {
185
- OINOBenchmark.start("OINODb", "sqlExec")
186
- let result:OINODbDataSet
187
- try {
188
- this._db?.exec(sql)
189
- result = new OINOBunSqliteDataset([[]], [])
190
-
191
- } catch (e:any) {
192
- result = new OINOBunSqliteDataset([[]], [OINO_ERROR_PREFIX + "(sqlExec): exception in _db.exec [" + e.message + "]"])
193
- }
194
- OINOBenchmark.end("OINODb", "sqlExec")
195
- return Promise.resolve(result)
196
- }
197
-
198
- /**
199
- * Initialize a data model by getting the SQL schema and populating OINODbDataFields of
200
- * the model.
201
- *
202
- * @param api api which data model to initialize.
203
- *
204
- */
205
- async initializeApiDatamodel(api:OINODbApi): Promise<void> {
206
- const res:OINODbDataSet|null = await this.sqlSelect("select sql from sqlite_schema WHERE name='" + api.params.tableName + "'")
207
- const sql_desc:string = (res?.getRow()[0]) as string
208
- const excluded_fields:string[] = []
209
- // OINOLog.debug("OINODbBunSqlite.initDatamodel.sql_desc=" + sql_desc)
210
- let table_matches = OINODbBunSqlite._tableDescriptionRegex.exec(sql_desc)
211
- // OINOLog.debug("OINODbBunSqlite.initDatamodel", {table_matches:table_matches})
212
- if (!table_matches || table_matches?.length < 2) {
213
- throw new Error("Table " + api.params.tableName + " not recognized as a valid Sqlite table!")
214
-
215
- } else {
216
- // OINOBenchmark.start("OINODbBunSqlite.initDatamodel")
217
- let field_strings:string[] = OINOStr.splitExcludingBrackets(table_matches[1], ',', '(', ')')
218
- // OINOLog.debug("OINODbBunSqlite.initDatamodel", {table_match:table_matches[1], field_strings:field_strings})
219
- for (let field_str of field_strings) {
220
- field_str = field_str.trim()
221
- let field_params = this._parseDbFieldParams(field_str)
222
- let field_match = OINODbBunSqlite._tableFieldTypeRegex.exec(field_str)
223
- // OINOLog.debug("initDatamodel next field", {field_str:field_str, field_match:field_match, field_params:field_params})
224
- if ((!field_match) || (field_match.length < 3)) {
225
- let primarykey_match = OINODbBunSqlite._tablePrimarykeyRegex.exec(field_str)
226
- let foreignkey_match = OINODbBunSqlite._tableForeignkeyRegex.exec(field_str)
227
- // OINOLog.debug("initDatamodel non-field definition", {primarykey_match:primarykey_match, foreignkey_match:foreignkey_match})
228
- if (primarykey_match && primarykey_match.length >= 2) {
229
- const primary_keys:string[] = primarykey_match[1].replaceAll("\"", "").split(',') // not sure if will have space or not so split by comma and trim later
230
- for (let i:number=0; i<primary_keys.length; i++) {
231
- const pk:string = primary_keys[i].trim() //..the trim
232
- if (excluded_fields.indexOf(pk) >= 0) {
233
- throw new Error(OINO_ERROR_PREFIX + "Primary key field excluded in API parameters: " + pk)
234
- }
235
- for (let j:number=0; j<api.datamodel.fields.length; j++) {
236
- if (api.datamodel.fields[j].name == pk) {
237
- api.datamodel.fields[j].fieldParams.isPrimaryKey = true
238
- }
239
- }
240
- }
241
-
242
- } else if (foreignkey_match && foreignkey_match.length >= 2) {
243
- const fk:string = foreignkey_match[1].trim()
244
- for (let j:number=0; j<api.datamodel.fields.length; j++) {
245
- if (api.datamodel.fields[j].name == fk) {
246
- api.datamodel.fields[j].fieldParams.isForeignKey = true
247
- }
248
- }
249
-
250
- } else {
251
- OINOLog.info("OINODbBunSqlite.initializeApiDatamodel: Unsupported field definition skipped.", { field: field_str })
252
- }
253
-
254
- } else {
255
- // field_str = "NAME TYPE (M, N)" -> 1:NAME, 2:TYPE, 4:M, 5:N
256
- // OINOLog.debug("OINODbBunSqlite.initializeApiDatamodel: field regex matches", { field_match: field_match })
257
- const field_name:string = field_match[1]
258
- const sql_type:string = field_match[2]
259
- const field_length:number = parseInt(field_match[4]) || 0
260
- // OINOLog.debug("OINODbBunSqlite.initializeApiDatamodel: field regex matches", { api.params: api.params, field_name:field_name })
261
- if (api.isFieldIncluded(field_name) == false) {
262
- excluded_fields.push(field_name)
263
- OINOLog.info("OINODbBunSqlite.initializeApiDatamodel: field excluded in API parameters.", {field:field_name})
264
-
265
- } else {
266
- if ((sql_type == "INTEGER") || (sql_type == "REAL") || (sql_type == "DOUBLE") || (sql_type == "NUMERIC") || (sql_type == "DECIMAL")) {
267
- api.datamodel.addField(new OINONumberDataField(this, field_name, sql_type, field_params ))
268
-
269
- } else if ((sql_type == "BLOB") ) {
270
- api.datamodel.addField(new OINOBlobDataField(this, field_name, sql_type, field_params, field_length))
271
-
272
- } else if ((sql_type == "TEXT")) {
273
- api.datamodel.addField(new OINOStringDataField(this, field_name, sql_type, field_params, field_length))
274
-
275
- } else if ((sql_type == "DATETIME") || (sql_type == "DATE")) {
276
- if (api.params.useDatesAsString) {
277
- api.datamodel.addField(new OINOStringDataField(this, field_name, sql_type, field_params, 0))
278
- } else {
279
- api.datamodel.addField(new OINODatetimeDataField(this, field_name, sql_type, field_params))
280
- }
281
-
282
- } else if ((sql_type == "BOOLEAN")) {
283
- api.datamodel.addField(new OINOBooleanDataField(this, field_name, sql_type, field_params))
284
-
285
- } else {
286
- OINOLog.info("OINODbBunSqlite.initializeApiDatamodel: unrecognized field type treated as string", {field_name: field_name, sql_type:sql_type, field_length:field_length, field_params:field_params })
287
- api.datamodel.addField(new OINOStringDataField(this, field_name, sql_type, field_params, 0))
288
- }
289
- }
290
- }
291
- };
292
- // OINOBenchmark.end("OINODbBunSqlite.initializeApiDatamodel")
293
- OINOLog.debug("OINODbBunSqlite.initializeDatasetModel:\n" + api.datamodel.printDebug("\n"))
294
- return Promise.resolve()
295
- }
296
- }
297
- }
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, OINODbMemoryDataSet, OINODataCell, OINOBenchmark, OINOBlobDataField, OINODatetimeDataField, OINOStr, OINOLog } from "@oino-ts/db";
8
+
9
+ import { Database as BunSqliteDb } from "bun:sqlite";
10
+
11
+ /**
12
+ * Implmentation of OINODbDataSet for BunSqlite.
13
+ *
14
+ */
15
+ class OINOBunSqliteDataset extends OINODbMemoryDataSet {
16
+ constructor(data: unknown, messages:string[]=[]) {
17
+ super(data, messages)
18
+ }
19
+ }
20
+
21
+ /**
22
+ * Implementation of BunSqlite-database.
23
+ *
24
+ */
25
+ export class OINODbBunSqlite extends OINODb {
26
+ private static _tableDescriptionRegex = /^CREATE TABLE\s*[\"\[]?\w+[\"\]]?\s*\(\s*(.*)\s*\)\s*(WITHOUT ROWID)?$/msi
27
+ private static _tablePrimarykeyRegex = /PRIMARY KEY \(([^\)]+)\)/i
28
+ private static _tableForeignkeyRegex = /FOREIGN KEY \(\[([^\)]+)\]\)/i
29
+ private static _tableFieldTypeRegex = /[\"\[\s]?(\w+)[\"\]\s]\s?(INTEGER|REAL|DOUBLE|NUMERIC|DECIMAL|TEXT|BLOB|VARCHAR|DATETIME|DATE|BOOLEAN)(\s?\((\d+)\s?\,?\s?(\d*)?\))?/i
30
+
31
+ private _db:BunSqliteDb|null
32
+
33
+ /**
34
+ * OINODbBunSqlite constructor
35
+ * @param params database parameters
36
+ */
37
+ constructor(params:OINODbParams) {
38
+ super(params)
39
+ this._db = null
40
+ if (!this._params.url.startsWith("file://")) {
41
+ throw new Error(OINO_ERROR_PREFIX + ": OINODbBunSqlite url must be a file://-url!")
42
+ }
43
+ // OINOLog.debug("OINODbBunSqlite.constructor", {params:params})
44
+
45
+ if (this._params.type !== "OINODbBunSqlite") {
46
+ throw new Error(OINO_ERROR_PREFIX + ": Not OINODbBunSqlite-type: " + this._params.type)
47
+ }
48
+ }
49
+
50
+ private _parseDbFieldParams(fieldStr:string): OINODbDataFieldParams {
51
+ const result:OINODbDataFieldParams = {
52
+ isPrimaryKey: fieldStr.indexOf("PRIMARY KEY") >= 0,
53
+ isForeignKey: false,
54
+ isAutoInc: fieldStr.indexOf("AUTOINCREMENT") >= 0,
55
+ isNotNull: fieldStr.indexOf("NOT NULL") >= 0
56
+ }
57
+ // OINOLog.debug("OINODbBunSqlite._parseDbFieldParams", {fieldStr:fieldStr, result:result})
58
+ return result
59
+ }
60
+
61
+ /**
62
+ * Print a table name using database specific SQL escaping.
63
+ *
64
+ * @param sqlTable name of the table
65
+ *
66
+ */
67
+ printSqlTablename(sqlTable:string): string {
68
+ return "["+sqlTable+"]"
69
+ }
70
+
71
+ /**
72
+ * Print a column name with correct SQL escaping.
73
+ *
74
+ * @param sqlColumn name of the column
75
+ *
76
+ */
77
+ printSqlColumnname(sqlColumn:string): string {
78
+ return "\""+sqlColumn+"\""
79
+ }
80
+
81
+ /**
82
+ * Print a single data value from serialization using the context of the native data
83
+ * type with the correct SQL escaping.
84
+ *
85
+ * @param cellValue data from sql results
86
+ * @param sqlType native type name for table column
87
+ *
88
+ */
89
+ printCellAsSqlValue(cellValue:OINODataCell, sqlType: string): string {
90
+ // OINOLog.debug("OINODbBunSqlite.printCellAsSqlValue", {cellValue:cellValue, sqlType:sqlType, type:typeof(cellValue)})
91
+ if (cellValue === null) {
92
+ return "NULL"
93
+
94
+ } else if (cellValue === undefined) {
95
+ return "UNDEFINED"
96
+
97
+ } else if ((sqlType == "INTEGER") || (sqlType == "REAL") || (sqlType == "DOUBLE" || (sqlType == "NUMERIC") || (sqlType == "DECIMAL"))) {
98
+ return cellValue.toString()
99
+
100
+ } else if (sqlType == "BLOB") {
101
+ if (cellValue instanceof Buffer) {
102
+ return "X'" + (cellValue as Buffer).toString("hex") + "'"
103
+ } else if (cellValue instanceof Uint8Array) {
104
+ return "X'" + Buffer.from(cellValue as Uint8Array).toString("hex") + "'"
105
+ } else {
106
+ return "'" + cellValue?.toString() + "'"
107
+ }
108
+
109
+ } else if (((sqlType == "DATETIME") || (sqlType == "DATE")) && (cellValue instanceof Date)) {
110
+ return "\'" + cellValue.toISOString() + "\'"
111
+
112
+ } else {
113
+ return "\"" + cellValue.toString().replaceAll("\"", "\"\"") + "\""
114
+ }
115
+ }
116
+
117
+ /**
118
+ * Parse a single SQL result value for serialization using the context of the native data
119
+ * type.
120
+ *
121
+ * @param sqlValue data from serialization
122
+ * @param sqlType native type name for table column
123
+ *
124
+ */
125
+ parseSqlValueAsCell(sqlValue:OINODataCell, sqlType: string): OINODataCell {
126
+ if ((sqlValue === null) || (sqlValue == "NULL")) {
127
+ return null
128
+
129
+ } else if (sqlValue === undefined) {
130
+ return undefined
131
+
132
+ } else if (((sqlType == "DATETIME") || (sqlType == "DATE")) && (typeof(sqlValue) == "string")) {
133
+ return new Date(sqlValue)
134
+
135
+ } else {
136
+ return sqlValue
137
+ }
138
+
139
+ }
140
+
141
+
142
+ /**
143
+ * Connect to database.
144
+ *
145
+ */
146
+ connect(): Promise<boolean> {
147
+ const filepath:string = this._params.url.substring(7)
148
+ try {
149
+ // OINOLog.debug("OINODbBunSqlite.connect", {params:this._params})
150
+ this._db = BunSqliteDb.open(filepath, { create: true, readonly: false, readwrite: true })
151
+ // OINOLog.debug("OINODbBunSqlite.connect done")
152
+ return Promise.resolve(true)
153
+ } catch (err) {
154
+ throw new Error(OINO_ERROR_PREFIX + ": Error connecting to Sqlite database ("+ filepath +"): " + err)
155
+ }
156
+ }
157
+
158
+ /**
159
+ * Execute a select operation.
160
+ *
161
+ * @param sql SQL statement.
162
+ *
163
+ */
164
+ async sqlSelect(sql:string): Promise<OINODbDataSet> {
165
+ OINOBenchmark.start("OINODb", "sqlSelect")
166
+ let result:OINODbDataSet
167
+ try {
168
+ result = new OINOBunSqliteDataset(this._db?.query(sql).values(), [])
169
+ // OINOLog.debug("OINODbBunSqlite.sqlSelect", {result:result})
170
+
171
+ } catch (e:any) {
172
+ result = new OINOBunSqliteDataset([[]], ["OINODbBunSqlite.sqlSelect exception in _db.query: " + e.message])
173
+ }
174
+ OINOBenchmark.end("OINODb", "sqlSelect")
175
+ return Promise.resolve(result)
176
+ }
177
+
178
+ /**
179
+ * Execute other sql operations.
180
+ *
181
+ * @param sql SQL statement.
182
+ *
183
+ */
184
+ async sqlExec(sql:string): Promise<OINODbDataSet> {
185
+ OINOBenchmark.start("OINODb", "sqlExec")
186
+ let result:OINODbDataSet
187
+ try {
188
+ this._db?.exec(sql)
189
+ result = new OINOBunSqliteDataset([[]], [])
190
+
191
+ } catch (e:any) {
192
+ result = new OINOBunSqliteDataset([[]], [OINO_ERROR_PREFIX + "(sqlExec): exception in _db.exec [" + e.message + "]"])
193
+ }
194
+ OINOBenchmark.end("OINODb", "sqlExec")
195
+ return Promise.resolve(result)
196
+ }
197
+
198
+ /**
199
+ * Initialize a data model by getting the SQL schema and populating OINODbDataFields of
200
+ * the model.
201
+ *
202
+ * @param api api which data model to initialize.
203
+ *
204
+ */
205
+ async initializeApiDatamodel(api:OINODbApi): Promise<void> {
206
+ const res:OINODbDataSet|null = await this.sqlSelect("select sql from sqlite_schema WHERE name='" + api.params.tableName + "'")
207
+ const sql_desc:string = (res?.getRow()[0]) as string
208
+ const excluded_fields:string[] = []
209
+ // OINOLog.debug("OINODbBunSqlite.initDatamodel.sql_desc=" + sql_desc)
210
+ let table_matches = OINODbBunSqlite._tableDescriptionRegex.exec(sql_desc)
211
+ // OINOLog.debug("OINODbBunSqlite.initDatamodel", {table_matches:table_matches})
212
+ if (!table_matches || table_matches?.length < 2) {
213
+ throw new Error("Table " + api.params.tableName + " not recognized as a valid Sqlite table!")
214
+
215
+ } else {
216
+ // OINOBenchmark.start("OINODbBunSqlite.initDatamodel")
217
+ let field_strings:string[] = OINOStr.splitExcludingBrackets(table_matches[1], ',', '(', ')')
218
+ // OINOLog.debug("OINODbBunSqlite.initDatamodel", {table_match:table_matches[1], field_strings:field_strings})
219
+ for (let field_str of field_strings) {
220
+ field_str = field_str.trim()
221
+ let field_params = this._parseDbFieldParams(field_str)
222
+ let field_match = OINODbBunSqlite._tableFieldTypeRegex.exec(field_str)
223
+ // OINOLog.debug("initDatamodel next field", {field_str:field_str, field_match:field_match, field_params:field_params})
224
+ if ((!field_match) || (field_match.length < 3)) {
225
+ let primarykey_match = OINODbBunSqlite._tablePrimarykeyRegex.exec(field_str)
226
+ let foreignkey_match = OINODbBunSqlite._tableForeignkeyRegex.exec(field_str)
227
+ // OINOLog.debug("initDatamodel non-field definition", {primarykey_match:primarykey_match, foreignkey_match:foreignkey_match})
228
+ if (primarykey_match && primarykey_match.length >= 2) {
229
+ const primary_keys:string[] = primarykey_match[1].replaceAll("\"", "").split(',') // not sure if will have space or not so split by comma and trim later
230
+ for (let i:number=0; i<primary_keys.length; i++) {
231
+ const pk:string = primary_keys[i].trim() //..the trim
232
+ if (excluded_fields.indexOf(pk) >= 0) {
233
+ throw new Error(OINO_ERROR_PREFIX + "Primary key field excluded in API parameters: " + pk)
234
+ }
235
+ for (let j:number=0; j<api.datamodel.fields.length; j++) {
236
+ if (api.datamodel.fields[j].name == pk) {
237
+ api.datamodel.fields[j].fieldParams.isPrimaryKey = true
238
+ }
239
+ }
240
+ }
241
+
242
+ } else if (foreignkey_match && foreignkey_match.length >= 2) {
243
+ const fk:string = foreignkey_match[1].trim()
244
+ for (let j:number=0; j<api.datamodel.fields.length; j++) {
245
+ if (api.datamodel.fields[j].name == fk) {
246
+ api.datamodel.fields[j].fieldParams.isForeignKey = true
247
+ }
248
+ }
249
+
250
+ } else {
251
+ OINOLog.info("OINODbBunSqlite.initializeApiDatamodel: Unsupported field definition skipped.", { field: field_str })
252
+ }
253
+
254
+ } else {
255
+ // field_str = "NAME TYPE (M, N)" -> 1:NAME, 2:TYPE, 4:M, 5:N
256
+ // OINOLog.debug("OINODbBunSqlite.initializeApiDatamodel: field regex matches", { field_match: field_match })
257
+ const field_name:string = field_match[1]
258
+ const sql_type:string = field_match[2]
259
+ const field_length:number = parseInt(field_match[4]) || 0
260
+ // OINOLog.debug("OINODbBunSqlite.initializeApiDatamodel: field regex matches", { api.params: api.params, field_name:field_name })
261
+ if (api.isFieldIncluded(field_name) == false) {
262
+ excluded_fields.push(field_name)
263
+ OINOLog.info("OINODbBunSqlite.initializeApiDatamodel: field excluded in API parameters.", {field:field_name})
264
+
265
+ } else {
266
+ if ((sql_type == "INTEGER") || (sql_type == "REAL") || (sql_type == "DOUBLE") || (sql_type == "NUMERIC") || (sql_type == "DECIMAL")) {
267
+ api.datamodel.addField(new OINONumberDataField(this, field_name, sql_type, field_params ))
268
+
269
+ } else if ((sql_type == "BLOB") ) {
270
+ api.datamodel.addField(new OINOBlobDataField(this, field_name, sql_type, field_params, field_length))
271
+
272
+ } else if ((sql_type == "TEXT")) {
273
+ api.datamodel.addField(new OINOStringDataField(this, field_name, sql_type, field_params, field_length))
274
+
275
+ } else if ((sql_type == "DATETIME") || (sql_type == "DATE")) {
276
+ if (api.params.useDatesAsString) {
277
+ api.datamodel.addField(new OINOStringDataField(this, field_name, sql_type, field_params, 0))
278
+ } else {
279
+ api.datamodel.addField(new OINODatetimeDataField(this, field_name, sql_type, field_params))
280
+ }
281
+
282
+ } else if ((sql_type == "BOOLEAN")) {
283
+ api.datamodel.addField(new OINOBooleanDataField(this, field_name, sql_type, field_params))
284
+
285
+ } else {
286
+ OINOLog.info("OINODbBunSqlite.initializeApiDatamodel: unrecognized field type treated as string", {field_name: field_name, sql_type:sql_type, field_length:field_length, field_params:field_params })
287
+ api.datamodel.addField(new OINOStringDataField(this, field_name, sql_type, field_params, 0))
288
+ }
289
+ }
290
+ }
291
+ };
292
+ // OINOBenchmark.end("OINODbBunSqlite.initializeApiDatamodel")
293
+ OINOLog.debug("OINODbBunSqlite.initializeDatasetModel:\n" + api.datamodel.printDebug("\n"))
294
+ return Promise.resolve()
295
+ }
296
+ }
297
+ }
package/src/index.ts CHANGED
@@ -1 +1 @@
1
- export { OINODbBunSqlite } from "./OINODbBunSqlite.js"
1
+ export { OINODbBunSqlite } from "./OINODbBunSqlite.js"
package/README.md DELETED
@@ -1,190 +0,0 @@
1
- # OINO TS
2
- OINO Is Not an ORM but it's trying to solve a similar problem for API development. Instead of mirroring your DB schema in code that needs manual updates, OINO will get the data schema from DBMS using SQL in real time. Every time your app starts, it has an updated data model which enables automatic (de)serialize SQL results to JSON/CSV and back. OINO works on the level below routing where you pass the method, URL ID, body and request parameters to the API-object. OINO will parse and validate the data against the data model and generate proper SQL for your DB. Because OINO knows how data is serialized (e.g. JSON), what column it belongs to (e.g. floating point number) and what the target database is, it knows how to parse, format and escape the value as valid SQL.
3
-
4
- ```
5
- const result:OINOApiResult = await api_orderdetails.doRequest("GET", id, body, params)
6
- return new Response(result.modelset.writeString(OINOContentType.json))
7
- ```
8
-
9
-
10
- # GETTING STARTED
11
-
12
- ### Setup
13
- Install the `@oino-ts/db` npm package and necessary database packages and import them in your code.
14
- ```
15
- bun install @oino-ts/db
16
- bun install @oino-ts/db-bunsqlite
17
- ```
18
-
19
- ```
20
- import { OINODb, OINOApi, OINOFactory } from "@oino-ts/db";
21
- import { OINODbBunSqlite } from "@oino-ts/db-bunsqlite"
22
- ```
23
-
24
- ### Register database and logger
25
- Register your database implementation and logger (see [`OINOConsoleLog`](https://pragmatta.github.io/oino-ts/classes/types_src.OINOConsoleLog.html) how to implement your own)
26
-
27
- ```
28
- OINOLog.setLogger(new OINOConsoleLog())
29
- OINOFactory.registerDb("OINODbBunSqlite", OINODbBunSqlite)
30
- ```
31
-
32
- ### Create a database
33
- Creating a database connection [`OINODb`](https://pragmatta.github.io/oino-ts/classes/db_src.OINODb.html) is done by passing [`OINODbParams`](https://pragmatta.github.io/oino-ts/types/db_src.OINODbParams.html) to the factory method. For [`OINODbBunSqlite`](https://pragmatta.github.io/oino-ts/classes/db_bunsqlite_src.OINODbBunSqlite.html) that means a file url for the database file, for others network host, port, credentials etc.
34
- ```
35
- const db:OINODb = await OINOFactory.createDb( { type: "OINODbBunSqlite", url: "file://../localDb/northwind.sqlite" } )
36
- ```
37
-
38
- ### Create an API
39
- From a database you can create an [`OINOApi`](https://pragmatta.github.io/oino-ts/classes/db_src.OINODbApi.html) by passing [`OINOApiParams`](https://pragmatta.github.io/oino-ts/types/db_src.OINODbApiParams.html) with table name and preferences to the factory method.
40
- ```
41
- const api_employees:OINOApi = await OINOFactory.createApi(db, { tableName: "Employees", excludeFields:["BirthDate"] })
42
- ```
43
-
44
- ### Pass HTTP requests to API
45
- When you receive a HTTP request, just pass the method, URL ID, body and params to the correct API, which will parse and validate input and return results.
46
-
47
- ```
48
- const result:OINOApiResult = await api_orderdetails.doRequest("GET", id, body, params)
49
- ```
50
-
51
- ### Write results back to HTTP Response
52
- The results for a GET request will contain [`OINOModelSet`](https://pragmatta.github.io/oino-ts/classes/db_src.OINODbModelSet.html) data that can be written out as JSON or CSV as needed. For other requests result is just success or error with messages.
53
- ```
54
- return new Response(result.data.writeString(OINOContentType.json))
55
- ```
56
-
57
-
58
- # FEATURES
59
-
60
- ## RESTfull
61
- OINO maps HTTP methods GET/POST/PUT/DELETE to SQL operations SELECT/INSERT/UPDATE/DELETE. The GET/POST requests can be made without URL ID to get all rows or insert new ones and others target a single row using URL ID.
62
-
63
- For example HTTP POST
64
- ```
65
- Request and response:
66
- > curl.exe -X POST http://localhost:3001/orderdetails -H "Content-Type: application/json" --data '[{\"OrderID\":11077,\"ProductID\":99,\"UnitPrice\":19,\"Quantity\":1,\"Discount\":0}]'
67
- {"success":true,"statusCode":200,"statusMessage":"OK","messages":[]}
68
-
69
- SQL:
70
- INSERT INTO [OrderDetails] ("OrderID","ProductID","UnitPrice","Quantity","Discount") VALUES (11077,99,19,1,0);
71
- ```
72
-
73
-
74
- ## Universal Serialization
75
- OINO handles serialization of data to JSON/CSV/etc. and back based on the data model. It knows what columns exist, what is their data type and how to convert each to JSON/CSV and back. This allows also partial data to be sent, i.e. you can send only columns that need updating or even send extra columns and have them ignored.
76
-
77
- ### Features
78
- - Files can be sent to BLOB fields using BASE64 or MIME multipart encoding. Also supports standard HTML form file submission to blob fields and returning them data url images.
79
- - Datetimes are (optionally) normalized to ISO 8601 format.
80
- - Extended JSON-encoding
81
- - Unquoted literal `undefined` can be used to represent non-existent values (leaving property out works too but preserving structure might be easier e.g. when translating data).
82
- - CSV
83
- - Comma-separated, doublequotes.
84
- - Unquoted literal `null` represents null values.
85
- - Unquoted empty string represents undefined values.
86
- - Form data
87
- - Multipart-mixed and binary files not supported.
88
- - Non-existent value line (i.e. nothing after the empty line) treated as a null value.
89
- - Url-encoded
90
- - No null values, missing properties treated as undefined.
91
- - Multiple lines could be used to post multiple rows.
92
-
93
-
94
- ## Database Abstraction
95
- OINO functions as a database abstraction, providing a consistent interface for working with different databases. It abstracts out different conventions in connecting, making queries and formatting data.
96
-
97
- Currently supported databases:
98
- - Bun Sqlite through Bun native implementation
99
- - Postgresql through [pg](https://www.npmjs.com/package/pg)-package
100
- - Mariadb / Mysql-support through [mariadb](https://www.npmjs.com/package/mariadb)-package
101
- - Sql Server through [mssql](https://www.npmjs.com/package/mssql)-package
102
-
103
- ## Composite Keys
104
- To support tables with multipart primary keys OINO generates a composite key `_OINOID_` that is included in the result and can be used as the REST ID. For example in the example above table `OrderDetails` has two primary keys `OrderID` and `ProductID` making the `_OINOID_` of form `11077:99`.
105
-
106
- ## Power Of SQL
107
- Since OINO is just generating SQL, WHERE-conditions can be defined with [`OINOSqlFilter`](https://pragmatta.github.io/oino-ts/classes/db_src.OINODbSqlFilter.html), order with [`OINOSqlOrder`](https://pragmatta.github.io/oino-ts/classes/db_src.OINODbSqlOrder.html) and limits/paging with [`OINOSqlLimit`](https://pragmatta.github.io/oino-ts/classes/db_src.OINODbSqlLimit.html) that are passed as HTTP request parameters. No more API development where you make unique API endpoints for each filter that fetch all data with original API and filter in backend code. Every API can be filtered when and as needed without unnessecary data tranfer and utilizing SQL indexing when available.
108
-
109
- ## Swagger Support
110
- Swagger is great as long as the definitions are updated and with OINO you can automatically get a Swagger definition including a data model schema.
111
- ```
112
- if (url.pathname == "/swagger.json") {
113
- return new Response(JSON.stringify(OINOSwagger.getApiDefinition(api_array)))
114
- }
115
- ```
116
- ![Swagger definition with a data model schema](img/readme-swagger.png)
117
-
118
- ## Node support
119
- OINO is developped Typescript first but compiles to standard CommonJS and the NPM packages should work on either ESM / CommonJS. Checkout sample apps `readmeApp` (ESM) and `nodeApp` (CommonJS).
120
-
121
- ## HTMX support
122
- OINO is [htmx.org](https://htmx.org) friendly, allowing easy translation of [`OINODataRow`](https://pragmatta.github.io/oino-ts/types/db_src.OINODataRow.html) to HTML output using templates (cf. the [htmx sample app](https://github.com/pragmatta/oino-ts/tree/main/samples/htmxApp)).
123
-
124
- ## Hashids
125
- Autoinc numeric id's are very pragmatic and fit well with OINO (e.g. using a form without primary key fields to insert new rows with database assigned ids). However it's not always sensible to share information about the sequence. Hashids solve this by masking the original values by encrypting the ids using AES-128 and some randomness. Length of the hashid can be chosen from 12-32 characters where longer ids provide more security. However this should not be considereded a cryptographic solution for keeping ids secret but rather making it infeasible to iterate all ids.
126
-
127
-
128
- # STATUS
129
- OINO is currently a hobby project which should and should considered in alpha status. That also means compatibility breaking changes can be made without prior notice when architectual issues are discovered.
130
-
131
- ## Beta
132
- For a beta status following milestones are planned:
133
-
134
- ### Realistic app
135
- There needs to be a realistic app built on top of OINO to get a better grasp of the edge cases.
136
-
137
- ## Roadmap
138
- Things that need to happen in some order before beta-status are at least following:
139
-
140
- ### Support for views
141
- Simple cases of views would work already in some databases but edge cases might get complicated. For example
142
- - How to handle a view which does not have a complete private key?
143
- - What edge cases exist in updating views?
144
-
145
- ### Batch updates
146
- Supporting batch updates similar to batch inserts is slightly bending the RESTfull principles but would still be a useful optional feature.
147
-
148
- ### Aggregation
149
- Similar to filtering, ordering and limits, aggregation could be implemented as HTTP request parameters telling what column is aggregated or used for ordering or how many results to return.
150
-
151
- ### Streaming
152
- One core idea is to be efficient in not making unnecessary copies of the data and minimizing garbage collection debt. This can be taken further by implementing streaming, allowing large dataset to be written to HTTP response as SQL result rows are received.
153
-
154
- ### SQL generation callbacks
155
- It would be useful to allow developer to validate / override SQL generation to cover cases OINO does not support or even workaround issues.
156
-
157
- ### Transactions
158
- Even though the basic case for OINO is executing SQL operations on individual rows, having an option to use SQL transactions could make sense at least for batch operations.
159
-
160
-
161
- # HELP
162
-
163
- ## Bug reports
164
- Fixing bugs is a priority and getting good quality bug reports helps. It's recommended to use the sample Northwind database included with project to replicate issues or make an SQL script export of the relevant table.
165
-
166
- ## Feedback
167
- Understanding and prioritizing the use cases for OINO is also important and feedback about how you'd use OINO is interesting. Feel free to raise issues and feature requests in Github, but understand that short term most of the effort goes towards reaching the beta stage.
168
-
169
- ## Typescript / Javascript architecture
170
- Typescript building with different targets and module-systemts and a ton of configuration is a complex domain and something I have little experience un so help in fixing problems and how thing ought to be done is appreciated.
171
-
172
- # LINKS
173
- - [Github repository](https://github.com/pragmatta/oino-ts)
174
- - [NPM repository](https://www.npmjs.com/org/oino-ts)
175
-
176
-
177
- # ACKNOWLEDGEMENTS
178
-
179
- ## Libraries
180
- OINO uses the following open source libraries and npm packages and I would like to thank everyone for their contributions:
181
- - Postgresql [node-postgres package](https://www.npmjs.com/package/pg)
182
- - Mariadb / Mysql [mariadb package](https://www.npmjs.com/package/mariadb)
183
- - Sql Server [mssql package](https://www.npmjs.com/package/mssql)
184
- - Custom base encoding [base-x package](https://www.npmjs.com/package/base-x)
185
-
186
- ## Bun
187
- OINO has been developed using the Bun runtime, not because of the speed improvements but for the first class Typescript support and integrated developper experience. Kudos on the bun team for making Typescript work more exiting again.
188
-
189
- ## SQL Scripts
190
- The SQL scripts for creating the sample Northwind database are based on [Google Code archive](https://code.google.com/archive/p/northwindextended/downloads) and have been further customized to ensure they would have identical data (in the scope of the automated testing).