@sharadox/database-web-library 0.0.0-stage → 0.1.0-development.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/LICENCA.md +76 -0
- package/LICENSE.md +76 -0
- package/NOTICE.md +3 -0
- package/README.md +122 -2
- package/distribution/database/index.d.ts +15 -0
- package/distribution/database/index.d.ts.map +1 -0
- package/distribution/database/index.js +17 -0
- package/distribution/database/index.js.map +1 -0
- package/distribution/database-configuration/index.d.ts +10 -0
- package/distribution/database-configuration/index.d.ts.map +1 -0
- package/distribution/database-configuration/index.js +20 -0
- package/distribution/database-configuration/index.js.map +1 -0
- package/distribution/database-configuration/type.d.ts +6 -0
- package/distribution/database-configuration/type.d.ts.map +1 -0
- package/distribution/database-configuration/type.js +2 -0
- package/distribution/database-configuration/type.js.map +1 -0
- package/distribution/es-lint-plugin/index.d.ts +29 -0
- package/distribution/es-lint-plugin/index.d.ts.map +1 -0
- package/distribution/es-lint-plugin/index.js +56 -0
- package/distribution/es-lint-plugin/index.js.map +1 -0
- package/distribution/memory-database/index.d.ts +14 -0
- package/distribution/memory-database/index.d.ts.map +1 -0
- package/distribution/memory-database/index.js +20 -0
- package/distribution/memory-database/index.js.map +1 -0
- package/distribution/memory-database/type.d.ts +9 -0
- package/distribution/memory-database/type.d.ts.map +1 -0
- package/distribution/memory-database/type.js +2 -0
- package/distribution/memory-database/type.js.map +1 -0
- package/distribution/migration/index.d.ts +13 -0
- package/distribution/migration/index.d.ts.map +1 -0
- package/distribution/migration/index.js +50 -0
- package/distribution/migration/index.js.map +1 -0
- package/distribution/migration/type.d.ts +11 -0
- package/distribution/migration/type.d.ts.map +1 -0
- package/distribution/migration/type.js +2 -0
- package/distribution/migration/type.js.map +1 -0
- package/distribution/migration-error/index.d.ts +18 -0
- package/distribution/migration-error/index.d.ts.map +1 -0
- package/distribution/migration-error/index.js +20 -0
- package/distribution/migration-error/index.js.map +1 -0
- package/distribution/migration-error/type.d.ts +7 -0
- package/distribution/migration-error/type.d.ts.map +1 -0
- package/distribution/migration-error/type.js +2 -0
- package/distribution/migration-error/type.js.map +1 -0
- package/distribution/migration-file/index.d.ts +11 -0
- package/distribution/migration-file/index.d.ts.map +1 -0
- package/distribution/migration-file/index.js +32 -0
- package/distribution/migration-file/index.js.map +1 -0
- package/distribution/pglite-pool/index.d.ts +15 -0
- package/distribution/pglite-pool/index.d.ts.map +1 -0
- package/distribution/pglite-pool/index.js +44 -0
- package/distribution/pglite-pool/index.js.map +1 -0
- package/package.json +104 -4
package/LICENCA.md
ADDED
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
# Licença Sharadox de Código Aberto
|
|
2
|
+
|
|
3
|
+
Versão 0.1.0
|
|
4
|
+
|
|
5
|
+
O texto em língua portuguesa é o único texto original e vinculativo desta licença. A tradução para inglês (`LICENSE.md`) é meramente informativa; em caso de divergência prevalece o texto em português.
|
|
6
|
+
|
|
7
|
+
## 1. Definições
|
|
8
|
+
|
|
9
|
+
Para efeitos desta licença:
|
|
10
|
+
|
|
11
|
+
1. **«Obra»** — o programa de computador, a sua documentação e quaisquer outros conteúdos disponibilizados pelo Licenciante ao abrigo desta licença, em código-fonte ou em qualquer outra forma.
|
|
12
|
+
2. **«Licenciante»** — o titular dos direitos de autor identificado no aviso de direitos de autor que acompanha a Obra.
|
|
13
|
+
3. **«Licenciado»** — qualquer pessoa, singular ou coletiva, que exerça os direitos concedidos por esta licença.
|
|
14
|
+
4. **«Obra Derivada»** — qualquer obra baseada na Obra ou que a incorpore, total ou parcialmente, com ou sem modificações, incluindo traduções, adaptações e programas que a integrem.
|
|
15
|
+
5. **«Aviso»** — o aviso de direitos de autor do Licenciante e a indicação de que a Obra está licenciada ao abrigo desta licença, incluindo a respetiva versão.
|
|
16
|
+
|
|
17
|
+
## 2. Concessão de direitos
|
|
18
|
+
|
|
19
|
+
1. Nos termos desta licença, o Licenciante concede ao Licenciado uma licença mundial, gratuita, não exclusiva e por todo o prazo de proteção dos direitos de autor para:
|
|
20
|
+
1. utilizar a Obra para qualquer finalidade, incluindo finalidades comerciais;
|
|
21
|
+
2. reproduzir a Obra, total ou parcialmente, por qualquer meio e sob qualquer forma;
|
|
22
|
+
3. modificar, traduzir, adaptar e transformar a Obra e criar Obras Derivadas;
|
|
23
|
+
4. distribuir, publicar, comunicar ao público, colocar à disposição, vender e sublicenciar a Obra e as Obras Derivadas.
|
|
24
|
+
2. Na medida em que o Licenciante seja titular de patentes necessariamente infringidas pela Obra tal como por si disponibilizada, concede igualmente ao Licenciado, nos mesmos termos, uma licença para utilizar essas patentes no exercício dos direitos previstos no número anterior.
|
|
25
|
+
3. Esta licença não transmite a titularidade de quaisquer direitos, que permanecem do Licenciante.
|
|
26
|
+
|
|
27
|
+
## 3. Condições
|
|
28
|
+
|
|
29
|
+
O exercício dos direitos concedidos fica sujeito às seguintes condições:
|
|
30
|
+
|
|
31
|
+
1. Todas as cópias da Obra, ou de partes substanciais da mesma, e todas as Obras Derivadas distribuídas devem incluir o Aviso e uma cópia desta licença ou uma ligação estável para o seu texto.
|
|
32
|
+
2. Quem distribuir uma versão modificada da Obra deve indicar de forma visível que a mesma foi modificada, não podendo apresentá-la como versão original do Licenciante.
|
|
33
|
+
3. O Licenciado pode licenciar as suas próprias modificações ao abrigo de outros termos, desde que a parte da Obra que delas faça parte continue sujeita às condições desta licença.
|
|
34
|
+
|
|
35
|
+
## 4. Nomes e marcas
|
|
36
|
+
|
|
37
|
+
Esta licença não concede qualquer direito sobre o nome, as marcas, os logótipos ou outros sinais distintivos do Licenciante, incluindo a designação «Sharadox», salvo na medida estritamente necessária para cumprir o dever de incluir o Aviso. É proibido utilizá-los para promover ou sugerir o apoio do Licenciante a Obras Derivadas ou a quaisquer produtos ou serviços sem autorização prévia e escrita.
|
|
38
|
+
|
|
39
|
+
## 5. Exclusão de garantias
|
|
40
|
+
|
|
41
|
+
A Obra é disponibilizada «tal como está» e «conforme disponível», sem qualquer garantia, expressa ou tácita, incluindo, designadamente, garantias de comerciabilidade, de adequação a um fim específico, de ausência de erros ou de não violação de direitos de terceiros, na medida máxima permitida pela lei aplicável.
|
|
42
|
+
|
|
43
|
+
## 6. Limitação de responsabilidade
|
|
44
|
+
|
|
45
|
+
1. Na medida máxima permitida pela lei aplicável, o Licenciante não é responsável por quaisquer danos, diretos ou indiretos, incluindo lucros cessantes, perda de dados ou interrupção de atividade, resultantes da utilização ou da impossibilidade de utilização da Obra, ainda que tenha sido avisado da possibilidade da sua ocorrência.
|
|
46
|
+
2. Nada nesta licença exclui ou limita a responsabilidade do Licenciante nos casos em que tal exclusão ou limitação não seja permitida por lei, designadamente por atos praticados com dolo ou culpa grave, nos termos do artigo 809.º e do n.º 2 do artigo 800.º do Código Civil, nem afeta os direitos que a lei imperativamente reconheça aos consumidores.
|
|
47
|
+
|
|
48
|
+
## 7. Cessação
|
|
49
|
+
|
|
50
|
+
1. Os direitos concedidos por esta licença cessam automaticamente se o Licenciado violar qualquer das suas condições.
|
|
51
|
+
2. Os direitos são repostos se a violação for sanada no prazo de 30 dias a contar do momento em que o Licenciado dela tome conhecimento, salvo se o Licenciante tiver entretanto comunicado por escrito a sua oposição.
|
|
52
|
+
3. A cessação não afeta as licenças validamente concedidas pelo Licenciado a terceiros que cumpram esta licença.
|
|
53
|
+
|
|
54
|
+
## 8. Lei aplicável e foro
|
|
55
|
+
|
|
56
|
+
1. Esta licença rege-se pela lei portuguesa, designadamente pelo Código do Direito de Autor e dos Direitos Conexos, aprovado pelo Decreto-Lei n.º 63/85, de 14 de março, e pelo Decreto-Lei n.º 252/94, de 20 de outubro, relativo à proteção jurídica dos programas de computador.
|
|
57
|
+
2. Para a resolução de quaisquer litígios emergentes desta licença é competente o Tribunal Judicial da Comarca de Faro, sem prejuízo das normas imperativas de competência aplicáveis, nomeadamente as que protegem os consumidores.
|
|
58
|
+
|
|
59
|
+
## 9. Versões da licença
|
|
60
|
+
|
|
61
|
+
O Licenciante pode publicar novas versões desta licença, identificadas por um número de versão. A Obra fica sujeita à versão indicada no Aviso. O Licenciado pode, se o Aviso o permitir, optar por qualquer versão posterior.
|
|
62
|
+
|
|
63
|
+
## 10. Disposições finais
|
|
64
|
+
|
|
65
|
+
1. Se alguma disposição desta licença for considerada inválida ou ineficaz, as restantes mantêm-se em vigor, devendo a disposição afetada ser interpretada de forma a aproximar-se, tanto quanto possível, da intenção original.
|
|
66
|
+
2. A não exigência, em qualquer momento, do cumprimento de uma disposição desta licença não constitui renúncia ao direito de o exigir posteriormente.
|
|
67
|
+
|
|
68
|
+
## Como aplicar esta licença
|
|
69
|
+
|
|
70
|
+
Inclua na Obra um ficheiro `LICENCA.md` com este texto, a tradução `LICENSE.md` e o seguinte aviso, preenchendo o ano e o titular:
|
|
71
|
+
|
|
72
|
+
```
|
|
73
|
+
Direitos de autor © <ano> <titular>.
|
|
74
|
+
Licenciado ao abrigo da Licença Sharadox de Código Aberto, versão 0.1.0.
|
|
75
|
+
https://github.com/Sharadox/sharadox-open-source-license
|
|
76
|
+
```
|
package/LICENSE.md
ADDED
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
# Sharadox Open Source Licence
|
|
2
|
+
|
|
3
|
+
Version 0.1.0
|
|
4
|
+
|
|
5
|
+
This is an informative English translation. The Portuguese text (`LICENCA.md`) is the only original and binding text of this licence; if the two differ, the Portuguese text prevails.
|
|
6
|
+
|
|
7
|
+
## 1. Definitions
|
|
8
|
+
|
|
9
|
+
For the purposes of this licence:
|
|
10
|
+
|
|
11
|
+
1. **"Work"** — the computer program, its documentation and any other content made available by the Licensor under this licence, in source code or in any other form.
|
|
12
|
+
2. **"Licensor"** — the copyright holder identified in the copyright notice that accompanies the Work.
|
|
13
|
+
3. **"Licensee"** — any natural or legal person exercising the rights granted by this licence.
|
|
14
|
+
4. **"Derivative Work"** — any work based on or incorporating the Work, in whole or in part, with or without modifications, including translations, adaptations and programs that integrate it.
|
|
15
|
+
5. **"Notice"** — the Licensor's copyright notice and the statement that the Work is licensed under this licence, including its version.
|
|
16
|
+
|
|
17
|
+
## 2. Grant of rights
|
|
18
|
+
|
|
19
|
+
1. Under this licence, the Licensor grants the Licensee a worldwide, royalty-free, non-exclusive licence, for the whole term of copyright protection, to:
|
|
20
|
+
1. use the Work for any purpose, including commercial purposes;
|
|
21
|
+
2. reproduce the Work, in whole or in part, by any means and in any form;
|
|
22
|
+
3. modify, translate, adapt and transform the Work and create Derivative Works;
|
|
23
|
+
4. distribute, publish, communicate to the public, make available, sell and sublicense the Work and Derivative Works.
|
|
24
|
+
2. To the extent the Licensor holds patents necessarily infringed by the Work as made available by it, the Licensor also grants the Licensee, on the same terms, a licence to use those patents in exercising the rights in the previous paragraph.
|
|
25
|
+
3. This licence does not transfer ownership of any rights, which remain with the Licensor.
|
|
26
|
+
|
|
27
|
+
## 3. Conditions
|
|
28
|
+
|
|
29
|
+
The exercise of the rights granted is subject to the following conditions:
|
|
30
|
+
|
|
31
|
+
1. Every copy of the Work, or of substantial parts of it, and every distributed Derivative Work must include the Notice and a copy of this licence or a stable link to its text.
|
|
32
|
+
2. Anyone distributing a modified version of the Work must state visibly that it has been modified and may not present it as the Licensor's original version.
|
|
33
|
+
3. The Licensee may license their own modifications under other terms, provided the part of the Work included in them remains subject to the conditions of this licence.
|
|
34
|
+
|
|
35
|
+
## 4. Names and trademarks
|
|
36
|
+
|
|
37
|
+
This licence grants no rights to the Licensor's name, trademarks, logos or other distinctive signs, including the name "Sharadox", except as strictly necessary to comply with the duty to include the Notice. Using them to promote or suggest the Licensor's endorsement of Derivative Works or of any products or services without prior written permission is prohibited.
|
|
38
|
+
|
|
39
|
+
## 5. Disclaimer of warranties
|
|
40
|
+
|
|
41
|
+
The Work is provided "as is" and "as available", without any warranty, express or implied, including in particular warranties of merchantability, fitness for a particular purpose, absence of errors or non-infringement of third-party rights, to the maximum extent permitted by applicable law.
|
|
42
|
+
|
|
43
|
+
## 6. Limitation of liability
|
|
44
|
+
|
|
45
|
+
1. To the maximum extent permitted by applicable law, the Licensor is not liable for any damages, direct or indirect, including loss of profits, loss of data or business interruption, arising from the use of or inability to use the Work, even if advised of the possibility of such damages.
|
|
46
|
+
2. Nothing in this licence excludes or limits the Licensor's liability where such exclusion or limitation is not permitted by law, in particular for acts committed with intent or gross negligence, under article 809 and article 800(2) of the Portuguese Civil Code, nor does it affect rights that the law mandatorily grants to consumers.
|
|
47
|
+
|
|
48
|
+
## 7. Termination
|
|
49
|
+
|
|
50
|
+
1. The rights granted by this licence terminate automatically if the Licensee breaches any of its conditions.
|
|
51
|
+
2. The rights are reinstated if the breach is remedied within 30 days of the Licensee becoming aware of it, unless the Licensor has meanwhile objected in writing.
|
|
52
|
+
3. Termination does not affect licences validly granted by the Licensee to third parties who comply with this licence.
|
|
53
|
+
|
|
54
|
+
## 8. Governing law and jurisdiction
|
|
55
|
+
|
|
56
|
+
1. This licence is governed by Portuguese law, in particular the Code of Copyright and Related Rights, approved by Decree-Law no. 63/85 of 14 March, and Decree-Law no. 252/94 of 20 October on the legal protection of computer programs.
|
|
57
|
+
2. The Judicial Court of the District of Faro has jurisdiction over any dispute arising from this licence, without prejudice to applicable mandatory rules of jurisdiction, in particular those protecting consumers.
|
|
58
|
+
|
|
59
|
+
## 9. Licence versions
|
|
60
|
+
|
|
61
|
+
The Licensor may publish new versions of this licence, identified by a version number. The Work is subject to the version stated in the Notice. If the Notice allows it, the Licensee may choose any later version.
|
|
62
|
+
|
|
63
|
+
## 10. Final provisions
|
|
64
|
+
|
|
65
|
+
1. If any provision of this licence is held invalid or unenforceable, the remaining provisions stay in force, and the affected provision shall be interpreted as closely as possible to its original intent.
|
|
66
|
+
2. Failure to enforce any provision of this licence at any time does not waive the right to enforce it later.
|
|
67
|
+
|
|
68
|
+
## How to apply this licence
|
|
69
|
+
|
|
70
|
+
Include in the Work a `LICENCA.md` file with the Portuguese text, this translation as `LICENSE.md`, and the following notice, filling in the year and holder:
|
|
71
|
+
|
|
72
|
+
```
|
|
73
|
+
Direitos de autor © <ano> <titular>.
|
|
74
|
+
Licenciado ao abrigo da Licença Sharadox de Código Aberto, versão 0.1.0.
|
|
75
|
+
https://github.com/Sharadox/sharadox-open-source-license
|
|
76
|
+
```
|
package/NOTICE.md
ADDED
package/README.md
CHANGED
|
@@ -1,3 +1,123 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @sharadox/database-web-library
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Typed, injection-safe Postgres for web applications: [Kysely](https://kysely.dev) queries over a
|
|
4
|
+
[Neon](https://neon.tech) pool, forward-only SQL migrations, a Postgres in memory for tests, and a lint rule that keeps
|
|
5
|
+
values out of SQL text.
|
|
6
|
+
|
|
7
|
+
- **Typed:** queries are checked against the schema's TypeScript types.
|
|
8
|
+
- **No SQL injection by construction:** values always travel as bound parameters. The `no-raw-sql` ESLint rule
|
|
9
|
+
reports the few calls that could send unchecked text (`sql.raw`, `sql.lit`, `.unsafe()`, SQL built with `+` or
|
|
10
|
+
`${…}`).
|
|
11
|
+
- **Migrations:** plain `.sql` files, run forward only, all or none, behind a lock, refused when an applied one was
|
|
12
|
+
edited, removed or overtaken.
|
|
13
|
+
- **Tests without a server:** `createMemoryDatabase()` is a real Postgres 18 in memory (PGlite).
|
|
14
|
+
|
|
15
|
+
## Install
|
|
16
|
+
|
|
17
|
+
```sh
|
|
18
|
+
pnpm add @sharadox/database-web-library
|
|
19
|
+
pnpm add -D @electric-sql/pglite # for createMemoryDatabase in tests
|
|
20
|
+
```
|
|
21
|
+
|
|
22
|
+
## Configuration
|
|
23
|
+
|
|
24
|
+
| Variable | Meaning |
|
|
25
|
+
| -------------- | ------------------------------------------------------------------------------------------- |
|
|
26
|
+
| `DATABASE_URL` | `postgresql://…` address (set by Vercel's Neon integration). A secret: it holds a password. |
|
|
27
|
+
|
|
28
|
+
## API
|
|
29
|
+
|
|
30
|
+
Each export has its own entry point (`@sharadox/database-web-library/<name>`).
|
|
31
|
+
|
|
32
|
+
### `database`: `createDatabase<Schema>({ connectionString })` → `Kysely<Schema>`
|
|
33
|
+
|
|
34
|
+
The production database over a Neon pool. Nothing connects until the first query.
|
|
35
|
+
|
|
36
|
+
```ts
|
|
37
|
+
import { createDatabase } from "@sharadox/database-web-library/database";
|
|
38
|
+
import { readDatabaseConfiguration } from "@sharadox/database-web-library/database-configuration";
|
|
39
|
+
|
|
40
|
+
const database = createDatabase<Schema>(readDatabaseConfiguration());
|
|
41
|
+
const account = await database.selectFrom("account").selectAll().where("id", "=", id).executeTakeFirst();
|
|
42
|
+
```
|
|
43
|
+
|
|
44
|
+
### `database-configuration`: `readDatabaseConfiguration(environment = process.env)` → `{ connectionString }`
|
|
45
|
+
|
|
46
|
+
Reads `DATABASE_URL`, which must start with `postgres://` or `postgresql://`. The error names the variable, never its
|
|
47
|
+
value.
|
|
48
|
+
|
|
49
|
+
### `migration`: `migrate(database, migrations, { table = "schema_migration" })` → names applied
|
|
50
|
+
|
|
51
|
+
Applies, in order and in one transaction, the migrations not applied yet. Each is recorded with a SHA-256 of its
|
|
52
|
+
SQL. Throws `MigrationError` with one of these codes:
|
|
53
|
+
|
|
54
|
+
- `changed`: an applied migration was edited;
|
|
55
|
+
- `missing`: an applied migration was removed;
|
|
56
|
+
- `out-of-order`: a new migration is numbered before one already applied;
|
|
57
|
+
- `invalid-name`: the record table's name isn't plain.
|
|
58
|
+
|
|
59
|
+
### `migration-file`: `readMigrations(folder: URL | string)` → `Migration[]`
|
|
60
|
+
|
|
61
|
+
Reads `<four digits>-<kebab-case>.sql` files in number order and ignores other files. A badly named `.sql` file is
|
|
62
|
+
refused with `invalid-name`, a repeated number with `duplicate`.
|
|
63
|
+
|
|
64
|
+
```ts
|
|
65
|
+
import { migrate } from "@sharadox/database-web-library/migration";
|
|
66
|
+
import { readMigrations } from "@sharadox/database-web-library/migration-file";
|
|
67
|
+
|
|
68
|
+
await migrate(database, await readMigrations(new URL("../../migration/", import.meta.url)));
|
|
69
|
+
```
|
|
70
|
+
|
|
71
|
+
### `migration-error`: `MigrationError`
|
|
72
|
+
|
|
73
|
+
`{ name: "MigrationError", code, message }`, with `code` one of `invalid-name`, `duplicate`, `changed`, `missing` or
|
|
74
|
+
`out-of-order`.
|
|
75
|
+
|
|
76
|
+
### `memory-database`: `createMemoryDatabase<Schema>()` → `{ database, close }`
|
|
77
|
+
|
|
78
|
+
A fresh, empty Postgres 18 in memory, behind the same Kysely, for unit tests. It needs `@electric-sql/pglite`.
|
|
79
|
+
|
|
80
|
+
```ts
|
|
81
|
+
const { database, close } = await createMemoryDatabase<Schema>();
|
|
82
|
+
await migrate(database, await readMigrations(new URL("../migration/", import.meta.url)));
|
|
83
|
+
// … test …
|
|
84
|
+
await close();
|
|
85
|
+
```
|
|
86
|
+
|
|
87
|
+
### `pglite-pool`: `pglitePool(pglite)` → Kysely `PostgresPool`
|
|
88
|
+
|
|
89
|
+
The adapter `createMemoryDatabase` uses. It hands out one connection at a time, and a query without parameters may
|
|
90
|
+
hold several statements.
|
|
91
|
+
|
|
92
|
+
### `es-lint-plugin`: `databaseEsLintPlugin`, `noRawSql`
|
|
93
|
+
|
|
94
|
+
```js
|
|
95
|
+
// eslint.config.mjs
|
|
96
|
+
import { nodeConfiguration } from "@sharadox/es-lint-configuration-web-library/node";
|
|
97
|
+
import { databaseEsLintPlugin } from "@sharadox/database-web-library/es-lint-plugin";
|
|
98
|
+
|
|
99
|
+
export default [...nodeConfiguration(), ...databaseEsLintPlugin.configs.recommended];
|
|
100
|
+
```
|
|
101
|
+
|
|
102
|
+
Rule `@sharadox/database/no-raw-sql` reports:
|
|
103
|
+
|
|
104
|
+
- `sql.raw()`, `sql.lit()`, `CompiledQuery.raw()` and any `.unsafe()`;
|
|
105
|
+
- a `.query()` whose SQL is built with `+` or a template with `${…}`.
|
|
106
|
+
|
|
107
|
+
Kysely's tagged ``sql`…${value}…` `` is allowed: its values are parameters.
|
|
108
|
+
|
|
109
|
+
## Ids
|
|
110
|
+
|
|
111
|
+
Use UUIDv7 ids, in a `uuid` column guarded by a check:
|
|
112
|
+
|
|
113
|
+
```sql
|
|
114
|
+
create table account (
|
|
115
|
+
id uuid primary key default uuidv7() check (uuid_extract_version(id) = 7)
|
|
116
|
+
);
|
|
117
|
+
```
|
|
118
|
+
|
|
119
|
+
Generate them in code with `uuidVersion7` from `@sharadox/web-library` when the id is needed before the insert.
|
|
120
|
+
|
|
121
|
+
## License
|
|
122
|
+
|
|
123
|
+
Sharadox Open Source License 0.1.0 (see `LICENSE.md`).
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import { Kysely } from "kysely";
|
|
2
|
+
import type { DatabaseConfiguration } from "@sharadox/database-web-library/database-configuration/type";
|
|
3
|
+
/**
|
|
4
|
+
* The production database: Kysely, typed by the schema, over a Neon connection pool (Postgres over WebSockets, made
|
|
5
|
+
* for serverless functions). Nothing connects until the first query. Every value goes to Postgres as a bound
|
|
6
|
+
* parameter; see the `no-raw-sql` lint rule.
|
|
7
|
+
*
|
|
8
|
+
* @example
|
|
9
|
+
* import { createDatabase } from "@sharadox/database-web-library/database";
|
|
10
|
+
* import { readDatabaseConfiguration } from "@sharadox/database-web-library/database-configuration";
|
|
11
|
+
* const database = createDatabase<Schema>(readDatabaseConfiguration());
|
|
12
|
+
* const account = await database.selectFrom("account").selectAll().where("id", "=", id).executeTakeFirst();
|
|
13
|
+
*/
|
|
14
|
+
export declare function createDatabase<Schema>({ connectionString }: DatabaseConfiguration): Kysely<Schema>;
|
|
15
|
+
//# sourceMappingURL=index.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../source/database/index.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,MAAM,EAAmB,MAAM,QAAQ,CAAC;AACjD,OAAO,KAAK,EAAE,qBAAqB,EAAE,MAAM,4DAA4D,CAAC;AAExG;;;;;;;;;;GAUG;AACH,wBAAgB,cAAc,CAAC,MAAM,EAAE,EAAE,gBAAgB,EAAE,EAAE,qBAAqB,GAAG,MAAM,CAAC,MAAM,CAAC,CAElG"}
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import { Pool } from "@neondatabase/serverless";
|
|
2
|
+
import { Kysely, PostgresDialect } from "kysely";
|
|
3
|
+
/**
|
|
4
|
+
* The production database: Kysely, typed by the schema, over a Neon connection pool (Postgres over WebSockets, made
|
|
5
|
+
* for serverless functions). Nothing connects until the first query. Every value goes to Postgres as a bound
|
|
6
|
+
* parameter; see the `no-raw-sql` lint rule.
|
|
7
|
+
*
|
|
8
|
+
* @example
|
|
9
|
+
* import { createDatabase } from "@sharadox/database-web-library/database";
|
|
10
|
+
* import { readDatabaseConfiguration } from "@sharadox/database-web-library/database-configuration";
|
|
11
|
+
* const database = createDatabase<Schema>(readDatabaseConfiguration());
|
|
12
|
+
* const account = await database.selectFrom("account").selectAll().where("id", "=", id).executeTakeFirst();
|
|
13
|
+
*/
|
|
14
|
+
export function createDatabase({ connectionString }) {
|
|
15
|
+
return new Kysely({ dialect: new PostgresDialect({ pool: new Pool({ connectionString }) }) });
|
|
16
|
+
}
|
|
17
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../source/database/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,IAAI,EAAE,MAAM,0BAA0B,CAAC;AAChD,OAAO,EAAE,MAAM,EAAE,eAAe,EAAE,MAAM,QAAQ,CAAC;AAGjD;;;;;;;;;;GAUG;AACH,MAAM,UAAU,cAAc,CAAS,EAAE,gBAAgB,EAAyB;IAChF,OAAO,IAAI,MAAM,CAAS,EAAE,OAAO,EAAE,IAAI,eAAe,CAAC,EAAE,IAAI,EAAE,IAAI,IAAI,CAAC,EAAE,gBAAgB,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,CAAC;AACxG,CAAC"}
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import type { DatabaseConfiguration } from "@sharadox/database-web-library/database-configuration/type";
|
|
2
|
+
/**
|
|
3
|
+
* Reads the database's address from the environment (`DATABASE_URL`, as Vercel's Neon integration sets it). Throws a
|
|
4
|
+
* message naming the variable, never its value (it holds the password).
|
|
5
|
+
*
|
|
6
|
+
* @example
|
|
7
|
+
* const database = createDatabase<Schema>(readDatabaseConfiguration());
|
|
8
|
+
*/
|
|
9
|
+
export declare function readDatabaseConfiguration(environment?: Record<string, string | undefined>): DatabaseConfiguration;
|
|
10
|
+
//# sourceMappingURL=index.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../source/database-configuration/index.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,qBAAqB,EAAE,MAAM,4DAA4D,CAAC;AAQxG;;;;;;GAMG;AACH,wBAAgB,yBAAyB,CACvC,WAAW,GAAE,MAAM,CAAC,MAAM,EAAE,MAAM,GAAG,SAAS,CAAe,GAC5D,qBAAqB,CAIvB"}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import { z } from "zod";
|
|
2
|
+
const schema = z.object({
|
|
3
|
+
DATABASE_URL: z
|
|
4
|
+
.string({ error: "DATABASE_URL is missing" })
|
|
5
|
+
.regex(/^postgres(?:ql)?:\/\//, { error: "DATABASE_URL must be a postgres:// or postgresql:// address" }),
|
|
6
|
+
});
|
|
7
|
+
/**
|
|
8
|
+
* Reads the database's address from the environment (`DATABASE_URL`, as Vercel's Neon integration sets it). Throws a
|
|
9
|
+
* message naming the variable, never its value (it holds the password).
|
|
10
|
+
*
|
|
11
|
+
* @example
|
|
12
|
+
* const database = createDatabase<Schema>(readDatabaseConfiguration());
|
|
13
|
+
*/
|
|
14
|
+
export function readDatabaseConfiguration(environment = process.env) {
|
|
15
|
+
const result = schema.safeParse(environment);
|
|
16
|
+
if (!result.success)
|
|
17
|
+
throw new Error(result.error.issues.map(({ message }) => message).join("; "));
|
|
18
|
+
return { connectionString: result.data.DATABASE_URL };
|
|
19
|
+
}
|
|
20
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../source/database-configuration/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAGxB,MAAM,MAAM,GAAG,CAAC,CAAC,MAAM,CAAC;IACtB,YAAY,EAAE,CAAC;SACZ,MAAM,CAAC,EAAE,KAAK,EAAE,yBAAyB,EAAE,CAAC;SAC5C,KAAK,CAAC,uBAAuB,EAAE,EAAE,KAAK,EAAE,6DAA6D,EAAE,CAAC;CAC5G,CAAC,CAAC;AAEH;;;;;;GAMG;AACH,MAAM,UAAU,yBAAyB,CACvC,cAAkD,OAAO,CAAC,GAAG;IAE7D,MAAM,MAAM,GAAG,MAAM,CAAC,SAAS,CAAC,WAAW,CAAC,CAAC;IAC7C,IAAI,CAAC,MAAM,CAAC,OAAO;QAAE,MAAM,IAAI,KAAK,CAAC,MAAM,CAAC,KAAK,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,EAAE,OAAO,EAAE,EAAE,EAAE,CAAC,OAAO,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,CAAC;IACnG,OAAO,EAAE,gBAAgB,EAAE,MAAM,CAAC,IAAI,CAAC,YAAY,EAAE,CAAC;AACxD,CAAC"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"type.d.ts","sourceRoot":"","sources":["../../source/database-configuration/type.ts"],"names":[],"mappings":"AAAA,iCAAiC;AACjC,MAAM,WAAW,qBAAqB;IACpC,iGAAiG;IACjG,gBAAgB,EAAE,MAAM,CAAC;CAC1B"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"type.js","sourceRoot":"","sources":["../../source/database-configuration/type.ts"],"names":[],"mappings":""}
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import type { Linter, Rule } from "eslint";
|
|
2
|
+
/**
|
|
3
|
+
* ESLint rule `no-raw-sql`: values reach the database only as bound parameters, never inside the SQL text. Reports
|
|
4
|
+
* `sql.raw()`, `sql.lit()`, `CompiledQuery.raw()` and any `.unsafe()`, and a `.query()` whose SQL is built with `+`
|
|
5
|
+
* or a template with `${…}`. Kysely's tagged ``sql`…${value}…` `` stays allowed: its values are parameters. The rare
|
|
6
|
+
* reviewed exception (running a migration file) disables the rule on that line, with the reason.
|
|
7
|
+
*/
|
|
8
|
+
export declare const noRawSql: Rule.RuleModule;
|
|
9
|
+
/**
|
|
10
|
+
* The ESLint plugin of database-web-library, with `configs.recommended` turning `no-raw-sql` on.
|
|
11
|
+
*
|
|
12
|
+
* @example
|
|
13
|
+
* // eslint.config.mjs
|
|
14
|
+
* import { nodeConfiguration } from "@sharadox/es-lint-configuration-web-library/node";
|
|
15
|
+
* import { databaseEsLintPlugin } from "@sharadox/database-web-library/es-lint-plugin";
|
|
16
|
+
* export default [...nodeConfiguration(), ...databaseEsLintPlugin.configs.recommended];
|
|
17
|
+
*/
|
|
18
|
+
export declare const databaseEsLintPlugin: {
|
|
19
|
+
meta: {
|
|
20
|
+
name: string;
|
|
21
|
+
};
|
|
22
|
+
rules: {
|
|
23
|
+
"no-raw-sql": Rule.RuleModule;
|
|
24
|
+
};
|
|
25
|
+
configs: {
|
|
26
|
+
recommended: Linter.Config[];
|
|
27
|
+
};
|
|
28
|
+
};
|
|
29
|
+
//# sourceMappingURL=index.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../source/es-lint-plugin/index.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAU,MAAM,EAAE,IAAI,EAAE,MAAM,QAAQ,CAAC;AAanD;;;;;GAKG;AACH,eAAO,MAAM,QAAQ,EAAE,IAAI,CAAC,UAmB3B,CAAC;AAWF;;;;;;;;GAQG;AACH,eAAO,MAAM,oBAAoB;;;;;;;aAfhB;QAAE,WAAW,EAAE,MAAM,CAAC,MAAM,EAAE,CAAA;KAAE;CAeP,CAAC"}
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
/** Calls that send text to the database as SQL, unchecked: `sql.raw`, `sql.lit`, `CompiledQuery.raw`, `.unsafe`. */
|
|
2
|
+
const RAW = new Map([
|
|
3
|
+
["sql", new Set(["raw", "lit"])],
|
|
4
|
+
["CompiledQuery", new Set(["raw"])],
|
|
5
|
+
]);
|
|
6
|
+
/** Whether SQL text is put together from pieces at run time (a template with values, or `+`). */
|
|
7
|
+
const isBuilt = (node) => node?.type === "BinaryExpression" ||
|
|
8
|
+
(node?.type === "TemplateLiteral" && node.expressions.length > 0);
|
|
9
|
+
/**
|
|
10
|
+
* ESLint rule `no-raw-sql`: values reach the database only as bound parameters, never inside the SQL text. Reports
|
|
11
|
+
* `sql.raw()`, `sql.lit()`, `CompiledQuery.raw()` and any `.unsafe()`, and a `.query()` whose SQL is built with `+`
|
|
12
|
+
* or a template with `${…}`. Kysely's tagged ``sql`…${value}…` `` stays allowed: its values are parameters. The rare
|
|
13
|
+
* reviewed exception (running a migration file) disables the rule on that line, with the reason.
|
|
14
|
+
*/
|
|
15
|
+
export const noRawSql = {
|
|
16
|
+
meta: {
|
|
17
|
+
type: "problem",
|
|
18
|
+
docs: { description: "Send values to the database as parameters, never inside SQL text" },
|
|
19
|
+
messages: {
|
|
20
|
+
raw: "Raw SQL can carry injected text: build the query with Kysely, or ``sql`…${value}…` `` (values become parameters).",
|
|
21
|
+
built: "This SQL is put together from pieces at run time: pass the values as parameters ($1, $2…) instead.",
|
|
22
|
+
},
|
|
23
|
+
schema: [],
|
|
24
|
+
},
|
|
25
|
+
create: (context) => ({
|
|
26
|
+
CallExpression(node) {
|
|
27
|
+
if (node.callee.type !== "MemberExpression" || node.callee.property.type !== "Identifier")
|
|
28
|
+
return;
|
|
29
|
+
const method = node.callee.property.name;
|
|
30
|
+
const object = node.callee.object.type === "Identifier" ? node.callee.object.name : "";
|
|
31
|
+
if (method === "unsafe" || RAW.get(object)?.has(method))
|
|
32
|
+
context.report({ node, messageId: "raw" });
|
|
33
|
+
else if (method === "query" && isBuilt(node.arguments[0]))
|
|
34
|
+
context.report({ node, messageId: "built" });
|
|
35
|
+
},
|
|
36
|
+
}),
|
|
37
|
+
};
|
|
38
|
+
const plugin = {
|
|
39
|
+
meta: { name: "@sharadox/database-web-library/es-lint-plugin" },
|
|
40
|
+
rules: { "no-raw-sql": noRawSql },
|
|
41
|
+
configs: {},
|
|
42
|
+
};
|
|
43
|
+
plugin.configs.recommended = [
|
|
44
|
+
{ plugins: { "@sharadox/database": plugin }, rules: { "@sharadox/database/no-raw-sql": "error" } },
|
|
45
|
+
];
|
|
46
|
+
/**
|
|
47
|
+
* The ESLint plugin of database-web-library, with `configs.recommended` turning `no-raw-sql` on.
|
|
48
|
+
*
|
|
49
|
+
* @example
|
|
50
|
+
* // eslint.config.mjs
|
|
51
|
+
* import { nodeConfiguration } from "@sharadox/es-lint-configuration-web-library/node";
|
|
52
|
+
* import { databaseEsLintPlugin } from "@sharadox/database-web-library/es-lint-plugin";
|
|
53
|
+
* export default [...nodeConfiguration(), ...databaseEsLintPlugin.configs.recommended];
|
|
54
|
+
*/
|
|
55
|
+
export const databaseEsLintPlugin = plugin;
|
|
56
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../source/es-lint-plugin/index.ts"],"names":[],"mappings":"AAEA,oHAAoH;AACpH,MAAM,GAAG,GAAG,IAAI,GAAG,CAAC;IAClB,CAAC,KAAK,EAAE,IAAI,GAAG,CAAC,CAAC,KAAK,EAAE,KAAK,CAAC,CAAC,CAAC;IAChC,CAAC,eAAe,EAAE,IAAI,GAAG,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC;CACpC,CAAC,CAAC;AAEH,iGAAiG;AACjG,MAAM,OAAO,GAAG,CAAC,IAAkC,EAAW,EAAE,CAC9D,IAAI,EAAE,IAAI,KAAK,kBAAkB;IACjC,CAAC,IAAI,EAAE,IAAI,KAAK,iBAAiB,IAAK,IAAiD,CAAC,WAAW,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC;AAElH;;;;;GAKG;AACH,MAAM,CAAC,MAAM,QAAQ,GAAoB;IACvC,IAAI,EAAE;QACJ,IAAI,EAAE,SAAS;QACf,IAAI,EAAE,EAAE,WAAW,EAAE,kEAAkE,EAAE;QACzF,QAAQ,EAAE;YACR,GAAG,EAAE,mHAAmH;YACxH,KAAK,EAAE,oGAAoG;SAC5G;QACD,MAAM,EAAE,EAAE;KACX;IACD,MAAM,EAAE,CAAC,OAAO,EAAE,EAAE,CAAC,CAAC;QACpB,cAAc,CAAC,IAAI;YACjB,IAAI,IAAI,CAAC,MAAM,CAAC,IAAI,KAAK,kBAAkB,IAAI,IAAI,CAAC,MAAM,CAAC,QAAQ,CAAC,IAAI,KAAK,YAAY;gBAAE,OAAO;YAClG,MAAM,MAAM,GAAG,IAAI,CAAC,MAAM,CAAC,QAAQ,CAAC,IAAI,CAAC;YACzC,MAAM,MAAM,GAAG,IAAI,CAAC,MAAM,CAAC,MAAM,CAAC,IAAI,KAAK,YAAY,CAAC,CAAC,CAAC,IAAI,CAAC,MAAM,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,CAAC;YACvF,IAAI,MAAM,KAAK,QAAQ,IAAI,GAAG,CAAC,GAAG,CAAC,MAAM,CAAC,EAAE,GAAG,CAAC,MAAM,CAAC;gBAAE,OAAO,CAAC,MAAM,CAAC,EAAE,IAAI,EAAE,SAAS,EAAE,KAAK,EAAE,CAAC,CAAC;iBAC/F,IAAI,MAAM,KAAK,OAAO,IAAI,OAAO,CAAC,IAAI,CAAC,SAAS,CAAC,CAAC,CAAC,CAAC;gBAAE,OAAO,CAAC,MAAM,CAAC,EAAE,IAAI,EAAE,SAAS,EAAE,OAAO,EAAE,CAAC,CAAC;QAC1G,CAAC;KACF,CAAC;CACH,CAAC;AAEF,MAAM,MAAM,GAAG;IACb,IAAI,EAAE,EAAE,IAAI,EAAE,+CAA+C,EAAE;IAC/D,KAAK,EAAE,EAAE,YAAY,EAAE,QAAQ,EAAE;IACjC,OAAO,EAAE,EAAsC;CACxB,CAAC;AAC1B,MAAM,CAAC,OAAO,CAAC,WAAW,GAAG;IAC3B,EAAE,OAAO,EAAE,EAAE,oBAAoB,EAAE,MAAM,EAAE,EAAE,KAAK,EAAE,EAAE,+BAA+B,EAAE,OAAO,EAAE,EAAE;CACnG,CAAC;AAEF;;;;;;;;GAQG;AACH,MAAM,CAAC,MAAM,oBAAoB,GAAG,MAAM,CAAC"}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import type { MemoryDatabase } from "@sharadox/database-web-library/memory-database/type";
|
|
2
|
+
/**
|
|
3
|
+
* A fresh, empty Postgres 18 in memory (PGlite), behind the same Kysely as production: for unit tests of anything
|
|
4
|
+
* that uses a database, with no server, network or cost. Needs `@electric-sql/pglite` installed (a development
|
|
5
|
+
* dependency is enough).
|
|
6
|
+
*
|
|
7
|
+
* @example
|
|
8
|
+
* const { database, close } = await createMemoryDatabase<Schema>();
|
|
9
|
+
* await migrate(database, await readMigrations(new URL("../migration/", import.meta.url)));
|
|
10
|
+
* // … test …
|
|
11
|
+
* await close();
|
|
12
|
+
*/
|
|
13
|
+
export declare function createMemoryDatabase<Schema>(): Promise<MemoryDatabase<Schema>>;
|
|
14
|
+
//# sourceMappingURL=index.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../source/memory-database/index.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,qDAAqD,CAAC;AAE1F;;;;;;;;;;GAUG;AACH,wBAAsB,oBAAoB,CAAC,MAAM,KAAK,OAAO,CAAC,cAAc,CAAC,MAAM,CAAC,CAAC,CAIpF"}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import { PGlite } from "@electric-sql/pglite";
|
|
2
|
+
import { Kysely, PostgresDialect } from "kysely";
|
|
3
|
+
import { pglitePool } from "@sharadox/database-web-library/pglite-pool";
|
|
4
|
+
/**
|
|
5
|
+
* A fresh, empty Postgres 18 in memory (PGlite), behind the same Kysely as production: for unit tests of anything
|
|
6
|
+
* that uses a database, with no server, network or cost. Needs `@electric-sql/pglite` installed (a development
|
|
7
|
+
* dependency is enough).
|
|
8
|
+
*
|
|
9
|
+
* @example
|
|
10
|
+
* const { database, close } = await createMemoryDatabase<Schema>();
|
|
11
|
+
* await migrate(database, await readMigrations(new URL("../migration/", import.meta.url)));
|
|
12
|
+
* // … test …
|
|
13
|
+
* await close();
|
|
14
|
+
*/
|
|
15
|
+
export async function createMemoryDatabase() {
|
|
16
|
+
const pglite = await PGlite.create();
|
|
17
|
+
const database = new Kysely({ dialect: new PostgresDialect({ pool: pglitePool(pglite) }) });
|
|
18
|
+
return { database, close: () => database.destroy() };
|
|
19
|
+
}
|
|
20
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../source/memory-database/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,MAAM,sBAAsB,CAAC;AAC9C,OAAO,EAAE,MAAM,EAAE,eAAe,EAAE,MAAM,QAAQ,CAAC;AACjD,OAAO,EAAE,UAAU,EAAE,MAAM,4CAA4C,CAAC;AAGxE;;;;;;;;;;GAUG;AACH,MAAM,CAAC,KAAK,UAAU,oBAAoB;IACxC,MAAM,MAAM,GAAG,MAAM,MAAM,CAAC,MAAM,EAAE,CAAC;IACrC,MAAM,QAAQ,GAAG,IAAI,MAAM,CAAS,EAAE,OAAO,EAAE,IAAI,eAAe,CAAC,EAAE,IAAI,EAAE,UAAU,CAAC,MAAM,CAAC,EAAE,CAAC,EAAE,CAAC,CAAC;IACpG,OAAO,EAAE,QAAQ,EAAE,KAAK,EAAE,GAAG,EAAE,CAAC,QAAQ,CAAC,OAAO,EAAE,EAAE,CAAC;AACvD,CAAC"}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import type { Kysely } from "kysely";
|
|
2
|
+
/** A database in memory and the way to close it. */
|
|
3
|
+
export interface MemoryDatabase<Schema> {
|
|
4
|
+
/** Kysely, typed by the schema. */
|
|
5
|
+
database: Kysely<Schema>;
|
|
6
|
+
/** Closes the database; it is gone afterwards. */
|
|
7
|
+
close(): Promise<void>;
|
|
8
|
+
}
|
|
9
|
+
//# sourceMappingURL=type.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"type.d.ts","sourceRoot":"","sources":["../../source/memory-database/type.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,QAAQ,CAAC;AAErC,oDAAoD;AACpD,MAAM,WAAW,cAAc,CAAC,MAAM;IACpC,mCAAmC;IACnC,QAAQ,EAAE,MAAM,CAAC,MAAM,CAAC,CAAC;IACzB,kDAAkD;IAClD,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC,CAAC;CACxB"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"type.js","sourceRoot":"","sources":["../../source/memory-database/type.ts"],"names":[],"mappings":""}
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import { type Kysely } from "kysely";
|
|
2
|
+
import type { MigrateOptions, Migration } from "@sharadox/database-web-library/migration/type";
|
|
3
|
+
/**
|
|
4
|
+
* Brings a database up to date: applies, in order, the migrations it hasn't applied yet, all in one transaction (all
|
|
5
|
+
* or none) behind a lock (two deployments never migrate at once), and records each with a checksum of its SQL.
|
|
6
|
+
* Forward only: it refuses (`MigrationError`) when an applied migration was edited or removed, or a new one is
|
|
7
|
+
* numbered before one already applied. Returns the names it applied.
|
|
8
|
+
*
|
|
9
|
+
* @example
|
|
10
|
+
* const applied = await migrate(database, await readMigrations(new URL("../../migration/", import.meta.url)));
|
|
11
|
+
*/
|
|
12
|
+
export declare function migrate(database: Kysely<unknown>, migrations: Migration[], { table }?: MigrateOptions): Promise<string[]>;
|
|
13
|
+
//# sourceMappingURL=index.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../source/migration/index.ts"],"names":[],"mappings":"AACA,OAAO,EAAO,KAAK,MAAM,EAAE,MAAM,QAAQ,CAAC;AAE1C,OAAO,KAAK,EAAE,cAAc,EAAE,SAAS,EAAE,MAAM,+CAA+C,CAAC;AAO/F;;;;;;;;GAQG;AACH,wBAAsB,OAAO,CAC3B,QAAQ,EAAE,MAAM,CAAC,OAAO,CAAC,EACzB,UAAU,EAAE,SAAS,EAAE,EACvB,EAAE,KAA0B,EAAE,GAAE,cAAmB,GAClD,OAAO,CAAC,MAAM,EAAE,CAAC,CAqCnB"}
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
import { createHash } from "node:crypto";
|
|
2
|
+
import { sql } from "kysely";
|
|
3
|
+
import { MigrationError } from "@sharadox/database-web-library/migration-error";
|
|
4
|
+
/** A table name `migrate` accepts: plain lowercase, so it never needs quoting. */
|
|
5
|
+
const IDENTIFIER = /^[a-z_][a-z0-9_]{0,62}$/;
|
|
6
|
+
const checksum = (text) => createHash("sha256").update(text).digest("hex");
|
|
7
|
+
/**
|
|
8
|
+
* Brings a database up to date: applies, in order, the migrations it hasn't applied yet, all in one transaction (all
|
|
9
|
+
* or none) behind a lock (two deployments never migrate at once), and records each with a checksum of its SQL.
|
|
10
|
+
* Forward only: it refuses (`MigrationError`) when an applied migration was edited or removed, or a new one is
|
|
11
|
+
* numbered before one already applied. Returns the names it applied.
|
|
12
|
+
*
|
|
13
|
+
* @example
|
|
14
|
+
* const applied = await migrate(database, await readMigrations(new URL("../../migration/", import.meta.url)));
|
|
15
|
+
*/
|
|
16
|
+
export async function migrate(database, migrations, { table = "schema_migration" } = {}) {
|
|
17
|
+
if (!IDENTIFIER.test(table))
|
|
18
|
+
throw new MigrationError("invalid-name", `"${table}" is not a plain table name`);
|
|
19
|
+
const records = sql.table(table);
|
|
20
|
+
return database.transaction().execute(async (transaction) => {
|
|
21
|
+
await sql `select pg_advisory_xact_lock(hashtext(${table}))`.execute(transaction);
|
|
22
|
+
await sql `create table if not exists ${records} (
|
|
23
|
+
name text primary key,
|
|
24
|
+
checksum text not null,
|
|
25
|
+
applied_at timestamptz not null default now()
|
|
26
|
+
)`.execute(transaction);
|
|
27
|
+
const applied = (await sql `select name, checksum from ${records} order by name`.execute(transaction)).rows;
|
|
28
|
+
const known = new Map(migrations.map((migration) => [migration.name, migration]));
|
|
29
|
+
for (const record of applied) {
|
|
30
|
+
const migration = known.get(record.name);
|
|
31
|
+
if (!migration)
|
|
32
|
+
throw new MigrationError("missing", `${record.name} was applied but is no longer there`);
|
|
33
|
+
if (checksum(migration.sql) !== record.checksum)
|
|
34
|
+
throw new MigrationError("changed", `${record.name} was changed after it was applied`);
|
|
35
|
+
}
|
|
36
|
+
const done = new Set(applied.map(({ name }) => name));
|
|
37
|
+
const last = applied.at(-1)?.name ?? "";
|
|
38
|
+
const pending = migrations.filter(({ name }) => !done.has(name));
|
|
39
|
+
for (const migration of pending) {
|
|
40
|
+
if (migration.name < last)
|
|
41
|
+
throw new MigrationError("out-of-order", `${migration.name} is numbered before ${last}, already applied`);
|
|
42
|
+
// A migration file is SQL we wrote and reviewed, run as it is: the one place raw SQL is allowed.
|
|
43
|
+
// eslint-disable-next-line @sharadox/database/no-raw-sql
|
|
44
|
+
await sql.raw(migration.sql).execute(transaction);
|
|
45
|
+
await sql `insert into ${records} (name, checksum) values (${migration.name}, ${checksum(migration.sql)})`.execute(transaction);
|
|
46
|
+
}
|
|
47
|
+
return pending.map(({ name }) => name);
|
|
48
|
+
});
|
|
49
|
+
}
|
|
50
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../source/migration/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AACzC,OAAO,EAAE,GAAG,EAAe,MAAM,QAAQ,CAAC;AAC1C,OAAO,EAAE,cAAc,EAAE,MAAM,gDAAgD,CAAC;AAGhF,kFAAkF;AAClF,MAAM,UAAU,GAAG,yBAAyB,CAAC;AAE7C,MAAM,QAAQ,GAAG,CAAC,IAAY,EAAE,EAAE,CAAC,UAAU,CAAC,QAAQ,CAAC,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;AAEnF;;;;;;;;GAQG;AACH,MAAM,CAAC,KAAK,UAAU,OAAO,CAC3B,QAAyB,EACzB,UAAuB,EACvB,EAAE,KAAK,GAAG,kBAAkB,KAAqB,EAAE;IAEnD,IAAI,CAAC,UAAU,CAAC,IAAI,CAAC,KAAK,CAAC;QAAE,MAAM,IAAI,cAAc,CAAC,cAAc,EAAE,IAAI,KAAK,6BAA6B,CAAC,CAAC;IAC9G,MAAM,OAAO,GAAG,GAAG,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC;IACjC,OAAO,QAAQ,CAAC,WAAW,EAAE,CAAC,OAAO,CAAC,KAAK,EAAE,WAAW,EAAE,EAAE;QAC1D,MAAM,GAAG,CAAA,yCAAyC,KAAK,IAAI,CAAC,OAAO,CAAC,WAAW,CAAC,CAAC;QACjF,MAAM,GAAG,CAAA,8BAA8B,OAAO;;;;MAI5C,CAAC,OAAO,CAAC,WAAW,CAAC,CAAC;QACxB,MAAM,OAAO,GAAG,CACd,MAAM,GAAG,CAAoC,8BAA8B,OAAO,gBAAgB,CAAC,OAAO,CACxG,WAAW,CACZ,CACF,CAAC,IAAI,CAAC;QACP,MAAM,KAAK,GAAG,IAAI,GAAG,CAAC,UAAU,CAAC,GAAG,CAAC,CAAC,SAAS,EAAE,EAAE,CAAC,CAAC,SAAS,CAAC,IAAI,EAAE,SAAS,CAAC,CAAC,CAAC,CAAC;QAClF,KAAK,MAAM,MAAM,IAAI,OAAO,EAAE,CAAC;YAC7B,MAAM,SAAS,GAAG,KAAK,CAAC,GAAG,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC;YACzC,IAAI,CAAC,SAAS;gBAAE,MAAM,IAAI,cAAc,CAAC,SAAS,EAAE,GAAG,MAAM,CAAC,IAAI,qCAAqC,CAAC,CAAC;YACzG,IAAI,QAAQ,CAAC,SAAS,CAAC,GAAG,CAAC,KAAK,MAAM,CAAC,QAAQ;gBAC7C,MAAM,IAAI,cAAc,CAAC,SAAS,EAAE,GAAG,MAAM,CAAC,IAAI,mCAAmC,CAAC,CAAC;QAC3F,CAAC;QACD,MAAM,IAAI,GAAG,IAAI,GAAG,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC,EAAE,IAAI,EAAE,EAAE,EAAE,CAAC,IAAI,CAAC,CAAC,CAAC;QACtD,MAAM,IAAI,GAAG,OAAO,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC,EAAE,IAAI,IAAI,EAAE,CAAC;QACxC,MAAM,OAAO,GAAG,UAAU,CAAC,MAAM,CAAC,CAAC,EAAE,IAAI,EAAE,EAAE,EAAE,CAAC,CAAC,IAAI,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC,CAAC;QACjE,KAAK,MAAM,SAAS,IAAI,OAAO,EAAE,CAAC;YAChC,IAAI,SAAS,CAAC,IAAI,GAAG,IAAI;gBACvB,MAAM,IAAI,cAAc,CAAC,cAAc,EAAE,GAAG,SAAS,CAAC,IAAI,uBAAuB,IAAI,mBAAmB,CAAC,CAAC;YAC5G,iGAAiG;YACjG,yDAAyD;YACzD,MAAM,GAAG,CAAC,GAAG,CAAC,SAAS,CAAC,GAAG,CAAC,CAAC,OAAO,CAAC,WAAW,CAAC,CAAC;YAClD,MAAM,GAAG,CAAA,eAAe,OAAO,6BAA6B,SAAS,CAAC,IAAI,KAAK,QAAQ,CAAC,SAAS,CAAC,GAAG,CAAC,GAAG,CAAC,OAAO,CAC/G,WAAW,CACZ,CAAC;QACJ,CAAC;QACD,OAAO,OAAO,CAAC,GAAG,CAAC,CAAC,EAAE,IAAI,EAAE,EAAE,EAAE,CAAC,IAAI,CAAC,CAAC;IACzC,CAAC,CAAC,CAAC;AACL,CAAC"}
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
/** One forward-only change to the database: its name (`0001-account`) and its SQL, one or more statements. */
|
|
2
|
+
export interface Migration {
|
|
3
|
+
name: string;
|
|
4
|
+
sql: string;
|
|
5
|
+
}
|
|
6
|
+
/** Where `migrate` keeps its records. */
|
|
7
|
+
export interface MigrateOptions {
|
|
8
|
+
/** The table that remembers applied migrations (a plain lowercase identifier); `schema_migration` by default. */
|
|
9
|
+
table?: string;
|
|
10
|
+
}
|
|
11
|
+
//# sourceMappingURL=type.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"type.d.ts","sourceRoot":"","sources":["../../source/migration/type.ts"],"names":[],"mappings":"AAAA,8GAA8G;AAC9G,MAAM,WAAW,SAAS;IACxB,IAAI,EAAE,MAAM,CAAC;IACb,GAAG,EAAE,MAAM,CAAC;CACb;AAED,yCAAyC;AACzC,MAAM,WAAW,cAAc;IAC7B,iHAAiH;IACjH,KAAK,CAAC,EAAE,MAAM,CAAC;CAChB"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"type.js","sourceRoot":"","sources":["../../source/migration/type.ts"],"names":[],"mappings":""}
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import type { MigrationErrorCode } from "@sharadox/database-web-library/migration-error/type";
|
|
2
|
+
/**
|
|
3
|
+
* The one error migrations throw when they refuse to run, with a `code` to branch on.
|
|
4
|
+
*
|
|
5
|
+
* @example
|
|
6
|
+
* try {
|
|
7
|
+
* await migrate(database, migrations);
|
|
8
|
+
* } catch (error) {
|
|
9
|
+
* if (error instanceof MigrationError && error.code === "changed") console.error(error.message);
|
|
10
|
+
* }
|
|
11
|
+
*/
|
|
12
|
+
export declare class MigrationError extends Error {
|
|
13
|
+
readonly name = "MigrationError";
|
|
14
|
+
/** What went wrong. */
|
|
15
|
+
readonly code: MigrationErrorCode;
|
|
16
|
+
constructor(code: MigrationErrorCode, message: string);
|
|
17
|
+
}
|
|
18
|
+
//# sourceMappingURL=index.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../source/migration-error/index.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,qDAAqD,CAAC;AAE9F;;;;;;;;;GASG;AACH,qBAAa,cAAe,SAAQ,KAAK;IACvC,SAAkB,IAAI,oBAAoB;IAC1C,uBAAuB;IACvB,QAAQ,CAAC,IAAI,EAAE,kBAAkB,CAAC;gBAEtB,IAAI,EAAE,kBAAkB,EAAE,OAAO,EAAE,MAAM;CAItD"}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The one error migrations throw when they refuse to run, with a `code` to branch on.
|
|
3
|
+
*
|
|
4
|
+
* @example
|
|
5
|
+
* try {
|
|
6
|
+
* await migrate(database, migrations);
|
|
7
|
+
* } catch (error) {
|
|
8
|
+
* if (error instanceof MigrationError && error.code === "changed") console.error(error.message);
|
|
9
|
+
* }
|
|
10
|
+
*/
|
|
11
|
+
export class MigrationError extends Error {
|
|
12
|
+
name = "MigrationError";
|
|
13
|
+
/** What went wrong. */
|
|
14
|
+
code;
|
|
15
|
+
constructor(code, message) {
|
|
16
|
+
super(message);
|
|
17
|
+
this.code = code;
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../source/migration-error/index.ts"],"names":[],"mappings":"AAEA;;;;;;;;;GASG;AACH,MAAM,OAAO,cAAe,SAAQ,KAAK;IACrB,IAAI,GAAG,gBAAgB,CAAC;IAC1C,uBAAuB;IACd,IAAI,CAAqB;IAElC,YAAY,IAAwB,EAAE,OAAe;QACnD,KAAK,CAAC,OAAO,CAAC,CAAC;QACf,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC;IACnB,CAAC;CACF"}
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Why migrations were refused: a file name that isn't `<four digits>-<kebab-case>.sql` (`invalid-name`), two
|
|
3
|
+
* files with one number (`duplicate`), an applied migration edited (`changed`) or removed (`missing`), or a new one
|
|
4
|
+
* numbered before one already applied (`out-of-order`).
|
|
5
|
+
*/
|
|
6
|
+
export type MigrationErrorCode = "invalid-name" | "duplicate" | "changed" | "missing" | "out-of-order";
|
|
7
|
+
//# sourceMappingURL=type.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"type.d.ts","sourceRoot":"","sources":["../../source/migration-error/type.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AACH,MAAM,MAAM,kBAAkB,GAAG,cAAc,GAAG,WAAW,GAAG,SAAS,GAAG,SAAS,GAAG,cAAc,CAAC"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"type.js","sourceRoot":"","sources":["../../source/migration-error/type.ts"],"names":[],"mappings":""}
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import type { Migration } from "@sharadox/database-web-library/migration/type";
|
|
2
|
+
/**
|
|
3
|
+
* Reads a folder's migrations: every `.sql` file, named `<four digits>-<kebab-case>.sql`, in number order (other
|
|
4
|
+
* files are ignored). Throws `MigrationError` for a badly named `.sql` file or two files with one number.
|
|
5
|
+
*
|
|
6
|
+
* @example
|
|
7
|
+
* const migrations = await readMigrations(new URL("../../migration/", import.meta.url));
|
|
8
|
+
* // [{ name: "0001-account", sql: "create table account (…);" }, …]
|
|
9
|
+
*/
|
|
10
|
+
export declare function readMigrations(folder: URL | string): Promise<Migration[]>;
|
|
11
|
+
//# sourceMappingURL=index.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../source/migration-file/index.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,+CAA+C,CAAC;AAK/E;;;;;;;GAOG;AACH,wBAAsB,cAAc,CAAC,MAAM,EAAE,GAAG,GAAG,MAAM,GAAG,OAAO,CAAC,SAAS,EAAE,CAAC,CAc/E"}
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import { readdir, readFile } from "node:fs/promises";
|
|
2
|
+
import { join } from "node:path";
|
|
3
|
+
import { fileURLToPath } from "node:url";
|
|
4
|
+
import { MigrationError } from "@sharadox/database-web-library/migration-error";
|
|
5
|
+
/** `0001-account.sql`: four digits, a kebab-case name. */
|
|
6
|
+
const FILE_NAME = /^(\d{4})-[a-z0-9]+(?:-[a-z0-9]+)*\.sql$/;
|
|
7
|
+
/**
|
|
8
|
+
* Reads a folder's migrations: every `.sql` file, named `<four digits>-<kebab-case>.sql`, in number order (other
|
|
9
|
+
* files are ignored). Throws `MigrationError` for a badly named `.sql` file or two files with one number.
|
|
10
|
+
*
|
|
11
|
+
* @example
|
|
12
|
+
* const migrations = await readMigrations(new URL("../../migration/", import.meta.url));
|
|
13
|
+
* // [{ name: "0001-account", sql: "create table account (…);" }, …]
|
|
14
|
+
*/
|
|
15
|
+
export async function readMigrations(folder) {
|
|
16
|
+
const directory = typeof folder === "string" ? folder : fileURLToPath(folder);
|
|
17
|
+
const files = (await readdir(directory)).filter((file) => file.endsWith(".sql")).sort();
|
|
18
|
+
const numbers = new Set();
|
|
19
|
+
const migrations = [];
|
|
20
|
+
for (const file of files) {
|
|
21
|
+
const match = FILE_NAME.exec(file);
|
|
22
|
+
if (!match)
|
|
23
|
+
throw new MigrationError("invalid-name", `${file} must be named <four digits>-<kebab-case>.sql`);
|
|
24
|
+
const number = match[1];
|
|
25
|
+
if (numbers.has(number))
|
|
26
|
+
throw new MigrationError("duplicate", `two migrations are numbered ${number}`);
|
|
27
|
+
numbers.add(number);
|
|
28
|
+
migrations.push({ name: file.slice(0, -".sql".length), sql: await readFile(join(directory, file), "utf8") });
|
|
29
|
+
}
|
|
30
|
+
return migrations;
|
|
31
|
+
}
|
|
32
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../source/migration-file/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,QAAQ,EAAE,MAAM,kBAAkB,CAAC;AACrD,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AACjC,OAAO,EAAE,aAAa,EAAE,MAAM,UAAU,CAAC;AACzC,OAAO,EAAE,cAAc,EAAE,MAAM,gDAAgD,CAAC;AAGhF,0DAA0D;AAC1D,MAAM,SAAS,GAAG,yCAAyC,CAAC;AAE5D;;;;;;;GAOG;AACH,MAAM,CAAC,KAAK,UAAU,cAAc,CAAC,MAAoB;IACvD,MAAM,SAAS,GAAG,OAAO,MAAM,KAAK,QAAQ,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,aAAa,CAAC,MAAM,CAAC,CAAC;IAC9E,MAAM,KAAK,GAAG,CAAC,MAAM,OAAO,CAAC,SAAS,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,IAAI,CAAC,QAAQ,CAAC,MAAM,CAAC,CAAC,CAAC,IAAI,EAAE,CAAC;IACxF,MAAM,OAAO,GAAG,IAAI,GAAG,EAAU,CAAC;IAClC,MAAM,UAAU,GAAgB,EAAE,CAAC;IACnC,KAAK,MAAM,IAAI,IAAI,KAAK,EAAE,CAAC;QACzB,MAAM,KAAK,GAAG,SAAS,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;QACnC,IAAI,CAAC,KAAK;YAAE,MAAM,IAAI,cAAc,CAAC,cAAc,EAAE,GAAG,IAAI,+CAA+C,CAAC,CAAC;QAC7G,MAAM,MAAM,GAAG,KAAK,CAAC,CAAC,CAAE,CAAC;QACzB,IAAI,OAAO,CAAC,GAAG,CAAC,MAAM,CAAC;YAAE,MAAM,IAAI,cAAc,CAAC,WAAW,EAAE,+BAA+B,MAAM,EAAE,CAAC,CAAC;QACxG,OAAO,CAAC,GAAG,CAAC,MAAM,CAAC,CAAC;QACpB,UAAU,CAAC,IAAI,CAAC,EAAE,IAAI,EAAE,IAAI,CAAC,KAAK,CAAC,CAAC,EAAE,CAAC,MAAM,CAAC,MAAM,CAAC,EAAE,GAAG,EAAE,MAAM,QAAQ,CAAC,IAAI,CAAC,SAAS,EAAE,IAAI,CAAC,EAAE,MAAM,CAAC,EAAE,CAAC,CAAC;IAC/G,CAAC;IACD,OAAO,UAAU,CAAC;AACpB,CAAC"}
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import type { PGlite } from "@electric-sql/pglite";
|
|
2
|
+
import type { PostgresPool } from "kysely";
|
|
3
|
+
/**
|
|
4
|
+
* A Kysely `PostgresPool` over one PGlite database (Postgres compiled to WebAssembly, in the same process), for tests
|
|
5
|
+
* and local work without a server. PGlite has a single connection, so connections are handed out one at a time, in
|
|
6
|
+
* the order asked. A query without parameters may hold several statements, as with node-postgres (Postgres's simple
|
|
7
|
+
* protocol); the result is the last statement's.
|
|
8
|
+
*
|
|
9
|
+
* @example
|
|
10
|
+
* import { PGlite } from "@electric-sql/pglite";
|
|
11
|
+
* import { Kysely, PostgresDialect } from "kysely";
|
|
12
|
+
* const database = new Kysely<Schema>({ dialect: new PostgresDialect({ pool: pglitePool(new PGlite()) }) });
|
|
13
|
+
*/
|
|
14
|
+
export declare function pglitePool(pglite: PGlite): PostgresPool;
|
|
15
|
+
//# sourceMappingURL=index.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../source/pglite-pool/index.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,MAAM,EAAW,MAAM,sBAAsB,CAAC;AAC5D,OAAO,KAAK,EAAE,YAAY,EAA2C,MAAM,QAAQ,CAAC;AAapF;;;;;;;;;;GAUG;AACH,wBAAgB,UAAU,CAAC,MAAM,EAAE,MAAM,GAAG,YAAY,CAuBvD"}
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
/** The shape node-postgres gives a result, from PGlite's own. */
|
|
2
|
+
function asPostgresResult(result) {
|
|
3
|
+
return {
|
|
4
|
+
command: (result.command ?? "SELECT"),
|
|
5
|
+
rowCount: result.rowCount ?? result.rows.length,
|
|
6
|
+
rows: result.rows,
|
|
7
|
+
};
|
|
8
|
+
}
|
|
9
|
+
/**
|
|
10
|
+
* A Kysely `PostgresPool` over one PGlite database (Postgres compiled to WebAssembly, in the same process), for tests
|
|
11
|
+
* and local work without a server. PGlite has a single connection, so connections are handed out one at a time, in
|
|
12
|
+
* the order asked. A query without parameters may hold several statements, as with node-postgres (Postgres's simple
|
|
13
|
+
* protocol); the result is the last statement's.
|
|
14
|
+
*
|
|
15
|
+
* @example
|
|
16
|
+
* import { PGlite } from "@electric-sql/pglite";
|
|
17
|
+
* import { Kysely, PostgresDialect } from "kysely";
|
|
18
|
+
* const database = new Kysely<Schema>({ dialect: new PostgresDialect({ pool: pglitePool(new PGlite()) }) });
|
|
19
|
+
*/
|
|
20
|
+
export function pglitePool(pglite) {
|
|
21
|
+
let queue = Promise.resolve();
|
|
22
|
+
const client = (release) => ({
|
|
23
|
+
async query(sql, parameters) {
|
|
24
|
+
if (typeof sql !== "string")
|
|
25
|
+
throw new Error("pglitePool: streaming is not supported");
|
|
26
|
+
if (parameters && parameters.length > 0)
|
|
27
|
+
return asPostgresResult(await pglite.query(sql, [...parameters]));
|
|
28
|
+
const results = await pglite.exec(sql);
|
|
29
|
+
return asPostgresResult(results.at(-1));
|
|
30
|
+
},
|
|
31
|
+
release,
|
|
32
|
+
});
|
|
33
|
+
return {
|
|
34
|
+
connect() {
|
|
35
|
+
let release;
|
|
36
|
+
const released = new Promise((resolve) => (release = resolve));
|
|
37
|
+
const turn = queue.then(() => client(release));
|
|
38
|
+
queue = queue.then(() => released);
|
|
39
|
+
return turn;
|
|
40
|
+
},
|
|
41
|
+
end: () => pglite.close(),
|
|
42
|
+
};
|
|
43
|
+
}
|
|
44
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../source/pglite-pool/index.ts"],"names":[],"mappings":"AAKA,iEAAiE;AACjE,SAAS,gBAAgB,CAAI,MAA4D;IACvF,OAAO;QACL,OAAO,EAAE,CAAC,MAAM,CAAC,OAAO,IAAI,QAAQ,CAAY;QAChD,QAAQ,EAAE,MAAM,CAAC,QAAQ,IAAI,MAAM,CAAC,IAAI,CAAC,MAAM;QAC/C,IAAI,EAAE,MAAM,CAAC,IAAI;KAClB,CAAC;AACJ,CAAC;AAED;;;;;;;;;;GAUG;AACH,MAAM,UAAU,UAAU,CAAC,MAAc;IACvC,IAAI,KAAK,GAAkB,OAAO,CAAC,OAAO,EAAE,CAAC;IAC7C,MAAM,MAAM,GAAG,CAAC,OAAmB,EAAsB,EAAE,CACzD,CAAC;QACC,KAAK,CAAC,KAAK,CAAI,GAAY,EAAE,UAAmC;YAC9D,IAAI,OAAO,GAAG,KAAK,QAAQ;gBAAE,MAAM,IAAI,KAAK,CAAC,wCAAwC,CAAC,CAAC;YACvF,IAAI,UAAU,IAAI,UAAU,CAAC,MAAM,GAAG,CAAC;gBACrC,OAAO,gBAAgB,CAAI,MAAM,MAAM,CAAC,KAAK,CAAI,GAAG,EAAE,CAAC,GAAG,UAAU,CAAC,CAAC,CAAC,CAAC;YAC1E,MAAM,OAAO,GAAG,MAAM,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;YACvC,OAAO,gBAAgB,CAAI,OAAO,CAAC,EAAE,CAAC,CAAC,CAAC,CAAe,CAAC,CAAC;QAC3D,CAAC;QACD,OAAO;KACR,CAAuB,CAAC;IAC3B,OAAO;QACL,OAAO;YACL,IAAI,OAAoB,CAAC;YACzB,MAAM,QAAQ,GAAG,IAAI,OAAO,CAAO,CAAC,OAAO,EAAE,EAAE,CAAC,CAAC,OAAO,GAAG,OAAO,CAAC,CAAC,CAAC;YACrE,MAAM,IAAI,GAAG,KAAK,CAAC,IAAI,CAAC,GAAG,EAAE,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC,CAAC;YAC/C,KAAK,GAAG,KAAK,CAAC,IAAI,CAAC,GAAG,EAAE,CAAC,QAAQ,CAAC,CAAC;YACnC,OAAO,IAAI,CAAC;QACd,CAAC;QACD,GAAG,EAAE,GAAG,EAAE,CAAC,MAAM,CAAC,KAAK,EAAE;KAC1B,CAAC;AACJ,CAAC"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,106 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@sharadox/database-web-library",
|
|
3
|
-
"version": "0.0.0
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.1.0-development.0",
|
|
4
|
+
"description": "Typed, injection-safe Postgres for web applications: queries, migrations, backups and restore drills.",
|
|
5
|
+
"private": false,
|
|
6
|
+
"license": "SEE LICENSE IN LICENCA.md",
|
|
7
|
+
"author": "Sharadox <contact@sharadox.com>",
|
|
8
|
+
"type": "module",
|
|
9
|
+
"exports": {
|
|
10
|
+
"./*/type": {
|
|
11
|
+
"sharadox-source": "./source/*/type.ts",
|
|
12
|
+
"types": "./distribution/*/type.d.ts"
|
|
13
|
+
},
|
|
14
|
+
"./*": {
|
|
15
|
+
"sharadox-source": [
|
|
16
|
+
"./source/*/index.ts"
|
|
17
|
+
],
|
|
18
|
+
"types": "./distribution/*/index.d.ts",
|
|
19
|
+
"default": "./distribution/*/index.js"
|
|
20
|
+
}
|
|
21
|
+
},
|
|
22
|
+
"files": [
|
|
23
|
+
"distribution",
|
|
24
|
+
"LICENCA.md",
|
|
25
|
+
"LICENSE.md",
|
|
26
|
+
"NOTICE.md"
|
|
27
|
+
],
|
|
28
|
+
"sideEffects": false,
|
|
29
|
+
"engines": {
|
|
30
|
+
"node": ">=26"
|
|
31
|
+
},
|
|
32
|
+
"packageManager": "pnpm@10.34.9",
|
|
33
|
+
"publishConfig": {
|
|
34
|
+
"access": "public"
|
|
35
|
+
},
|
|
36
|
+
"scripts": {
|
|
37
|
+
"build": "library-build",
|
|
38
|
+
"lint": "eslint --max-warnings=0 .",
|
|
39
|
+
"format": "prettier --write .",
|
|
40
|
+
"format:check": "prettier --check .",
|
|
41
|
+
"type-check": "tsc --noEmit",
|
|
42
|
+
"test:unit": "vitest run --coverage",
|
|
43
|
+
"test:benchmark": "vitest bench --run --passWithNoTests",
|
|
44
|
+
"documentation": "typedoc",
|
|
45
|
+
"verify": "turbo run format:check lint type-check test:unit test:benchmark build",
|
|
46
|
+
"prepare": "turborepo-configuration library && (husky || true)"
|
|
47
|
+
},
|
|
48
|
+
"lint-staged": {
|
|
49
|
+
"*.{ts,js,mjs,cjs}": [
|
|
50
|
+
"prettier --write",
|
|
51
|
+
"eslint --fix --max-warnings=0"
|
|
52
|
+
],
|
|
53
|
+
"*.{json,md,yml,yaml}": "prettier --write"
|
|
54
|
+
},
|
|
55
|
+
"dependencies": {
|
|
56
|
+
"@neondatabase/serverless": "^1.2.0",
|
|
57
|
+
"@sharadox/web-library": "^0.11.1",
|
|
58
|
+
"kysely": "^0.28.19",
|
|
59
|
+
"zod": "^4.6.7"
|
|
60
|
+
},
|
|
61
|
+
"devDependencies": {
|
|
62
|
+
"@electric-sql/pglite": "0.5.16",
|
|
63
|
+
"@sharadox/es-lint-configuration-web-library": "^0.1.3",
|
|
64
|
+
"@sharadox/library-build-web-library": "^0.2.1",
|
|
65
|
+
"@sharadox/prettier-configuration-web-library": "^0.1.2",
|
|
66
|
+
"@sharadox/turborepo-configuration-web-library": "^0.1.4",
|
|
67
|
+
"@sharadox/type-script-configuration-web-library": "^0.2.3",
|
|
68
|
+
"@sharadox/vitest-configuration-web-library": "^0.2.1",
|
|
69
|
+
"@types/node": "^26.6.6",
|
|
70
|
+
"@vitest/coverage-v8": "^5.1.1",
|
|
71
|
+
"eslint": "9.39.5",
|
|
72
|
+
"happy-dom": "^21.0.4",
|
|
73
|
+
"husky": "^9.1.7",
|
|
74
|
+
"lint-staged": "^17.6.2",
|
|
75
|
+
"prettier": "^3.10.1",
|
|
76
|
+
"turbo": "^2.11.13",
|
|
77
|
+
"typedoc": "^0.28.20",
|
|
78
|
+
"typescript": "6.0.3",
|
|
79
|
+
"vitest": "^5.1.1"
|
|
80
|
+
},
|
|
81
|
+
"repository": {
|
|
82
|
+
"type": "git",
|
|
83
|
+
"url": "git+https://github.com/Sharadox/database-web-library.git"
|
|
84
|
+
},
|
|
85
|
+
"homepage": "https://github.com/Sharadox/database-web-library#readme",
|
|
86
|
+
"keywords": [
|
|
87
|
+
"postgres",
|
|
88
|
+
"kysely",
|
|
89
|
+
"neon",
|
|
90
|
+
"migrations",
|
|
91
|
+
"backup",
|
|
92
|
+
"type-safe"
|
|
93
|
+
],
|
|
94
|
+
"peerDependencies": {
|
|
95
|
+
"@electric-sql/pglite": "^0.5.16",
|
|
96
|
+
"eslint": ">=9"
|
|
97
|
+
},
|
|
98
|
+
"peerDependenciesMeta": {
|
|
99
|
+
"@electric-sql/pglite": {
|
|
100
|
+
"optional": true
|
|
101
|
+
},
|
|
102
|
+
"eslint": {
|
|
103
|
+
"optional": true
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
}
|