@simtlix/simfinity-postgres 3.2.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/LICENSE +201 -0
- package/README.md +89 -0
- package/package.json +36 -0
- package/src/adapter.js +125 -0
- package/src/codecs.js +70 -0
- package/src/index.js +46 -0
- package/src/query/compiler.js +255 -0
- package/src/query/functions.js +47 -0
- package/src/records.js +219 -0
- package/src/schema/constraints.js +142 -0
- package/src/schema/ddl.js +29 -0
- package/src/schema/describe.js +138 -0
- package/src/schema/initialize.js +271 -0
- package/src/schema/sql.js +28 -0
- package/src/transactions.js +32 -0
- package/types/index.d.ts +173 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for reasonable and customary use in describing the
|
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
|
177
|
+
|
|
178
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
179
|
+
|
|
180
|
+
To apply the Apache License to your work, attach the following
|
|
181
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
182
|
+
replaced with your own identifying information. (Don't include
|
|
183
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
184
|
+
comment syntax for the file format. We also recommend that a
|
|
185
|
+
file or class name and description of purpose be included on the
|
|
186
|
+
same "printed page" as the copyright notice for easier
|
|
187
|
+
identification within third-party archives.
|
|
188
|
+
|
|
189
|
+
Copyright [yyyy] [name of copyright owner]
|
|
190
|
+
|
|
191
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
192
|
+
you may not use this file except in compliance with the License.
|
|
193
|
+
You may obtain a copy of the License at
|
|
194
|
+
|
|
195
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
196
|
+
|
|
197
|
+
Unless required by applicable law or agreed to in writing, software
|
|
198
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
199
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
200
|
+
See the License for the specific language governing permissions and
|
|
201
|
+
limitations under the License.
|
package/README.md
ADDED
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
# @simtlix/simfinity-postgres
|
|
2
|
+
|
|
3
|
+
PostgreSQL 15 or later support for the Simfinity GraphQL runtime. The package requires GraphQL 16 and Node.js 18.18 or later, depends on `pg` and `@simtlix/simfinity-core`, and has no Mongoose or MongoDB dependency.
|
|
4
|
+
|
|
5
|
+
Version 3.2.0 is released together with the other Simfinity packages. Install from npm and keep their versions aligned. Source and the complete startup guide: [simtlix/simfinity.js](https://github.com/simtlix/simfinity.js), [`docs/guide/postgresql.md`](https://github.com/simtlix/simfinity.js/blob/master/docs/guide/postgresql.md).
|
|
6
|
+
|
|
7
|
+
## Runtime
|
|
8
|
+
|
|
9
|
+
Create an instance, register the same GraphQL object types used by Simfinity, build the schema, and await database initialization before serving operations:
|
|
10
|
+
|
|
11
|
+
```javascript
|
|
12
|
+
import pg from 'pg';
|
|
13
|
+
import { createPostgres } from '@simtlix/simfinity-postgres';
|
|
14
|
+
|
|
15
|
+
const pool = new pg.Pool({ connectionString: process.env.DATABASE_URL });
|
|
16
|
+
const simfinity = createPostgres({ pool, schema: 'library' });
|
|
17
|
+
|
|
18
|
+
simfinity.connect(null, BookType, 'book', 'books', bookController);
|
|
19
|
+
const schema = simfinity.createSchema();
|
|
20
|
+
await simfinity.initializeDatabase({ mode: 'create' });
|
|
21
|
+
|
|
22
|
+
// Serve `schema`; the application remains responsible for `await pool.end()`.
|
|
23
|
+
```
|
|
24
|
+
|
|
25
|
+
`createPostgres` permanently binds one pool and schema. The returned runtime supports registration, generated queries and mutations, middleware and scopes, controllers and validators, custom mutations, state machines, nested relationship writes, embedded reconstruction, and native PostgreSQL model handles. Native handles expose `findById`, `find`, `create`, `update`, and `delete`; they are not Mongoose models.
|
|
26
|
+
|
|
27
|
+
Operations attempted before successful initialization fail with `DATABASE_NOT_INITIALIZED`. Call `createSchema` before `initializeDatabase`. Configuration and registrations become immutable once schema preparation begins. `preventCreatingCollection(true)` makes instance initialization validate existing storage without issuing creation DDL.
|
|
28
|
+
|
|
29
|
+
A default module instance is also available when a singleton facade is preferable:
|
|
30
|
+
|
|
31
|
+
```javascript
|
|
32
|
+
import {
|
|
33
|
+
configure,
|
|
34
|
+
connect,
|
|
35
|
+
createSchema,
|
|
36
|
+
initializeDatabase,
|
|
37
|
+
} from '@simtlix/simfinity-postgres';
|
|
38
|
+
|
|
39
|
+
configure({ pool, schema: 'library' });
|
|
40
|
+
connect(null, BookType, 'book', 'books');
|
|
41
|
+
const schema = createSchema();
|
|
42
|
+
await initializeDatabase({ mode: 'validate' });
|
|
43
|
+
```
|
|
44
|
+
|
|
45
|
+
Transactions use one borrowed `pg` client and repeatable-read isolation. A supplied Simfinity PostgreSQL session joins the active transaction. Serialization failures and deadlocks are retried up to five times; mutation input is reset for each attempt. The caller owns the pool lifecycle.
|
|
46
|
+
|
|
47
|
+
The module and every `createPostgres` instance expose the shared `auth`, `validators`, `scalars`, and `plugins` helpers. These are the same helper objects exported by the MongoDB package, so rules, scalar identities, and errors can be shared safely between backends.
|
|
48
|
+
|
|
49
|
+
MCP integration is an independent opt-in and does not add MCP dependencies to PostgreSQL applications:
|
|
50
|
+
|
|
51
|
+
```sh
|
|
52
|
+
npm install @simtlix/simfinity-mcp@3.2.0 @modelcontextprotocol/sdk@^1.13.0
|
|
53
|
+
```
|
|
54
|
+
|
|
55
|
+
```javascript
|
|
56
|
+
import { createMCPServer } from '@simtlix/simfinity-mcp';
|
|
57
|
+
|
|
58
|
+
const mcpServer = await createMCPServer(schema);
|
|
59
|
+
```
|
|
60
|
+
|
|
61
|
+
## Storage and compatible subset
|
|
62
|
+
|
|
63
|
+
Entity identities and references use UUIDs. Scalars use native PostgreSQL types, scalar lists use arrays, reference-free embedded values use JSONB, and embedded values containing references use private owned tables. Foreign keys, inverse collections, explicit linking entities, missing/null markers, nullable embedded-list items, hooks, rollback, and state transitions are supported by the runtime.
|
|
64
|
+
|
|
65
|
+
Queries support nested scalar/reference paths, logical filter groups, scopes, sort, pagination, count, and grouped `SUM`, `COUNT`, `AVG`, `MIN`, and `MAX` facts. The PostgreSQL implementation preserves root multiplicity when joining collection paths.
|
|
66
|
+
|
|
67
|
+
PostgreSQL enforces required values, real FKs, JSONB/owned embedded shapes, root and embedded scalar/reference uniqueness, and scalar-list multikey uniqueness. Root unique indexes use `NULLS NOT DISTINCT`; private typed owner-key tables allow repeated keys within one owner but reject the same key across owners. Presence markers preserve missing versus explicit null fields. This is stronger and broader than generated Mongoose storage.
|
|
68
|
+
|
|
69
|
+
Scalar-list leaves inside nested embedded lists support filters, sorts, ragged group projections, and array-valued facts. Array `MIN`/`MAX` compares complete arrays; result sorting uses immediate extrema. Date parameters use per-query UTC encoding without changing global `pg` behavior.
|
|
70
|
+
|
|
71
|
+
The following mappings remain unsupported and fail explicitly: implicit many-to-many reciprocal lists, non-embedded collections inside embedded objects, embedded cycles, nested list wrappers, whole embedded-object uniqueness, conflicting relationship metadata, enum values that collide after text conversion, and custom scalars without a recognized base scalar. Query paths cannot sort or group whole embedded objects. Arbitrary MongoDB pipelines and Mongoose-native methods are outside the PostgreSQL contract.
|
|
72
|
+
|
|
73
|
+
## Low-level schema API
|
|
74
|
+
|
|
75
|
+
The foundation API remains available independently of a runtime:
|
|
76
|
+
|
|
77
|
+
```javascript
|
|
78
|
+
import {
|
|
79
|
+
compileDatabaseSchema,
|
|
80
|
+
describeDatabase,
|
|
81
|
+
initializeDatabase,
|
|
82
|
+
} from '@simtlix/simfinity-postgres';
|
|
83
|
+
|
|
84
|
+
const description = describeDatabase([{ gqltype: BookType }], { schema: 'library' });
|
|
85
|
+
const statements = compileDatabaseSchema(description);
|
|
86
|
+
await initializeDatabase(pool, description, { mode: 'validate' });
|
|
87
|
+
```
|
|
88
|
+
|
|
89
|
+
`compileDatabaseSchema` returns reviewable SQL. Low-level `initializeDatabase(pool, description, { mode })` creates or validates storage transactionally and never closes the pool. Create mode adds missing objects and rejects incompatible definitions; validate mode performs no DDL. Neither mode performs destructive schema synchronization or data migration.
|
package/package.json
ADDED
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@simtlix/simfinity-postgres",
|
|
3
|
+
"version": "3.2.0",
|
|
4
|
+
"description": "PostgreSQL GraphQL runtime and schema generation with foreign keys for Simfinity",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"main": "./src/index.js",
|
|
7
|
+
"types": "./types/index.d.ts",
|
|
8
|
+
"exports": {
|
|
9
|
+
".": {
|
|
10
|
+
"types": "./types/index.d.ts",
|
|
11
|
+
"default": "./src/index.js"
|
|
12
|
+
}
|
|
13
|
+
},
|
|
14
|
+
"files": [
|
|
15
|
+
"src",
|
|
16
|
+
"types",
|
|
17
|
+
"README.md",
|
|
18
|
+
"LICENSE"
|
|
19
|
+
],
|
|
20
|
+
"engines": {
|
|
21
|
+
"node": ">=18.18.0"
|
|
22
|
+
},
|
|
23
|
+
"license": "Apache-2.0",
|
|
24
|
+
"repository": {
|
|
25
|
+
"type": "git",
|
|
26
|
+
"url": "https://github.com/simtlix/simfinity.js",
|
|
27
|
+
"directory": "packages/postgres"
|
|
28
|
+
},
|
|
29
|
+
"dependencies": {
|
|
30
|
+
"@simtlix/simfinity-core": "3.2.0",
|
|
31
|
+
"pg": "^8.16.3"
|
|
32
|
+
},
|
|
33
|
+
"peerDependencies": {
|
|
34
|
+
"graphql": "^16.11.0"
|
|
35
|
+
}
|
|
36
|
+
}
|
package/src/adapter.js
ADDED
|
@@ -0,0 +1,125 @@
|
|
|
1
|
+
import { randomUUID } from 'node:crypto';
|
|
2
|
+
import { getNamedType } from 'graphql';
|
|
3
|
+
import { describeModels, createQueryPlan, SimfinityError } from '@simtlix/simfinity-core';
|
|
4
|
+
import { describeDatabase } from './schema/describe.js';
|
|
5
|
+
import { initializeDatabase } from './schema/initialize.js';
|
|
6
|
+
import { compileQuery } from './query/compiler.js';
|
|
7
|
+
import { createRecordStore } from './records.js';
|
|
8
|
+
import { createTransactions } from './transactions.js';
|
|
9
|
+
import { castId, encodeParameter, normalizeDatabaseError } from './codecs.js';
|
|
10
|
+
|
|
11
|
+
export const createPostgresAdapter = (options) => {
|
|
12
|
+
let configured = options ? Object.freeze({ ...options }) : null;
|
|
13
|
+
let prepared = false;
|
|
14
|
+
let ready = false;
|
|
15
|
+
let allowSchemaCreation = true;
|
|
16
|
+
let models; let database; let records;
|
|
17
|
+
const handles = new Map();
|
|
18
|
+
const assertReady = () => {
|
|
19
|
+
if (!ready) throw new SimfinityError('Initialize the PostgreSQL database before executing operations', 'DATABASE_NOT_INITIALIZED', 503);
|
|
20
|
+
};
|
|
21
|
+
const getPool = () => configured.pool;
|
|
22
|
+
const transactions = createTransactions(getPool, assertReady);
|
|
23
|
+
const query = async (text, values, session) => {
|
|
24
|
+
assertReady();
|
|
25
|
+
// Retryable errors must reach withTransaction unchanged, so normalize only at operation boundaries.
|
|
26
|
+
const client = session ? transactions.requireSession(session) : getPool();
|
|
27
|
+
return client.query(text, values?.map(encodeParameter));
|
|
28
|
+
};
|
|
29
|
+
const safe = (operation) => async (...args) => {
|
|
30
|
+
try { return await operation(...args); } catch (error) {
|
|
31
|
+
if (['40001', '40P01'].includes(error.code)) throw error;
|
|
32
|
+
throw normalizeDatabaseError(error);
|
|
33
|
+
}
|
|
34
|
+
};
|
|
35
|
+
const nameOf = (model) => {
|
|
36
|
+
assertReady();
|
|
37
|
+
if (!model || handles.get(model.name) !== model || !models.entities.some((item) => item.name === model.name)) throw new SimfinityError('Invalid PostgreSQL model handle', 'INVALID_MODEL', 400);
|
|
38
|
+
return model.name;
|
|
39
|
+
};
|
|
40
|
+
const execute = async (model, gqltype, args, session, mode, extra) => {
|
|
41
|
+
const name = nameOf(model);
|
|
42
|
+
const plan = createQueryPlan(models, name, args, { mode });
|
|
43
|
+
const compiled = compileQuery(models, database, plan, extra);
|
|
44
|
+
const { rows } = await query(compiled.text, compiled.values, session);
|
|
45
|
+
if (mode === 'count') return Number(rows[0]?.size || 0);
|
|
46
|
+
const decodeAggregate = (value, field) => Array.isArray(value) ? value.map((item) => decodeAggregate(item, field)) : value != null && field.scalar === 'DateTime' ? new Date(value) : value;
|
|
47
|
+
if (mode === 'aggregate') return rows.map((row) => ({
|
|
48
|
+
groupId: decodeAggregate(row.groupId, compiled.aggregateFields[0]),
|
|
49
|
+
facts: Object.fromEntries(plan.aggregation.facts.map((fact, index) => {
|
|
50
|
+
const value = row[`fact_${index}`];
|
|
51
|
+
return [fact.factName, value == null ? null : ['SUM', 'COUNT', 'AVG'].includes(fact.operation) ? Number(value) : decodeAggregate(value, compiled.aggregateFields[index + 1])];
|
|
52
|
+
})),
|
|
53
|
+
}));
|
|
54
|
+
return records.hydrateRows(name, rows, session);
|
|
55
|
+
};
|
|
56
|
+
const adapter = {
|
|
57
|
+
configure(value) {
|
|
58
|
+
if (configured || prepared) throw new SimfinityError('PostgreSQL configuration is already bound', 'DATABASE_ALREADY_CONFIGURED', 409);
|
|
59
|
+
configured = Object.freeze({ ...value });
|
|
60
|
+
},
|
|
61
|
+
validateRegistration(registration) {
|
|
62
|
+
if (prepared) throw new SimfinityError('Register types before creating the schema', 'SCHEMA_ALREADY_CREATED', 409);
|
|
63
|
+
const model = registration.model;
|
|
64
|
+
if (model && !handles.has(model.name)) throw new SimfinityError('External Mongoose models cannot be used with PostgreSQL', 'INVALID_MODEL', 400);
|
|
65
|
+
},
|
|
66
|
+
prepare(registrations, { createCollection = true } = {}) {
|
|
67
|
+
if (prepared) return;
|
|
68
|
+
if (!configured?.pool?.connect || !configured.pool.query) throw new SimfinityError('Configure a pg.Pool before creating the schema', 'DATABASE_NOT_CONFIGURED', 500);
|
|
69
|
+
models = describeModels(registrations);
|
|
70
|
+
for (const registration of registrations.filter((item) => item.stateMachine)) {
|
|
71
|
+
const state = models.entities.find((item) => item.name === registration.gqltype.name)?.fields.find((item) => item.name === 'state');
|
|
72
|
+
if (state) state.stateNames = getNamedType(registration.gqltype.getFields().state.type).getValues().map((item) => ({ value: String(item.value), name: item.name }));
|
|
73
|
+
}
|
|
74
|
+
database = describeDatabase(registrations, { schema: configured.schema || 'public' });
|
|
75
|
+
allowSchemaCreation = createCollection;
|
|
76
|
+
records = createRecordStore(models, database, query);
|
|
77
|
+
prepared = true;
|
|
78
|
+
},
|
|
79
|
+
createModel(gqltype, onModelCreated) {
|
|
80
|
+
const model = {
|
|
81
|
+
name: gqltype.name, gqltype,
|
|
82
|
+
findById: (id, { session } = {}) => adapter.getById(model, id, session),
|
|
83
|
+
find: (args = {}, { session } = {}) => adapter.find(model, gqltype, args, session),
|
|
84
|
+
create: (data, { session } = {}) => adapter.withTransaction(session, (transaction) => adapter.saveRecord(model, adapter.newRecord(model, data, transaction), transaction)),
|
|
85
|
+
update: (id, changes, { session } = {}) => adapter.withTransaction(session, (transaction) => adapter.update(model, id, changes, transaction)),
|
|
86
|
+
delete: (id, { session } = {}) => adapter.withTransaction(session, (transaction) => adapter.delete(model, id, transaction)),
|
|
87
|
+
};
|
|
88
|
+
handles.set(model.name, model);
|
|
89
|
+
if (onModelCreated) onModelCreated(model);
|
|
90
|
+
return model;
|
|
91
|
+
},
|
|
92
|
+
castId,
|
|
93
|
+
stateValue: (state) => state.value,
|
|
94
|
+
withTransaction: transactions.withTransaction,
|
|
95
|
+
newRecord(model, data) { nameOf(model); const id = data._id || data.id || randomUUID(); return { ...data, _id: castId(id), id: castId(id) }; },
|
|
96
|
+
toObject(record) { return record == null ? record : { ...record }; },
|
|
97
|
+
saveRecord: safe((model, record, session) => transactions.withTransaction(session, (transaction) => records.create(nameOf(model), record, transaction))),
|
|
98
|
+
getById: safe((model, id, session, options = {}) => transactions.withTransaction(session, (transaction) => records.getById(nameOf(model), id, transaction, options))),
|
|
99
|
+
prepareUpdate(set, unset) { return { ...set, ...(Object.keys(unset).length ? { $unset: { ...unset } } : {}) }; },
|
|
100
|
+
update: safe((model, id, update, session) => records.update(nameOf(model), id, update, session)),
|
|
101
|
+
delete: safe((model, id, session) => records.remove(nameOf(model), id, session)),
|
|
102
|
+
find: safe((model, gqltype, args, session, { requiredId } = {}) => transactions.withTransaction(session, (transaction) => execute(model, gqltype, args, transaction, 'find', requiredId == null ? null : { column: 'id', id: castId(requiredId) }))),
|
|
103
|
+
count: safe((model, gqltype, args, session) => execute(model, gqltype, args, session, 'count')),
|
|
104
|
+
aggregate: safe((model, gqltype, args, session) => execute(model, gqltype, args, session, 'aggregate')),
|
|
105
|
+
findChildren: safe((model, gqltype, connectionField, parentId, args, session) => {
|
|
106
|
+
const entity = models.entities.find((item) => item.name === nameOf(model));
|
|
107
|
+
const field = entity.fields.find((item) => item.name === connectionField || item.storageName === connectionField);
|
|
108
|
+
if (!field || field.kind !== 'reference') throw new SimfinityError('Invalid inverse connection field', 'INVALID_MODEL', 400);
|
|
109
|
+
return transactions.withTransaction(session, (transaction) => execute(model, gqltype, args, transaction, 'find', { column: field.storageName, id: castId(parentId) }));
|
|
110
|
+
}),
|
|
111
|
+
async initialize(options = {}) {
|
|
112
|
+
if (!prepared) throw new SimfinityError('Create the GraphQL schema before initializing storage', 'SCHEMA_NOT_CREATED', 500);
|
|
113
|
+
ready = false;
|
|
114
|
+
if (!allowSchemaCreation && options.mode && options.mode !== 'validate') throw new SimfinityError('Database creation is disabled; initialize in validate mode', 'DATABASE_CREATION_DISABLED', 409);
|
|
115
|
+
const result = await initializeDatabase(getPool(), database, allowSchemaCreation ? options : { ...options, mode: 'validate' });
|
|
116
|
+
ready = true;
|
|
117
|
+
return result;
|
|
118
|
+
},
|
|
119
|
+
describeDatabase() {
|
|
120
|
+
if (!prepared) throw new SimfinityError('Create the GraphQL schema first', 'SCHEMA_NOT_CREATED', 500);
|
|
121
|
+
return structuredClone(database);
|
|
122
|
+
},
|
|
123
|
+
};
|
|
124
|
+
return adapter;
|
|
125
|
+
};
|
package/src/codecs.js
ADDED
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
import { getNamedType, isEnumType } from 'graphql';
|
|
2
|
+
import { SimfinityError } from '@simtlix/simfinity-core';
|
|
3
|
+
|
|
4
|
+
export const storageTypes = { ID: 'uuid', String: 'text', Enum: 'text', Int: 'integer', Float: 'double precision', Boolean: 'boolean', DateTime: 'timestamp with time zone' };
|
|
5
|
+
export const invalidValue = (message) => { throw new SimfinityError(message, 'INVALID_FILTER_VALUE', 400); };
|
|
6
|
+
export const castId = (value) => {
|
|
7
|
+
const id = typeof value === 'object' && value ? value._id || value.id : value;
|
|
8
|
+
if (typeof id !== 'string' || !/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(id)) {
|
|
9
|
+
throw new SimfinityError('Expected a UUID identifier', 'NOT_VALID_ID', 400);
|
|
10
|
+
}
|
|
11
|
+
return id.toLowerCase();
|
|
12
|
+
};
|
|
13
|
+
|
|
14
|
+
export const encodeScalar = (field, value) => {
|
|
15
|
+
if (value == null) return null;
|
|
16
|
+
if (field.kind === 'reference' || field.scalar === 'ID') return castId(value);
|
|
17
|
+
switch (field.scalar) {
|
|
18
|
+
case 'Enum': {
|
|
19
|
+
const encoded = String(value);
|
|
20
|
+
if (!field.values.includes(encoded)) invalidValue(`Invalid enum value for ${field.name}`);
|
|
21
|
+
return encoded;
|
|
22
|
+
}
|
|
23
|
+
case 'String': if (typeof value !== 'string') invalidValue(`Expected a string for ${field.name}`); break;
|
|
24
|
+
case 'Boolean': if (typeof value !== 'boolean') invalidValue(`Expected a boolean for ${field.name}`); break;
|
|
25
|
+
case 'Int': if (!Number.isInteger(value) || value < -2147483648 || value > 2147483647) invalidValue(`Expected a 32-bit integer for ${field.name}`); break;
|
|
26
|
+
case 'Float': if (typeof value !== 'number' || !Number.isFinite(value)) invalidValue(`Expected a finite number for ${field.name}`); break;
|
|
27
|
+
case 'DateTime': {
|
|
28
|
+
const date = value instanceof Date ? value : typeof value === 'string' ? new Date(value) : null;
|
|
29
|
+
if (!date || !Number.isFinite(date.getTime())) invalidValue(`Invalid date for ${field.name}`);
|
|
30
|
+
return date;
|
|
31
|
+
}
|
|
32
|
+
default: invalidValue(`Unsupported scalar for ${field.name}`);
|
|
33
|
+
}
|
|
34
|
+
return value;
|
|
35
|
+
};
|
|
36
|
+
|
|
37
|
+
export const decodeScalar = (field, value, gqlField) => {
|
|
38
|
+
if (value == null) return value;
|
|
39
|
+
if (field.scalar === 'Enum' && gqlField) {
|
|
40
|
+
const type = getNamedType(gqlField.type);
|
|
41
|
+
if (isEnumType(type)) return type.getValues().find((item) => String(item.value) === value)?.value ?? value;
|
|
42
|
+
}
|
|
43
|
+
if (field.scalar === 'DateTime') return value instanceof Date ? value : new Date(value);
|
|
44
|
+
return value;
|
|
45
|
+
};
|
|
46
|
+
|
|
47
|
+
export const normalizeDatabaseError = (error) => {
|
|
48
|
+
if (error instanceof SimfinityError || !error.code) return error;
|
|
49
|
+
const errors = {
|
|
50
|
+
'23503': ['Reference constraint violated', 'REFERENCE_CONSTRAINT_VIOLATION', 409],
|
|
51
|
+
'23505': ['Unique value already exists', 'DUPLICATE_KEY', 409],
|
|
52
|
+
'23502': ['A required value is missing', 'REQUIRED_VALUE', 400],
|
|
53
|
+
'23514': ['A value violates the generated schema', 'INVALID_VALUE', 400],
|
|
54
|
+
'22P02': ['Invalid stored value', 'INVALID_VALUE', 400],
|
|
55
|
+
'22003': ['Numeric value is out of range', 'INVALID_VALUE', 400],
|
|
56
|
+
'40001': ['Concurrent write could not be completed', 'TRANSACTION_RETRY_EXCEEDED', 409],
|
|
57
|
+
'40P01': ['Concurrent write could not be completed', 'TRANSACTION_RETRY_EXCEEDED', 409],
|
|
58
|
+
};
|
|
59
|
+
return new SimfinityError(...(errors[error.code] || ['Database operation failed', 'DATABASE_ERROR', 500]));
|
|
60
|
+
};
|
|
61
|
+
|
|
62
|
+
/** pg's local Date formatting truncates historical offset seconds; use UTC per parameter. */
|
|
63
|
+
export const encodeParameter = (value) => {
|
|
64
|
+
if (Array.isArray(value)) return value.map(encodeParameter);
|
|
65
|
+
if (!(value instanceof Date)) return value;
|
|
66
|
+
const year = value.getUTCFullYear();
|
|
67
|
+
const iso = value.toISOString();
|
|
68
|
+
const rest = iso.slice(iso.indexOf('-', iso.startsWith('-') || iso.startsWith('+') ? 1 : 0));
|
|
69
|
+
return `${String(year <= 0 ? 1 - year : year).padStart(4, '0')}${rest.slice(0, -1)}+00:00${year <= 0 ? ' BC' : ''}`;
|
|
70
|
+
};
|
package/src/index.js
ADDED
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
import {
|
|
2
|
+
auth,
|
|
3
|
+
createRuntime,
|
|
4
|
+
plugins,
|
|
5
|
+
scalars,
|
|
6
|
+
validators,
|
|
7
|
+
} from '@simtlix/simfinity-core';
|
|
8
|
+
import { createPostgresAdapter } from './adapter.js';
|
|
9
|
+
import { initializeDatabase as initializeSchema } from './schema/initialize.js';
|
|
10
|
+
|
|
11
|
+
export { describeDatabase } from './schema/describe.js';
|
|
12
|
+
export { compileDatabaseSchema } from './schema/ddl.js';
|
|
13
|
+
export {
|
|
14
|
+
auth,
|
|
15
|
+
buildErrorFormatter,
|
|
16
|
+
createValidatedScalar,
|
|
17
|
+
InternalServerError,
|
|
18
|
+
plugins,
|
|
19
|
+
scalars,
|
|
20
|
+
SimfinityError,
|
|
21
|
+
validators,
|
|
22
|
+
} from '@simtlix/simfinity-core';
|
|
23
|
+
|
|
24
|
+
/** Each instance permanently binds one pool/schema; getModel exposes PostgreSQL native helpers. */
|
|
25
|
+
export const createPostgres = (options) => {
|
|
26
|
+
const adapter = createPostgresAdapter(options);
|
|
27
|
+
const runtime = createRuntime(adapter);
|
|
28
|
+
return {
|
|
29
|
+
...runtime,
|
|
30
|
+
auth,
|
|
31
|
+
configure: (configuration) => adapter.configure(configuration),
|
|
32
|
+
initializeDatabase: (initialization) => adapter.initialize(initialization),
|
|
33
|
+
describeDatabase: () => adapter.describeDatabase(),
|
|
34
|
+
plugins,
|
|
35
|
+
scalars,
|
|
36
|
+
validators,
|
|
37
|
+
withTransaction: (session, callback) => adapter.withTransaction(session, callback),
|
|
38
|
+
};
|
|
39
|
+
};
|
|
40
|
+
const defaultInstance = createPostgres();
|
|
41
|
+
export const { configureQueryLimits, configure, connect, addNoEndpointType, createSchema, getModel, getType, getInputType, getRegistrations, use, registerMutation, saveObject, preventCreatingCollection, withTransaction } = defaultInstance;
|
|
42
|
+
|
|
43
|
+
/** Preserve the foundation low-level API while allowing initialization of the configured default instance. */
|
|
44
|
+
export const initializeDatabase = (poolOrOptions, description, options) => description
|
|
45
|
+
? initializeSchema(poolOrOptions, description, options)
|
|
46
|
+
: defaultInstance.initializeDatabase(poolOrOptions);
|