@mikro-orm/sql-js 7.2.0-dev.22
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 +21 -0
- package/README.md +227 -0
- package/SqlJsConnection.d.ts +23 -0
- package/SqlJsConnection.js +82 -0
- package/SqlJsDatabase.d.ts +9 -0
- package/SqlJsDatabase.js +84 -0
- package/SqlJsDriver.d.ts +10 -0
- package/SqlJsDriver.js +13 -0
- package/SqlJsMikroORM.d.ts +20 -0
- package/SqlJsMikroORM.js +25 -0
- package/index.d.ts +9 -0
- package/index.js +6 -0
- package/package.json +62 -0
- package/typings.d.ts +41 -0
- package/typings.js +6 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2018 Martin Adámek
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
ADDED
|
@@ -0,0 +1,227 @@
|
|
|
1
|
+
<h1 align="center">
|
|
2
|
+
<a href="https://mikro-orm.io"><img src="https://raw.githubusercontent.com/mikro-orm/mikro-orm/master/docs/static/img/logo-readme.svg?sanitize=true" alt="MikroORM" /></a>
|
|
3
|
+
</h1>
|
|
4
|
+
|
|
5
|
+
TypeScript ORM for Node.js based on Data Mapper, [Unit of Work](https://mikro-orm.io/docs/unit-of-work/) and [Identity Map](https://mikro-orm.io/docs/identity-map/) patterns. Supports MongoDB, MySQL, MariaDB, PostgreSQL (including CockroachDB and PGlite), SQLite (including libSQL), MSSQL and Oracle databases.
|
|
6
|
+
|
|
7
|
+
> Heavily inspired by [Doctrine](https://www.doctrine-project.org/) and [Hibernate](https://hibernate.org/).
|
|
8
|
+
|
|
9
|
+
[](https://npmx.dev/package/@mikro-orm/core)
|
|
10
|
+
[](https://npmx.dev/package/@mikro-orm/core)
|
|
11
|
+
[](https://discord.gg/w8bjxFHS7X)
|
|
12
|
+
[](https://npmx.dev/package/@mikro-orm/core)
|
|
13
|
+
[](https://coveralls.io/r/mikro-orm/mikro-orm?branch=master)
|
|
14
|
+
[](https://github.com/mikro-orm/mikro-orm/actions?workflow=tests)
|
|
15
|
+
|
|
16
|
+
## Quick Start
|
|
17
|
+
|
|
18
|
+
Install a driver package for your database:
|
|
19
|
+
|
|
20
|
+
```sh
|
|
21
|
+
npm install @mikro-orm/postgresql # PostgreSQL
|
|
22
|
+
npm install @mikro-orm/pglite # PGlite (embedded PostgreSQL in WASM)
|
|
23
|
+
npm install @mikro-orm/mysql # MySQL
|
|
24
|
+
npm install @mikro-orm/mariadb # MariaDB
|
|
25
|
+
npm install @mikro-orm/sqlite # SQLite
|
|
26
|
+
npm install @mikro-orm/libsql # libSQL / Turso
|
|
27
|
+
npm install @mikro-orm/sql-js # sql.js (in-memory SQLite in WASM)
|
|
28
|
+
npm install @mikro-orm/mongodb # MongoDB
|
|
29
|
+
npm install @mikro-orm/mssql # MS SQL Server
|
|
30
|
+
npm install @mikro-orm/oracledb # Oracle
|
|
31
|
+
```
|
|
32
|
+
|
|
33
|
+
> If you use additional packages like `@mikro-orm/cli`, `@mikro-orm/migrations`, or `@mikro-orm/entity-generator`, install `@mikro-orm/core` explicitly as well. See the [quick start guide](https://mikro-orm.io/docs/quick-start) for details.
|
|
34
|
+
|
|
35
|
+
### Define Entities
|
|
36
|
+
|
|
37
|
+
The recommended way to define entities is using [`defineEntity`](https://mikro-orm.io/docs/define-entity) with `setClass`:
|
|
38
|
+
|
|
39
|
+
```typescript
|
|
40
|
+
import { defineEntity, p, MikroORM } from '@mikro-orm/postgresql';
|
|
41
|
+
|
|
42
|
+
const AuthorSchema = defineEntity({
|
|
43
|
+
name: 'Author',
|
|
44
|
+
properties: {
|
|
45
|
+
id: p.integer().primary(),
|
|
46
|
+
name: p.string(),
|
|
47
|
+
email: p.string(),
|
|
48
|
+
born: p.datetime().nullable(),
|
|
49
|
+
books: () => p.oneToMany(Book).mappedBy('author'),
|
|
50
|
+
},
|
|
51
|
+
});
|
|
52
|
+
|
|
53
|
+
export class Author extends AuthorSchema.class {}
|
|
54
|
+
AuthorSchema.setClass(Author);
|
|
55
|
+
|
|
56
|
+
const BookSchema = defineEntity({
|
|
57
|
+
name: 'Book',
|
|
58
|
+
properties: {
|
|
59
|
+
id: p.integer().primary(),
|
|
60
|
+
title: p.string(),
|
|
61
|
+
author: () => p.manyToOne(Author).inversedBy('books'),
|
|
62
|
+
},
|
|
63
|
+
});
|
|
64
|
+
|
|
65
|
+
export class Book extends BookSchema.class {}
|
|
66
|
+
BookSchema.setClass(Book);
|
|
67
|
+
```
|
|
68
|
+
|
|
69
|
+
You can also define entities using [decorators](https://mikro-orm.io/docs/using-decorators) or [`EntitySchema`](https://mikro-orm.io/docs/define-entity#entityschema-low-level-api). See the [defining entities guide](https://mikro-orm.io/docs/defining-entities) for all options.
|
|
70
|
+
|
|
71
|
+
### Initialize and Use
|
|
72
|
+
|
|
73
|
+
```typescript
|
|
74
|
+
import { MikroORM, RequestContext } from '@mikro-orm/postgresql';
|
|
75
|
+
|
|
76
|
+
const orm = await MikroORM.init({
|
|
77
|
+
entities: [Author, Book],
|
|
78
|
+
dbName: 'my-db',
|
|
79
|
+
});
|
|
80
|
+
|
|
81
|
+
// Create new entities
|
|
82
|
+
const author = orm.em.create(Author, {
|
|
83
|
+
name: 'Jon Snow',
|
|
84
|
+
email: 'snow@wall.st',
|
|
85
|
+
});
|
|
86
|
+
const book = orm.em.create(Book, {
|
|
87
|
+
title: 'My Life on The Wall',
|
|
88
|
+
author,
|
|
89
|
+
});
|
|
90
|
+
|
|
91
|
+
// Flush persists all tracked changes in a single transaction
|
|
92
|
+
await orm.em.flush();
|
|
93
|
+
```
|
|
94
|
+
|
|
95
|
+
### Querying
|
|
96
|
+
|
|
97
|
+
```typescript
|
|
98
|
+
// Find with relations
|
|
99
|
+
const authors = await orm.em.findAll(Author, {
|
|
100
|
+
populate: ['books'],
|
|
101
|
+
orderBy: { name: 'asc' },
|
|
102
|
+
});
|
|
103
|
+
|
|
104
|
+
// Type-safe QueryBuilder
|
|
105
|
+
const qb = orm.em.createQueryBuilder(Author);
|
|
106
|
+
const result = await qb
|
|
107
|
+
.select('*')
|
|
108
|
+
.where({ books: { title: { $like: '%Wall%' } } })
|
|
109
|
+
.getResult();
|
|
110
|
+
```
|
|
111
|
+
|
|
112
|
+
### Request Context
|
|
113
|
+
|
|
114
|
+
In web applications, use `RequestContext` to isolate the identity map per request:
|
|
115
|
+
|
|
116
|
+
```typescript
|
|
117
|
+
const app = express();
|
|
118
|
+
|
|
119
|
+
app.use((req, res, next) => {
|
|
120
|
+
RequestContext.create(orm.em, next);
|
|
121
|
+
});
|
|
122
|
+
```
|
|
123
|
+
|
|
124
|
+
More info about `RequestContext` is described [here](https://mikro-orm.io/docs/identity-map/#request-context).
|
|
125
|
+
|
|
126
|
+
## Unit of Work
|
|
127
|
+
|
|
128
|
+
> Unit of Work maintains a list of objects (_entities_) affected by a business transaction
|
|
129
|
+
> and coordinates the writing out of changes. [(Martin Fowler)](https://www.martinfowler.com/eaaCatalog/unitOfWork.html)
|
|
130
|
+
|
|
131
|
+
When you call `em.flush()`, all computed changes are queried inside a database transaction. This means you can control transaction boundaries simply by making changes to your entities and calling `flush()` when ready.
|
|
132
|
+
|
|
133
|
+
```typescript
|
|
134
|
+
const author = await em.findOneOrFail(Author, 1, {
|
|
135
|
+
populate: ['books'],
|
|
136
|
+
});
|
|
137
|
+
author.name = 'Jon Snow II';
|
|
138
|
+
author.books.getItems().forEach(book => book.title += ' (2nd ed.)');
|
|
139
|
+
author.books.add(orm.em.create(Book, { title: 'New Book', author }));
|
|
140
|
+
|
|
141
|
+
// Flush computes change sets and executes them in a single transaction
|
|
142
|
+
await em.flush();
|
|
143
|
+
```
|
|
144
|
+
|
|
145
|
+
The above flush will execute:
|
|
146
|
+
|
|
147
|
+
```sql
|
|
148
|
+
begin;
|
|
149
|
+
update "author" set "name" = 'Jon Snow II' where "id" = 1;
|
|
150
|
+
update "book"
|
|
151
|
+
set "title" = case
|
|
152
|
+
when ("id" = 1) then 'My Life on The Wall (2nd ed.)'
|
|
153
|
+
when ("id" = 2) then 'Another Book (2nd ed.)'
|
|
154
|
+
else "title" end
|
|
155
|
+
where "id" in (1, 2);
|
|
156
|
+
insert into "book" ("title", "author_id") values ('New Book', 1);
|
|
157
|
+
commit;
|
|
158
|
+
```
|
|
159
|
+
|
|
160
|
+
## Core Features
|
|
161
|
+
|
|
162
|
+
- [Clean and Simple Entity Definition](https://mikro-orm.io/docs/defining-entities) — decorators, `EntitySchema`, or `defineEntity`
|
|
163
|
+
- [Identity Map](https://mikro-orm.io/docs/identity-map) and [Unit of Work](https://mikro-orm.io/docs/unit-of-work) — automatic change tracking
|
|
164
|
+
- [Entity References](https://mikro-orm.io/docs/entity-references) and [Collections](https://mikro-orm.io/docs/collections)
|
|
165
|
+
- [QueryBuilder](https://mikro-orm.io/docs/query-builder) and [Kysely Integration](https://mikro-orm.io/docs/kysely)
|
|
166
|
+
- [Transactions](https://mikro-orm.io/docs/transactions) and [Cascading](https://mikro-orm.io/docs/cascading)
|
|
167
|
+
- [Populating Relations](https://mikro-orm.io/docs/populating-relations) and [Loading Strategies](https://mikro-orm.io/docs/loading-strategies)
|
|
168
|
+
- [Filters](https://mikro-orm.io/docs/filters) and [Lifecycle Hooks](https://mikro-orm.io/docs/events#hooks)
|
|
169
|
+
- [Schema Generator](https://mikro-orm.io/docs/schema-generator) and [Migrations](https://mikro-orm.io/docs/migrations)
|
|
170
|
+
- [Entity Generator](https://mikro-orm.io/docs/entity-generator) and [Seeding](https://mikro-orm.io/docs/seeding)
|
|
171
|
+
- [Embeddables](https://mikro-orm.io/docs/embeddables), [Custom Types](https://mikro-orm.io/docs/custom-types), and [Serialization](https://mikro-orm.io/docs/serializing)
|
|
172
|
+
- [Composite and Foreign Keys as Primary Key](https://mikro-orm.io/docs/composite-keys)
|
|
173
|
+
- [Entity Constructors](https://mikro-orm.io/docs/entity-constructors) and [Property Validation](https://mikro-orm.io/docs/property-validation)
|
|
174
|
+
- [Modelling Relationships](https://mikro-orm.io/docs/relationships) and [Vanilla JS Support](https://mikro-orm.io/docs/usage-with-js)
|
|
175
|
+
|
|
176
|
+
## Documentation
|
|
177
|
+
|
|
178
|
+
MikroORM documentation, included in this repo in the root directory, is built with [Docusaurus](https://docusaurus.io) and publicly hosted on GitHub Pages at https://mikro-orm.io.
|
|
179
|
+
|
|
180
|
+
There is also auto-generated [CHANGELOG.md](CHANGELOG.md) file based on commit messages (via `semantic-release`).
|
|
181
|
+
|
|
182
|
+
## Example Integrations
|
|
183
|
+
|
|
184
|
+
You can find example integrations for some popular frameworks in the [`mikro-orm-examples` repository](https://github.com/mikro-orm/mikro-orm-examples):
|
|
185
|
+
|
|
186
|
+
### TypeScript Examples
|
|
187
|
+
|
|
188
|
+
- [Express + MongoDB](https://github.com/mikro-orm/express-ts-example-app)
|
|
189
|
+
- [Nest + MySQL](https://github.com/mikro-orm/nestjs-example-app)
|
|
190
|
+
- [RealWorld example app (Nest + MySQL)](https://github.com/mikro-orm/nestjs-realworld-example-app)
|
|
191
|
+
- [Koa + SQLite](https://github.com/mikro-orm/koa-ts-example-app)
|
|
192
|
+
- [GraphQL + PostgreSQL](https://github.com/driescroons/mikro-orm-graphql-example)
|
|
193
|
+
- [Inversify + PostgreSQL](https://github.com/PodaruDragos/inversify-example-app)
|
|
194
|
+
- [NextJS + MySQL](https://github.com/jonahallibone/mikro-orm-nextjs)
|
|
195
|
+
- [Accounts.js REST and GraphQL authentication + SQLite](https://github.com/darkbasic/mikro-orm-accounts-example)
|
|
196
|
+
- [Nest + Shopify + PostgreSQL + GraphQL](https://github.com/Cloudshelf/Shopify_CSConnector)
|
|
197
|
+
- [Elysia.js + libSQL + Bun](https://github.com/mikro-orm/elysia-bun-example-app)
|
|
198
|
+
- [Electron.js + PostgreSQL](https://github.com/adnanlah/electron-mikro-orm-example-app)
|
|
199
|
+
|
|
200
|
+
### JavaScript Examples
|
|
201
|
+
|
|
202
|
+
- [Express + SQLite](https://github.com/mikro-orm/express-js-example-app)
|
|
203
|
+
|
|
204
|
+
## Contributing
|
|
205
|
+
|
|
206
|
+
Contributions, issues and feature requests are welcome. Please read [CONTRIBUTING.md](CONTRIBUTING.md) for details on the process for submitting pull requests to us.
|
|
207
|
+
|
|
208
|
+
## Authors
|
|
209
|
+
|
|
210
|
+
**Martin Adámek**
|
|
211
|
+
|
|
212
|
+
- Twitter: [@B4nan](https://twitter.com/B4nan)
|
|
213
|
+
- Github: [@b4nan](https://github.com/b4nan)
|
|
214
|
+
|
|
215
|
+
See also the list of contributors who [participated](https://github.com/mikro-orm/mikro-orm/contributors) in this project.
|
|
216
|
+
|
|
217
|
+
## Show Your Support
|
|
218
|
+
|
|
219
|
+
Please star this repository if this project helped you!
|
|
220
|
+
|
|
221
|
+
> If you'd like to support my open-source work, consider sponsoring me directly at [github.com/sponsors/b4nan](https://github.com/sponsors/b4nan).
|
|
222
|
+
|
|
223
|
+
## License
|
|
224
|
+
|
|
225
|
+
Copyright © 2018-present [Martin Adámek](https://github.com/b4nan).
|
|
226
|
+
|
|
227
|
+
This project is licensed under the MIT License - see the [LICENSE file](LICENSE) for details.
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import { BaseSqliteConnection, type Dictionary } from '@mikro-orm/sql';
|
|
2
|
+
import { type Dialect } from 'kysely';
|
|
3
|
+
import type { Routine, Transaction } from '@mikro-orm/core';
|
|
4
|
+
import type { SqlJsNativeDatabase } from './typings.js';
|
|
5
|
+
/** In-memory SQLite connection backed by sql.js (SQLite compiled to WebAssembly). */
|
|
6
|
+
export declare class SqlJsConnection extends BaseSqliteConnection {
|
|
7
|
+
#private;
|
|
8
|
+
connect(options?: {
|
|
9
|
+
skipOnConnect?: boolean;
|
|
10
|
+
}): Promise<void>;
|
|
11
|
+
createKyselyDialect(options: Dictionary): Dialect;
|
|
12
|
+
close(force?: boolean): Promise<void>;
|
|
13
|
+
/** @inheritDoc */
|
|
14
|
+
executeDump(dump: string): Promise<void>;
|
|
15
|
+
/**
|
|
16
|
+
* Returns the sql.js `Database` backing this connection, e.g. to persist it via `db.export()`.
|
|
17
|
+
* It is closed together with the ORM, so do not hold on to the returned handle across `orm.close()`.
|
|
18
|
+
*/
|
|
19
|
+
getNativeClient(): Promise<SqlJsNativeDatabase>;
|
|
20
|
+
/** SQLite has no procedures; functions bridge via `bodyJs` registered as a UDF. */
|
|
21
|
+
callRoutine<T>(routine: Routine, args?: Record<string, unknown>, ctx?: Transaction): Promise<T>;
|
|
22
|
+
private validateAttachSupport;
|
|
23
|
+
}
|
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
// the ambient declaration has to be pulled in explicitly, consumers compile our sources via the `exports` map
|
|
2
|
+
// eslint-disable-next-line typescript/triple-slash-reference
|
|
3
|
+
/// <reference path="./sql-js.d.ts" />
|
|
4
|
+
import { BaseSqliteConnection } from '@mikro-orm/sql';
|
|
5
|
+
import { SqliteDialect } from 'kysely';
|
|
6
|
+
import initSqlJs from 'sql.js';
|
|
7
|
+
import { SqlJsDatabase } from './SqlJsDatabase.js';
|
|
8
|
+
// the ambient `sql.js` declaration is intentionally loose, our own types describe what we actually use
|
|
9
|
+
const init = initSqlJs;
|
|
10
|
+
/** In-memory SQLite connection backed by sql.js (SQLite compiled to WebAssembly). */
|
|
11
|
+
export class SqlJsConnection extends BaseSqliteConnection {
|
|
12
|
+
#database;
|
|
13
|
+
// Routine name → registered `bodyJs` ref. Reference compare to detect HMR swaps and re-register.
|
|
14
|
+
#registeredRoutines = new Map();
|
|
15
|
+
async connect(options) {
|
|
16
|
+
this.validateAttachSupport();
|
|
17
|
+
await super.connect(options);
|
|
18
|
+
}
|
|
19
|
+
createKyselyDialect(options) {
|
|
20
|
+
const { sqlJs, data, ...config } = options;
|
|
21
|
+
return new SqliteDialect({
|
|
22
|
+
// sql.js loads its WASM module asynchronously, so the database can only be built inside the async factory
|
|
23
|
+
database: async () => {
|
|
24
|
+
const SQL = typeof sqlJs === 'function' ? await sqlJs() : (sqlJs ?? (await init(config)));
|
|
25
|
+
this.#database = new SQL.Database(data);
|
|
26
|
+
// fresh Database = fresh function table; clear cached registrations
|
|
27
|
+
this.#registeredRoutines.clear();
|
|
28
|
+
return new SqlJsDatabase(this.#database);
|
|
29
|
+
},
|
|
30
|
+
onCreateConnection: this.options.onCreateConnection ?? this.config.get('onCreateConnection'),
|
|
31
|
+
});
|
|
32
|
+
}
|
|
33
|
+
async close(force) {
|
|
34
|
+
await super.close(force);
|
|
35
|
+
// kysely already closed the sql.js database; drop it so a reconnect builds a new one
|
|
36
|
+
this.#database = undefined;
|
|
37
|
+
}
|
|
38
|
+
/** @inheritDoc */
|
|
39
|
+
async executeDump(dump) {
|
|
40
|
+
const db = await this.getNativeClient();
|
|
41
|
+
db.exec(dump);
|
|
42
|
+
}
|
|
43
|
+
/**
|
|
44
|
+
* Returns the sql.js `Database` backing this connection, e.g. to persist it via `db.export()`.
|
|
45
|
+
* It is closed together with the ORM, so do not hold on to the returned handle across `orm.close()`.
|
|
46
|
+
*/
|
|
47
|
+
async getNativeClient() {
|
|
48
|
+
await this.ensureConnection();
|
|
49
|
+
return this.requireNativeClient(this.#database);
|
|
50
|
+
}
|
|
51
|
+
/** SQLite has no procedures; functions bridge via `bodyJs` registered as a UDF. */
|
|
52
|
+
async callRoutine(routine, args = {}, ctx) {
|
|
53
|
+
if (routine.type === 'procedure') {
|
|
54
|
+
throw new Error(`Stored procedures are not supported on SQLite. Routine ${routine.name} cannot be invoked here — define a separate code path for SQLite or call it only against a server-side database.`);
|
|
55
|
+
}
|
|
56
|
+
if (!routine.bodyJs) {
|
|
57
|
+
throw new Error(`Function ${routine.name} cannot be invoked on SQLite without a 'bodyJs' fallback. Add a JS implementation to the Routine declaration to enable cross-DB testing.`);
|
|
58
|
+
}
|
|
59
|
+
const db = await this.getNativeClient();
|
|
60
|
+
const fn = routine.bodyJs;
|
|
61
|
+
// Re-register on reference mismatch (HMR or a re-bound closure); sql.js replaces silently.
|
|
62
|
+
if (this.#registeredRoutines.get(routine.name) !== fn) {
|
|
63
|
+
const udf = (...positional) => {
|
|
64
|
+
const named = {};
|
|
65
|
+
routine.params.forEach((p, i) => {
|
|
66
|
+
named[p.name] = positional[i];
|
|
67
|
+
});
|
|
68
|
+
return fn(named);
|
|
69
|
+
};
|
|
70
|
+
// sql.js derives the SQL arity from the callback's declared parameter count, which rest args report as 0
|
|
71
|
+
Object.defineProperty(udf, 'length', { value: routine.params.length });
|
|
72
|
+
db.create_function(routine.name, udf);
|
|
73
|
+
this.#registeredRoutines.set(routine.name, fn);
|
|
74
|
+
}
|
|
75
|
+
return this.callRoutineFunction(routine, args, ctx);
|
|
76
|
+
}
|
|
77
|
+
validateAttachSupport() {
|
|
78
|
+
if (this.config.get('attachDatabases')?.length) {
|
|
79
|
+
throw new Error('ATTACH DATABASE is not supported by the sql.js driver, as it has no filesystem access. Load the additional data into the single in-memory database instead.');
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import type { SqliteDatabase, SqliteStatement } from 'kysely';
|
|
2
|
+
import type { SqlJsNativeDatabase } from './typings.js';
|
|
3
|
+
/** Kysely compatible `SqliteDatabase` backed by an in-memory sql.js instance. */
|
|
4
|
+
export declare class SqlJsDatabase implements SqliteDatabase {
|
|
5
|
+
#private;
|
|
6
|
+
constructor(db: SqlJsNativeDatabase);
|
|
7
|
+
prepare(sql: string): SqliteStatement;
|
|
8
|
+
close(): void;
|
|
9
|
+
}
|
package/SqlJsDatabase.js
ADDED
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
/** sql.js has no bigint support and rejects `undefined`, so both need coercing first. */
|
|
2
|
+
function coerceParams(parameters) {
|
|
3
|
+
return parameters.map(value => {
|
|
4
|
+
if (typeof value === 'bigint') {
|
|
5
|
+
// values beyond the safe integer range go in as strings, INTEGER column affinity converts them back
|
|
6
|
+
return Number.isSafeInteger(Number(value)) ? Number(value) : value.toString();
|
|
7
|
+
}
|
|
8
|
+
return (value ?? null);
|
|
9
|
+
});
|
|
10
|
+
}
|
|
11
|
+
/** sql.js rejects unbindable values by throwing plain strings, which would leave the driver exception without a message. */
|
|
12
|
+
function toError(e) {
|
|
13
|
+
return typeof e === 'string' ? new Error(e) : e;
|
|
14
|
+
}
|
|
15
|
+
/** Wraps a sql.js statement in the better-sqlite3 shaped interface kysely expects. */
|
|
16
|
+
class SqlJsStatementAdapter {
|
|
17
|
+
#db;
|
|
18
|
+
#stmt;
|
|
19
|
+
constructor(db, sql) {
|
|
20
|
+
this.#db = db;
|
|
21
|
+
this.#stmt = db.prepare(sql);
|
|
22
|
+
// sql.js consumes only the first statement and drops the rest silently, so reject the input like better-sqlite3 does
|
|
23
|
+
const tail = sql
|
|
24
|
+
.slice(this.#stmt.getSQL().length)
|
|
25
|
+
.replace(/--[^\n]*|\/\*[\s\S]*?\*\//g, '')
|
|
26
|
+
.replaceAll(';', '');
|
|
27
|
+
if (tail.trim()) {
|
|
28
|
+
this.#stmt.free();
|
|
29
|
+
throw new Error('The supplied SQL string contains more than one statement');
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
/** Only statements producing a result set have columns, which is what `reader` means for kysely. */
|
|
33
|
+
get reader() {
|
|
34
|
+
return this.#stmt.getColumnNames().length > 0;
|
|
35
|
+
}
|
|
36
|
+
all(parameters) {
|
|
37
|
+
return [...this.iterate(parameters)];
|
|
38
|
+
}
|
|
39
|
+
*iterate(parameters) {
|
|
40
|
+
const stmt = this.#stmt;
|
|
41
|
+
try {
|
|
42
|
+
stmt.bind(coerceParams(parameters));
|
|
43
|
+
while (stmt.step()) {
|
|
44
|
+
yield stmt.getAsObject();
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
catch (e) {
|
|
48
|
+
throw toError(e);
|
|
49
|
+
}
|
|
50
|
+
finally {
|
|
51
|
+
stmt.free();
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
run(parameters) {
|
|
55
|
+
const stmt = this.#stmt;
|
|
56
|
+
try {
|
|
57
|
+
stmt.bind(coerceParams(parameters));
|
|
58
|
+
stmt.step();
|
|
59
|
+
}
|
|
60
|
+
catch (e) {
|
|
61
|
+
throw toError(e);
|
|
62
|
+
}
|
|
63
|
+
finally {
|
|
64
|
+
stmt.free();
|
|
65
|
+
}
|
|
66
|
+
// sql.js exposes neither of these on the statement, they are database level functions
|
|
67
|
+
const changes = this.#db.getRowsModified();
|
|
68
|
+
const lastInsertRowid = Number(this.#db.exec('select last_insert_rowid()')[0].values[0][0]);
|
|
69
|
+
return { changes, lastInsertRowid };
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
/** Kysely compatible `SqliteDatabase` backed by an in-memory sql.js instance. */
|
|
73
|
+
export class SqlJsDatabase {
|
|
74
|
+
#db;
|
|
75
|
+
constructor(db) {
|
|
76
|
+
this.#db = db;
|
|
77
|
+
}
|
|
78
|
+
prepare(sql) {
|
|
79
|
+
return new SqlJsStatementAdapter(this.#db, sql);
|
|
80
|
+
}
|
|
81
|
+
close() {
|
|
82
|
+
this.#db.close();
|
|
83
|
+
}
|
|
84
|
+
}
|
package/SqlJsDriver.d.ts
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import type { Configuration, Constructor } from '@mikro-orm/core';
|
|
2
|
+
import { AbstractSqlDriver } from '@mikro-orm/sql';
|
|
3
|
+
import { SqlJsConnection } from './SqlJsConnection.js';
|
|
4
|
+
import { SqlJsMikroORM } from './SqlJsMikroORM.js';
|
|
5
|
+
/** Database driver for in-memory SQLite via sql.js (WebAssembly). */
|
|
6
|
+
export declare class SqlJsDriver extends AbstractSqlDriver<SqlJsConnection> {
|
|
7
|
+
constructor(config: Configuration);
|
|
8
|
+
/** @inheritDoc */
|
|
9
|
+
getORMClass(): Constructor<SqlJsMikroORM>;
|
|
10
|
+
}
|
package/SqlJsDriver.js
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import { AbstractSqlDriver, SqlitePlatform } from '@mikro-orm/sql';
|
|
2
|
+
import { SqlJsConnection } from './SqlJsConnection.js';
|
|
3
|
+
import { SqlJsMikroORM } from './SqlJsMikroORM.js';
|
|
4
|
+
/** Database driver for in-memory SQLite via sql.js (WebAssembly). */
|
|
5
|
+
export class SqlJsDriver extends AbstractSqlDriver {
|
|
6
|
+
constructor(config) {
|
|
7
|
+
super(config, new SqlitePlatform(), SqlJsConnection, ['kysely', 'sql.js']);
|
|
8
|
+
}
|
|
9
|
+
/** @inheritDoc */
|
|
10
|
+
getORMClass() {
|
|
11
|
+
return SqlJsMikroORM;
|
|
12
|
+
}
|
|
13
|
+
}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import { type AnyEntity, type EntityClass, type EntitySchema, type MikroORM, type Options, type IDatabaseDriver, type EntityManager, type EntityManagerType } from '@mikro-orm/core';
|
|
2
|
+
import { SqlMikroORM, type SqlEntityManager } from '@mikro-orm/sql';
|
|
3
|
+
import { SqlJsDriver } from './SqlJsDriver.js';
|
|
4
|
+
/** Configuration options for the sql.js driver. */
|
|
5
|
+
export type SqlJsOptions<EM extends SqlEntityManager<SqlJsDriver> = SqlEntityManager<SqlJsDriver>, Entities extends readonly (string | EntityClass<AnyEntity> | EntitySchema)[] = (string | EntityClass<AnyEntity> | EntitySchema)[]> = Partial<Options<SqlJsDriver, EM, Entities>>;
|
|
6
|
+
/** Creates a type-safe configuration object for the sql.js driver. */
|
|
7
|
+
export declare function defineSqlJsConfig<EM extends SqlEntityManager<SqlJsDriver> = SqlEntityManager<SqlJsDriver>, Entities extends readonly (string | EntityClass<AnyEntity> | EntitySchema)[] = (string | EntityClass<AnyEntity> | EntitySchema)[]>(options: SqlJsOptions<EM, Entities>): SqlJsOptions<EM, Entities>;
|
|
8
|
+
/**
|
|
9
|
+
* @inheritDoc
|
|
10
|
+
*/
|
|
11
|
+
export declare class SqlJsMikroORM<EM extends SqlEntityManager<SqlJsDriver> = SqlEntityManager<SqlJsDriver>, Entities extends readonly (string | EntityClass<AnyEntity> | EntitySchema)[] = (string | EntityClass<AnyEntity> | EntitySchema)[]> extends SqlMikroORM<SqlJsDriver, EM, Entities> {
|
|
12
|
+
/**
|
|
13
|
+
* @inheritDoc
|
|
14
|
+
*/
|
|
15
|
+
static init<D extends IDatabaseDriver = SqlJsDriver, EM extends EntityManager<D> = D[typeof EntityManagerType] & EntityManager<D>, Entities extends readonly (string | EntityClass<AnyEntity> | EntitySchema)[] = (string | EntityClass<AnyEntity> | EntitySchema)[]>(options: Partial<Options<D, EM, Entities>>): Promise<MikroORM<D, EM, Entities>>;
|
|
16
|
+
/**
|
|
17
|
+
* @inheritDoc
|
|
18
|
+
*/
|
|
19
|
+
constructor(options: Partial<Options<SqlJsDriver, EM, Entities>>);
|
|
20
|
+
}
|
package/SqlJsMikroORM.js
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import { defineConfig, } from '@mikro-orm/core';
|
|
2
|
+
import { SqlMikroORM } from '@mikro-orm/sql';
|
|
3
|
+
import { SqlJsDriver } from './SqlJsDriver.js';
|
|
4
|
+
/** Creates a type-safe configuration object for the sql.js driver. */
|
|
5
|
+
export function defineSqlJsConfig(options) {
|
|
6
|
+
// sql.js is always in-memory; satisfy MikroORM's `dbName` validation without forcing every user to spell it out.
|
|
7
|
+
return defineConfig({ driver: SqlJsDriver, dbName: ':memory:', ...options });
|
|
8
|
+
}
|
|
9
|
+
/**
|
|
10
|
+
* @inheritDoc
|
|
11
|
+
*/
|
|
12
|
+
export class SqlJsMikroORM extends SqlMikroORM {
|
|
13
|
+
/**
|
|
14
|
+
* @inheritDoc
|
|
15
|
+
*/
|
|
16
|
+
static async init(options) {
|
|
17
|
+
return super.init(defineSqlJsConfig(options));
|
|
18
|
+
}
|
|
19
|
+
/**
|
|
20
|
+
* @inheritDoc
|
|
21
|
+
*/
|
|
22
|
+
constructor(options) {
|
|
23
|
+
super(defineSqlJsConfig(options));
|
|
24
|
+
}
|
|
25
|
+
}
|
package/index.d.ts
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
export * from '@mikro-orm/sql';
|
|
2
|
+
export * from './SqlJsConnection.js';
|
|
3
|
+
export * from './SqlJsDriver.js';
|
|
4
|
+
export type * from './typings.js';
|
|
5
|
+
export { SqlJsMikroORM as MikroORM, type SqlJsOptions as Options, defineSqlJsConfig as defineConfig, } from './SqlJsMikroORM.js';
|
|
6
|
+
import { type AbstractSqlDriver, SqlEntityManager } from '@mikro-orm/sql';
|
|
7
|
+
import type { SqlJsDriver } from './SqlJsDriver.js';
|
|
8
|
+
export type EntityManager<Driver extends AbstractSqlDriver = SqlJsDriver> = SqlEntityManager<Driver>;
|
|
9
|
+
export declare const EntityManager: typeof SqlEntityManager;
|
package/index.js
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
export * from '@mikro-orm/sql';
|
|
2
|
+
export * from './SqlJsConnection.js';
|
|
3
|
+
export * from './SqlJsDriver.js';
|
|
4
|
+
export { SqlJsMikroORM as MikroORM, defineSqlJsConfig as defineConfig, } from './SqlJsMikroORM.js';
|
|
5
|
+
import { SqlEntityManager } from '@mikro-orm/sql';
|
|
6
|
+
export const EntityManager = SqlEntityManager;
|
package/package.json
ADDED
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@mikro-orm/sql-js",
|
|
3
|
+
"version": "7.2.0-dev.22",
|
|
4
|
+
"description": "TypeScript ORM for Node.js based on Data Mapper, Unit of Work and Identity Map patterns. Supports MongoDB, MySQL, PostgreSQL and SQLite databases as well as usage with vanilla JavaScript.",
|
|
5
|
+
"keywords": [
|
|
6
|
+
"data-mapper",
|
|
7
|
+
"ddd",
|
|
8
|
+
"entity",
|
|
9
|
+
"identity-map",
|
|
10
|
+
"javascript",
|
|
11
|
+
"js",
|
|
12
|
+
"mariadb",
|
|
13
|
+
"mikro-orm",
|
|
14
|
+
"mongo",
|
|
15
|
+
"mongodb",
|
|
16
|
+
"mysql",
|
|
17
|
+
"orm",
|
|
18
|
+
"postgresql",
|
|
19
|
+
"sql.js",
|
|
20
|
+
"sqlite",
|
|
21
|
+
"sqlite3",
|
|
22
|
+
"ts",
|
|
23
|
+
"typescript",
|
|
24
|
+
"unit-of-work",
|
|
25
|
+
"wasm"
|
|
26
|
+
],
|
|
27
|
+
"homepage": "https://mikro-orm.io",
|
|
28
|
+
"bugs": {
|
|
29
|
+
"url": "https://github.com/mikro-orm/mikro-orm/issues"
|
|
30
|
+
},
|
|
31
|
+
"license": "MIT",
|
|
32
|
+
"author": "Martin Adámek",
|
|
33
|
+
"repository": {
|
|
34
|
+
"type": "git",
|
|
35
|
+
"url": "git+ssh://git@github.com/mikro-orm/mikro-orm.git"
|
|
36
|
+
},
|
|
37
|
+
"type": "module",
|
|
38
|
+
"exports": {
|
|
39
|
+
"./package.json": "./package.json",
|
|
40
|
+
".": "./index.js"
|
|
41
|
+
},
|
|
42
|
+
"publishConfig": {
|
|
43
|
+
"access": "public"
|
|
44
|
+
},
|
|
45
|
+
"scripts": {
|
|
46
|
+
"build": "yarn compile && yarn copy",
|
|
47
|
+
"clean": "yarn run -T rimraf ./dist ./tsconfig.build.tsbuildinfo",
|
|
48
|
+
"compile": "yarn run -T tsc -p tsconfig.build.json",
|
|
49
|
+
"copy": "node ../../scripts/copy.mjs"
|
|
50
|
+
},
|
|
51
|
+
"dependencies": {
|
|
52
|
+
"@mikro-orm/sql": "7.2.0-dev.22",
|
|
53
|
+
"kysely": "0.29.5",
|
|
54
|
+
"sql.js": "1.14.2"
|
|
55
|
+
},
|
|
56
|
+
"peerDependencies": {
|
|
57
|
+
"@mikro-orm/core": "7.2.0-dev.22"
|
|
58
|
+
},
|
|
59
|
+
"engines": {
|
|
60
|
+
"node": ">= 22.17.0"
|
|
61
|
+
}
|
|
62
|
+
}
|
package/typings.d.ts
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Minimal subset of the sql.js surface this driver relies on. Declared locally on purpose —
|
|
3
|
+
* `@types/sql.js` references `@types/emscripten`, which needs DOM globals and breaks every
|
|
4
|
+
* consumer compiling without `lib: dom` or `skipLibCheck`.
|
|
5
|
+
*/
|
|
6
|
+
/** Column value sql.js can bind and return natively. */
|
|
7
|
+
export type SqlValue = number | string | Uint8Array | null;
|
|
8
|
+
/** Prepared statement handle, as returned by `db.prepare()`. */
|
|
9
|
+
export interface SqlJsStatement {
|
|
10
|
+
bind(params?: SqlValue[]): boolean;
|
|
11
|
+
/** The single statement sql.js actually consumed from the string passed to `db.prepare()`. */
|
|
12
|
+
getSQL(): string;
|
|
13
|
+
step(): boolean;
|
|
14
|
+
getAsObject(): Record<string, SqlValue>;
|
|
15
|
+
getColumnNames(): string[];
|
|
16
|
+
free(): boolean;
|
|
17
|
+
}
|
|
18
|
+
/** The native sql.js `Database` instance backing a connection. */
|
|
19
|
+
export interface SqlJsNativeDatabase {
|
|
20
|
+
prepare(sql: string): SqlJsStatement;
|
|
21
|
+
exec(sql: string): {
|
|
22
|
+
columns: string[];
|
|
23
|
+
values: SqlValue[][];
|
|
24
|
+
}[];
|
|
25
|
+
create_function(name: string, fn: (...args: SqlValue[]) => SqlValue | undefined): void;
|
|
26
|
+
getRowsModified(): number;
|
|
27
|
+
export(): Uint8Array;
|
|
28
|
+
close(): void;
|
|
29
|
+
}
|
|
30
|
+
/** The module `initSqlJs()` resolves with. */
|
|
31
|
+
export interface SqlJsStatic {
|
|
32
|
+
Database: new (data?: ArrayLike<number> | null) => SqlJsNativeDatabase;
|
|
33
|
+
}
|
|
34
|
+
/** Options accepted by `initSqlJs()`; an open bag, as everything is forwarded to the emscripten module. */
|
|
35
|
+
export interface SqlJsConfig {
|
|
36
|
+
locateFile?(file: string, scriptDirectory: string): string;
|
|
37
|
+
wasmBinary?: ArrayBuffer | Uint8Array;
|
|
38
|
+
[key: string]: unknown;
|
|
39
|
+
}
|
|
40
|
+
/** Signature of the `sql.js` default export. */
|
|
41
|
+
export type InitSqlJs = (config?: SqlJsConfig) => Promise<SqlJsStatic>;
|
package/typings.js
ADDED