@fhirforge/pg 0.0.0-stage → 0.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 +55 -0
- package/README.md +16 -2
- package/dist/database.d.ts +27 -0
- package/dist/database.d.ts.map +1 -0
- package/dist/database.js +30 -0
- package/dist/database.js.map +1 -0
- package/dist/index.d.ts +5 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +5 -0
- package/dist/index.js.map +1 -0
- package/dist/migrations.d.ts +22 -0
- package/dist/migrations.d.ts.map +1 -0
- package/dist/migrations.js +92 -0
- package/dist/migrations.js.map +1 -0
- package/dist/search.d.ts +19 -0
- package/dist/search.d.ts.map +1 -0
- package/dist/search.js +223 -0
- package/dist/search.js.map +1 -0
- package/dist/sql.d.ts +15 -0
- package/dist/sql.d.ts.map +1 -0
- package/dist/sql.js +32 -0
- package/dist/sql.js.map +1 -0
- package/dist/storage.d.ts +20 -0
- package/dist/storage.d.ts.map +1 -0
- package/dist/storage.js +186 -0
- package/dist/storage.js.map +1 -0
- package/dist/transport.d.ts +24 -0
- package/dist/transport.d.ts.map +1 -0
- package/dist/transport.js +55 -0
- package/dist/transport.js.map +1 -0
- package/package.json +49 -3
package/LICENSE
ADDED
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
|
|
3
|
+
Version 2.0, January 2004
|
|
4
|
+
|
|
5
|
+
http://www.apache.org/licenses/
|
|
6
|
+
|
|
7
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
8
|
+
|
|
9
|
+
1. Definitions.
|
|
10
|
+
|
|
11
|
+
"License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document.
|
|
12
|
+
|
|
13
|
+
"Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity.
|
|
16
|
+
|
|
17
|
+
"You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License.
|
|
18
|
+
|
|
19
|
+
"Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files.
|
|
20
|
+
|
|
21
|
+
"Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types.
|
|
22
|
+
|
|
23
|
+
"Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below).
|
|
24
|
+
|
|
25
|
+
"Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof.
|
|
26
|
+
|
|
27
|
+
"Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution."
|
|
28
|
+
|
|
29
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work.
|
|
30
|
+
|
|
31
|
+
2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form.
|
|
32
|
+
|
|
33
|
+
3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed.
|
|
34
|
+
|
|
35
|
+
4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions:
|
|
36
|
+
|
|
37
|
+
You must give any other recipients of the Work or Derivative Works a copy of this License; and
|
|
38
|
+
|
|
39
|
+
You must cause any modified files to carry prominent notices stating that You changed the files; and
|
|
40
|
+
|
|
41
|
+
You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and
|
|
42
|
+
|
|
43
|
+
If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License.
|
|
44
|
+
|
|
45
|
+
5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions.
|
|
46
|
+
|
|
47
|
+
6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file.
|
|
48
|
+
|
|
49
|
+
7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License.
|
|
50
|
+
|
|
51
|
+
8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages.
|
|
52
|
+
|
|
53
|
+
9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability.
|
|
54
|
+
|
|
55
|
+
END OF TERMS AND CONDITIONS
|
package/README.md
CHANGED
|
@@ -1,3 +1,17 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @fhirforge/pg
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Postgres storage for fhirforge: resources as JSONB with full history and search index tables in their own schema, migrations with an advisory lock, optimistic locking, and TLS enforcement for remote connections.
|
|
4
|
+
|
|
5
|
+
```ts
|
|
6
|
+
import pg from 'pg';
|
|
7
|
+
import { postgresStorage, migrationSql } from '@fhirforge/pg';
|
|
8
|
+
|
|
9
|
+
const storage = postgresStorage(new pg.Pool({ connectionString, ssl: true }));
|
|
10
|
+
const sql = migrationSql(['Patient', 'Observation']); // plain SQL for your own migration tool
|
|
11
|
+
```
|
|
12
|
+
|
|
13
|
+
A Pool pointing at a non-local host must use TLS (`ssl`, or `sslmode=require` / `verify-ca` / `verify-full`); `{ allowInsecure: true }` overrides it for development only.
|
|
14
|
+
|
|
15
|
+
Part of [fhirforge](https://github.com/schlegz/fhirforge), an embeddable FHIR storage library for Node and TypeScript. Early development: expect breaking changes in 0.x releases.
|
|
16
|
+
|
|
17
|
+
License: Apache-2.0. FHIR® is a registered trademark of HL7; this project is not affiliated with or endorsed by HL7.
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
/** Anything that can run a parameterized query. */
|
|
2
|
+
export interface SqlClient {
|
|
3
|
+
query<R = Record<string, unknown>>(sql: string, params?: unknown[]): Promise<{
|
|
4
|
+
rows: R[];
|
|
5
|
+
}>;
|
|
6
|
+
}
|
|
7
|
+
/** A SqlClient that can also run a function inside a transaction. */
|
|
8
|
+
export interface Database extends SqlClient {
|
|
9
|
+
transaction<T>(fn: (tx: SqlClient) => Promise<T>): Promise<T>;
|
|
10
|
+
}
|
|
11
|
+
/** The parts of a `pg` Pool that fhirforge uses (no hard dependency on `pg`). */
|
|
12
|
+
export interface PgPoolLike {
|
|
13
|
+
query(text: string, values?: unknown[]): Promise<{
|
|
14
|
+
rows: unknown[];
|
|
15
|
+
}>;
|
|
16
|
+
connect(): Promise<PgPoolClientLike>;
|
|
17
|
+
}
|
|
18
|
+
export interface PgPoolClientLike {
|
|
19
|
+
query(text: string, values?: unknown[]): Promise<{
|
|
20
|
+
rows: unknown[];
|
|
21
|
+
}>;
|
|
22
|
+
release(err?: Error | boolean): void;
|
|
23
|
+
}
|
|
24
|
+
export declare function isDatabase(value: unknown): value is Database;
|
|
25
|
+
/** Wraps a `pg` Pool. Transactions check out one client and run BEGIN/COMMIT on it. */
|
|
26
|
+
export declare function pgPoolDatabase(pool: PgPoolLike): Database;
|
|
27
|
+
//# sourceMappingURL=database.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"database.d.ts","sourceRoot":"","sources":["../src/database.ts"],"names":[],"mappings":"AAAA,mDAAmD;AACnD,MAAM,WAAW,SAAS;IACxB,KAAK,CAAC,CAAC,GAAG,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EAAE,GAAG,EAAE,MAAM,EAAE,MAAM,CAAC,EAAE,OAAO,EAAE,GAAG,OAAO,CAAC;QAAE,IAAI,EAAE,CAAC,EAAE,CAAA;KAAE,CAAC,CAAC;CAC7F;AAED,qEAAqE;AACrE,MAAM,WAAW,QAAS,SAAQ,SAAS;IACzC,WAAW,CAAC,CAAC,EAAE,EAAE,EAAE,CAAC,EAAE,EAAE,SAAS,KAAK,OAAO,CAAC,CAAC,CAAC,GAAG,OAAO,CAAC,CAAC,CAAC,CAAC;CAC/D;AAED,iFAAiF;AACjF,MAAM,WAAW,UAAU;IACzB,KAAK,CAAC,IAAI,EAAE,MAAM,EAAE,MAAM,CAAC,EAAE,OAAO,EAAE,GAAG,OAAO,CAAC;QAAE,IAAI,EAAE,OAAO,EAAE,CAAA;KAAE,CAAC,CAAC;IACtE,OAAO,IAAI,OAAO,CAAC,gBAAgB,CAAC,CAAC;CACtC;AAED,MAAM,WAAW,gBAAgB;IAC/B,KAAK,CAAC,IAAI,EAAE,MAAM,EAAE,MAAM,CAAC,EAAE,OAAO,EAAE,GAAG,OAAO,CAAC;QAAE,IAAI,EAAE,OAAO,EAAE,CAAA;KAAE,CAAC,CAAC;IACtE,OAAO,CAAC,GAAG,CAAC,EAAE,KAAK,GAAG,OAAO,GAAG,IAAI,CAAC;CACtC;AAED,wBAAgB,UAAU,CAAC,KAAK,EAAE,OAAO,GAAG,KAAK,IAAI,QAAQ,CAE5D;AAED,uFAAuF;AACvF,wBAAgB,cAAc,CAAC,IAAI,EAAE,UAAU,GAAG,QAAQ,CAsBzD"}
|
package/dist/database.js
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
export function isDatabase(value) {
|
|
2
|
+
return typeof value?.transaction === 'function' && typeof value?.query === 'function';
|
|
3
|
+
}
|
|
4
|
+
/** Wraps a `pg` Pool. Transactions check out one client and run BEGIN/COMMIT on it. */
|
|
5
|
+
export function pgPoolDatabase(pool) {
|
|
6
|
+
return {
|
|
7
|
+
query: (sql, params) => pool.query(sql, params),
|
|
8
|
+
async transaction(fn) {
|
|
9
|
+
const client = await pool.connect();
|
|
10
|
+
let broken = false;
|
|
11
|
+
try {
|
|
12
|
+
await client.query('BEGIN');
|
|
13
|
+
const result = await fn({ query: (sql, params) => client.query(sql, params) });
|
|
14
|
+
await client.query('COMMIT');
|
|
15
|
+
return result;
|
|
16
|
+
}
|
|
17
|
+
catch (err) {
|
|
18
|
+
await client.query('ROLLBACK').catch(() => {
|
|
19
|
+
broken = true;
|
|
20
|
+
});
|
|
21
|
+
throw err;
|
|
22
|
+
}
|
|
23
|
+
finally {
|
|
24
|
+
// If ROLLBACK failed the connection is in an unknown state: destroy it instead of reusing it.
|
|
25
|
+
client.release(broken);
|
|
26
|
+
}
|
|
27
|
+
},
|
|
28
|
+
};
|
|
29
|
+
}
|
|
30
|
+
//# sourceMappingURL=database.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"database.js","sourceRoot":"","sources":["../src/database.ts"],"names":[],"mappings":"AAqBA,MAAM,UAAU,UAAU,CAAC,KAAc;IACvC,OAAO,OAAQ,KAAkB,EAAE,WAAW,KAAK,UAAU,IAAI,OAAQ,KAAkB,EAAE,KAAK,KAAK,UAAU,CAAC;AACpH,CAAC;AAED,uFAAuF;AACvF,MAAM,UAAU,cAAc,CAAC,IAAgB;IAC7C,OAAO;QACL,KAAK,EAAE,CAAC,GAAG,EAAE,MAAM,EAAE,EAAE,CAAC,IAAI,CAAC,KAAK,CAAC,GAAG,EAAE,MAAM,CAAU;QACxD,KAAK,CAAC,WAAW,CAAC,EAAE;YAClB,MAAM,MAAM,GAAG,MAAM,IAAI,CAAC,OAAO,EAAE,CAAC;YACpC,IAAI,MAAM,GAAG,KAAK,CAAC;YACnB,IAAI,CAAC;gBACH,MAAM,MAAM,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC;gBAC5B,MAAM,MAAM,GAAG,MAAM,EAAE,CAAC,EAAE,KAAK,EAAE,CAAC,GAAG,EAAE,MAAM,EAAE,EAAE,CAAC,MAAM,CAAC,KAAK,CAAC,GAAG,EAAE,MAAM,CAAU,EAAE,CAAC,CAAC;gBACxF,MAAM,MAAM,CAAC,KAAK,CAAC,QAAQ,CAAC,CAAC;gBAC7B,OAAO,MAAM,CAAC;YAChB,CAAC;YAAC,OAAO,GAAG,EAAE,CAAC;gBACb,MAAM,MAAM,CAAC,KAAK,CAAC,UAAU,CAAC,CAAC,KAAK,CAAC,GAAG,EAAE;oBACxC,MAAM,GAAG,IAAI,CAAC;gBAChB,CAAC,CAAC,CAAC;gBACH,MAAM,GAAG,CAAC;YACZ,CAAC;oBAAS,CAAC;gBACT,8FAA8F;gBAC9F,MAAM,CAAC,OAAO,CAAC,MAAM,CAAC,CAAC;YACzB,CAAC;QACH,CAAC;KACF,CAAC;AACJ,CAAC"}
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
export { postgresStorage, type PostgresStorageOptions } from './storage.js';
|
|
2
|
+
export { migrationSql, migrationsFor, type Migration } from './migrations.js';
|
|
3
|
+
export { pgPoolDatabase, isDatabase, type Database, type SqlClient, type PgPoolLike, type PgPoolClientLike, } from './database.js';
|
|
4
|
+
export { assertSecureTransport, inspectPoolTransport, type TransportOptions, type TransportCheck } from './transport.js';
|
|
5
|
+
//# sourceMappingURL=index.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,eAAe,EAAE,KAAK,sBAAsB,EAAE,MAAM,cAAc,CAAC;AAC5E,OAAO,EAAE,YAAY,EAAE,aAAa,EAAE,KAAK,SAAS,EAAE,MAAM,iBAAiB,CAAC;AAC9E,OAAO,EACL,cAAc,EACd,UAAU,EACV,KAAK,QAAQ,EACb,KAAK,SAAS,EACd,KAAK,UAAU,EACf,KAAK,gBAAgB,GACtB,MAAM,eAAe,CAAC;AACvB,OAAO,EAAE,qBAAqB,EAAE,oBAAoB,EAAE,KAAK,gBAAgB,EAAE,KAAK,cAAc,EAAE,MAAM,gBAAgB,CAAC"}
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
export { postgresStorage } from './storage.js';
|
|
2
|
+
export { migrationSql, migrationsFor } from './migrations.js';
|
|
3
|
+
export { pgPoolDatabase, isDatabase, } from './database.js';
|
|
4
|
+
export { assertSecureTransport, inspectPoolTransport } from './transport.js';
|
|
5
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,eAAe,EAA+B,MAAM,cAAc,CAAC;AAC5E,OAAO,EAAE,YAAY,EAAE,aAAa,EAAkB,MAAM,iBAAiB,CAAC;AAC9E,OAAO,EACL,cAAc,EACd,UAAU,GAKX,MAAM,eAAe,CAAC;AACvB,OAAO,EAAE,qBAAqB,EAAE,oBAAoB,EAA8C,MAAM,gBAAgB,CAAC"}
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
/** Migrations that create search index tables: existing resources must be reindexed after them. */
|
|
2
|
+
export declare function isIndexMigration(id: string): boolean;
|
|
3
|
+
export interface Migration {
|
|
4
|
+
/** Stable id recorded in `<schema>._migrations`, e.g. `resource:Patient:1`. */
|
|
5
|
+
id: string;
|
|
6
|
+
statements: string[];
|
|
7
|
+
}
|
|
8
|
+
/**
|
|
9
|
+
* Every migration fhirforge knows for these resource types, in order.
|
|
10
|
+
* Migrations are append-only: never edit one that has shipped, add a new id.
|
|
11
|
+
*/
|
|
12
|
+
export declare function migrationsFor(schema: string, resourceTypes: readonly string[]): Migration[];
|
|
13
|
+
/** Statements that create the schema and the migration log. Always safe to re-run. */
|
|
14
|
+
export declare function bootstrapStatements(schema: string): string[];
|
|
15
|
+
/**
|
|
16
|
+
* The full migration as plain SQL, for teams that run migrations with their
|
|
17
|
+
* own tool (Prisma, Drizzle, Flyway). Idempotent: every statement uses IF NOT EXISTS.
|
|
18
|
+
*/
|
|
19
|
+
export declare function migrationSql(resourceTypes: readonly string[], options?: {
|
|
20
|
+
schema?: string;
|
|
21
|
+
}): string;
|
|
22
|
+
//# sourceMappingURL=migrations.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"migrations.d.ts","sourceRoot":"","sources":["../src/migrations.ts"],"names":[],"mappings":"AAEA,mGAAmG;AACnG,wBAAgB,gBAAgB,CAAC,EAAE,EAAE,MAAM,GAAG,OAAO,CAEpD;AAED,MAAM,WAAW,SAAS;IACxB,+EAA+E;IAC/E,EAAE,EAAE,MAAM,CAAC;IACX,UAAU,EAAE,MAAM,EAAE,CAAC;CACtB;AAED;;;GAGG;AACH,wBAAgB,aAAa,CAAC,MAAM,EAAE,MAAM,EAAE,aAAa,EAAE,SAAS,MAAM,EAAE,GAAG,SAAS,EAAE,CAmD3F;AAED,sFAAsF;AACtF,wBAAgB,mBAAmB,CAAC,MAAM,EAAE,MAAM,GAAG,MAAM,EAAE,CAS5D;AAED;;;GAGG;AACH,wBAAgB,YAAY,CAAC,aAAa,EAAE,SAAS,MAAM,EAAE,EAAE,OAAO,GAAE;IAAE,MAAM,CAAC,EAAE,MAAM,CAAA;CAAO,GAAG,MAAM,CAYxG"}
|
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
import { checkSchemaName, ident, tablesFor } from './sql.js';
|
|
2
|
+
/** Migrations that create search index tables: existing resources must be reindexed after them. */
|
|
3
|
+
export function isIndexMigration(id) {
|
|
4
|
+
return /^resource:[A-Za-z]+:2$/.test(id);
|
|
5
|
+
}
|
|
6
|
+
/**
|
|
7
|
+
* Every migration fhirforge knows for these resource types, in order.
|
|
8
|
+
* Migrations are append-only: never edit one that has shipped, add a new id.
|
|
9
|
+
*/
|
|
10
|
+
export function migrationsFor(schema, resourceTypes) {
|
|
11
|
+
checkSchemaName(schema);
|
|
12
|
+
const migrations = [];
|
|
13
|
+
for (const resourceType of [...resourceTypes].sort()) {
|
|
14
|
+
const t = tablesFor(schema, resourceType);
|
|
15
|
+
const idx = (suffix) => ident(`${resourceType}_${suffix}`);
|
|
16
|
+
migrations.push({
|
|
17
|
+
id: `resource:${resourceType}:1`,
|
|
18
|
+
statements: [
|
|
19
|
+
// Current version of each resource. `content` is null for a deleted resource.
|
|
20
|
+
`CREATE TABLE IF NOT EXISTS ${t.current} (
|
|
21
|
+
id text PRIMARY KEY,
|
|
22
|
+
version_id bigint NOT NULL,
|
|
23
|
+
last_updated timestamptz NOT NULL,
|
|
24
|
+
deleted boolean NOT NULL DEFAULT false,
|
|
25
|
+
content jsonb
|
|
26
|
+
)`,
|
|
27
|
+
// Every version, including the current one and delete markers.
|
|
28
|
+
`CREATE TABLE IF NOT EXISTS ${t.history} (
|
|
29
|
+
id text NOT NULL,
|
|
30
|
+
version_id bigint NOT NULL,
|
|
31
|
+
last_updated timestamptz NOT NULL,
|
|
32
|
+
deleted boolean NOT NULL,
|
|
33
|
+
content jsonb,
|
|
34
|
+
PRIMARY KEY (id, version_id)
|
|
35
|
+
)`,
|
|
36
|
+
`CREATE INDEX IF NOT EXISTS ${idx('last_updated_idx')} ON ${t.current} (last_updated)`,
|
|
37
|
+
],
|
|
38
|
+
});
|
|
39
|
+
// Search indexes: one table per value kind. Rows are copies of resource data (may be PHI)
|
|
40
|
+
// and cascade away with the resource row, so expunge can't leave them behind.
|
|
41
|
+
const fk = `resource_id text NOT NULL REFERENCES ${t.current} (id) ON DELETE CASCADE,\n param text NOT NULL`;
|
|
42
|
+
const table = (kind, columns, lookup) => [
|
|
43
|
+
`CREATE TABLE IF NOT EXISTS ${t.index[kind]} (\n ${fk},\n ${columns}\n)`,
|
|
44
|
+
`CREATE INDEX IF NOT EXISTS ${idx(`${kind}_resource_idx`)} ON ${t.index[kind]} (resource_id)`,
|
|
45
|
+
`CREATE INDEX IF NOT EXISTS ${idx(`${kind}_lookup_idx`)} ON ${t.index[kind]} (${lookup})`,
|
|
46
|
+
];
|
|
47
|
+
migrations.push({
|
|
48
|
+
id: `resource:${resourceType}:2`,
|
|
49
|
+
statements: [
|
|
50
|
+
...table('string', 'value_norm text NOT NULL,\n value_exact text NOT NULL', 'param, value_norm text_pattern_ops'),
|
|
51
|
+
...table('token', 'system text,\n code text NOT NULL', 'param, code, system'),
|
|
52
|
+
...table('date', 'low timestamptz,\n high timestamptz', 'param, low, high'),
|
|
53
|
+
...table('reference', 'target_type text,\n target_id text,\n reference text NOT NULL', 'param, target_id, target_type'),
|
|
54
|
+
...table('number', 'value numeric NOT NULL', 'param, value'),
|
|
55
|
+
...table('quantity', 'value numeric NOT NULL,\n system text,\n code text', 'param, value'),
|
|
56
|
+
...table('uri', 'value text NOT NULL', 'param, value'),
|
|
57
|
+
],
|
|
58
|
+
});
|
|
59
|
+
}
|
|
60
|
+
return migrations;
|
|
61
|
+
}
|
|
62
|
+
/** Statements that create the schema and the migration log. Always safe to re-run. */
|
|
63
|
+
export function bootstrapStatements(schema) {
|
|
64
|
+
const s = ident(checkSchemaName(schema));
|
|
65
|
+
return [
|
|
66
|
+
`CREATE SCHEMA IF NOT EXISTS ${s}`,
|
|
67
|
+
`CREATE TABLE IF NOT EXISTS ${s}."_migrations" (
|
|
68
|
+
id text PRIMARY KEY,
|
|
69
|
+
applied_at timestamptz NOT NULL DEFAULT now()
|
|
70
|
+
)`,
|
|
71
|
+
];
|
|
72
|
+
}
|
|
73
|
+
/**
|
|
74
|
+
* The full migration as plain SQL, for teams that run migrations with their
|
|
75
|
+
* own tool (Prisma, Drizzle, Flyway). Idempotent: every statement uses IF NOT EXISTS.
|
|
76
|
+
*/
|
|
77
|
+
export function migrationSql(resourceTypes, options = {}) {
|
|
78
|
+
const schema = options.schema ?? 'fhir';
|
|
79
|
+
const migrations = migrationsFor(schema, resourceTypes);
|
|
80
|
+
const lines = ['-- Generated by @fhirforge/pg', 'BEGIN;', ''];
|
|
81
|
+
for (const stmt of bootstrapStatements(schema))
|
|
82
|
+
lines.push(`${stmt};`, '');
|
|
83
|
+
for (const m of migrations) {
|
|
84
|
+
lines.push(`-- ${m.id}`);
|
|
85
|
+
for (const stmt of m.statements)
|
|
86
|
+
lines.push(`${stmt};`, '');
|
|
87
|
+
lines.push(`INSERT INTO ${ident(schema)}."_migrations" (id) VALUES ('${m.id}') ON CONFLICT (id) DO NOTHING;`, '');
|
|
88
|
+
}
|
|
89
|
+
lines.push('COMMIT;', '');
|
|
90
|
+
return lines.join('\n');
|
|
91
|
+
}
|
|
92
|
+
//# sourceMappingURL=migrations.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"migrations.js","sourceRoot":"","sources":["../src/migrations.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,eAAe,EAAE,KAAK,EAAE,SAAS,EAAE,MAAM,UAAU,CAAC;AAE7D,mGAAmG;AACnG,MAAM,UAAU,gBAAgB,CAAC,EAAU;IACzC,OAAO,wBAAwB,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC;AAC3C,CAAC;AAQD;;;GAGG;AACH,MAAM,UAAU,aAAa,CAAC,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,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC;QACzB,KAAK,MAAM,IAAI,IAAI,CAAC,CAAC,UAAU;YAAE,KAAK,CAAC,IAAI,CAAC,GAAG,IAAI,GAAG,EAAE,EAAE,CAAC,CAAC;QAC5D,KAAK,CAAC,IAAI,CAAC,eAAe,KAAK,CAAC,MAAM,CAAC,gCAAgC,CAAC,CAAC,EAAE,iCAAiC,EAAE,EAAE,CAAC,CAAC;IACpH,CAAC;IACD,KAAK,CAAC,IAAI,CAAC,SAAS,EAAE,EAAE,CAAC,CAAC;IAC1B,OAAO,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;AAC1B,CAAC"}
|
package/dist/search.d.ts
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import type { IndexRow, SearchQuery } from '@fhirforge/core';
|
|
2
|
+
import type { SqlClient } from './database.js';
|
|
3
|
+
import { type Tables } from './sql.js';
|
|
4
|
+
export interface SearchRow {
|
|
5
|
+
id: string;
|
|
6
|
+
v: string;
|
|
7
|
+
last_updated: Date | string;
|
|
8
|
+
deleted: boolean;
|
|
9
|
+
content: unknown;
|
|
10
|
+
total: string | number;
|
|
11
|
+
}
|
|
12
|
+
export declare function runSearch(db: SqlClient, t: Tables, query: SearchQuery): Promise<{
|
|
13
|
+
rows: SearchRow[];
|
|
14
|
+
total: number;
|
|
15
|
+
}>;
|
|
16
|
+
/** Replaces a resource's index rows: delete all, insert the new set. Runs inside the caller's transaction. */
|
|
17
|
+
export declare function writeIndexRows(tx: SqlClient, t: Tables, resourceId: string, rows: readonly IndexRow[]): Promise<void>;
|
|
18
|
+
export declare function deleteIndexRows(tx: SqlClient, t: Tables, resourceId: string): Promise<void>;
|
|
19
|
+
//# sourceMappingURL=search.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"search.d.ts","sourceRoot":"","sources":["../src/search.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,QAAQ,EAAyC,WAAW,EAAW,MAAM,iBAAiB,CAAC;AAC7G,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,eAAe,CAAC;AAC/C,OAAO,EAA+B,KAAK,MAAM,EAAE,MAAM,UAAU,CAAC;AAiLpE,MAAM,WAAW,SAAS;IACxB,EAAE,EAAE,MAAM,CAAC;IACX,CAAC,EAAE,MAAM,CAAC;IACV,YAAY,EAAE,IAAI,GAAG,MAAM,CAAC;IAC5B,OAAO,EAAE,OAAO,CAAC;IACjB,OAAO,EAAE,OAAO,CAAC;IACjB,KAAK,EAAE,MAAM,GAAG,MAAM,CAAC;CACxB;AAED,wBAAsB,SAAS,CAAC,EAAE,EAAE,SAAS,EAAE,CAAC,EAAE,MAAM,EAAE,KAAK,EAAE,WAAW,GAAG,OAAO,CAAC;IAAE,IAAI,EAAE,SAAS,EAAE,CAAC;IAAC,KAAK,EAAE,MAAM,CAAA;CAAE,CAAC,CAsB3H;AAED,8GAA8G;AAC9G,wBAAsB,cAAc,CAAC,EAAE,EAAE,SAAS,EAAE,CAAC,EAAE,MAAM,EAAE,UAAU,EAAE,MAAM,EAAE,IAAI,EAAE,SAAS,QAAQ,EAAE,GAAG,OAAO,CAAC,IAAI,CAAC,CAW3H;AA+BD,wBAAsB,eAAe,CAAC,EAAE,EAAE,SAAS,EAAE,CAAC,EAAE,MAAM,EAAE,UAAU,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC,CAEjG"}
|
package/dist/search.js
ADDED
|
@@ -0,0 +1,223 @@
|
|
|
1
|
+
import { INDEX_KINDS } from './sql.js';
|
|
2
|
+
/**
|
|
3
|
+
* Builds SQL with bind parameters only. Every value from a query or a
|
|
4
|
+
* resource goes through `bind()`; the only things interpolated into SQL text
|
|
5
|
+
* are table names from `tablesFor()` and fixed fragments in this file.
|
|
6
|
+
*/
|
|
7
|
+
class Sql {
|
|
8
|
+
params = [];
|
|
9
|
+
bind(value) {
|
|
10
|
+
this.params.push(value);
|
|
11
|
+
return `$${this.params.length}`;
|
|
12
|
+
}
|
|
13
|
+
}
|
|
14
|
+
/** Escapes LIKE wildcards so a search for `50%` matches the text "50%", not anything starting with "50". */
|
|
15
|
+
function likeEscape(value) {
|
|
16
|
+
return value.replace(/[\\%_]/g, (c) => `\\${c}`);
|
|
17
|
+
}
|
|
18
|
+
/** Parameters are bound only when used: Postgres rejects bind parameters it can't type. */
|
|
19
|
+
function rangeCondition(prefix, r, lazyLow, lazyHigh) {
|
|
20
|
+
let low;
|
|
21
|
+
let high;
|
|
22
|
+
const pl = () => (low ??= lazyLow());
|
|
23
|
+
const ph = () => (high ??= lazyHigh());
|
|
24
|
+
switch (prefix) {
|
|
25
|
+
case 'eq':
|
|
26
|
+
return `(${r.lo} >= ${pl()} AND ${r.hi} <= ${ph()})`;
|
|
27
|
+
case 'ne':
|
|
28
|
+
return `NOT (${r.lo} >= ${pl()} AND ${r.hi} <= ${ph()})`;
|
|
29
|
+
case 'gt':
|
|
30
|
+
return `(${r.hi} > ${ph()})`;
|
|
31
|
+
case 'lt':
|
|
32
|
+
return `(${r.lo} < ${pl()})`;
|
|
33
|
+
case 'ge':
|
|
34
|
+
return `(${r.hi} > ${pl()})`;
|
|
35
|
+
case 'le':
|
|
36
|
+
return `(${r.lo} < ${ph()})`;
|
|
37
|
+
case 'sa':
|
|
38
|
+
return `(${r.lo} >= ${ph()})`;
|
|
39
|
+
case 'eb':
|
|
40
|
+
return `(${r.hi} <= ${pl()})`;
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
/** FHIR prefix semantics for a stored point value against a search value with precision range [low, high). */
|
|
44
|
+
function pointCondition(prefix, col, lazyValue, lazyLow, lazyHigh) {
|
|
45
|
+
const value = () => lazyValue();
|
|
46
|
+
const low = () => lazyLow();
|
|
47
|
+
const high = () => lazyHigh();
|
|
48
|
+
switch (prefix) {
|
|
49
|
+
case 'eq':
|
|
50
|
+
return `(${col} >= ${low()} AND ${col} < ${high()})`;
|
|
51
|
+
case 'ne':
|
|
52
|
+
return `NOT (${col} >= ${low()} AND ${col} < ${high()})`;
|
|
53
|
+
case 'gt':
|
|
54
|
+
case 'sa':
|
|
55
|
+
return `(${col} > ${value()})`;
|
|
56
|
+
case 'lt':
|
|
57
|
+
case 'eb':
|
|
58
|
+
return `(${col} < ${value()})`;
|
|
59
|
+
case 'ge':
|
|
60
|
+
return `(${col} >= ${value()})`;
|
|
61
|
+
case 'le':
|
|
62
|
+
return `(${col} <= ${value()})`;
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
function condition(sql, c) {
|
|
66
|
+
switch (c.kind) {
|
|
67
|
+
case 'string':
|
|
68
|
+
if (c.mode === 'exact')
|
|
69
|
+
return `i.value_exact = ${sql.bind(c.value)}`;
|
|
70
|
+
if (c.mode === 'contains')
|
|
71
|
+
return `i.value_norm LIKE ${sql.bind(`%${likeEscape(c.value)}%`)} ESCAPE '\\'`;
|
|
72
|
+
return `i.value_norm LIKE ${sql.bind(`${likeEscape(c.value)}%`)} ESCAPE '\\'`;
|
|
73
|
+
case 'token': {
|
|
74
|
+
const parts = [];
|
|
75
|
+
if (c.code !== undefined)
|
|
76
|
+
parts.push(`i.code = ${sql.bind(c.code)}`);
|
|
77
|
+
if (c.system === null)
|
|
78
|
+
parts.push('i.system IS NULL');
|
|
79
|
+
else if (c.system !== undefined)
|
|
80
|
+
parts.push(`i.system = ${sql.bind(c.system)}`);
|
|
81
|
+
return `(${parts.join(' AND ')})`;
|
|
82
|
+
}
|
|
83
|
+
case 'date':
|
|
84
|
+
return rangeCondition(c.prefix, { lo: `COALESCE(i.low, '-infinity'::timestamptz)`, hi: `COALESCE(i.high, 'infinity'::timestamptz)` }, () => `${sql.bind(c.low)}::timestamptz`, () => `${sql.bind(c.high)}::timestamptz`);
|
|
85
|
+
case 'reference': {
|
|
86
|
+
if (c.reference !== undefined)
|
|
87
|
+
return `i.reference = ${sql.bind(c.reference)}`;
|
|
88
|
+
const parts = [`i.target_id = ${sql.bind(c.targetId)}`];
|
|
89
|
+
if (c.targetType !== undefined)
|
|
90
|
+
parts.push(`i.target_type = ${sql.bind(c.targetType)}`);
|
|
91
|
+
return `(${parts.join(' AND ')})`;
|
|
92
|
+
}
|
|
93
|
+
case 'number':
|
|
94
|
+
return pointCondition(c.prefix, 'i.value', () => `${sql.bind(c.value)}::numeric`, () => `${sql.bind(c.low)}::numeric`, () => `${sql.bind(c.high)}::numeric`);
|
|
95
|
+
case 'quantity': {
|
|
96
|
+
const parts = [
|
|
97
|
+
pointCondition(c.prefix, 'i.value', () => `${sql.bind(c.value)}::numeric`, () => `${sql.bind(c.low)}::numeric`, () => `${sql.bind(c.high)}::numeric`),
|
|
98
|
+
];
|
|
99
|
+
if (c.system === null)
|
|
100
|
+
parts.push('i.system IS NULL');
|
|
101
|
+
else if (c.system !== undefined)
|
|
102
|
+
parts.push(`i.system = ${sql.bind(c.system)}`);
|
|
103
|
+
if (c.code !== undefined)
|
|
104
|
+
parts.push(`i.code = ${sql.bind(c.code)}`);
|
|
105
|
+
return `(${parts.join(' AND ')})`;
|
|
106
|
+
}
|
|
107
|
+
case 'uri':
|
|
108
|
+
return `i.value = ${sql.bind(c.value)}`;
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
function indexKindOf(type) {
|
|
112
|
+
if (type === 'id' || type === 'lastUpdated')
|
|
113
|
+
throw new Error(`${type} has no index table`);
|
|
114
|
+
return type;
|
|
115
|
+
}
|
|
116
|
+
function clauseSql(sql, t, clause) {
|
|
117
|
+
if (clause.type === 'id') {
|
|
118
|
+
const ids = clause.conditions.flatMap((c) => (c.kind === 'token' && c.code !== undefined ? [c.code] : []));
|
|
119
|
+
return `r.id = ANY(${sql.bind(ids)}::text[])`;
|
|
120
|
+
}
|
|
121
|
+
if (clause.type === 'lastUpdated') {
|
|
122
|
+
const r = { lo: 'r.last_updated', hi: `(r.last_updated + interval '1 millisecond')` };
|
|
123
|
+
const ors = clause.conditions.map((c) => c.kind === 'date'
|
|
124
|
+
? rangeCondition(c.prefix, r, () => `${sql.bind(c.low)}::timestamptz`, () => `${sql.bind(c.high)}::timestamptz`)
|
|
125
|
+
: 'false');
|
|
126
|
+
return `(${ors.join(' OR ')})`;
|
|
127
|
+
}
|
|
128
|
+
const table = t.index[indexKindOf(clause.type)];
|
|
129
|
+
const base = `SELECT 1 FROM ${table} i WHERE i.resource_id = r.id AND i.param = ${sql.bind(clause.param)}`;
|
|
130
|
+
if (clause.missing !== undefined) {
|
|
131
|
+
return clause.missing ? `NOT EXISTS (${base})` : `EXISTS (${base})`;
|
|
132
|
+
}
|
|
133
|
+
const ors = clause.conditions.map((c) => condition(sql, c)).join(' OR ');
|
|
134
|
+
return `${clause.negate ? 'NOT ' : ''}EXISTS (${base} AND (${ors}))`;
|
|
135
|
+
}
|
|
136
|
+
function sortSql(sql, t, key) {
|
|
137
|
+
const dir = key.descending ? 'DESC' : 'ASC';
|
|
138
|
+
if (key.type === 'id')
|
|
139
|
+
return `r.id ${dir}`;
|
|
140
|
+
if (key.type === 'lastUpdated')
|
|
141
|
+
return `r.last_updated ${dir}`;
|
|
142
|
+
const table = t.index[indexKindOf(key.type)];
|
|
143
|
+
const agg = key.descending ? 'max' : 'min';
|
|
144
|
+
const col = key.type === 'date'
|
|
145
|
+
? key.descending
|
|
146
|
+
? `COALESCE(i.high, 'infinity'::timestamptz)`
|
|
147
|
+
: `COALESCE(i.low, '-infinity'::timestamptz)`
|
|
148
|
+
: key.type === 'string'
|
|
149
|
+
? 'i.value_norm'
|
|
150
|
+
: key.type === 'token'
|
|
151
|
+
? 'i.code'
|
|
152
|
+
: key.type === 'reference'
|
|
153
|
+
? 'i.reference'
|
|
154
|
+
: 'i.value';
|
|
155
|
+
return `(SELECT ${agg}(${col}) FROM ${table} i WHERE i.resource_id = r.id AND i.param = ${sql.bind(key.param)}) ${dir} NULLS LAST`;
|
|
156
|
+
}
|
|
157
|
+
export async function runSearch(db, t, query) {
|
|
158
|
+
const sql = new Sql();
|
|
159
|
+
const where = ['NOT r.deleted', ...query.clauses.map((c) => clauseSql(sql, t, c))].join('\n AND ');
|
|
160
|
+
const order = [...query.sort.map((k) => sortSql(sql, t, k)), 'r.id ASC'].join(', ');
|
|
161
|
+
const limit = sql.bind(query.count);
|
|
162
|
+
const offset = sql.bind(query.offset);
|
|
163
|
+
const text = `SELECT r.id, r.version_id::text AS v, r.last_updated, r.deleted, r.content, count(*) OVER () AS total
|
|
164
|
+
FROM ${t.current} r
|
|
165
|
+
WHERE ${where}
|
|
166
|
+
ORDER BY ${order}
|
|
167
|
+
LIMIT ${limit} OFFSET ${offset}`;
|
|
168
|
+
const { rows } = await db.query(text, sql.params);
|
|
169
|
+
if (rows.length > 0)
|
|
170
|
+
return { rows, total: Number(rows[0].total) };
|
|
171
|
+
if (query.offset === 0)
|
|
172
|
+
return { rows, total: 0 };
|
|
173
|
+
// Past the last page: the window count is gone, so count separately (same WHERE, same binds).
|
|
174
|
+
const countSql = new Sql();
|
|
175
|
+
const countWhere = ['NOT r.deleted', ...query.clauses.map((c) => clauseSql(countSql, t, c))].join(' AND ');
|
|
176
|
+
const { rows: count } = await db.query(`SELECT count(*)::text AS n FROM ${t.current} r WHERE ${countWhere}`, countSql.params);
|
|
177
|
+
return { rows, total: Number(count[0]?.n ?? 0) };
|
|
178
|
+
}
|
|
179
|
+
/** Replaces a resource's index rows: delete all, insert the new set. Runs inside the caller's transaction. */
|
|
180
|
+
export async function writeIndexRows(tx, t, resourceId, rows) {
|
|
181
|
+
for (const kind of INDEX_KINDS) {
|
|
182
|
+
await tx.query(`DELETE FROM ${t.index[kind]} WHERE resource_id = $1`, [resourceId]);
|
|
183
|
+
}
|
|
184
|
+
for (const kind of INDEX_KINDS) {
|
|
185
|
+
const ofKind = rows.filter((r) => r.kind === kind);
|
|
186
|
+
if (ofKind.length === 0)
|
|
187
|
+
continue;
|
|
188
|
+
const sql = new Sql();
|
|
189
|
+
const values = ofKind.map((r) => `(${[resourceId, r.param, ...columnValues(r)].map((v) => sql.bind(v)).join(', ')})`);
|
|
190
|
+
await tx.query(`INSERT INTO ${t.index[kind]} (resource_id, param, ${COLUMNS[kind]}) VALUES ${values.join(', ')}`, sql.params);
|
|
191
|
+
}
|
|
192
|
+
}
|
|
193
|
+
const COLUMNS = {
|
|
194
|
+
string: 'value_norm, value_exact',
|
|
195
|
+
token: 'system, code',
|
|
196
|
+
date: 'low, high',
|
|
197
|
+
reference: 'target_type, target_id, reference',
|
|
198
|
+
number: 'value',
|
|
199
|
+
quantity: 'value, system, code',
|
|
200
|
+
uri: 'value',
|
|
201
|
+
};
|
|
202
|
+
function columnValues(r) {
|
|
203
|
+
switch (r.kind) {
|
|
204
|
+
case 'string':
|
|
205
|
+
return [r.valueNorm, r.valueExact];
|
|
206
|
+
case 'token':
|
|
207
|
+
return [r.system, r.code];
|
|
208
|
+
case 'date':
|
|
209
|
+
return [r.low, r.high];
|
|
210
|
+
case 'reference':
|
|
211
|
+
return [r.targetType, r.targetId, r.reference];
|
|
212
|
+
case 'number':
|
|
213
|
+
return [r.value];
|
|
214
|
+
case 'quantity':
|
|
215
|
+
return [r.value, r.system, r.code];
|
|
216
|
+
case 'uri':
|
|
217
|
+
return [r.value];
|
|
218
|
+
}
|
|
219
|
+
}
|
|
220
|
+
export async function deleteIndexRows(tx, t, resourceId) {
|
|
221
|
+
await writeIndexRows(tx, t, resourceId, []);
|
|
222
|
+
}
|
|
223
|
+
//# sourceMappingURL=search.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"search.js","sourceRoot":"","sources":["../src/search.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,WAAW,EAA+B,MAAM,UAAU,CAAC;AAEpE;;;;GAIG;AACH,MAAM,GAAG;IACE,MAAM,GAAc,EAAE,CAAC;IAChC,IAAI,CAAC,KAAc;QACjB,IAAI,CAAC,MAAM,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;QACxB,OAAO,IAAI,IAAI,CAAC,MAAM,CAAC,MAAM,EAAE,CAAC;IAClC,CAAC;CACF;AAED,4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IACrB,IAAI,EAAE,WAAW;IACjB,SAAS,EAAE,mCAAmC;IAC9C,MAAM,EAAE,OAAO;IACf,QAAQ,EAAE,qBAAqB;IAC/B,GAAG,EAAE,OAAO;CACb,CAAC;AAEF,SAAS,YAAY,CAAC,CAAW;IAC/B,QAAQ,CAAC,CAAC,IAAI,EAAE,CAAC;QACf,KAAK,QAAQ;YACX,OAAO,CAAC,CAAC,CAAC,SAAS,EAAE,CAAC,CAAC,UAAU,CAAC,CAAC;QACrC,KAAK,OAAO;YACV,OAAO,CAAC,CAAC,CAAC,MAAM,EAAE,CAAC,CAAC,IAAI,CAAC,CAAC;QAC5B,KAAK,MAAM;YACT,OAAO,CAAC,CAAC,CAAC,GAAG,EAAE,CAAC,CAAC,IAAI,CAAC,CAAC;QACzB,KAAK,WAAW;YACd,OAAO,CAAC,CAAC,CAAC,UAAU,EAAE,CAAC,CAAC,QAAQ,EAAE,CAAC,CAAC,SAAS,CAAC,CAAC;QACjD,KAAK,QAAQ;YACX,OAAO,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC;QACnB,KAAK,UAAU;YACb,OAAO,CAAC,CAAC,CAAC,KAAK,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,CAAC,IAAI,CAAC,CAAC;QACrC,KAAK,KAAK;YACR,OAAO,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC;IACrB,CAAC;AACH,CAAC;AAED,MAAM,CAAC,KAAK,UAAU,eAAe,CAAC,EAAa,EAAE,CAAS,EAAE,UAAkB;IAChF,MAAM,cAAc,CAAC,EAAE,EAAE,CAAC,EAAE,UAAU,EAAE,EAAE,CAAC,CAAC;AAC9C,CAAC"}
|
package/dist/sql.d.ts
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
/** Quotes a Postgres identifier. Only accepts the names fhirforge generates, so nothing user-controlled ever reaches SQL text. */
|
|
2
|
+
export declare function ident(name: string): string;
|
|
3
|
+
export declare function checkSchemaName(schema: string): string;
|
|
4
|
+
export declare function checkResourceType(resourceType: string): string;
|
|
5
|
+
export declare const INDEX_KINDS: readonly ['string', 'token', 'date', 'reference', 'number', 'quantity', 'uri'];
|
|
6
|
+
export type IndexKind = (typeof INDEX_KINDS)[number];
|
|
7
|
+
export interface Tables {
|
|
8
|
+
schema: string;
|
|
9
|
+
current: string;
|
|
10
|
+
history: string;
|
|
11
|
+
/** Search index table per value kind, e.g. `"fhir"."Patient_token"`. */
|
|
12
|
+
index: Record<IndexKind, string>;
|
|
13
|
+
}
|
|
14
|
+
export declare function tablesFor(schema: string, resourceType: string): Tables;
|
|
15
|
+
//# sourceMappingURL=sql.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"sql.d.ts","sourceRoot":"","sources":["../src/sql.ts"],"names":[],"mappings":"AAAA,kIAAkI;AAClI,wBAAgB,KAAK,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,CAK1C;AAED,wBAAgB,eAAe,CAAC,MAAM,EAAE,MAAM,GAAG,MAAM,CAKtD;AAED,wBAAgB,iBAAiB,CAAC,YAAY,EAAE,MAAM,GAAG,MAAM,CAK9D;AAED,eAAO,MAAM,WAAW,YAAI,QAAQ,EAAE,OAAO,EAAE,MAAM,EAAE,WAAW,EAAE,QAAQ,EAAE,UAAU,EAAE,KAAK,CAAU,CAAC;AAC1G,MAAM,MAAM,SAAS,GAAG,CAAC,OAAO,WAAW,CAAC,CAAC,MAAM,CAAC,CAAC;AAErD,MAAM,WAAW,MAAM;IACrB,MAAM,EAAE,MAAM,CAAC;IACf,OAAO,EAAE,MAAM,CAAC;IAChB,OAAO,EAAE,MAAM,CAAC;IAChB,wEAAwE;IACxE,KAAK,EAAE,MAAM,CAAC,SAAS,EAAE,MAAM,CAAC,CAAC;CAClC;AAED,wBAAgB,SAAS,CAAC,MAAM,EAAE,MAAM,EAAE,YAAY,EAAE,MAAM,GAAG,MAAM,CAYtE"}
|
package/dist/sql.js
ADDED
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
/** Quotes a Postgres identifier. Only accepts the names fhirforge generates, so nothing user-controlled ever reaches SQL text. */
|
|
2
|
+
export function ident(name) {
|
|
3
|
+
if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(name)) {
|
|
4
|
+
throw new Error(`Refusing unsafe SQL identifier: ${JSON.stringify(name)}`);
|
|
5
|
+
}
|
|
6
|
+
return `"${name}"`;
|
|
7
|
+
}
|
|
8
|
+
export function checkSchemaName(schema) {
|
|
9
|
+
if (!/^[a-z_][a-z0-9_]{0,62}$/.test(schema)) {
|
|
10
|
+
throw new Error(`Invalid schema name ${JSON.stringify(schema)}: use lowercase letters, digits and underscores`);
|
|
11
|
+
}
|
|
12
|
+
return schema;
|
|
13
|
+
}
|
|
14
|
+
export function checkResourceType(resourceType) {
|
|
15
|
+
if (!/^[A-Z][A-Za-z]{0,62}$/.test(resourceType)) {
|
|
16
|
+
throw new Error(`Invalid resource type ${JSON.stringify(resourceType)}`);
|
|
17
|
+
}
|
|
18
|
+
return resourceType;
|
|
19
|
+
}
|
|
20
|
+
export const INDEX_KINDS = ['string', 'token', 'date', 'reference', 'number', 'quantity', 'uri'];
|
|
21
|
+
export function tablesFor(schema, resourceType) {
|
|
22
|
+
checkResourceType(resourceType);
|
|
23
|
+
const s = ident(schema);
|
|
24
|
+
const index = Object.fromEntries(INDEX_KINDS.map((k) => [k, `${s}.${ident(`${resourceType}_${k}`)}`]));
|
|
25
|
+
return {
|
|
26
|
+
schema: s,
|
|
27
|
+
current: `${s}.${ident(resourceType)}`,
|
|
28
|
+
history: `${s}.${ident(`${resourceType}_history`)}`,
|
|
29
|
+
index,
|
|
30
|
+
};
|
|
31
|
+
}
|
|
32
|
+
//# sourceMappingURL=sql.js.map
|
package/dist/sql.js.map
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"sql.js","sourceRoot":"","sources":["../src/sql.ts"],"names":[],"mappings":"AAAA,kIAAkI;AAClI,MAAM,UAAU,KAAK,CAAC,IAAY;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MAAM,EAAE,CAAC;QACT,OAAO,EAAE,GAAG,CAAC,IAAI,KAAK,CAAC,YAAY,CAAC,EAAE;QACtC,OAAO,EAAE,GAAG,CAAC,IAAI,KAAK,CAAC,GAAG,YAAY,UAAU,CAAC,EAAE;QACnD,KAAK;KACN,CAAC;AACJ,CAAC"}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import { type FhirStorage } from '@fhirforge/core';
|
|
2
|
+
import { type Database, type PgPoolLike } from './database.js';
|
|
3
|
+
import { type TransportOptions } from './transport.js';
|
|
4
|
+
export interface PostgresStorageOptions extends TransportOptions {
|
|
5
|
+
/** Postgres schema for all fhirforge tables. Default `fhir`. */
|
|
6
|
+
schema?: string;
|
|
7
|
+
}
|
|
8
|
+
/**
|
|
9
|
+
* FHIR storage on Postgres. Pass a `pg` Pool or any `Database`
|
|
10
|
+
* (e.g. `pgliteDatabase(pglite)` from `@fhirforge/pglite`).
|
|
11
|
+
*
|
|
12
|
+
* A Pool pointing at a non-local host must be configured for TLS, or this
|
|
13
|
+
* throws (opt out for development with `allowInsecure: true`).
|
|
14
|
+
*
|
|
15
|
+
* Layout per resource type, in the `fhir` schema by default:
|
|
16
|
+
* - `"Patient"`: the current version (JSONB), one row per resource
|
|
17
|
+
* - `"Patient_history"`: every version, including delete markers
|
|
18
|
+
*/
|
|
19
|
+
export declare function postgresStorage(db: Database | PgPoolLike, options?: PostgresStorageOptions): FhirStorage;
|
|
20
|
+
//# sourceMappingURL=storage.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"storage.d.ts","sourceRoot":"","sources":["../src/storage.ts"],"names":[],"mappings":"AAAA,OAAO,EAIL,KAAK,WAAW,EAGjB,MAAM,iBAAiB,CAAC;AACzB,OAAO,EAA8B,KAAK,QAAQ,EAAE,KAAK,UAAU,EAAkB,MAAM,eAAe,CAAC;AAI3G,OAAO,EAAyB,KAAK,gBAAgB,EAAE,MAAM,gBAAgB,CAAC;AAE9E,MAAM,WAAW,sBAAuB,SAAQ,gBAAgB;IAC9D,gEAAgE;IAChE,MAAM,CAAC,EAAE,MAAM,CAAC;CACjB;AASD;;;;;;;;;;GAUG;AACH,wBAAgB,eAAe,CAAC,EAAE,EAAE,QAAQ,GAAG,UAAU,EAAE,OAAO,GAAE,sBAA2B,GAAG,WAAW,CAoN5G"}
|
package/dist/storage.js
ADDED
|
@@ -0,0 +1,186 @@
|
|
|
1
|
+
import { FhirError, stampMeta, } from '@fhirforge/core';
|
|
2
|
+
import { isDatabase, pgPoolDatabase } from './database.js';
|
|
3
|
+
import { bootstrapStatements, isIndexMigration, migrationsFor } from './migrations.js';
|
|
4
|
+
import { deleteIndexRows, runSearch, writeIndexRows } from './search.js';
|
|
5
|
+
import { checkSchemaName, ident, tablesFor } from './sql.js';
|
|
6
|
+
import { assertSecureTransport } from './transport.js';
|
|
7
|
+
/**
|
|
8
|
+
* FHIR storage on Postgres. Pass a `pg` Pool or any `Database`
|
|
9
|
+
* (e.g. `pgliteDatabase(pglite)` from `@fhirforge/pglite`).
|
|
10
|
+
*
|
|
11
|
+
* A Pool pointing at a non-local host must be configured for TLS, or this
|
|
12
|
+
* throws (opt out for development with `allowInsecure: true`).
|
|
13
|
+
*
|
|
14
|
+
* Layout per resource type, in the `fhir` schema by default:
|
|
15
|
+
* - `"Patient"`: the current version (JSONB), one row per resource
|
|
16
|
+
* - `"Patient_history"`: every version, including delete markers
|
|
17
|
+
*/
|
|
18
|
+
export function postgresStorage(db, options = {}) {
|
|
19
|
+
// A pg Pool must use TLS unless it connects locally (see transport.ts).
|
|
20
|
+
if (!isDatabase(db))
|
|
21
|
+
assertSecureTransport(db, options);
|
|
22
|
+
const database = isDatabase(db) ? db : pgPoolDatabase(db);
|
|
23
|
+
const schema = checkSchemaName(options.schema ?? 'fhir');
|
|
24
|
+
const run = async (resourceType, fn) => {
|
|
25
|
+
try {
|
|
26
|
+
return await fn();
|
|
27
|
+
}
|
|
28
|
+
catch (err) {
|
|
29
|
+
if (err.code === '42P01') {
|
|
30
|
+
throw new Error(`fhirforge: the tables for ${resourceType} don't exist in schema "${schema}". Run store.migrate() first.`, { cause: err });
|
|
31
|
+
}
|
|
32
|
+
throw err;
|
|
33
|
+
}
|
|
34
|
+
};
|
|
35
|
+
const toVersion = (row) => {
|
|
36
|
+
const content = typeof row.content === 'string' ? JSON.parse(row.content) : row.content;
|
|
37
|
+
return {
|
|
38
|
+
versionId: String(row.v),
|
|
39
|
+
lastUpdated: new Date(row.last_updated).toISOString(),
|
|
40
|
+
deleted: row.deleted,
|
|
41
|
+
resource: content ?? null,
|
|
42
|
+
};
|
|
43
|
+
};
|
|
44
|
+
/** Locks the current row (if any) for the rest of the transaction. */
|
|
45
|
+
const lockCurrent = async (tx, resourceType, id) => {
|
|
46
|
+
const t = tablesFor(schema, resourceType);
|
|
47
|
+
const { rows } = await tx.query(`SELECT version_id::text AS v, deleted FROM ${t.current} WHERE id = $1 FOR UPDATE`, [id]);
|
|
48
|
+
return rows[0];
|
|
49
|
+
};
|
|
50
|
+
/** Writes a version to both tables. `insert` = no current row yet. */
|
|
51
|
+
const writeVersion = async (tx, resourceType, id, versionId, resource, insert, index) => {
|
|
52
|
+
const t = tablesFor(schema, resourceType);
|
|
53
|
+
const lastUpdated = new Date().toISOString();
|
|
54
|
+
const stamped = resource ? stampMeta(resource, String(versionId), lastUpdated) : null;
|
|
55
|
+
const content = stamped ? JSON.stringify(stamped) : null;
|
|
56
|
+
const deleted = resource === null;
|
|
57
|
+
if (insert) {
|
|
58
|
+
const { rows } = await tx.query(`INSERT INTO ${t.current} (id, version_id, last_updated, deleted, content)
|
|
59
|
+
VALUES ($1, $2, $3, $4, $5::jsonb) ON CONFLICT (id) DO NOTHING RETURNING id`, [id, versionId, lastUpdated, deleted, content]);
|
|
60
|
+
if (rows.length === 0)
|
|
61
|
+
throw FhirError.duplicate(resourceType, id);
|
|
62
|
+
}
|
|
63
|
+
else {
|
|
64
|
+
await tx.query(`UPDATE ${t.current} SET version_id = $2, last_updated = $3, deleted = $4, content = $5::jsonb WHERE id = $1`, [id, versionId, lastUpdated, deleted, content]);
|
|
65
|
+
}
|
|
66
|
+
await tx.query(`INSERT INTO ${t.history} (id, version_id, last_updated, deleted, content) VALUES ($1, $2, $3, $4, $5::jsonb)`, [id, versionId, lastUpdated, deleted, content]);
|
|
67
|
+
// Search index rows are replaced in the same transaction, so a search never sees a stale index.
|
|
68
|
+
if (stamped && index)
|
|
69
|
+
await writeIndexRows(tx, t, id, index(stamped));
|
|
70
|
+
else if (!stamped)
|
|
71
|
+
await deleteIndexRows(tx, t, id);
|
|
72
|
+
return { versionId: String(versionId), lastUpdated, deleted, resource: stamped };
|
|
73
|
+
};
|
|
74
|
+
return {
|
|
75
|
+
async migrate(resourceTypes) {
|
|
76
|
+
const migrations = migrationsFor(schema, resourceTypes);
|
|
77
|
+
return database.transaction(async (tx) => {
|
|
78
|
+
// Serialize concurrent migrations (several app instances starting at once).
|
|
79
|
+
// The lock is released automatically at COMMIT or ROLLBACK.
|
|
80
|
+
await tx.query(`SELECT pg_advisory_xact_lock(hashtext($1))`, [`fhirforge:migrate:${schema}`]);
|
|
81
|
+
for (const stmt of bootstrapStatements(schema))
|
|
82
|
+
await tx.query(stmt);
|
|
83
|
+
const { rows } = await tx.query(`SELECT id FROM ${ident(schema)}."_migrations"`);
|
|
84
|
+
const done = new Set(rows.map((r) => r.id));
|
|
85
|
+
const applied = [];
|
|
86
|
+
for (const m of migrations) {
|
|
87
|
+
if (done.has(m.id))
|
|
88
|
+
continue;
|
|
89
|
+
for (const stmt of m.statements)
|
|
90
|
+
await tx.query(stmt);
|
|
91
|
+
await tx.query(`INSERT INTO ${ident(schema)}."_migrations" (id) VALUES ($1)`, [m.id]);
|
|
92
|
+
applied.push(m.id);
|
|
93
|
+
}
|
|
94
|
+
// New index tables are empty: existing resources of that type must be indexed.
|
|
95
|
+
const reindex = applied.filter(isIndexMigration).map((id) => id.split(':')[1]);
|
|
96
|
+
return reindex.length ? { applied, reindex } : { applied };
|
|
97
|
+
});
|
|
98
|
+
},
|
|
99
|
+
create(resource, opts = {}) {
|
|
100
|
+
return run(resource.resourceType, () => database.transaction((tx) => writeVersion(tx, resource.resourceType, resource.id, 1, resource, true, opts.index)));
|
|
101
|
+
},
|
|
102
|
+
update(resource, opts = {}) {
|
|
103
|
+
const { resourceType, id } = resource;
|
|
104
|
+
return run(resourceType, () => database.transaction(async (tx) => {
|
|
105
|
+
const current = await lockCurrent(tx, resourceType, id);
|
|
106
|
+
if (opts.ifMatch !== undefined && opts.ifMatch !== current?.v) {
|
|
107
|
+
throw FhirError.versionConflict(resourceType, id, opts.ifMatch, current?.v);
|
|
108
|
+
}
|
|
109
|
+
if (opts.ifNoneExist && current) {
|
|
110
|
+
throw FhirError.versionConflict(resourceType, id, 'none', current.v);
|
|
111
|
+
}
|
|
112
|
+
if (!current) {
|
|
113
|
+
return { version: await writeVersion(tx, resourceType, id, 1, resource, true, opts.index), created: true };
|
|
114
|
+
}
|
|
115
|
+
const version = await writeVersion(tx, resourceType, id, Number(current.v) + 1, resource, false, opts.index);
|
|
116
|
+
return { version, created: current.deleted };
|
|
117
|
+
}));
|
|
118
|
+
},
|
|
119
|
+
delete(resourceType, id, opts = {}) {
|
|
120
|
+
return run(resourceType, () => database.transaction(async (tx) => {
|
|
121
|
+
const current = await lockCurrent(tx, resourceType, id);
|
|
122
|
+
if (opts.ifMatch !== undefined && opts.ifMatch !== current?.v) {
|
|
123
|
+
throw FhirError.versionConflict(resourceType, id, opts.ifMatch, current?.v);
|
|
124
|
+
}
|
|
125
|
+
if (!current || current.deleted)
|
|
126
|
+
return undefined;
|
|
127
|
+
return writeVersion(tx, resourceType, id, Number(current.v) + 1, null, false, undefined);
|
|
128
|
+
}));
|
|
129
|
+
},
|
|
130
|
+
read(resourceType, id) {
|
|
131
|
+
const t = tablesFor(schema, resourceType);
|
|
132
|
+
return run(resourceType, async () => {
|
|
133
|
+
const { rows } = await database.query(`SELECT version_id::text AS v, last_updated, deleted, content FROM ${t.current} WHERE id = $1`, [id]);
|
|
134
|
+
return rows[0] ? toVersion(rows[0]) : undefined;
|
|
135
|
+
});
|
|
136
|
+
},
|
|
137
|
+
vread(resourceType, id, versionId) {
|
|
138
|
+
if (!/^[1-9]\d{0,17}$/.test(versionId))
|
|
139
|
+
return Promise.resolve(undefined);
|
|
140
|
+
const t = tablesFor(schema, resourceType);
|
|
141
|
+
return run(resourceType, async () => {
|
|
142
|
+
const { rows } = await database.query(`SELECT version_id::text AS v, last_updated, deleted, content FROM ${t.history} WHERE id = $1 AND version_id = $2`, [id, versionId]);
|
|
143
|
+
return rows[0] ? toVersion(rows[0]) : undefined;
|
|
144
|
+
});
|
|
145
|
+
},
|
|
146
|
+
history(resourceType, id) {
|
|
147
|
+
const t = tablesFor(schema, resourceType);
|
|
148
|
+
return run(resourceType, async () => {
|
|
149
|
+
const { rows } = await database.query(`SELECT version_id::text AS v, last_updated, deleted, content FROM ${t.history} WHERE id = $1 ORDER BY version_id DESC`, [id]);
|
|
150
|
+
return rows.map(toVersion);
|
|
151
|
+
});
|
|
152
|
+
},
|
|
153
|
+
search(query) {
|
|
154
|
+
const t = tablesFor(schema, query.resourceType);
|
|
155
|
+
return run(query.resourceType, async () => {
|
|
156
|
+
const { rows, total } = await runSearch(database, t, query);
|
|
157
|
+
return { versions: rows.map((r) => toVersion(r)), total };
|
|
158
|
+
});
|
|
159
|
+
},
|
|
160
|
+
reindex(resourceType, index) {
|
|
161
|
+
const t = tablesFor(schema, resourceType);
|
|
162
|
+
return run(resourceType, async () => {
|
|
163
|
+
let count = 0;
|
|
164
|
+
let after = '';
|
|
165
|
+
for (;;) {
|
|
166
|
+
const { rows } = await database.query(`SELECT id FROM ${t.current} WHERE NOT deleted AND id > $1 ORDER BY id LIMIT 500`, [after]);
|
|
167
|
+
if (rows.length === 0)
|
|
168
|
+
return count;
|
|
169
|
+
for (const { id } of rows) {
|
|
170
|
+
// One short transaction per resource, with the row locked, so concurrent writes are never overwritten.
|
|
171
|
+
await database.transaction(async (tx) => {
|
|
172
|
+
const { rows: locked } = await tx.query(`SELECT version_id::text AS v, last_updated, deleted, content FROM ${t.current} WHERE id = $1 FOR UPDATE`, [id]);
|
|
173
|
+
const v = locked[0] ? toVersion(locked[0]) : undefined;
|
|
174
|
+
if (v?.resource && !v.deleted) {
|
|
175
|
+
await writeIndexRows(tx, t, id, index(v.resource));
|
|
176
|
+
count++;
|
|
177
|
+
}
|
|
178
|
+
});
|
|
179
|
+
}
|
|
180
|
+
after = rows[rows.length - 1].id;
|
|
181
|
+
}
|
|
182
|
+
});
|
|
183
|
+
},
|
|
184
|
+
};
|
|
185
|
+
}
|
|
186
|
+
//# sourceMappingURL=storage.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"storage.js","sourceRoot":"","sources":["../src/storage.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,SAAS,EACT,SAAS,GAKV,MAAM,iBAAiB,CAAC;AACzB,OAAO,EAAE,UAAU,EAAE,cAAc,EAAkD,MAAM,eAAe,CAAC;AAC3G,OAAO,EAAE,mBAAmB,EAAE,gBAAgB,EAAE,aAAa,EAAE,MAAM,iBAAiB,CAAC;AACvF,OAAO,EAAE,eAAe,EAAE,SAAS,EAAE,cAAc,EAAE,MAAM,aAAa,CAAC;AACzE,OAAO,EAAE,eAAe,EAAE,KAAK,EAAE,SAAS,EAAE,MAAM,UAAU,CAAC;AAC7D,OAAO,EAAE,qBAAqB,EAAyB,MAAM,gBAAgB,CAAC;AAc9E;;;;;;;;;;GAUG;AACH,MAAM,UAAU,eAAe,CAAC,EAAyB,EAAE,OAAO,GAA2B,EAAE;IAC7F,wEAAwE;IACxE,IAAI,CAAC,UAAU,CAAC,EAAE,CAAC;QAAE,qBAAqB,CAAC,EAAE,EAAE,OAAO,CAAC,CAAC;IACxD,MAAM,QAAQ,GAAa,UAAU,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,cAAc,CAA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I,CAAC,IAAI,CAAC,MAAM,GAAG,CAAC,CAAE,CAAC,EAAE,CAAC;gBACpC,CAAC;YACH,CAAC,CAAC,CAAC;QACL,CAAC;KACF,CAAC;AACJ,CAAC"}
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* TLS enforcement for `pg` Pools. PHI must not cross a network unencrypted, so
|
|
3
|
+
* a Pool that points at a non-local host must be configured for TLS.
|
|
4
|
+
*
|
|
5
|
+
* Only the Pool's own configuration is checked (`ssl` option or `sslmode` /
|
|
6
|
+
* `ssl` in the connection string). A custom `Database` is the app's
|
|
7
|
+
* responsibility: fhirforge can't see how it connects.
|
|
8
|
+
*/
|
|
9
|
+
export interface TransportOptions {
|
|
10
|
+
/**
|
|
11
|
+
* Allow a non-TLS connection to a non-local host. For local development
|
|
12
|
+
* against a remote dev database only; never in production.
|
|
13
|
+
*/
|
|
14
|
+
allowInsecure?: boolean;
|
|
15
|
+
}
|
|
16
|
+
export interface TransportCheck {
|
|
17
|
+
host: string | undefined;
|
|
18
|
+
local: boolean;
|
|
19
|
+
tls: boolean;
|
|
20
|
+
}
|
|
21
|
+
export declare function inspectPoolTransport(pool: unknown): TransportCheck | undefined;
|
|
22
|
+
/** Throws unless the Pool uses TLS, connects locally, or `allowInsecure` is set. */
|
|
23
|
+
export declare function assertSecureTransport(pool: unknown, options?: TransportOptions): void;
|
|
24
|
+
//# sourceMappingURL=transport.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"transport.d.ts","sourceRoot":"","sources":["../src/transport.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAEH,MAAM,WAAW,gBAAgB;IAC/B;;;OAGG;IACH,aAAa,CAAC,EAAE,OAAO,CAAC;CACzB;AAiBD,MAAM,WAAW,cAAc;IAC7B,IAAI,EAAE,MAAM,GAAG,SAAS,CAAC;IACzB,KAAK,EAAE,OAAO,CAAC;IACf,GAAG,EAAE,OAAO,CAAC;CACd;AAED,wBAAgB,oBAAoB,CAAC,IAAI,EAAE,OAAO,GAAG,cAAc,GAAG,SAAS,CAuB9E;AAOD,oFAAoF;AACpF,wBAAgB,qBAAqB,CAAC,IAAI,EAAE,OAAO,EAAE,OAAO,GAAE,gBAAqB,GAAG,IAAI,CASzF"}
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* TLS enforcement for `pg` Pools. PHI must not cross a network unencrypted, so
|
|
3
|
+
* a Pool that points at a non-local host must be configured for TLS.
|
|
4
|
+
*
|
|
5
|
+
* Only the Pool's own configuration is checked (`ssl` option or `sslmode` /
|
|
6
|
+
* `ssl` in the connection string). A custom `Database` is the app's
|
|
7
|
+
* responsibility: fhirforge can't see how it connects.
|
|
8
|
+
*/
|
|
9
|
+
const LOCAL_HOSTS = new Set(['localhost', '127.0.0.1', '::1', '[::1]']);
|
|
10
|
+
/** sslmode values that guarantee TLS. `prefer`, `allow` and `disable` don't. */
|
|
11
|
+
const SECURE_SSLMODES = new Set(['require', 'verify-ca', 'verify-full']);
|
|
12
|
+
export function inspectPoolTransport(pool) {
|
|
13
|
+
const options = pool?.options;
|
|
14
|
+
if (!options || typeof options !== 'object')
|
|
15
|
+
return undefined;
|
|
16
|
+
let host = options.host;
|
|
17
|
+
let tls = isTlsOption(options.ssl);
|
|
18
|
+
if (options.connectionString) {
|
|
19
|
+
try {
|
|
20
|
+
const url = new URL(options.connectionString);
|
|
21
|
+
host ??= decodeURIComponent(url.hostname) || url.searchParams.get('host') || undefined;
|
|
22
|
+
const sslmode = url.searchParams.get('sslmode');
|
|
23
|
+
const ssl = url.searchParams.get('ssl');
|
|
24
|
+
if (sslmode && SECURE_SSLMODES.has(sslmode))
|
|
25
|
+
tls = true;
|
|
26
|
+
if (sslmode && !SECURE_SSLMODES.has(sslmode) && options.ssl === undefined)
|
|
27
|
+
tls = false;
|
|
28
|
+
if (ssl === 'true' || ssl === '1')
|
|
29
|
+
tls = true;
|
|
30
|
+
}
|
|
31
|
+
catch {
|
|
32
|
+
// Not a URL (e.g. key=value form): fall through with what the options say.
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
// libpq defaults: no host means a Unix socket (or PGHOST, which we can't see here).
|
|
36
|
+
host ??= globalThis.process?.env?.PGHOST;
|
|
37
|
+
const local = host === undefined || host === '' || host.startsWith('/') || LOCAL_HOSTS.has(host);
|
|
38
|
+
return { host, local, tls };
|
|
39
|
+
}
|
|
40
|
+
/** `ssl: true` or an ssl options object both mean the connection is encrypted. */
|
|
41
|
+
function isTlsOption(ssl) {
|
|
42
|
+
return ssl === true || (ssl !== null && typeof ssl === 'object');
|
|
43
|
+
}
|
|
44
|
+
/** Throws unless the Pool uses TLS, connects locally, or `allowInsecure` is set. */
|
|
45
|
+
export function assertSecureTransport(pool, options = {}) {
|
|
46
|
+
if (options.allowInsecure)
|
|
47
|
+
return;
|
|
48
|
+
const check = inspectPoolTransport(pool);
|
|
49
|
+
if (!check || check.local || check.tls)
|
|
50
|
+
return;
|
|
51
|
+
throw new Error(`fhirforge: refusing a non-TLS Postgres connection to ${check.host}. ` +
|
|
52
|
+
`PHI must be encrypted in transit: configure the Pool with \`ssl\` (or sslmode=require / verify-full). ` +
|
|
53
|
+
`For local development only, pass { allowInsecure: true }.`);
|
|
54
|
+
}
|
|
55
|
+
//# sourceMappingURL=transport.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"transport.js","sourceRoot":"","sources":["../src/transport.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAoBH,MAAM,WAAW,GAAG,IAAI,GAAG,CAAC,CAAC,WAAW,EAAE,WAAW,EAAE,KAAK,EAAE,OAAO,CAAC,CAAC,CAAC;AAExE,gFAAgF;AAChF,MAAM,eAAe,GAAG,IAAI,GAAG,CAAC,CAAC,SAAS,EAAE,WAAW,EAAE,aAAa,CAAC,CAAC,CAAC;AAQzE,MAAM,UAAU,oBAAoB,CAAC,IAAa;IAChD,MAAM,OAAO,GAAI,I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G,CAAC,IAAI,CAAC,CAAC;IACjG,OAAO,EAAE,IAAI,EAAE,KAAK,EAAE,GAAG,EAAE,CAAC;AAC9B,CAAC;AAED,kFAAkF;AAClF,SAAS,WAAW,CAAC,GAAY;IAC/B,OAAO,GAAG,KAAK,IAAI,IAAI,CAAC,GAAG,KAAK,IAAI,IAAI,OAAO,GAAG,KAAK,QAAQ,CAAC,CAAC;AACnE,CAAC;AAED,oFAAoF;AACpF,MAAM,UAAU,qBAAqB,CAAC,IAAa,EAAE,OAAO,GAAqB,EAAE;IACjF,IAAI,OAAO,CAAC,aAAa;QAAE,OAAO;IAClC,MAAM,KAAK,GAAG,oBAAoB,CAAC,IAAI,CAAC,CAAC;IACzC,IAAI,CAAC,KAAK,IAAI,KAAK,CAAC,KAAK,IAAI,KAAK,CAAC,GAAG;QAAE,OAAO;IAC/C,MAAM,IAAI,KAAK,CACb,wDAAwD,KAAK,CAAC,IAAI,IAAI;QACpE,wGAAwG;QACxG,2DAA2D,CAC9D,CAAC;AACJ,CAAC"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,52 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@fhirforge/pg",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
3
|
+
"version": "0.2.0",
|
|
4
|
+
"description": "Postgres storage for fhirforge: JSONB resources and history in their own schema, with migrations.",
|
|
5
|
+
"license": "Apache-2.0",
|
|
6
|
+
"author": "Scott Schlegel",
|
|
7
|
+
"repository": {
|
|
8
|
+
"type": "git",
|
|
9
|
+
"url": "git+https://github.com/schlegz/fhirforge.git",
|
|
10
|
+
"directory": "packages/pg"
|
|
11
|
+
},
|
|
12
|
+
"homepage": "https://github.com/schlegz/fhirforge#readme",
|
|
13
|
+
"bugs": {
|
|
14
|
+
"url": "https://github.com/schlegz/fhirforge/issues"
|
|
15
|
+
},
|
|
16
|
+
"keywords": [
|
|
17
|
+
"fhir",
|
|
18
|
+
"postgres",
|
|
19
|
+
"postgresql",
|
|
20
|
+
"healthcare",
|
|
21
|
+
"fhir-store"
|
|
22
|
+
],
|
|
23
|
+
"type": "module",
|
|
24
|
+
"main": "./dist/index.js",
|
|
25
|
+
"types": "./dist/index.d.ts",
|
|
26
|
+
"exports": {
|
|
27
|
+
".": {
|
|
28
|
+
"types": "./dist/index.d.ts",
|
|
29
|
+
"default": "./dist/index.js"
|
|
30
|
+
}
|
|
31
|
+
},
|
|
32
|
+
"files": [
|
|
33
|
+
"dist"
|
|
34
|
+
],
|
|
35
|
+
"engines": {
|
|
36
|
+
"node": ">=20"
|
|
37
|
+
},
|
|
38
|
+
"publishConfig": {
|
|
39
|
+
"access": "public"
|
|
40
|
+
},
|
|
41
|
+
"dependencies": {
|
|
42
|
+
"@fhirforge/core": "0.2.0"
|
|
43
|
+
},
|
|
44
|
+
"peerDependencies": {
|
|
45
|
+
"pg": ">=8"
|
|
46
|
+
},
|
|
47
|
+
"peerDependenciesMeta": {
|
|
48
|
+
"pg": {
|
|
49
|
+
"optional": true
|
|
50
|
+
}
|
|
51
|
+
}
|
|
6
52
|
}
|