@oino-ts/db-mssql 0.6.0 → 0.6.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,190 +1,183 @@
1
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).
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
+ # MAIN 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
+ - 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.
78
+ - Datetimes are (optionally) normalized to ISO 8601 format.
79
+ - Extended JSON-encoding
80
+ - 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).
81
+ - CSV
82
+ - Comma-separated, doublequotes.
83
+ - Unquoted literal `null` represents null values.
84
+ - Unquoted empty string represents undefined values.
85
+ - Form data
86
+ - Multipart-mixed and binary files not supported.
87
+ - Non-existent value line (i.e. nothing after the empty line) treated as a null value.
88
+ - Url-encoded
89
+ - No null values, missing properties treated as undefined.
90
+ - Multiple lines could be used to post multiple rows.
91
+
92
+
93
+ ## Database Abstraction
94
+ 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.
95
+
96
+ Currently supported databases:
97
+ - Bun Sqlite through Bun native implementation
98
+ - Postgresql through [pg](https://www.npmjs.com/package/pg)-package
99
+ - Mariadb / Mysql-support through [mariadb](https://www.npmjs.com/package/mariadb)-package
100
+ - Sql Server through [mssql](https://www.npmjs.com/package/mssql)-package
101
+
102
+ ## Composite Keys
103
+ 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`.
104
+
105
+ ## Power Of SQL
106
+ 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.
107
+
108
+ ## Swagger Support
109
+ 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.
110
+ ```
111
+ if (url.pathname == "/swagger.json") {
112
+ return new Response(JSON.stringify(OINOSwagger.getApiDefinition(api_array)))
113
+ }
114
+ ```
115
+ ![Swagger definition with a data model schema](img/readme-swagger.png)
116
+
117
+ ## Node support
118
+ 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).
119
+
120
+ ## HTMX support
121
+ 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)).
122
+
123
+ ## Hashids
124
+ 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.
125
+
126
+
127
+ # STATUS
128
+ OINO is currently a side project which should considered in beta status. That means that semantic versioning is the goal but backwards incompatible changes can still happen in point releases if serious architectual issues are discovered.
129
+
130
+ ## Roadmap
131
+ Major features that are considered in future releases ()
132
+
133
+ ### Support for views
134
+ Simple cases of views probably work already in some databases but edge cases might get complicated.
135
+
136
+ For example issues could be
137
+ - How to handle a view which does not have a complete private key?
138
+ - What edge cases exist in updating views?
139
+ - Can views be handled transparently to the DBMS or is there some fundamentally platform specific behavior?
140
+
141
+ ### Batch updates
142
+ Supporting batch updates similar to batch inserts is slightly bending the RESTfull principles but would still be a useful optional feature in some situations.
143
+
144
+ ### Streaming
145
+ 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.
146
+
147
+ ### SQL generation callbacks
148
+ It would be useful to allow developer to validate / override SQL generation to cover cases OINO does not support or even workaround issues.
149
+
150
+ ### Transactions
151
+ 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.
152
+
153
+
154
+ # HELP
155
+
156
+ ## Bug reports
157
+ 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.
158
+
159
+ ## Feedback
160
+ 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.
161
+
162
+ ## Typescript / Javascript architecture
163
+ 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.
164
+
165
+ # LINKS
166
+ - [Github repository](https://github.com/pragmatta/oino-ts)
167
+ - [NPM repository](https://www.npmjs.com/org/oino-ts)
168
+
169
+
170
+ # ACKNOWLEDGEMENTS
171
+
172
+ ## Libraries
173
+ OINO uses the following open source libraries and npm packages and I would like to thank everyone for their contributions:
174
+ - Postgresql [node-postgres package](https://www.npmjs.com/package/pg)
175
+ - Mariadb / Mysql [mariadb package](https://www.npmjs.com/package/mariadb)
176
+ - Sql Server [mssql package](https://www.npmjs.com/package/mssql)
177
+ - Custom base encoding [base-x package](https://www.npmjs.com/package/base-x)
178
+
179
+ ## Bun
180
+ 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.
181
+
182
+ ## SQL Scripts
183
+ 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).
@@ -109,11 +109,11 @@ class OINODbMsSql extends db_1.OINODb {
109
109
  throw new Error(db_1.OINO_ERROR_PREFIX + ": Not OINODbMsSql-type: " + this._params.type);
110
110
  }
111
111
  this._pool = new mssql_1.ConnectionPool({
112
- user: params.user,
113
- password: params.password,
114
- server: params.url,
115
- port: params.port,
116
- database: params.database,
112
+ user: this._params.user,
113
+ password: this._params.password,
114
+ server: this._params.url,
115
+ port: this._params.port,
116
+ database: this._params.database,
117
117
  arrayRowMode: true,
118
118
  options: {
119
119
  encrypt: true, // Use encryption for Azure SQL Database
@@ -122,18 +122,19 @@ class OINODbMsSql extends db_1.OINODb {
122
122
  trustServerCertificate: true // Change to false for production
123
123
  }
124
124
  });
125
- //this._pool = new ConnectionPool({connectionString: "Server=localhost,1433;Database=database;User Id=username;Password=" + params.password + ";Encrypt=true"})
125
+ delete this._params.password; // do not store password in db object
126
126
  this._pool.on("error", (conn) => {
127
- // console.log("OINODbMsSql error", conn)
128
- });
129
- this._pool.on("debug", (event) => {
130
- // console.log("OINODbMsSql debug",event)
127
+ db_1.OINOLog.error("OINODbMsSql error event", conn);
131
128
  });
129
+ // this._pool.on("debug", (event:any) => {
130
+ // console.log("OINODbMsSql debug",event)
131
+ // })
132
132
  }
133
133
  async _query(sql) {
134
134
  // OINOLog.debug("OINODbMsSql._query", {sql:sql})
135
135
  try {
136
- const sql_res = await this._pool.request().query(sql);
136
+ const request = this._pool.request(); // this does not need to be released but the pool will handle it
137
+ const sql_res = await request.query(sql);
137
138
  // console.log("OINODbMsSql._query result:" + JSON.stringify(sql_res.recordsets))
138
139
  const result = new OINOMsSqlData(sql_res.recordsets);
139
140
  return Promise.resolve(result);
@@ -294,45 +295,53 @@ class OINODbMsSql extends db_1.OINODb {
294
295
  *
295
296
  */
296
297
  async connect() {
298
+ let result = new db_1.OINOResult();
297
299
  try {
298
300
  // make sure that any items are correctly URL encoded in the connection string
299
301
  await this._pool.connect();
300
302
  // OINOLog.info("OINODbMsSql.connect: Connected to database server.")
301
- await this._pool.request().query("SELECT 1 as test");
302
- return Promise.resolve(true);
303
+ // await this._pool.request().query("SELECT 1 as test")
304
+ this.isConnected = true;
303
305
  }
304
306
  catch (err) {
305
307
  // ... error checks
306
- throw new Error(db_1.OINO_ERROR_PREFIX + ": Error connecting to OINODbMsSql server: " + err);
308
+ result.setError(500, "Exception connecting to database: " + err.message, "OINODbMsSql.connect");
309
+ db_1.OINOLog.error(result.statusMessage, { error: err });
307
310
  }
311
+ return Promise.resolve(result);
308
312
  }
309
313
  /**
310
314
  * Validate connection to database is working.
311
315
  *
312
316
  */
313
317
  async validate() {
314
- db_1.OINOBenchmark.start("OINODb", "validate");
315
318
  let result = new db_1.OINOResult();
319
+ if (!this.isConnected) {
320
+ result.setError(400, "Database is not connected!", "OINODbMsSql.validate");
321
+ return result;
322
+ }
323
+ db_1.OINOBenchmark.start("OINODb", "validate");
316
324
  try {
317
325
  const sql = this._getValidateSql(this._params.database);
318
- // OINOLog.debug("OINODbBunSqlite.validate", {sql:sql})
326
+ // OINOLog.debug("OINODbMsSql.validate", {sql:sql})
319
327
  const sql_res = await this.sqlSelect(sql);
320
- // OINOLog.debug("OINODbBunSqlite.validate", {sql_res:sql_res})
328
+ // OINOLog.debug("OINODbMsSql.validate", {sql_res:sql_res})
321
329
  if (sql_res.isEmpty()) {
322
- result.setError(400, "DB returned no rows for select!", "OINODbBunSqlite.validate");
330
+ result.setError(400, "DB returned no rows for select!", "OINODbMsSql.validate");
323
331
  }
324
332
  else if (sql_res.getRow().length == 0) {
325
- result.setError(400, "DB returned no values for database!", "OINODbBunSqlite.validate");
333
+ result.setError(400, "DB returned no values for database!", "OINODbMsSql.validate");
326
334
  }
327
335
  else if (sql_res.getRow()[0] == "0") {
328
- result.setError(400, "DB returned no schema for database!", "OINODbBunSqlite.validate");
336
+ result.setError(400, "DB returned no schema for database!", "OINODbMsSql.validate");
329
337
  }
330
338
  else {
331
339
  // connection is working
340
+ this.isValidated = true;
332
341
  }
333
342
  }
334
343
  catch (e) {
335
- result.setError(500, db_1.OINO_ERROR_PREFIX + " (validate): OINODbBunSqlite.validate exception in _db.query: " + e.message, "OINODbBunSqlite.validate");
344
+ result.setError(500, "Exception in validating connection: " + e.message, "OINODbMsSql.validate");
336
345
  }
337
346
  db_1.OINOBenchmark.end("OINODb", "validate");
338
347
  return result;
@@ -106,11 +106,11 @@ export class OINODbMsSql extends OINODb {
106
106
  throw new Error(OINO_ERROR_PREFIX + ": Not OINODbMsSql-type: " + this._params.type);
107
107
  }
108
108
  this._pool = new ConnectionPool({
109
- user: params.user,
110
- password: params.password,
111
- server: params.url,
112
- port: params.port,
113
- database: params.database,
109
+ user: this._params.user,
110
+ password: this._params.password,
111
+ server: this._params.url,
112
+ port: this._params.port,
113
+ database: this._params.database,
114
114
  arrayRowMode: true,
115
115
  options: {
116
116
  encrypt: true, // Use encryption for Azure SQL Database
@@ -119,18 +119,19 @@ export class OINODbMsSql extends OINODb {
119
119
  trustServerCertificate: true // Change to false for production
120
120
  }
121
121
  });
122
- //this._pool = new ConnectionPool({connectionString: "Server=localhost,1433;Database=database;User Id=username;Password=" + params.password + ";Encrypt=true"})
122
+ delete this._params.password; // do not store password in db object
123
123
  this._pool.on("error", (conn) => {
124
- // console.log("OINODbMsSql error", conn)
125
- });
126
- this._pool.on("debug", (event) => {
127
- // console.log("OINODbMsSql debug",event)
124
+ OINOLog.error("OINODbMsSql error event", conn);
128
125
  });
126
+ // this._pool.on("debug", (event:any) => {
127
+ // console.log("OINODbMsSql debug",event)
128
+ // })
129
129
  }
130
130
  async _query(sql) {
131
131
  // OINOLog.debug("OINODbMsSql._query", {sql:sql})
132
132
  try {
133
- const sql_res = await this._pool.request().query(sql);
133
+ const request = this._pool.request(); // this does not need to be released but the pool will handle it
134
+ const sql_res = await request.query(sql);
134
135
  // console.log("OINODbMsSql._query result:" + JSON.stringify(sql_res.recordsets))
135
136
  const result = new OINOMsSqlData(sql_res.recordsets);
136
137
  return Promise.resolve(result);
@@ -291,45 +292,53 @@ export class OINODbMsSql extends OINODb {
291
292
  *
292
293
  */
293
294
  async connect() {
295
+ let result = new OINOResult();
294
296
  try {
295
297
  // make sure that any items are correctly URL encoded in the connection string
296
298
  await this._pool.connect();
297
299
  // OINOLog.info("OINODbMsSql.connect: Connected to database server.")
298
- await this._pool.request().query("SELECT 1 as test");
299
- return Promise.resolve(true);
300
+ // await this._pool.request().query("SELECT 1 as test")
301
+ this.isConnected = true;
300
302
  }
301
303
  catch (err) {
302
304
  // ... error checks
303
- throw new Error(OINO_ERROR_PREFIX + ": Error connecting to OINODbMsSql server: " + err);
305
+ result.setError(500, "Exception connecting to database: " + err.message, "OINODbMsSql.connect");
306
+ OINOLog.error(result.statusMessage, { error: err });
304
307
  }
308
+ return Promise.resolve(result);
305
309
  }
306
310
  /**
307
311
  * Validate connection to database is working.
308
312
  *
309
313
  */
310
314
  async validate() {
311
- OINOBenchmark.start("OINODb", "validate");
312
315
  let result = new OINOResult();
316
+ if (!this.isConnected) {
317
+ result.setError(400, "Database is not connected!", "OINODbMsSql.validate");
318
+ return result;
319
+ }
320
+ OINOBenchmark.start("OINODb", "validate");
313
321
  try {
314
322
  const sql = this._getValidateSql(this._params.database);
315
- // OINOLog.debug("OINODbBunSqlite.validate", {sql:sql})
323
+ // OINOLog.debug("OINODbMsSql.validate", {sql:sql})
316
324
  const sql_res = await this.sqlSelect(sql);
317
- // OINOLog.debug("OINODbBunSqlite.validate", {sql_res:sql_res})
325
+ // OINOLog.debug("OINODbMsSql.validate", {sql_res:sql_res})
318
326
  if (sql_res.isEmpty()) {
319
- result.setError(400, "DB returned no rows for select!", "OINODbBunSqlite.validate");
327
+ result.setError(400, "DB returned no rows for select!", "OINODbMsSql.validate");
320
328
  }
321
329
  else if (sql_res.getRow().length == 0) {
322
- result.setError(400, "DB returned no values for database!", "OINODbBunSqlite.validate");
330
+ result.setError(400, "DB returned no values for database!", "OINODbMsSql.validate");
323
331
  }
324
332
  else if (sql_res.getRow()[0] == "0") {
325
- result.setError(400, "DB returned no schema for database!", "OINODbBunSqlite.validate");
333
+ result.setError(400, "DB returned no schema for database!", "OINODbMsSql.validate");
326
334
  }
327
335
  else {
328
336
  // connection is working
337
+ this.isValidated = true;
329
338
  }
330
339
  }
331
340
  catch (e) {
332
- result.setError(500, OINO_ERROR_PREFIX + " (validate): OINODbBunSqlite.validate exception in _db.query: " + e.message, "OINODbBunSqlite.validate");
341
+ result.setError(500, "Exception in validating connection: " + e.message, "OINODbMsSql.validate");
333
342
  }
334
343
  OINOBenchmark.end("OINODb", "validate");
335
344
  return result;
@@ -67,7 +67,7 @@ export declare class OINODbMsSql extends OINODb {
67
67
  * Connect to database.
68
68
  *
69
69
  */
70
- connect(): Promise<boolean>;
70
+ connect(): Promise<OINOResult>;
71
71
  /**
72
72
  * Validate connection to database is working.
73
73
  *
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@oino-ts/db-mssql",
3
- "version": "0.6.0",
3
+ "version": "0.6.1",
4
4
  "description": "OINO TS package for using Microsoft Sql databases.",
5
5
  "author": "Matias Kiviniemi (pragmatta)",
6
6
  "license": "MPL-2.0",
@@ -22,7 +22,7 @@
22
22
  "module": "./dist/esm/index.js",
23
23
  "types": "./dist/types/index.d.ts",
24
24
  "dependencies": {
25
- "@oino-ts/db": "0.6.0",
25
+ "@oino-ts/db": "0.6.1",
26
26
  "mssql": "^11.0.1"
27
27
  },
28
28
  "devDependencies": {
@@ -117,11 +117,11 @@ export class OINODbMsSql extends OINODb {
117
117
  throw new Error(OINO_ERROR_PREFIX + ": Not OINODbMsSql-type: " + this._params.type)
118
118
  }
119
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,
120
+ user: this._params.user,
121
+ password: this._params.password,
122
+ server: this._params.url,
123
+ port: this._params.port,
124
+ database: this._params.database,
125
125
  arrayRowMode:true,
126
126
  options: {
127
127
  encrypt: true, // Use encryption for Azure SQL Database
@@ -130,20 +130,21 @@ export class OINODbMsSql extends OINODb {
130
130
  trustServerCertificate: true // Change to false for production
131
131
  }
132
132
  })
133
- //this._pool = new ConnectionPool({connectionString: "Server=localhost,1433;Database=database;User Id=username;Password=" + params.password + ";Encrypt=true"})
133
+ delete this._params.password // do not store password in db object
134
134
 
135
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)
136
+ OINOLog.error("OINODbMsSql error event", conn)
140
137
  })
138
+ // this._pool.on("debug", (event:any) => {
139
+ // console.log("OINODbMsSql debug",event)
140
+ // })
141
141
  }
142
142
 
143
143
  private async _query(sql:string):Promise<OINOMsSqlData> {
144
144
  // OINOLog.debug("OINODbMsSql._query", {sql:sql})
145
145
  try {
146
- const sql_res = await this._pool.request().query(sql);
146
+ const request = this._pool.request() // this does not need to be released but the pool will handle it
147
+ const sql_res = await request.query(sql)
147
148
  // console.log("OINODbMsSql._query result:" + JSON.stringify(sql_res.recordsets))
148
149
  const result:OINOMsSqlData = new OINOMsSqlData(sql_res.recordsets)
149
150
  return Promise.resolve(result)
@@ -309,17 +310,21 @@ export class OINODbMsSql extends OINODb {
309
310
  * Connect to database.
310
311
  *
311
312
  */
312
- async connect(): Promise<boolean> {
313
+ async connect(): Promise<OINOResult> {
314
+ let result:OINOResult = new OINOResult()
313
315
  try {
314
316
  // make sure that any items are correctly URL encoded in the connection string
315
317
  await this._pool.connect()
316
318
  // OINOLog.info("OINODbMsSql.connect: Connected to database server.")
317
- await this._pool.request().query("SELECT 1 as test")
318
- return Promise.resolve(true)
319
- } catch (err) {
319
+ // await this._pool.request().query("SELECT 1 as test")
320
+ this.isConnected = true
321
+
322
+ } catch (err:any) {
320
323
  // ... error checks
321
- throw new Error(OINO_ERROR_PREFIX + ": Error connecting to OINODbMsSql server: " + err)
324
+ result.setError(500, "Exception connecting to database: " + err.message, "OINODbMsSql.connect")
325
+ OINOLog.error(result.statusMessage, {error:err})
322
326
  }
327
+ return Promise.resolve(result)
323
328
  }
324
329
 
325
330
  /**
@@ -327,27 +332,32 @@ export class OINODbMsSql extends OINODb {
327
332
  *
328
333
  */
329
334
  async validate(): Promise<OINOResult> {
330
- OINOBenchmark.start("OINODb", "validate")
331
335
  let result:OINOResult = new OINOResult()
336
+ if (!this.isConnected) {
337
+ result.setError(400, "Database is not connected!", "OINODbMsSql.validate")
338
+ return result
339
+ }
340
+ OINOBenchmark.start("OINODb", "validate")
332
341
  try {
333
342
  const sql = this._getValidateSql(this._params.database)
334
- // OINOLog.debug("OINODbBunSqlite.validate", {sql:sql})
343
+ // OINOLog.debug("OINODbMsSql.validate", {sql:sql})
335
344
  const sql_res:OINODbDataSet = await this.sqlSelect(sql)
336
- // OINOLog.debug("OINODbBunSqlite.validate", {sql_res:sql_res})
345
+ // OINOLog.debug("OINODbMsSql.validate", {sql_res:sql_res})
337
346
  if (sql_res.isEmpty()) {
338
- result.setError(400, "DB returned no rows for select!", "OINODbBunSqlite.validate")
347
+ result.setError(400, "DB returned no rows for select!", "OINODbMsSql.validate")
339
348
 
340
349
  } else if (sql_res.getRow().length == 0) {
341
- result.setError(400, "DB returned no values for database!", "OINODbBunSqlite.validate")
350
+ result.setError(400, "DB returned no values for database!", "OINODbMsSql.validate")
342
351
 
343
352
  } else if (sql_res.getRow()[0] == "0") {
344
- result.setError(400, "DB returned no schema for database!", "OINODbBunSqlite.validate")
353
+ result.setError(400, "DB returned no schema for database!", "OINODbMsSql.validate")
345
354
 
346
355
  } else {
347
356
  // connection is working
357
+ this.isValidated = true
348
358
  }
349
359
  } catch (e:any) {
350
- result.setError(500, OINO_ERROR_PREFIX + " (validate): OINODbBunSqlite.validate exception in _db.query: " + e.message, "OINODbBunSqlite.validate")
360
+ result.setError(500, "Exception in validating connection: " + e.message, "OINODbMsSql.validate")
351
361
  }
352
362
  OINOBenchmark.end("OINODb", "validate")
353
363
  return result