@oino-ts/db-postgresql 0.3.3 → 0.4.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.
- package/dist/cjs/OINODbPostgresql.js +33 -24
- package/dist/esm/OINODbPostgresql.js +33 -24
- package/dist/types/OINODbPostgresql.d.ts +7 -0
- package/package.json +37 -37
- package/src/OINODbPostgresql.ts +396 -385
- package/src/index.ts +1 -1
- package/README.md +0 -190
|
@@ -186,9 +186,18 @@ class OINODbPostgresql extends db_1.OINODb {
|
|
|
186
186
|
return "\'" + cellValue.toISOString() + "\'";
|
|
187
187
|
}
|
|
188
188
|
else {
|
|
189
|
-
return
|
|
189
|
+
return this.printSqlString(cellValue.toString());
|
|
190
190
|
}
|
|
191
191
|
}
|
|
192
|
+
/**
|
|
193
|
+
* Print a single string value as valid sql literal
|
|
194
|
+
*
|
|
195
|
+
* @param sqlString string value
|
|
196
|
+
*
|
|
197
|
+
*/
|
|
198
|
+
printSqlString(sqlString) {
|
|
199
|
+
return "\'" + sqlString.replaceAll("'", "''") + "\'";
|
|
200
|
+
}
|
|
192
201
|
/**
|
|
193
202
|
* Parse a single SQL result value for serialization using the context of the native data
|
|
194
203
|
* type.
|
|
@@ -201,7 +210,7 @@ class OINODbPostgresql extends db_1.OINODb {
|
|
|
201
210
|
if ((sqlValue === null) || (sqlValue == "NULL")) {
|
|
202
211
|
return null;
|
|
203
212
|
}
|
|
204
|
-
else if (
|
|
213
|
+
else if (sqlValue === undefined) {
|
|
205
214
|
return undefined;
|
|
206
215
|
}
|
|
207
216
|
else if (((sqlType == "date")) && (typeof (sqlValue) == "string")) {
|
|
@@ -269,28 +278,28 @@ class OINODbPostgresql extends db_1.OINODb {
|
|
|
269
278
|
return result;
|
|
270
279
|
}
|
|
271
280
|
_getSchemaSql(dbName, tableName) {
|
|
272
|
-
const sql = `SELECT
|
|
273
|
-
col.column_name,
|
|
274
|
-
col.data_type,
|
|
275
|
-
col.character_maximum_length,
|
|
276
|
-
col.is_nullable,
|
|
277
|
-
con.constraint_type,
|
|
278
|
-
col.numeric_precision,
|
|
279
|
-
col.numeric_scale,
|
|
280
|
-
col.column_default
|
|
281
|
-
FROM information_schema.columns col
|
|
282
|
-
LEFT JOIN LATERAL
|
|
283
|
-
(select kcu.column_name, STRING_AGG(tco.constraint_type,',') as constraint_type
|
|
284
|
-
from
|
|
285
|
-
information_schema.table_constraints tco,
|
|
286
|
-
information_schema.key_column_usage kcu
|
|
287
|
-
where
|
|
288
|
-
kcu.constraint_name = tco.constraint_name
|
|
289
|
-
and kcu.constraint_schema = tco.constraint_schema
|
|
290
|
-
and tco.table_catalog = col.table_catalog
|
|
291
|
-
and tco.table_name = col.table_name
|
|
292
|
-
and (tco.constraint_type = 'PRIMARY KEY' OR tco.constraint_type = 'FOREIGN KEY')
|
|
293
|
-
group by kcu.column_name) con on col.column_name = con.column_name
|
|
281
|
+
const sql = `SELECT
|
|
282
|
+
col.column_name,
|
|
283
|
+
col.data_type,
|
|
284
|
+
col.character_maximum_length,
|
|
285
|
+
col.is_nullable,
|
|
286
|
+
con.constraint_type,
|
|
287
|
+
col.numeric_precision,
|
|
288
|
+
col.numeric_scale,
|
|
289
|
+
col.column_default
|
|
290
|
+
FROM information_schema.columns col
|
|
291
|
+
LEFT JOIN LATERAL
|
|
292
|
+
(select kcu.column_name, STRING_AGG(tco.constraint_type,',') as constraint_type
|
|
293
|
+
from
|
|
294
|
+
information_schema.table_constraints tco,
|
|
295
|
+
information_schema.key_column_usage kcu
|
|
296
|
+
where
|
|
297
|
+
kcu.constraint_name = tco.constraint_name
|
|
298
|
+
and kcu.constraint_schema = tco.constraint_schema
|
|
299
|
+
and tco.table_catalog = col.table_catalog
|
|
300
|
+
and tco.table_name = col.table_name
|
|
301
|
+
and (tco.constraint_type = 'PRIMARY KEY' OR tco.constraint_type = 'FOREIGN KEY')
|
|
302
|
+
group by kcu.column_name) con on col.column_name = con.column_name
|
|
294
303
|
WHERE col.table_catalog = '${dbName}' AND col.table_name = '${tableName}'`;
|
|
295
304
|
return sql;
|
|
296
305
|
}
|
|
@@ -183,9 +183,18 @@ export class OINODbPostgresql extends OINODb {
|
|
|
183
183
|
return "\'" + cellValue.toISOString() + "\'";
|
|
184
184
|
}
|
|
185
185
|
else {
|
|
186
|
-
return
|
|
186
|
+
return this.printSqlString(cellValue.toString());
|
|
187
187
|
}
|
|
188
188
|
}
|
|
189
|
+
/**
|
|
190
|
+
* Print a single string value as valid sql literal
|
|
191
|
+
*
|
|
192
|
+
* @param sqlString string value
|
|
193
|
+
*
|
|
194
|
+
*/
|
|
195
|
+
printSqlString(sqlString) {
|
|
196
|
+
return "\'" + sqlString.replaceAll("'", "''") + "\'";
|
|
197
|
+
}
|
|
189
198
|
/**
|
|
190
199
|
* Parse a single SQL result value for serialization using the context of the native data
|
|
191
200
|
* type.
|
|
@@ -198,7 +207,7 @@ export class OINODbPostgresql extends OINODb {
|
|
|
198
207
|
if ((sqlValue === null) || (sqlValue == "NULL")) {
|
|
199
208
|
return null;
|
|
200
209
|
}
|
|
201
|
-
else if (
|
|
210
|
+
else if (sqlValue === undefined) {
|
|
202
211
|
return undefined;
|
|
203
212
|
}
|
|
204
213
|
else if (((sqlType == "date")) && (typeof (sqlValue) == "string")) {
|
|
@@ -266,28 +275,28 @@ export class OINODbPostgresql extends OINODb {
|
|
|
266
275
|
return result;
|
|
267
276
|
}
|
|
268
277
|
_getSchemaSql(dbName, tableName) {
|
|
269
|
-
const sql = `SELECT
|
|
270
|
-
col.column_name,
|
|
271
|
-
col.data_type,
|
|
272
|
-
col.character_maximum_length,
|
|
273
|
-
col.is_nullable,
|
|
274
|
-
con.constraint_type,
|
|
275
|
-
col.numeric_precision,
|
|
276
|
-
col.numeric_scale,
|
|
277
|
-
col.column_default
|
|
278
|
-
FROM information_schema.columns col
|
|
279
|
-
LEFT JOIN LATERAL
|
|
280
|
-
(select kcu.column_name, STRING_AGG(tco.constraint_type,',') as constraint_type
|
|
281
|
-
from
|
|
282
|
-
information_schema.table_constraints tco,
|
|
283
|
-
information_schema.key_column_usage kcu
|
|
284
|
-
where
|
|
285
|
-
kcu.constraint_name = tco.constraint_name
|
|
286
|
-
and kcu.constraint_schema = tco.constraint_schema
|
|
287
|
-
and tco.table_catalog = col.table_catalog
|
|
288
|
-
and tco.table_name = col.table_name
|
|
289
|
-
and (tco.constraint_type = 'PRIMARY KEY' OR tco.constraint_type = 'FOREIGN KEY')
|
|
290
|
-
group by kcu.column_name) con on col.column_name = con.column_name
|
|
278
|
+
const sql = `SELECT
|
|
279
|
+
col.column_name,
|
|
280
|
+
col.data_type,
|
|
281
|
+
col.character_maximum_length,
|
|
282
|
+
col.is_nullable,
|
|
283
|
+
con.constraint_type,
|
|
284
|
+
col.numeric_precision,
|
|
285
|
+
col.numeric_scale,
|
|
286
|
+
col.column_default
|
|
287
|
+
FROM information_schema.columns col
|
|
288
|
+
LEFT JOIN LATERAL
|
|
289
|
+
(select kcu.column_name, STRING_AGG(tco.constraint_type,',') as constraint_type
|
|
290
|
+
from
|
|
291
|
+
information_schema.table_constraints tco,
|
|
292
|
+
information_schema.key_column_usage kcu
|
|
293
|
+
where
|
|
294
|
+
kcu.constraint_name = tco.constraint_name
|
|
295
|
+
and kcu.constraint_schema = tco.constraint_schema
|
|
296
|
+
and tco.table_catalog = col.table_catalog
|
|
297
|
+
and tco.table_name = col.table_name
|
|
298
|
+
and (tco.constraint_type = 'PRIMARY KEY' OR tco.constraint_type = 'FOREIGN KEY')
|
|
299
|
+
group by kcu.column_name) con on col.column_name = con.column_name
|
|
291
300
|
WHERE col.table_catalog = '${dbName}' AND col.table_name = '${tableName}'`;
|
|
292
301
|
return sql;
|
|
293
302
|
}
|
|
@@ -36,6 +36,13 @@ export declare class OINODbPostgresql extends OINODb {
|
|
|
36
36
|
*
|
|
37
37
|
*/
|
|
38
38
|
printCellAsSqlValue(cellValue: OINODataCell, sqlType: string): string;
|
|
39
|
+
/**
|
|
40
|
+
* Print a single string value as valid sql literal
|
|
41
|
+
*
|
|
42
|
+
* @param sqlString string value
|
|
43
|
+
*
|
|
44
|
+
*/
|
|
45
|
+
printSqlString(sqlString: string): string;
|
|
39
46
|
/**
|
|
40
47
|
* Parse a single SQL result value for serialization using the context of the native data
|
|
41
48
|
* type.
|
package/package.json
CHANGED
|
@@ -1,37 +1,37 @@
|
|
|
1
|
-
{
|
|
2
|
-
"name": "@oino-ts/db-postgresql",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"description": "OINO TS package for using Postgresql 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
|
-
"postgresql"
|
|
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.
|
|
24
|
-
"pg": "^8.11.3"
|
|
25
|
-
},
|
|
26
|
-
"devDependencies": {
|
|
27
|
-
"@types/node": "^20.12.7",
|
|
28
|
-
"@types/pg": "^8.11.5",
|
|
29
|
-
"@types/bun": "latest"
|
|
30
|
-
},
|
|
31
|
-
"files": [
|
|
32
|
-
"src/*.ts",
|
|
33
|
-
"dist/cjs/*.js",
|
|
34
|
-
"dist/esm/*.js",
|
|
35
|
-
"dist/types/*.d.ts"
|
|
36
|
-
]
|
|
37
|
-
}
|
|
1
|
+
{
|
|
2
|
+
"name": "@oino-ts/db-postgresql",
|
|
3
|
+
"version": "0.4.0",
|
|
4
|
+
"description": "OINO TS package for using Postgresql 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
|
+
"postgresql"
|
|
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.4.0",
|
|
24
|
+
"pg": "^8.11.3"
|
|
25
|
+
},
|
|
26
|
+
"devDependencies": {
|
|
27
|
+
"@types/node": "^20.12.7",
|
|
28
|
+
"@types/pg": "^8.11.5",
|
|
29
|
+
"@types/bun": "latest"
|
|
30
|
+
},
|
|
31
|
+
"files": [
|
|
32
|
+
"src/*.ts",
|
|
33
|
+
"dist/cjs/*.js",
|
|
34
|
+
"dist/esm/*.js",
|
|
35
|
+
"dist/types/*.d.ts"
|
|
36
|
+
]
|
|
37
|
+
}
|
package/src/OINODbPostgresql.ts
CHANGED
|
@@ -1,385 +1,396 @@
|
|
|
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, OINOLog } from "@oino-ts/db";
|
|
8
|
-
|
|
9
|
-
import { Pool, QueryResult } from "pg";
|
|
10
|
-
|
|
11
|
-
const EMPTY_ROW:string[] = []
|
|
12
|
-
|
|
13
|
-
/**
|
|
14
|
-
* Implmentation of OINODbDataSet for Postgresql.
|
|
15
|
-
*
|
|
16
|
-
*/
|
|
17
|
-
class OINOPostgresqlData extends OINODbDataSet {
|
|
18
|
-
private _rows:OINODataRow[]
|
|
19
|
-
|
|
20
|
-
/**
|
|
21
|
-
* OINOPostgresqlData constructor
|
|
22
|
-
* @param params database parameters
|
|
23
|
-
*/
|
|
24
|
-
constructor(data: unknown, messages:string[]=[]) {
|
|
25
|
-
super(data, messages)
|
|
26
|
-
|
|
27
|
-
if ((data != null) && !(Array.isArray(data))) {
|
|
28
|
-
throw new Error(OINO_ERROR_PREFIX + ": Invalid Posgresql data type!") // TODO: maybe check all rows
|
|
29
|
-
}
|
|
30
|
-
this._rows = data as OINODataRow[]
|
|
31
|
-
if (this.isEmpty()) {
|
|
32
|
-
this._currentRow = -1
|
|
33
|
-
this._eof = true
|
|
34
|
-
} else {
|
|
35
|
-
this._currentRow = 0
|
|
36
|
-
this._eof = false
|
|
37
|
-
}
|
|
38
|
-
}
|
|
39
|
-
private _currentRow: number
|
|
40
|
-
private _eof: boolean
|
|
41
|
-
|
|
42
|
-
/**
|
|
43
|
-
* Is data set empty.
|
|
44
|
-
*
|
|
45
|
-
*/
|
|
46
|
-
isEmpty():boolean {
|
|
47
|
-
return (this._rows.length == 0)
|
|
48
|
-
}
|
|
49
|
-
|
|
50
|
-
/**
|
|
51
|
-
* Is there no more content, i.e. either dataset is empty or we have moved beyond last line
|
|
52
|
-
*
|
|
53
|
-
*/
|
|
54
|
-
isEof():boolean {
|
|
55
|
-
return (this._eof)
|
|
56
|
-
}
|
|
57
|
-
|
|
58
|
-
/**
|
|
59
|
-
* Attempts to moves dataset to the next row, possibly waiting for more data to become available. Returns !isEof().
|
|
60
|
-
*
|
|
61
|
-
*/
|
|
62
|
-
async next():Promise<boolean> {
|
|
63
|
-
// OINOLog.debug("OINODbDataSet.next", {currentRow:this._currentRow, length:this.sqlResult.data.length})
|
|
64
|
-
if (this._currentRow < this._rows.length-1) {
|
|
65
|
-
this._currentRow = this._currentRow + 1
|
|
66
|
-
} else {
|
|
67
|
-
this._eof = true
|
|
68
|
-
}
|
|
69
|
-
return Promise.resolve(!this._eof)
|
|
70
|
-
}
|
|
71
|
-
|
|
72
|
-
/**
|
|
73
|
-
* Gets current row of data.
|
|
74
|
-
*
|
|
75
|
-
*/
|
|
76
|
-
getRow(): OINODataRow {
|
|
77
|
-
if ((this._currentRow >=0) && (this._currentRow < this._rows.length)) {
|
|
78
|
-
return this._rows[this._currentRow]
|
|
79
|
-
} else {
|
|
80
|
-
return EMPTY_ROW
|
|
81
|
-
}
|
|
82
|
-
}
|
|
83
|
-
}
|
|
84
|
-
|
|
85
|
-
/**
|
|
86
|
-
* Implementation of Postgresql-database.
|
|
87
|
-
*
|
|
88
|
-
*/
|
|
89
|
-
export class OINODbPostgresql extends OINODb {
|
|
90
|
-
|
|
91
|
-
private _pool:Pool
|
|
92
|
-
|
|
93
|
-
/**
|
|
94
|
-
* Constructor of `OINODbPostgresql`
|
|
95
|
-
* @param params database paraneters
|
|
96
|
-
*/
|
|
97
|
-
constructor(params:OINODbParams) {
|
|
98
|
-
super(params)
|
|
99
|
-
|
|
100
|
-
// OINOLog.debug("OINODbPostgresql.constructor", {params:params})
|
|
101
|
-
if (this._params.type !== "OINODbPostgresql") {
|
|
102
|
-
throw new Error(OINO_ERROR_PREFIX + ": Not OINODbPostgresql-type: " + this._params.type)
|
|
103
|
-
}
|
|
104
|
-
const ssl_enabled:boolean = !(params.url == "localhost" || params.url == "127.0.0.1")
|
|
105
|
-
this._pool = new Pool({ host: params.url, database: params.database, port: params.port, user: params.user, password: params.password, ssl: ssl_enabled })
|
|
106
|
-
this._pool.on("error", (err: any) => {
|
|
107
|
-
OINOLog.error("OINODbPostgresql error", {err:err})
|
|
108
|
-
})
|
|
109
|
-
this._pool.on("connect", (message: any) => {
|
|
110
|
-
// OINOLog.info("OINODbPostgresql connect")
|
|
111
|
-
})
|
|
112
|
-
this._pool.on("release", (message: any) => {
|
|
113
|
-
// OINOLog.info("OINODbPostgresql notice")
|
|
114
|
-
})
|
|
115
|
-
this._pool.on("acquire", () => {
|
|
116
|
-
// OINOLog.info("OINODbPostgresql end")
|
|
117
|
-
})
|
|
118
|
-
}
|
|
119
|
-
|
|
120
|
-
private _parseFieldLength(fieldLength:OINODataCell):number {
|
|
121
|
-
let result:number = parseInt((fieldLength || "0").toString())
|
|
122
|
-
if (Number.isNaN(result)) {
|
|
123
|
-
result = 0
|
|
124
|
-
}
|
|
125
|
-
return result
|
|
126
|
-
}
|
|
127
|
-
|
|
128
|
-
private async _query(sql:string):Promise<OINODataRow[]> {
|
|
129
|
-
// OINOLog.debug("OINODbPostgresql._query", {sql:sql})
|
|
130
|
-
const query_result:QueryResult = await this._pool.query({rowMode: "array", text: sql})
|
|
131
|
-
// OINOLog.debug("OINODbPostgresql._query", {result:query_result})
|
|
132
|
-
return Promise.resolve(query_result.rows)
|
|
133
|
-
}
|
|
134
|
-
|
|
135
|
-
private async _exec(sql:string):Promise<OINODataRow[]> {
|
|
136
|
-
// OINOLog.debug("OINODbPostgresql._query", {sql:sql})
|
|
137
|
-
const query_result:QueryResult = await this._pool.query({rowMode: "array", text: sql})
|
|
138
|
-
// OINOLog.debug("OINODbPostgresql._query", {result:query_result})
|
|
139
|
-
return Promise.resolve(query_result.rows)
|
|
140
|
-
}
|
|
141
|
-
|
|
142
|
-
/**
|
|
143
|
-
* Print a table name using database specific SQL escaping.
|
|
144
|
-
*
|
|
145
|
-
* @param sqlTable name of the table
|
|
146
|
-
*
|
|
147
|
-
*/
|
|
148
|
-
printSqlTablename(sqlTable:string): string {
|
|
149
|
-
return "\""+sqlTable.toLowerCase()+"\""
|
|
150
|
-
}
|
|
151
|
-
|
|
152
|
-
/**
|
|
153
|
-
* Print a column name with correct SQL escaping.
|
|
154
|
-
*
|
|
155
|
-
* @param sqlColumn name of the column
|
|
156
|
-
*
|
|
157
|
-
*/
|
|
158
|
-
printSqlColumnname(sqlColumn:string): string {
|
|
159
|
-
return "\""+sqlColumn+"\""
|
|
160
|
-
}
|
|
161
|
-
|
|
162
|
-
/**
|
|
163
|
-
* Print a single data value from serialization using the context of the native data
|
|
164
|
-
* type with the correct SQL escaping.
|
|
165
|
-
*
|
|
166
|
-
* @param cellValue data from sql results
|
|
167
|
-
* @param sqlType native type name for table column
|
|
168
|
-
*
|
|
169
|
-
*/
|
|
170
|
-
printCellAsSqlValue(cellValue:OINODataCell, sqlType: string): string {
|
|
171
|
-
if (cellValue === null) {
|
|
172
|
-
return "NULL"
|
|
173
|
-
|
|
174
|
-
} else if (cellValue === undefined) {
|
|
175
|
-
return "UNDEFINED"
|
|
176
|
-
|
|
177
|
-
} else if ((sqlType == "integer") || (sqlType == "smallint") || (sqlType == "real")) {
|
|
178
|
-
return cellValue.toString()
|
|
179
|
-
|
|
180
|
-
} else if (sqlType == "bytea") {
|
|
181
|
-
if (cellValue instanceof Buffer) {
|
|
182
|
-
return "'\\x" + (cellValue as Buffer).toString("hex") + "'"
|
|
183
|
-
} else if (cellValue instanceof Uint8Array) {
|
|
184
|
-
return "'\\x" + Buffer.from(cellValue as Uint8Array).toString("hex") + "'"
|
|
185
|
-
} else {
|
|
186
|
-
return "\'" + cellValue?.toString() + "\'"
|
|
187
|
-
}
|
|
188
|
-
|
|
189
|
-
} else if (sqlType == "boolean") {
|
|
190
|
-
if (cellValue == null || cellValue == "" || cellValue.toString().toLowerCase() == "false" || cellValue == "0") {
|
|
191
|
-
return "false"
|
|
192
|
-
} else {
|
|
193
|
-
return "true"
|
|
194
|
-
}
|
|
195
|
-
|
|
196
|
-
} else if ((sqlType == "date") && (cellValue instanceof Date)) {
|
|
197
|
-
return "\'" + cellValue.toISOString() + "\'"
|
|
198
|
-
|
|
199
|
-
} else {
|
|
200
|
-
return
|
|
201
|
-
}
|
|
202
|
-
}
|
|
203
|
-
|
|
204
|
-
/**
|
|
205
|
-
*
|
|
206
|
-
*
|
|
207
|
-
*
|
|
208
|
-
*
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
OINOBenchmark.
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
|
|
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, OINOLog } from "@oino-ts/db";
|
|
8
|
+
|
|
9
|
+
import { Pool, QueryResult } from "pg";
|
|
10
|
+
|
|
11
|
+
const EMPTY_ROW:string[] = []
|
|
12
|
+
|
|
13
|
+
/**
|
|
14
|
+
* Implmentation of OINODbDataSet for Postgresql.
|
|
15
|
+
*
|
|
16
|
+
*/
|
|
17
|
+
class OINOPostgresqlData extends OINODbDataSet {
|
|
18
|
+
private _rows:OINODataRow[]
|
|
19
|
+
|
|
20
|
+
/**
|
|
21
|
+
* OINOPostgresqlData constructor
|
|
22
|
+
* @param params database parameters
|
|
23
|
+
*/
|
|
24
|
+
constructor(data: unknown, messages:string[]=[]) {
|
|
25
|
+
super(data, messages)
|
|
26
|
+
|
|
27
|
+
if ((data != null) && !(Array.isArray(data))) {
|
|
28
|
+
throw new Error(OINO_ERROR_PREFIX + ": Invalid Posgresql data type!") // TODO: maybe check all rows
|
|
29
|
+
}
|
|
30
|
+
this._rows = data as OINODataRow[]
|
|
31
|
+
if (this.isEmpty()) {
|
|
32
|
+
this._currentRow = -1
|
|
33
|
+
this._eof = true
|
|
34
|
+
} else {
|
|
35
|
+
this._currentRow = 0
|
|
36
|
+
this._eof = false
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
private _currentRow: number
|
|
40
|
+
private _eof: boolean
|
|
41
|
+
|
|
42
|
+
/**
|
|
43
|
+
* Is data set empty.
|
|
44
|
+
*
|
|
45
|
+
*/
|
|
46
|
+
isEmpty():boolean {
|
|
47
|
+
return (this._rows.length == 0)
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/**
|
|
51
|
+
* Is there no more content, i.e. either dataset is empty or we have moved beyond last line
|
|
52
|
+
*
|
|
53
|
+
*/
|
|
54
|
+
isEof():boolean {
|
|
55
|
+
return (this._eof)
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/**
|
|
59
|
+
* Attempts to moves dataset to the next row, possibly waiting for more data to become available. Returns !isEof().
|
|
60
|
+
*
|
|
61
|
+
*/
|
|
62
|
+
async next():Promise<boolean> {
|
|
63
|
+
// OINOLog.debug("OINODbDataSet.next", {currentRow:this._currentRow, length:this.sqlResult.data.length})
|
|
64
|
+
if (this._currentRow < this._rows.length-1) {
|
|
65
|
+
this._currentRow = this._currentRow + 1
|
|
66
|
+
} else {
|
|
67
|
+
this._eof = true
|
|
68
|
+
}
|
|
69
|
+
return Promise.resolve(!this._eof)
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/**
|
|
73
|
+
* Gets current row of data.
|
|
74
|
+
*
|
|
75
|
+
*/
|
|
76
|
+
getRow(): OINODataRow {
|
|
77
|
+
if ((this._currentRow >=0) && (this._currentRow < this._rows.length)) {
|
|
78
|
+
return this._rows[this._currentRow]
|
|
79
|
+
} else {
|
|
80
|
+
return EMPTY_ROW
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/**
|
|
86
|
+
* Implementation of Postgresql-database.
|
|
87
|
+
*
|
|
88
|
+
*/
|
|
89
|
+
export class OINODbPostgresql extends OINODb {
|
|
90
|
+
|
|
91
|
+
private _pool:Pool
|
|
92
|
+
|
|
93
|
+
/**
|
|
94
|
+
* Constructor of `OINODbPostgresql`
|
|
95
|
+
* @param params database paraneters
|
|
96
|
+
*/
|
|
97
|
+
constructor(params:OINODbParams) {
|
|
98
|
+
super(params)
|
|
99
|
+
|
|
100
|
+
// OINOLog.debug("OINODbPostgresql.constructor", {params:params})
|
|
101
|
+
if (this._params.type !== "OINODbPostgresql") {
|
|
102
|
+
throw new Error(OINO_ERROR_PREFIX + ": Not OINODbPostgresql-type: " + this._params.type)
|
|
103
|
+
}
|
|
104
|
+
const ssl_enabled:boolean = !(params.url == "localhost" || params.url == "127.0.0.1")
|
|
105
|
+
this._pool = new Pool({ host: params.url, database: params.database, port: params.port, user: params.user, password: params.password, ssl: ssl_enabled })
|
|
106
|
+
this._pool.on("error", (err: any) => {
|
|
107
|
+
OINOLog.error("OINODbPostgresql error", {err:err})
|
|
108
|
+
})
|
|
109
|
+
this._pool.on("connect", (message: any) => {
|
|
110
|
+
// OINOLog.info("OINODbPostgresql connect")
|
|
111
|
+
})
|
|
112
|
+
this._pool.on("release", (message: any) => {
|
|
113
|
+
// OINOLog.info("OINODbPostgresql notice")
|
|
114
|
+
})
|
|
115
|
+
this._pool.on("acquire", () => {
|
|
116
|
+
// OINOLog.info("OINODbPostgresql end")
|
|
117
|
+
})
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
private _parseFieldLength(fieldLength:OINODataCell):number {
|
|
121
|
+
let result:number = parseInt((fieldLength || "0").toString())
|
|
122
|
+
if (Number.isNaN(result)) {
|
|
123
|
+
result = 0
|
|
124
|
+
}
|
|
125
|
+
return result
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
private async _query(sql:string):Promise<OINODataRow[]> {
|
|
129
|
+
// OINOLog.debug("OINODbPostgresql._query", {sql:sql})
|
|
130
|
+
const query_result:QueryResult = await this._pool.query({rowMode: "array", text: sql})
|
|
131
|
+
// OINOLog.debug("OINODbPostgresql._query", {result:query_result})
|
|
132
|
+
return Promise.resolve(query_result.rows)
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
private async _exec(sql:string):Promise<OINODataRow[]> {
|
|
136
|
+
// OINOLog.debug("OINODbPostgresql._query", {sql:sql})
|
|
137
|
+
const query_result:QueryResult = await this._pool.query({rowMode: "array", text: sql})
|
|
138
|
+
// OINOLog.debug("OINODbPostgresql._query", {result:query_result})
|
|
139
|
+
return Promise.resolve(query_result.rows)
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
/**
|
|
143
|
+
* Print a table name using database specific SQL escaping.
|
|
144
|
+
*
|
|
145
|
+
* @param sqlTable name of the table
|
|
146
|
+
*
|
|
147
|
+
*/
|
|
148
|
+
printSqlTablename(sqlTable:string): string {
|
|
149
|
+
return "\""+sqlTable.toLowerCase()+"\""
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
/**
|
|
153
|
+
* Print a column name with correct SQL escaping.
|
|
154
|
+
*
|
|
155
|
+
* @param sqlColumn name of the column
|
|
156
|
+
*
|
|
157
|
+
*/
|
|
158
|
+
printSqlColumnname(sqlColumn:string): string {
|
|
159
|
+
return "\""+sqlColumn+"\""
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
/**
|
|
163
|
+
* Print a single data value from serialization using the context of the native data
|
|
164
|
+
* type with the correct SQL escaping.
|
|
165
|
+
*
|
|
166
|
+
* @param cellValue data from sql results
|
|
167
|
+
* @param sqlType native type name for table column
|
|
168
|
+
*
|
|
169
|
+
*/
|
|
170
|
+
printCellAsSqlValue(cellValue:OINODataCell, sqlType: string): string {
|
|
171
|
+
if (cellValue === null) {
|
|
172
|
+
return "NULL"
|
|
173
|
+
|
|
174
|
+
} else if (cellValue === undefined) {
|
|
175
|
+
return "UNDEFINED"
|
|
176
|
+
|
|
177
|
+
} else if ((sqlType == "integer") || (sqlType == "smallint") || (sqlType == "real")) {
|
|
178
|
+
return cellValue.toString()
|
|
179
|
+
|
|
180
|
+
} else if (sqlType == "bytea") {
|
|
181
|
+
if (cellValue instanceof Buffer) {
|
|
182
|
+
return "'\\x" + (cellValue as Buffer).toString("hex") + "'"
|
|
183
|
+
} else if (cellValue instanceof Uint8Array) {
|
|
184
|
+
return "'\\x" + Buffer.from(cellValue as Uint8Array).toString("hex") + "'"
|
|
185
|
+
} else {
|
|
186
|
+
return "\'" + cellValue?.toString() + "\'"
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
} else if (sqlType == "boolean") {
|
|
190
|
+
if (cellValue == null || cellValue == "" || cellValue.toString().toLowerCase() == "false" || cellValue == "0") {
|
|
191
|
+
return "false"
|
|
192
|
+
} else {
|
|
193
|
+
return "true"
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
} else if ((sqlType == "date") && (cellValue instanceof Date)) {
|
|
197
|
+
return "\'" + cellValue.toISOString() + "\'"
|
|
198
|
+
|
|
199
|
+
} else {
|
|
200
|
+
return this.printSqlString(cellValue.toString())
|
|
201
|
+
}
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
/**
|
|
205
|
+
* Print a single string value as valid sql literal
|
|
206
|
+
*
|
|
207
|
+
* @param sqlString string value
|
|
208
|
+
*
|
|
209
|
+
*/
|
|
210
|
+
printSqlString(sqlString:string): string {
|
|
211
|
+
return "\'" + sqlString.replaceAll("'", "''") + "\'"
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
|
|
215
|
+
/**
|
|
216
|
+
* Parse a single SQL result value for serialization using the context of the native data
|
|
217
|
+
* type.
|
|
218
|
+
*
|
|
219
|
+
* @param sqlValue data from serialization
|
|
220
|
+
* @param sqlType native type name for table column
|
|
221
|
+
*
|
|
222
|
+
*/
|
|
223
|
+
parseSqlValueAsCell(sqlValue:OINODataCell, sqlType: string): OINODataCell {
|
|
224
|
+
if ((sqlValue === null) || (sqlValue == "NULL")) {
|
|
225
|
+
return null
|
|
226
|
+
|
|
227
|
+
} else if (sqlValue === undefined) {
|
|
228
|
+
return undefined
|
|
229
|
+
|
|
230
|
+
} else if (((sqlType == "date")) && (typeof(sqlValue) == "string")) {
|
|
231
|
+
return new Date(sqlValue)
|
|
232
|
+
|
|
233
|
+
} else {
|
|
234
|
+
return sqlValue
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
/**
|
|
240
|
+
* Connect to database.
|
|
241
|
+
*
|
|
242
|
+
*/
|
|
243
|
+
async connect(): Promise<boolean> {
|
|
244
|
+
try {
|
|
245
|
+
// make sure that any items are correctly URL encoded in the connection string
|
|
246
|
+
// OINOLog.debug("OINODbPostgresql.connect")
|
|
247
|
+
// await this._pool.connect()
|
|
248
|
+
// await this._client.connect()
|
|
249
|
+
return Promise.resolve(true)
|
|
250
|
+
} catch (err) {
|
|
251
|
+
// ... error checks
|
|
252
|
+
throw new Error(OINO_ERROR_PREFIX + ": Error connecting to Postgresql server: " + err)
|
|
253
|
+
}
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
/**
|
|
257
|
+
* Execute a select operation.
|
|
258
|
+
*
|
|
259
|
+
* @param sql SQL statement.
|
|
260
|
+
*
|
|
261
|
+
*/
|
|
262
|
+
async sqlSelect(sql:string): Promise<OINODbDataSet> {
|
|
263
|
+
OINOBenchmark.start("OINODb", "sqlSelect")
|
|
264
|
+
let result:OINODbDataSet
|
|
265
|
+
try {
|
|
266
|
+
const rows:OINODataRow[] = await this._query(sql)
|
|
267
|
+
// OINOLog.debug("OINODbPostgresql.sqlSelect", {rows:rows})
|
|
268
|
+
result = new OINOPostgresqlData(rows, [])
|
|
269
|
+
|
|
270
|
+
} catch (e:any) {
|
|
271
|
+
result = new OINOPostgresqlData([[]], [OINO_ERROR_PREFIX + " (sqlSelect): exception in _db.query [" + e.message + "]"])
|
|
272
|
+
}
|
|
273
|
+
OINOBenchmark.end("OINODb", "sqlSelect")
|
|
274
|
+
return result
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
/**
|
|
278
|
+
* Execute other sql operations.
|
|
279
|
+
*
|
|
280
|
+
* @param sql SQL statement.
|
|
281
|
+
*
|
|
282
|
+
*/
|
|
283
|
+
async sqlExec(sql:string): Promise<OINODbDataSet> {
|
|
284
|
+
OINOBenchmark.start("OINODb", "sqlExec")
|
|
285
|
+
let result:OINODbDataSet
|
|
286
|
+
try {
|
|
287
|
+
const rows:OINODataRow[] = await this._exec(sql)
|
|
288
|
+
// OINOLog.debug("OINODbPostgresql.sqlExec", {rows:rows})
|
|
289
|
+
result = new OINOPostgresqlData(rows, [])
|
|
290
|
+
|
|
291
|
+
} catch (e:any) {
|
|
292
|
+
result = new OINOPostgresqlData([[]], [OINO_ERROR_PREFIX + " (sqlExec): exception in _db.exec [" + e.message + "]"])
|
|
293
|
+
}
|
|
294
|
+
OINOBenchmark.end("OINODb", "sqlExec")
|
|
295
|
+
return result
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
private _getSchemaSql(dbName:string, tableName:string):string {
|
|
299
|
+
const sql =
|
|
300
|
+
`SELECT
|
|
301
|
+
col.column_name,
|
|
302
|
+
col.data_type,
|
|
303
|
+
col.character_maximum_length,
|
|
304
|
+
col.is_nullable,
|
|
305
|
+
con.constraint_type,
|
|
306
|
+
col.numeric_precision,
|
|
307
|
+
col.numeric_scale,
|
|
308
|
+
col.column_default
|
|
309
|
+
FROM information_schema.columns col
|
|
310
|
+
LEFT JOIN LATERAL
|
|
311
|
+
(select kcu.column_name, STRING_AGG(tco.constraint_type,',') as constraint_type
|
|
312
|
+
from
|
|
313
|
+
information_schema.table_constraints tco,
|
|
314
|
+
information_schema.key_column_usage kcu
|
|
315
|
+
where
|
|
316
|
+
kcu.constraint_name = tco.constraint_name
|
|
317
|
+
and kcu.constraint_schema = tco.constraint_schema
|
|
318
|
+
and tco.table_catalog = col.table_catalog
|
|
319
|
+
and tco.table_name = col.table_name
|
|
320
|
+
and (tco.constraint_type = 'PRIMARY KEY' OR tco.constraint_type = 'FOREIGN KEY')
|
|
321
|
+
group by kcu.column_name) con on col.column_name = con.column_name
|
|
322
|
+
WHERE col.table_catalog = '${dbName}' AND col.table_name = '${tableName}'`
|
|
323
|
+
return sql
|
|
324
|
+
}
|
|
325
|
+
|
|
326
|
+
/**
|
|
327
|
+
* Initialize a data model by getting the SQL schema and populating OINODbDataFields of
|
|
328
|
+
* the model.
|
|
329
|
+
*
|
|
330
|
+
* @param api api which data model to initialize.
|
|
331
|
+
*
|
|
332
|
+
*/
|
|
333
|
+
async initializeApiDatamodel(api:OINODbApi): Promise<void> {
|
|
334
|
+
|
|
335
|
+
const res:OINODbDataSet = await this.sqlSelect(this._getSchemaSql(this._params.database, api.params.tableName.toLowerCase()))
|
|
336
|
+
// OINOLog.debug("OINODbPostgresql.initializeApiDatamodel: table description ", {res: res })
|
|
337
|
+
while (!res.isEof()) {
|
|
338
|
+
const row:OINODataRow = res.getRow()
|
|
339
|
+
// OINOLog.debug("OINODbPostgresql.initializeApiDatamodel: next row ", {row: row })
|
|
340
|
+
const field_name:string = row[0]?.toString() || ""
|
|
341
|
+
const sql_type:string = row[1]?.toString() || ""
|
|
342
|
+
const field_length:number = this._parseFieldLength(row[2])
|
|
343
|
+
const constraints = row[4]?.toString() || ""
|
|
344
|
+
const numeric_precision:number = this._parseFieldLength(row[5])
|
|
345
|
+
const numeric_scale:number = this._parseFieldLength(row[6])
|
|
346
|
+
const default_val:string = row[7]?.toString() || ""
|
|
347
|
+
const field_params:OINODbDataFieldParams = {
|
|
348
|
+
isPrimaryKey: constraints.indexOf('PRIMARY KEY') >= 0 || false,
|
|
349
|
+
isForeignKey: constraints.indexOf('FOREIGN KEY') >= 0 || false,
|
|
350
|
+
isNotNull: row[3] == "NO",
|
|
351
|
+
isAutoInc: default_val.startsWith("nextval(")
|
|
352
|
+
}
|
|
353
|
+
if (api.isFieldIncluded(field_name) == false) {
|
|
354
|
+
OINOLog.info("OINODbPostgresql.initializeApiDatamodel: field excluded in API parameters.", {field:field_name})
|
|
355
|
+
if (field_params.isPrimaryKey) {
|
|
356
|
+
throw new Error(OINO_ERROR_PREFIX + "Primary key field excluded in API parameters: " + field_name)
|
|
357
|
+
}
|
|
358
|
+
|
|
359
|
+
} else {
|
|
360
|
+
// OINOLog.debug("OINODbPostgresql.initializeApiDatamodel: next field ", {field_name: field_name, sql_type:sql_type, field_length:field_length, field_params:field_params })
|
|
361
|
+
if ((sql_type == "integer") || (sql_type == "smallint") || (sql_type == "real")) {
|
|
362
|
+
api.datamodel.addField(new OINONumberDataField(this, field_name, sql_type, field_params ))
|
|
363
|
+
|
|
364
|
+
} else if ((sql_type == "date")) {
|
|
365
|
+
if (api.params.useDatesAsString) {
|
|
366
|
+
api.datamodel.addField(new OINOStringDataField(this, field_name, sql_type, field_params, 0))
|
|
367
|
+
} else {
|
|
368
|
+
api.datamodel.addField(new OINODatetimeDataField(this, field_name, sql_type, field_params))
|
|
369
|
+
}
|
|
370
|
+
|
|
371
|
+
} else if ((sql_type == "character") || (sql_type == "character varying") || (sql_type == "varchar") || (sql_type == "text")) {
|
|
372
|
+
api.datamodel.addField(new OINOStringDataField(this, field_name, sql_type, field_params, field_length))
|
|
373
|
+
|
|
374
|
+
} else if ((sql_type == "bytea")) {
|
|
375
|
+
api.datamodel.addField(new OINOBlobDataField(this, field_name, sql_type, field_params, field_length))
|
|
376
|
+
|
|
377
|
+
} else if ((sql_type == "boolean")) {
|
|
378
|
+
api.datamodel.addField(new OINOBooleanDataField(this, field_name, sql_type, field_params))
|
|
379
|
+
|
|
380
|
+
} else if ((sql_type == "decimal") || (sql_type == "numeric")) {
|
|
381
|
+
api.datamodel.addField(new OINOStringDataField(this, field_name, sql_type, field_params, numeric_precision + numeric_scale + 1))
|
|
382
|
+
|
|
383
|
+
} else {
|
|
384
|
+
OINOLog.info("OINODbPostgresql.initializeApiDatamodel: unrecognized field type treated as string", {field_name: field_name, sql_type:sql_type, field_length:field_length, field_params:field_params })
|
|
385
|
+
api.datamodel.addField(new OINOStringDataField(this, field_name, sql_type, field_params, 0))
|
|
386
|
+
}
|
|
387
|
+
}
|
|
388
|
+
await res.next()
|
|
389
|
+
}
|
|
390
|
+
OINOLog.debug("OINODbPostgresql.initializeDatasetModel:\n" + api.datamodel.printDebug("\n"))
|
|
391
|
+
return Promise.resolve()
|
|
392
|
+
}
|
|
393
|
+
}
|
|
394
|
+
|
|
395
|
+
|
|
396
|
+
|
package/src/index.ts
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export { OINODbPostgresql } from "./OINODbPostgresql.js"
|
|
1
|
+
export { OINODbPostgresql } from "./OINODbPostgresql.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
|
-

|
|
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).
|