doix-db 1.0.74 → 1.0.76
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 +223 -11
- package/package.json +2 -2
package/README.md
CHANGED
|
@@ -1,16 +1,228 @@
|
|
|
1
1
|

|
|
2
2
|

|
|
3
3
|
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
4
|
+
`doix-db` is an extension to the [doix](https://github.com/do-/node-doix) framework for working with [relational databases](https://en.wikipedia.org/wiki/Relational_database).
|
|
5
|
+
|
|
6
|
+
# tl;dr
|
|
7
|
+
|
|
8
|
+
Start a trivial Web service project with [doix-http](https://github.com/do-/node-doix-http/wiki), add a connection to [PostgreSQL](https://github.com/do-/node-doix-db-postgresql/wiki#tldr) or to [ClickHouse](https://github.com/do-/node-doix-db-clickhouse/wiki#tldr) and hack on.
|
|
9
|
+
|
|
10
|
+
# Description
|
|
11
|
+
|
|
12
|
+
Basically, this is the common [RDB](https://en.wikipedia.org/wiki/Relational_database) interface for `doix`, the same as ODBC for Windows, JDBC for Java and so on.
|
|
13
|
+
|
|
14
|
+
Aside from processing given statements, it features some SQL generation capabilities.
|
|
15
|
+
|
|
16
|
+
# Connection & Basic Operation
|
|
17
|
+
|
|
18
|
+
For an [Application](https://github.com/do-/node-doix/wiki/Application) to operate on a database, you have to register therein the properly configured vendor specific [`DbPool`](https://github.com/do-/node-doix-db/wiki/DbPool):
|
|
19
|
+
|
|
20
|
+
```js
|
|
21
|
+
const {DbPoolPg} = require ('doix-db-postgresql')
|
|
22
|
+
// const {DbPoolCh} = require ('doix-db-clickhouse')
|
|
23
|
+
|
|
24
|
+
const db = new DbPoolPg (conf.db)
|
|
25
|
+
// const dbArchive = new DbPoolCh (conf.dbArchive)
|
|
26
|
+
|
|
27
|
+
///...
|
|
28
|
+
pools: {
|
|
29
|
+
db,
|
|
30
|
+
// dbArchive,
|
|
31
|
+
},
|
|
32
|
+
///...
|
|
33
|
+
```
|
|
34
|
+
|
|
35
|
+
Then, corresponding [`DbClient`](https://github.com/do-/node-doix-db/wiki/DbClient) instances will be automatically [injected](https://github.com/do-/node-doix/wiki#dependency-injection) in execution contexts:
|
|
36
|
+
|
|
37
|
+
```js
|
|
38
|
+
const dt = await this.db.getScalar ('SELECT CURRENT_DATE')
|
|
39
|
+
// await this.dbArchive.do ('ALTER TABLE facts DROP PARTITION ?', [dt])
|
|
40
|
+
```
|
|
41
|
+
|
|
42
|
+
Asynchronous methods can be called right away; initialization and cleanup are up to `doix` internals.
|
|
43
|
+
|
|
44
|
+
Just in case, the hosting application is always in hand, with all its internals, including the `pools` [Map](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map), so developers may operate on it directly, at their own risk:
|
|
45
|
+
|
|
46
|
+
```js
|
|
47
|
+
this.app.pools.get ('db').pool.end () // see https://node-postgres.com/apis/pool#poolend
|
|
48
|
+
```
|
|
49
|
+
|
|
50
|
+
## Executing Arbitrary SQL
|
|
51
|
+
[`DbClient`](https://github.com/do-/node-doix-db/wiki/DbClient)'s most common methods are:
|
|
52
|
+
* [`do`](https://github.com/do-/node-doix-db/wiki/DbClient#do-q-p-options) for write only [DML](https://en.wikipedia.org/wiki/Data_manipulation_language)/[DDL](https://en.wikipedia.org/wiki/Data_definition_language) commands;
|
|
53
|
+
* [`get***` family](https://github.com/do-/node-doix-db/wiki/DbClient#data-fetching) for `SELECT` and other data returning requests.
|
|
54
|
+
|
|
55
|
+
The API is designed to be versatile yet concise. Each request is invoked by a single call; scalars, arrays and streams are represented uniformly.
|
|
56
|
+
|
|
57
|
+
In result sets, the primitive types mapping depends on the specific driver, but, in general, when ambiguous, strings are used. In particular:
|
|
58
|
+
* fixed precision numbers (`DECIMAL` etc.) are returned as [`String`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String)s, never by [`Number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number)s to avoid rounding errors;
|
|
59
|
+
* dates are represented by [ISO](https://en.wikipedia.org/wiki/ISO_8601) strings, never by [`Date`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date)s, because of time zone related issues.
|
|
60
|
+
|
|
61
|
+
For bound parameters, contrarily, `doix-db` accepts nearly everything and do the best to map it properly in an intuitive way. It's recommended however to
|
|
62
|
+
provide all values but safe integers in the string form.
|
|
63
|
+
|
|
64
|
+
Like every process in `doix`, each SQL statement execution is transparently [logged](https://github.com/do-/node-doix/wiki#logging), with references to the containing [`job`](https://github.com/do-/node-doix/wiki/Job).
|
|
65
|
+
|
|
66
|
+
# Using a Database Model
|
|
67
|
+
|
|
68
|
+
Far from embracing the [MDA](https://en.wikipedia.org/wiki/Model-driven_architecture) approach in its totality, `doix-db` is developed keeping in mind that an application must be aware of, and effectively use meta information about data structures in operates on. Even more, a well designed application must keep the image of the _required_ structure of its database and should be able to compare it to the actual one, maybe outdated, and to _upgrade_ it according to requirements: primarily, with automatic migrations during deployments.
|
|
69
|
+
|
|
70
|
+
To this end, `doix-db` offers a means to load the presumed database schemata from source files next to the [`Application`](https://github.com/do-/node-doix/wiki/Application)'s modules.
|
|
71
|
+
|
|
72
|
+
## Setting Up, Exploring Content
|
|
73
|
+
Each database object, such as a [table](https://github.com/do-/node-doix-db/wiki/DbTable), [sql view](https://github.com/do-/node-doix-db/wiki/DbView) and so on, must be described by an eponymous [module](https://nodejs.org/api/modules.html). Suppose you have all necessary modules in a directory called` /path/to/the/model`. To make use of this information, you have to associate it with the corresponding pool on application start (here, we suppose the `db` and `dbArchive` variables are the same as in the example above):
|
|
74
|
+
|
|
75
|
+
```js
|
|
76
|
+
const {DbModel} = require ('doix-db')
|
|
77
|
+
|
|
78
|
+
// simple case:
|
|
79
|
+
new DbModel ({db, src: [{root: `/path/to/the/model`}]}).loadModules ()
|
|
80
|
+
|
|
81
|
+
// advanced usage:
|
|
82
|
+
{
|
|
83
|
+
const dbModel = new DbModel ({dbArchive, src: [{root: `/path/to/the/model`}]})
|
|
84
|
+
// dbModel.on ('objects-created', function () {/*...*/}) // after resolveReferences ()
|
|
85
|
+
// dbModel.prependListener ('objects-created', function () {/*...*/}) // before
|
|
86
|
+
dbModel.loadModules ()
|
|
87
|
+
}
|
|
88
|
+
```
|
|
89
|
+
|
|
90
|
+
Now both pools, and each [`DbClient`](https://github.com/do-/node-doix-db/wiki/DbClient) acquired, will have corresponding [`.model`](https://github.com/do-/node-doix-db/wiki/DbModel) properties injected therein. For simple tasks, you can use them like this:
|
|
91
|
+
|
|
92
|
+
```js
|
|
93
|
+
const {data: {length}} = this.db.model.find ('dim.gender') // known table, mandatory fixed content
|
|
94
|
+
this.logger.log ({message: `We suppose there are ${length} genders`})
|
|
95
|
+
|
|
96
|
+
const tmpTables = []; for (const o of this.db.model.objects) // iterate over schemata
|
|
97
|
+
if (o instanceof DbTable && o.isToPurge) // check for a custom tag
|
|
98
|
+
tmpTables.push (o.qName)
|
|
99
|
+
if (tmpTables.length !== 0)
|
|
100
|
+
await db.do (`TRUNCATE ${tmpTables}`)
|
|
101
|
+
```
|
|
102
|
+
More advanced API is covered below.
|
|
103
|
+
|
|
104
|
+
## NOSQL: Not Only SQL
|
|
105
|
+
### Document Oriented API
|
|
106
|
+
Given a table name and its primary key value(s), you can fetch the single record without coding SQL:
|
|
107
|
+
|
|
108
|
+
```js
|
|
109
|
+
const user = await this.db.getObject ('users', [id]
|
|
110
|
+
// , {notFound: {id: 0}} // fail safe demo, just in case
|
|
111
|
+
)
|
|
112
|
+
```
|
|
113
|
+
|
|
114
|
+
It may look similar to some other frameworks functionality, namely [Sequelize](https://sequelize.org/docs/v6/core-concepts/model-querying-finders/#findbypk), but let's underline that `doix-db` <u>is by no means an</u> [ORM](https://en.wikipedia.org/wiki/Object%E2%80%93relational_mapping) framework. In this section, records are represented by plain objects, not strictly typed ones. No such ORMish things here as _eager/lazy loading_, _detached state_ etc.
|
|
115
|
+
|
|
116
|
+
To save a given record in a given table, [insert](https://github.com/do-/node-doix-db/wiki/DbClient#insert-tablename-records-options), [update](https://github.com/do-/node-doix-db/wiki/DbClient#update-tablename-record-options) and [upsert](https://github.com/do-/node-doix-db-postgresql/wiki/DbClientPg#upsert-tablename-record-options) are available:
|
|
117
|
+
|
|
118
|
+
```js
|
|
119
|
+
await this.db.insert ('log', {id: 1, message: 'Test', level: 1}, {
|
|
120
|
+
// onlyIfMissing: true // ON CONFLICT DO NOTHING, PostgreSQL only
|
|
121
|
+
// result: 'record' // what to return, PostgreSQL too
|
|
122
|
+
})
|
|
123
|
+
await this.db.update ('log', {id: 1, message: 'The test'})
|
|
124
|
+
await this.db.upsert ('user_options', {id_user: 1, id_option: 10, value: true}, {
|
|
125
|
+
// key: ['id_user', 'id_option'] // if differs from the primary key
|
|
126
|
+
})
|
|
127
|
+
```
|
|
128
|
+
Naturally, field names must match. Extra properties unknown to the data model are silently ignored. Although not recommended for mission critical high load operations, this technique can save a lot of time while prototyping a simple CRUD functionality.
|
|
129
|
+
|
|
130
|
+
For developer's convenience, the umbrella `insert` method, aside from processing single records, features the mass loading. It accepts arrays:
|
|
131
|
+
```js
|
|
132
|
+
await this.db.insert ('log', [
|
|
133
|
+
{id: 2, message: 'Two'},
|
|
134
|
+
{id: 3, message: 'Three'},
|
|
135
|
+
])
|
|
136
|
+
```
|
|
137
|
+
and [object streams](https://nodejs.org/api/stream.html#object-mode):
|
|
138
|
+
```js
|
|
139
|
+
const objectStream = await this.db.getStream (`SELECT * FROM vw_sales_to_archive`)
|
|
140
|
+
await this.dbArchive.insert ('sales', objectStream)
|
|
141
|
+
```
|
|
142
|
+
For maximal performance, native database streams are used whenever possible.
|
|
143
|
+
|
|
144
|
+
### Dynamic Search Queries
|
|
145
|
+
|
|
146
|
+
Most user interfaces (especially, Web ones) contain scrollable roasters with multiple search fields. Commonly, most of filters are unset by default, and empty values must be ignored.
|
|
147
|
+
|
|
148
|
+
In this situation, the SQL query is better generated based on the actual set of search terms requested: at least the `WHERE` clause, but quite often the `FROM` part too, may be some others. And to display a page counter, a secondary `SELECT COUNT(*)` is needed, with a specific optimization (excluding `ORDER BY`, omitting some `OUTER JOIN`s, etc.)
|
|
149
|
+
|
|
150
|
+
To facilitate the code generation is most such cases, `doix-db` features a [dynamic query builder](https://github.com/do-/node-doix-db/wiki/DbQuery). Unlike some well known analogs (e. g. [Knex.js](https://knexjs.org/guide/query-builder.html)), its API doesn't mock a SQL AST in form of multiple chained method calls.
|
|
151
|
+
|
|
152
|
+
From the application perspective, given a set of filters in form of a plain object, it takes a single [`this.db.model.createQuery ()`](https://github.com/do-/node-doix-db/wiki/DbModel#createquery) call to obtain a builder instance and immediately pass it as a parameter to [this.db.getArray ()](https://github.com/do-/node-doix-db/wiki/DbClient#getarray-q-p-options).
|
|
153
|
+
|
|
154
|
+
```js
|
|
155
|
+
const q = this.db.model.createQuery (
|
|
156
|
+
[['notes', {filters: [['txt', 'ILIKE', '%' + v + '%']]}]],
|
|
157
|
+
{order: 'created', limit: 50, offset: 0}
|
|
158
|
+
)
|
|
159
|
+
, range = await this.db.getArray (q) // LIMIT / OFFSET applied
|
|
160
|
+
, count = selection [Symbol.for ('count')] // extra COUNT(*) result
|
|
161
|
+
```
|
|
162
|
+
|
|
163
|
+
But what is the right structure for that _set of filters_ mentioned above? Surprisingly, no common standard for this is in sight. Every DHTML AJAX library featuring some advanced data grid seems to invent its own one: the same thing once expressed as `filter: ['label', 'startswith', 'admin']`, looks like `search: [{field: 'label', operator: 'begins', value: 'admin'}]` elsewhere and so on.
|
|
164
|
+
|
|
165
|
+
They are all pretty similar though, those micro languages. No problem to translate from one to another, more versatile one (the `doix-db` one, that is). Two translators of this kind are available: [for DevExtreme](https://github.com/do-/node-doix-devextreme) and [for w2ui](https://github.com/do-/node-doix-w2ui) frameworks. More can be cloned easily.
|
|
166
|
+
|
|
167
|
+
## Planning and Performing Migrations
|
|
168
|
+
|
|
169
|
+
The aforementioned [Sequelize](https://sequelize.org/docs/v6/other-topics/migrations/#running-migrations) and [Knex.js](https://knexjs.org/guide/migrations.html) both offer tools to automate database migrations, very similar to ones implemented by [Liquibase](https://www.npmjs.com/package/liquibase) and [Flyway](https://www.npmjs.com/package/node-flywaydb) both ported from the Java universe. In all those cases, developers code migration steps in an imperative manner, and the framework assembles those fragments in a sequence based on initial and final version numbers.
|
|
170
|
+
|
|
171
|
+
`doix-db` takes a completely different approach to the same problem. It features [`DbMigrationPlan`](https://github.com/do-/node-doix-db/wiki/DbMigrationPlan): a diff/patch like tool comparing the actual physical database structure to the required one and generating necessary DDL statements.
|
|
172
|
+
|
|
173
|
+
```js
|
|
174
|
+
const plan = this.db.createMigrationPlan ()
|
|
175
|
+
|
|
176
|
+
// plan.on (..., ...) // ...set custom event handlers
|
|
177
|
+
|
|
178
|
+
await plan.loadStructure () // read the INFORMATION_SCHEMA
|
|
179
|
+
|
|
180
|
+
// ...adjust something, based on plan.asIs
|
|
181
|
+
|
|
182
|
+
plan.inspectStructure () // compare with this.db.model
|
|
183
|
+
|
|
184
|
+
// ...adjust something more, based on plan.toDo
|
|
185
|
+
|
|
186
|
+
await this.db.doAll (plan.genDDL ()) // execute (or maybe just record plan.genDDL ())
|
|
187
|
+
```
|
|
188
|
+
|
|
189
|
+
So, in essence, `doix-db`'s `DbMigrationPlan` vs. Liquibase like tools is [closed loop vs. open loop](https://en.wikipedia.org/w/index.php?title=Control_loop&oldid=1281798171#Open-loop_and_closed-loop) control.
|
|
190
|
+
|
|
191
|
+
## Ensuring Fixed Data
|
|
192
|
+
|
|
193
|
+
It's quite a common case to have several relational tables only filled up with few known records each. These are dictionaries of values like system roles, document status etc. They need to be kept in the database to be available for `JOIN`s, but in fact are application constants.
|
|
194
|
+
|
|
195
|
+
In `doix-db`, such fixed content is normally added to [table definitions](https://github.com/do-/node-doix-db/wiki/DbTable)
|
|
196
|
+
|
|
197
|
+
```js
|
|
198
|
+
...
|
|
199
|
+
data: [
|
|
200
|
+
{id: 1, name: 'admin'},
|
|
201
|
+
{id: 2, name: 'user'},
|
|
202
|
+
],
|
|
203
|
+
...
|
|
204
|
+
```
|
|
205
|
+
what guarantees it to be present in the table (via [`DbMigrationPlan`](https://github.com/do-/node-doix-db/wiki/DbMigrationPlan)) and makes it visible to the application code.
|
|
206
|
+
|
|
207
|
+
When developing AJAX backends, a frequent task is to augment an object representing a data record with some dictionaries for its fields. For sure such data must be taken right from the application's memory rather than fetched from the database:
|
|
208
|
+
|
|
209
|
+
```js
|
|
210
|
+
const user = await this.db.getObject ('users', [id])
|
|
211
|
+
user.roles = this.db.model.find ('roles').data
|
|
212
|
+
user.status = this.db.model.find ('status').data
|
|
213
|
+
//...
|
|
214
|
+
return user
|
|
215
|
+
```
|
|
216
|
+
|
|
217
|
+
And there is some [API sugar](https://github.com/do-/node-doix-db/wiki/DbModel#assigndata) for this:
|
|
218
|
+
```js
|
|
219
|
+
return this.db.model.assignData (
|
|
220
|
+
await this.db.getObject ('users', [id]),
|
|
221
|
+
[
|
|
222
|
+
'roles',
|
|
223
|
+
'status',
|
|
224
|
+
]
|
|
225
|
+
)
|
|
226
|
+
```
|
|
15
227
|
|
|
16
228
|
More information is available at https://github.com/do-/node-doix-db/wiki
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "doix-db",
|
|
3
|
-
"version": "1.0.
|
|
3
|
+
"version": "1.0.76",
|
|
4
4
|
"description": "Shared database related code for doix",
|
|
5
5
|
"main": "index.js",
|
|
6
6
|
"files": [
|
|
@@ -40,7 +40,7 @@
|
|
|
40
40
|
},
|
|
41
41
|
"homepage": "https://github.com/do-/node-doix-db#readme",
|
|
42
42
|
"peerDependencies": {
|
|
43
|
-
"doix": "^1.0.
|
|
43
|
+
"doix": "^1.0.57"
|
|
44
44
|
},
|
|
45
45
|
"devDependencies": {
|
|
46
46
|
"jest": "^29.6.1"
|