@ohos-ports/effect-sql-sqlite-node 0.53.0-beta.1

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 ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2023-present The Contributors
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,7 @@
1
+ # `@effect/sql-sqlite-node`
2
+
3
+ An `@effect/sql` implementation using the `better-sqlite3` library.
4
+
5
+ ## Documentation
6
+
7
+ - **API Reference**: [View the full documentation](https://effect-ts.github.io/effect/docs/sql-sqlite-node).
@@ -0,0 +1,6 @@
1
+ {
2
+ "sideEffects": [],
3
+ "main": "../dist/cjs/SqliteClient.js",
4
+ "module": "../dist/esm/SqliteClient.js",
5
+ "types": "../dist/dts/SqliteClient.d.ts"
6
+ }
@@ -0,0 +1,6 @@
1
+ {
2
+ "sideEffects": [],
3
+ "main": "../dist/cjs/SqliteMigrator.js",
4
+ "module": "../dist/esm/SqliteMigrator.js",
5
+ "types": "../dist/dts/SqliteMigrator.d.ts"
6
+ }
@@ -0,0 +1,171 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.make = exports.layerConfig = exports.layer = exports.TypeId = exports.SqliteClient = void 0;
7
+ var Reactivity = _interopRequireWildcard(require("@effect/experimental/Reactivity"));
8
+ var Client = _interopRequireWildcard(require("@effect/sql/SqlClient"));
9
+ var _SqlError = require("@effect/sql/SqlError");
10
+ var Statement = _interopRequireWildcard(require("@effect/sql/Statement"));
11
+ var _betterSqlite = _interopRequireDefault(require("better-sqlite3"));
12
+ var Cache = _interopRequireWildcard(require("effect/Cache"));
13
+ var Config = _interopRequireWildcard(require("effect/Config"));
14
+ var Context = _interopRequireWildcard(require("effect/Context"));
15
+ var Duration = _interopRequireWildcard(require("effect/Duration"));
16
+ var Effect = _interopRequireWildcard(require("effect/Effect"));
17
+ var _Function = require("effect/Function");
18
+ var Layer = _interopRequireWildcard(require("effect/Layer"));
19
+ var Scope = _interopRequireWildcard(require("effect/Scope"));
20
+ function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }
21
+ function _interopRequireWildcard(e, t) { if ("function" == typeof WeakMap) var r = new WeakMap(), n = new WeakMap(); return (_interopRequireWildcard = function (e, t) { if (!t && e && e.__esModule) return e; var o, i, f = { __proto__: null, default: e }; if (null === e || "object" != typeof e && "function" != typeof e) return f; if (o = t ? n : r) { if (o.has(e)) return o.get(e); o.set(e, f); } for (const t in e) "default" !== t && {}.hasOwnProperty.call(e, t) && ((i = (o = Object.defineProperty) && Object.getOwnPropertyDescriptor(e, t)) && (i.get || i.set) ? o(f, t, i) : f[t] = e[t]); return f; })(e, t); }
22
+ /**
23
+ * @since 1.0.0
24
+ */
25
+
26
+ const ATTR_DB_SYSTEM_NAME = "db.system.name";
27
+ /**
28
+ * @category type ids
29
+ * @since 1.0.0
30
+ */
31
+ const TypeId = exports.TypeId = /*#__PURE__*/Symbol.for("@effect/sql-sqlite-node/SqliteClient");
32
+ /**
33
+ * @category tags
34
+ * @since 1.0.0
35
+ */
36
+ const SqliteClient = exports.SqliteClient = /*#__PURE__*/Context.GenericTag("@effect/sql-sqlite-node/SqliteClient");
37
+ /**
38
+ * @category constructor
39
+ * @since 1.0.0
40
+ */
41
+ const make = options => Effect.gen(function* () {
42
+ const compiler = Statement.makeCompilerSqlite(options.transformQueryNames);
43
+ const transformRows = options.transformResultNames ? Statement.defaultTransforms(options.transformResultNames).array : undefined;
44
+ const makeConnection = Effect.gen(function* () {
45
+ const scope = yield* Effect.scope;
46
+ const db = new _betterSqlite.default(options.filename, {
47
+ readonly: options.readonly ?? false
48
+ });
49
+ yield* Scope.addFinalizer(scope, Effect.sync(() => db.close()));
50
+ if (options.disableWAL !== true) {
51
+ db.pragma("journal_mode = WAL");
52
+ }
53
+ const prepareCache = yield* Cache.make({
54
+ capacity: options.prepareCacheSize ?? 200,
55
+ timeToLive: options.prepareCacheTTL ?? Duration.minutes(10),
56
+ lookup: sql => Effect.try({
57
+ try: () => db.prepare(sql),
58
+ catch: cause => new _SqlError.SqlError({
59
+ cause,
60
+ message: "Failed to prepare statement "
61
+ })
62
+ })
63
+ });
64
+ const runStatement = (statement, params, raw) => Effect.withFiberRuntime(fiber => {
65
+ if (Context.get(fiber.currentContext, Client.SafeIntegers)) {
66
+ statement.safeIntegers(true);
67
+ }
68
+ try {
69
+ if (statement.reader) {
70
+ return Effect.succeed(statement.all(...params));
71
+ }
72
+ const result = statement.run(...params);
73
+ return Effect.succeed(raw ? result : []);
74
+ } catch (cause) {
75
+ return Effect.fail(new _SqlError.SqlError({
76
+ cause,
77
+ message: "Failed to execute statement"
78
+ }));
79
+ }
80
+ });
81
+ const run = (sql, params, raw = false) => Effect.flatMap(prepareCache.get(sql), s => runStatement(s, params, raw));
82
+ const runValues = (sql, params) => Effect.acquireUseRelease(prepareCache.get(sql), statement => Effect.try({
83
+ try: () => {
84
+ if (statement.reader) {
85
+ statement.raw(true);
86
+ return statement.all(...params);
87
+ }
88
+ statement.run(...params);
89
+ return [];
90
+ },
91
+ catch: cause => new _SqlError.SqlError({
92
+ cause,
93
+ message: "Failed to execute statement"
94
+ })
95
+ }), statement => Effect.sync(() => statement.reader && statement.raw(false)));
96
+ return (0, _Function.identity)({
97
+ execute(sql, params, transformRows) {
98
+ return transformRows ? Effect.map(run(sql, params), transformRows) : run(sql, params);
99
+ },
100
+ executeRaw(sql, params) {
101
+ return run(sql, params, true);
102
+ },
103
+ executeValues(sql, params) {
104
+ return runValues(sql, params);
105
+ },
106
+ executeUnprepared(sql, params, transformRows) {
107
+ const effect = runStatement(db.prepare(sql), params ?? [], false);
108
+ return transformRows ? Effect.map(effect, transformRows) : effect;
109
+ },
110
+ executeStream(_sql, _params) {
111
+ return Effect.dieMessage("executeStream not implemented");
112
+ },
113
+ export: Effect.try({
114
+ try: () => db.serialize(),
115
+ catch: cause => new _SqlError.SqlError({
116
+ cause,
117
+ message: "Failed to export database"
118
+ })
119
+ }),
120
+ backup(destination) {
121
+ return Effect.tryPromise({
122
+ try: () => db.backup(destination),
123
+ catch: cause => new _SqlError.SqlError({
124
+ cause,
125
+ message: "Failed to backup database"
126
+ })
127
+ });
128
+ },
129
+ loadExtension(path) {
130
+ return Effect.tap(Effect.try({
131
+ try: () => db.loadExtension(path),
132
+ catch: cause => new _SqlError.SqlError({
133
+ cause,
134
+ message: "Failed to load extension"
135
+ })
136
+ }), () => prepareCache.invalidateAll);
137
+ }
138
+ });
139
+ });
140
+ const semaphore = yield* Effect.makeSemaphore(1);
141
+ const connection = yield* makeConnection;
142
+ const acquirer = semaphore.withPermits(1)(Effect.succeed(connection));
143
+ const transactionAcquirer = Effect.uninterruptibleMask(restore => Effect.as(Effect.zipRight(restore(semaphore.take(1)), Effect.tap(Effect.scope, scope => Scope.addFinalizer(scope, semaphore.release(1)))), connection));
144
+ return Object.assign(yield* Client.make({
145
+ acquirer,
146
+ compiler,
147
+ transactionAcquirer,
148
+ spanAttributes: [...(options.spanAttributes ? Object.entries(options.spanAttributes) : []), [ATTR_DB_SYSTEM_NAME, "sqlite"]],
149
+ transformRows
150
+ }), {
151
+ [TypeId]: TypeId,
152
+ config: options,
153
+ export: Effect.flatMap(acquirer, _ => _.export),
154
+ backup: destination => Effect.flatMap(acquirer, _ => _.backup(destination)),
155
+ loadExtension: path => Effect.flatMap(acquirer, _ => _.loadExtension(path))
156
+ });
157
+ });
158
+ /**
159
+ * @category layers
160
+ * @since 1.0.0
161
+ */
162
+ exports.make = make;
163
+ const layerConfig = config => Layer.scopedContext(Config.unwrap(config).pipe(Effect.flatMap(make), Effect.map(client => Context.make(SqliteClient, client).pipe(Context.add(Client.SqlClient, client))))).pipe(Layer.provide(Reactivity.layer));
164
+ /**
165
+ * @category layers
166
+ * @since 1.0.0
167
+ */
168
+ exports.layerConfig = layerConfig;
169
+ const layer = config => Layer.scopedContext(Effect.map(make(config), client => Context.make(SqliteClient, client).pipe(Context.add(Client.SqlClient, client)))).pipe(Layer.provide(Reactivity.layer));
170
+ exports.layer = layer;
171
+ //# sourceMappingURL=SqliteClient.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"SqliteClient.js","names":["Reactivity","_interopRequireWildcard","require","Client","_SqlError","Statement","_betterSqlite","_interopRequireDefault","Cache","Config","Context","Duration","Effect","_Function","Layer","Scope","e","__esModule","default","t","WeakMap","r","n","o","i","f","__proto__","has","get","set","hasOwnProperty","call","Object","defineProperty","getOwnPropertyDescriptor","ATTR_DB_SYSTEM_NAME","TypeId","exports","Symbol","for","SqliteClient","GenericTag","make","options","gen","compiler","makeCompilerSqlite","transformQueryNames","transformRows","transformResultNames","defaultTransforms","array","undefined","makeConnection","scope","db","Sqlite","filename","readonly","addFinalizer","sync","close","disableWAL","pragma","prepareCache","capacity","prepareCacheSize","timeToLive","prepareCacheTTL","minutes","lookup","sql","try","prepare","catch","cause","SqlError","message","runStatement","statement","params","raw","withFiberRuntime","fiber","currentContext","SafeIntegers","safeIntegers","reader","succeed","all","result","run","fail","flatMap","s","runValues","acquireUseRelease","identity","execute","map","executeRaw","executeValues","executeUnprepared","effect","executeStream","_sql","_params","dieMessage","export","serialize","backup","destination","tryPromise","loadExtension","path","tap","invalidateAll","semaphore","makeSemaphore","connection","acquirer","withPermits","transactionAcquirer","uninterruptibleMask","restore","as","zipRight","take","release","assign","spanAttributes","entries","config","_","layerConfig","scopedContext","unwrap","pipe","client","add","SqlClient","provide","layer"],"sources":["../../src/SqliteClient.ts"],"sourcesContent":[null],"mappings":";;;;;;AAGA,IAAAA,UAAA,GAAAC,uBAAA,CAAAC,OAAA;AACA,IAAAC,MAAA,GAAAF,uBAAA,CAAAC,OAAA;AAEA,IAAAE,SAAA,GAAAF,OAAA;AACA,IAAAG,SAAA,GAAAJ,uBAAA,CAAAC,OAAA;AACA,IAAAI,aAAA,GAAAC,sBAAA,CAAAL,OAAA;AACA,IAAAM,KAAA,GAAAP,uBAAA,CAAAC,OAAA;AACA,IAAAO,MAAA,GAAAR,uBAAA,CAAAC,OAAA;AAEA,IAAAQ,OAAA,GAAAT,uBAAA,CAAAC,OAAA;AACA,IAAAS,QAAA,GAAAV,uBAAA,CAAAC,OAAA;AACA,IAAAU,MAAA,GAAAX,uBAAA,CAAAC,OAAA;AACA,IAAAW,SAAA,GAAAX,OAAA;AACA,IAAAY,KAAA,GAAAb,uBAAA,CAAAC,OAAA;AACA,IAAAa,KAAA,GAAAd,uBAAA,CAAAC,OAAA;AAAqC,SAAAK,uBAAAS,CAAA,WAAAA,CAAA,IAAAA,CAAA,CAAAC,UAAA,GAAAD,CAAA,KAAAE,OAAA,EAAAF,CAAA;AAAA,SAAAf,wBAAAe,CAAA,EAAAG,CAAA,6BAAAC,OAAA,MAAAC,CAAA,OAAAD,OAAA,IAAAE,CAAA,OAAAF,OAAA,YAAAnB,uBAAA,YAAAA,CAAAe,CAAA,EAAAG,CAAA,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,CAACiI,GAAG,CAACxI,MAAM,CAACyI,SAAS,EAAEF,MAAM,CAAC,CACtC,CACF,CACF,CACF,CAACD,IAAI,CAAC3H,KAAK,CAAC+H,OAAO,CAAC7I,UAAU,CAAC8I,KAAK,CAAC,CAAC;AAEzC;;;;AAAAzG,OAAA,CAAAiG,WAAA,GAAAA,WAAA;AAIO,MAAMQ,KAAK,GAChBV,MAA0B,IAE1BtH,KAAK,CAACyH,aAAa,CACjB3H,MAAM,CAACuF,GAAG,CAACzD,IAAI,CAAC0F,MAAM,CAAC,EAAGM,MAAM,IAC9BhI,OAAO,CAACgC,IAAI,CAACF,YAAY,EAAEkG,MAAM,CAAC,CAACD,IAAI,CACrC/H,OAAO,CAACiI,GAAG,CAACxI,MAAM,CAACyI,SAAS,EAAEF,MAAM,CAAC,CACtC,CAAC,CACL,CAACD,IAAI,CAAC3H,KAAK,CAAC+H,OAAO,CAAC7I,UAAU,CAAC8I,KAAK,CAAC,CAAC;AAAAzG,OAAA,CAAAyG,KAAA,GAAAA,KAAA","ignoreList":[]}
@@ -0,0 +1,95 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ var _exportNames = {
7
+ run: true,
8
+ layer: true
9
+ };
10
+ exports.run = exports.layer = void 0;
11
+ var Command = _interopRequireWildcard(require("@effect/platform/Command"));
12
+ var _FileSystem = require("@effect/platform/FileSystem");
13
+ var _Path = require("@effect/platform/Path");
14
+ var Migrator = _interopRequireWildcard(require("@effect/sql/Migrator"));
15
+ Object.keys(Migrator).forEach(function (key) {
16
+ if (key === "default" || key === "__esModule") return;
17
+ if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return;
18
+ if (key in exports && exports[key] === Migrator[key]) return;
19
+ Object.defineProperty(exports, key, {
20
+ enumerable: true,
21
+ get: function () {
22
+ return Migrator[key];
23
+ }
24
+ });
25
+ });
26
+ var Effect = _interopRequireWildcard(require("effect/Effect"));
27
+ var _Function = require("effect/Function");
28
+ var Layer = _interopRequireWildcard(require("effect/Layer"));
29
+ var _SqliteClient = require("./SqliteClient.js");
30
+ var _FileSystem2 = require("@effect/sql/Migrator/FileSystem");
31
+ Object.keys(_FileSystem2).forEach(function (key) {
32
+ if (key === "default" || key === "__esModule") return;
33
+ if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return;
34
+ if (key in exports && exports[key] === _FileSystem2[key]) return;
35
+ Object.defineProperty(exports, key, {
36
+ enumerable: true,
37
+ get: function () {
38
+ return _FileSystem2[key];
39
+ }
40
+ });
41
+ });
42
+ function _interopRequireWildcard(e, t) { if ("function" == typeof WeakMap) var r = new WeakMap(), n = new WeakMap(); return (_interopRequireWildcard = function (e, t) { if (!t && e && e.__esModule) return e; var o, i, f = { __proto__: null, default: e }; if (null === e || "object" != typeof e && "function" != typeof e) return f; if (o = t ? n : r) { if (o.has(e)) return o.get(e); o.set(e, f); } for (const t in e) "default" !== t && {}.hasOwnProperty.call(e, t) && ((i = (o = Object.defineProperty) && Object.getOwnPropertyDescriptor(e, t)) && (i.get || i.set) ? o(f, t, i) : f[t] = e[t]); return f; })(e, t); }
43
+ /**
44
+ * @since 1.0.0
45
+ */
46
+
47
+ /**
48
+ * @since 1.0.0
49
+ */
50
+
51
+ /**
52
+ * @since 1.0.0
53
+ */
54
+
55
+ /**
56
+ * @category constructor
57
+ * @since 1.0.0
58
+ */
59
+ const run = exports.run = /*#__PURE__*/Migrator.make({
60
+ dumpSchema(path, table) {
61
+ const dump = args => Effect.gen(function* () {
62
+ const sql = yield* _SqliteClient.SqliteClient;
63
+ const dump = yield* (0, _Function.pipe)(Command.make("sqlite3", sql.config.filename, ...args), Command.string);
64
+ return dump.replace(/^create table sqlite_sequence\(.*$/im, "").replace(/\n{2,}/gm, "\n\n").trim();
65
+ }).pipe(Effect.mapError(error => new Migrator.MigrationError({
66
+ reason: "failed",
67
+ message: error.message
68
+ })));
69
+ const dumpSchema = dump([".schema"]);
70
+ const dumpMigrations = dump(["--cmd", `.mode insert ${table}`, `select * from ${table}`]);
71
+ const dumpAll = Effect.map(Effect.all([dumpSchema, dumpMigrations], {
72
+ concurrency: 2
73
+ }), ([schema, migrations]) => schema + "\n\n" + migrations);
74
+ const dumpFile = file => Effect.gen(function* () {
75
+ const fs = yield* _FileSystem.FileSystem;
76
+ const path = yield* _Path.Path;
77
+ const dump = yield* dumpAll;
78
+ yield* fs.makeDirectory(path.dirname(file), {
79
+ recursive: true
80
+ });
81
+ yield* fs.writeFileString(file, dump);
82
+ }).pipe(Effect.mapError(error => new Migrator.MigrationError({
83
+ reason: "failed",
84
+ message: error.message
85
+ })));
86
+ return dumpFile(path);
87
+ }
88
+ });
89
+ /**
90
+ * @category constructor
91
+ * @since 1.0.0
92
+ */
93
+ const layer = options => Layer.effectDiscard(run(options));
94
+ exports.layer = layer;
95
+ //# sourceMappingURL=SqliteMigrator.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"SqliteMigrator.js","names":["Command","_interopRequireWildcard","require","_FileSystem","_Path","Migrator","Object","keys","forEach","key","prototype","hasOwnProperty","call","_exportNames","exports","defineProperty","enumerable","get","Effect","_Function","Layer","_SqliteClient","_FileSystem2","e","t","WeakMap","r","n","__esModule","o","i","f","__proto__","default","has","set","getOwnPropertyDescriptor","run","make","dumpSchema","path","table","dump","args","gen","sql","SqliteClient","pipe","config","filename","string","replace","trim","mapError","error","MigrationError","reason","message","dumpMigrations","dumpAll","map","all","concurrency","schema","migrations","dumpFile","file","fs","FileSystem","Path","makeDirectory","dirname","recursive","writeFileString","layer","options","effectDiscard"],"sources":["../../src/SqliteMigrator.ts"],"sourcesContent":[null],"mappings":";;;;;;;;;;AAGA,IAAAA,OAAA,GAAAC,uBAAA,CAAAC,OAAA;AAEA,IAAAC,WAAA,GAAAD,OAAA;AACA,IAAAE,KAAA,GAAAF,OAAA;AACA,IAAAG,QAAA,GAAAJ,uBAAA,CAAAC,OAAA;AAWAI,MAAA,CAAAC,IAAA,CAAAF,QAAA,EAAAG,OAAA,WA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EH,KAAK,CAACG;IAAO,CAAE,CAAC,CAAC,CACtG;IAEH,OAAOQ,QAAQ,CAACzB,IAAI,CAAC;EACvB;CACD,CAAC;AAEF;;;;AAIO,MAAMkC,KAAK,GAChBC,OAAoC,IAKjCvD,KAAK,CAACwD,aAAa,CAACvC,GAAG,CAACsC,OAAO,CAAC,CAAC;AAAA7D,OAAA,CAAA4D,KAAA,GAAAA,KAAA","ignoreList":[]}
@@ -0,0 +1,12 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.SqliteMigrator = exports.SqliteClient = void 0;
7
+ var _SqliteClient = _interopRequireWildcard(require("./SqliteClient.js"));
8
+ exports.SqliteClient = _SqliteClient;
9
+ var _SqliteMigrator = _interopRequireWildcard(require("./SqliteMigrator.js"));
10
+ exports.SqliteMigrator = _SqliteMigrator;
11
+ function _interopRequireWildcard(e, t) { if ("function" == typeof WeakMap) var r = new WeakMap(), n = new WeakMap(); return (_interopRequireWildcard = function (e, t) { if (!t && e && e.__esModule) return e; var o, i, f = { __proto__: null, default: e }; if (null === e || "object" != typeof e && "function" != typeof e) return f; if (o = t ? n : r) { if (o.has(e)) return o.get(e); o.set(e, f); } for (const t in e) "default" !== t && {}.hasOwnProperty.call(e, t) && ((i = (o = Object.defineProperty) && Object.getOwnPropertyDescriptor(e, t)) && (i.get || i.set) ? o(f, t, i) : f[t] = e[t]); return f; })(e, t); }
12
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","names":[],"sources":["../../src/index.ts"],"sourcesContent":[null],"mappings":"","ignoreList":[]}
@@ -0,0 +1,79 @@
1
+ /**
2
+ * @since 1.0.0
3
+ */
4
+ import * as Reactivity from "@effect/experimental/Reactivity";
5
+ import * as Client from "@effect/sql/SqlClient";
6
+ import { SqlError } from "@effect/sql/SqlError";
7
+ import * as Config from "effect/Config";
8
+ import type { ConfigError } from "effect/ConfigError";
9
+ import * as Context from "effect/Context";
10
+ import * as Duration from "effect/Duration";
11
+ import * as Effect from "effect/Effect";
12
+ import * as Layer from "effect/Layer";
13
+ import * as Scope from "effect/Scope";
14
+ /**
15
+ * @category type ids
16
+ * @since 1.0.0
17
+ */
18
+ export declare const TypeId: unique symbol;
19
+ /**
20
+ * @category type ids
21
+ * @since 1.0.0
22
+ */
23
+ export type TypeId = typeof TypeId;
24
+ /**
25
+ * @category models
26
+ * @since 1.0.0
27
+ */
28
+ export interface SqliteClient extends Client.SqlClient {
29
+ readonly [TypeId]: TypeId;
30
+ readonly config: SqliteClientConfig;
31
+ readonly export: Effect.Effect<Uint8Array, SqlError>;
32
+ readonly backup: (destination: string) => Effect.Effect<BackupMetadata, SqlError>;
33
+ readonly loadExtension: (path: string) => Effect.Effect<void, SqlError>;
34
+ /** Not supported in sqlite */
35
+ readonly updateValues: never;
36
+ }
37
+ /**
38
+ * @category models
39
+ * @since 1.0.0
40
+ */
41
+ export interface BackupMetadata {
42
+ readonly totalPages: number;
43
+ readonly remainingPages: number;
44
+ }
45
+ /**
46
+ * @category tags
47
+ * @since 1.0.0
48
+ */
49
+ export declare const SqliteClient: Context.Tag<SqliteClient, SqliteClient>;
50
+ /**
51
+ * @category models
52
+ * @since 1.0.0
53
+ */
54
+ export interface SqliteClientConfig {
55
+ readonly filename: string;
56
+ readonly readonly?: boolean | undefined;
57
+ readonly prepareCacheSize?: number | undefined;
58
+ readonly prepareCacheTTL?: Duration.DurationInput | undefined;
59
+ readonly disableWAL?: boolean | undefined;
60
+ readonly spanAttributes?: Record<string, unknown> | undefined;
61
+ readonly transformResultNames?: ((str: string) => string) | undefined;
62
+ readonly transformQueryNames?: ((str: string) => string) | undefined;
63
+ }
64
+ /**
65
+ * @category constructor
66
+ * @since 1.0.0
67
+ */
68
+ export declare const make: (options: SqliteClientConfig) => Effect.Effect<SqliteClient, never, Scope.Scope | Reactivity.Reactivity>;
69
+ /**
70
+ * @category layers
71
+ * @since 1.0.0
72
+ */
73
+ export declare const layerConfig: (config: Config.Config.Wrap<SqliteClientConfig>) => Layer.Layer<SqliteClient | Client.SqlClient, ConfigError>;
74
+ /**
75
+ * @category layers
76
+ * @since 1.0.0
77
+ */
78
+ export declare const layer: (config: SqliteClientConfig) => Layer.Layer<SqliteClient | Client.SqlClient, ConfigError>;
79
+ //# sourceMappingURL=SqliteClient.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"SqliteClient.d.ts","sourceRoot":"","sources":["../../src/SqliteClient.ts"],"names":[],"mappings":"AAAA;;GAEG;AACH,OAAO,KAAK,UAAU,MAAM,iCAAiC,CAAA;AAC7D,OAAO,KAAK,MAAM,MAAM,uBAAuB,CAAA;AAE/C,OAAO,EAAE,QAAQ,EAAE,MAAM,sBAAsB,CAAA;AAI/C,OAAO,KAAK,MAAM,MAAM,eAAe,CAAA;AACvC,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,oBAAoB,CAAA;AACrD,OAAO,KAAK,OAAO,MAAM,gBAAgB,CAAA;AACzC,OAAO,KAAK,QAAQ,MAAM,iBAAiB,CAAA;AAC3C,OAAO,KAAK,MAAM,MAAM,eAAe,CAAA;AAEvC,OAAO,KAAK,KAAK,MAAM,cAAc,CAAA;AACrC,OAAO,KAAK,KAAK,MAAM,cAAc,CAAA;AAIrC;;;GAGG;AACH,eAAO,MAAM,MAAM,EAAE,OAAO,MAA2D,CAAA;AAEvF;;;GAGG;AACH,MAAM,MAAM,MAAM,GAAG,OAAO,MAAM,CAAA;AAElC;;;GAGG;AACH,MAAM,WAAW,YAAa,SAAQ,MAAM,CAAC,SAAS;IACpD,QAAQ,CAAC,CAAC,MAAM,CAAC,EAAE,MAAM,CAAA;IACzB,QAAQ,CAAC,MAAM,EAAE,kBAAkB,CAAA;IACnC,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC,MAAM,CAAC,UAAU,EAAE,QAAQ,CAAC,CAAA;IACpD,QAAQ,CAAC,MAAM,EAAE,CAAC,WAAW,EAAE,MAAM,KAAK,MA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,CAgKrE,CAAA;AAEJ;;;GAGG;AACH,eAAO,MAAM,WAAW,GACtB,QAAQ,MAAM,CAAC,MAAM,CAAC,IAAI,CAAC,kBAAkB,CAAC,KAC7C,KAAK,CAAC,KAAK,CAAC,YAAY,GAAG,MAAM,CAAC,SAAS,EAAE,WAAW,CAUlB,CAAA;AAEzC;;;GAGG;AACH,eAAO,MAAM,KAAK,GAChB,QAAQ,kBAAkB,KACzB,KAAK,CAAC,KAAK,CAAC,YAAY,GAAG,MAAM,CAAC,SAAS,EAAE,WAAW,CAMlB,CAAA"}
@@ -0,0 +1,28 @@
1
+ import type { CommandExecutor } from "@effect/platform/CommandExecutor";
2
+ import { FileSystem } from "@effect/platform/FileSystem";
3
+ import { Path } from "@effect/platform/Path";
4
+ import * as Migrator from "@effect/sql/Migrator";
5
+ import type * as Client from "@effect/sql/SqlClient";
6
+ import type { SqlError } from "@effect/sql/SqlError";
7
+ import * as Effect from "effect/Effect";
8
+ import * as Layer from "effect/Layer";
9
+ import { SqliteClient } from "./SqliteClient.js";
10
+ /**
11
+ * @since 1.0.0
12
+ */
13
+ export * from "@effect/sql/Migrator";
14
+ /**
15
+ * @since 1.0.0
16
+ */
17
+ export * from "@effect/sql/Migrator/FileSystem";
18
+ /**
19
+ * @category constructor
20
+ * @since 1.0.0
21
+ */
22
+ export declare const run: <R2 = never>(options: Migrator.MigratorOptions<R2>) => Effect.Effect<ReadonlyArray<readonly [id: number, name: string]>, Migrator.MigrationError | SqlError, FileSystem | Path | SqliteClient | Client.SqlClient | CommandExecutor | R2>;
23
+ /**
24
+ * @category constructor
25
+ * @since 1.0.0
26
+ */
27
+ export declare const layer: <R>(options: Migrator.MigratorOptions<R>) => Layer.Layer<never, SqlError | Migrator.MigrationError, SqliteClient | Client.SqlClient | CommandExecutor | FileSystem | Path | R>;
28
+ //# sourceMappingURL=SqliteMigrator.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"SqliteMigrator.d.ts","sourceRoot":"","sources":["../../src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* @since 1.0.0
3
+ */
4
+ export * as SqliteClient from "./SqliteClient.js";
5
+ /**
6
+ * @since 1.0.0
7
+ */
8
+ export * as SqliteMigrator from "./SqliteMigrator.js";
9
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA;;GAEG;AACH,OAAO,KAAK,YAAY,MAAM,mBAAmB,CAAA;AAEjD;;GAEG;AACH,OAAO,KAAK,cAAc,MAAM,qBAAqB,CAAA"}
@@ -0,0 +1,159 @@
1
+ /**
2
+ * @since 1.0.0
3
+ */
4
+ import * as Reactivity from "@effect/experimental/Reactivity";
5
+ import * as Client from "@effect/sql/SqlClient";
6
+ import { SqlError } from "@effect/sql/SqlError";
7
+ import * as Statement from "@effect/sql/Statement";
8
+ import Sqlite from "better-sqlite3";
9
+ import * as Cache from "effect/Cache";
10
+ import * as Config from "effect/Config";
11
+ import * as Context from "effect/Context";
12
+ import * as Duration from "effect/Duration";
13
+ import * as Effect from "effect/Effect";
14
+ import { identity } from "effect/Function";
15
+ import * as Layer from "effect/Layer";
16
+ import * as Scope from "effect/Scope";
17
+ const ATTR_DB_SYSTEM_NAME = "db.system.name";
18
+ /**
19
+ * @category type ids
20
+ * @since 1.0.0
21
+ */
22
+ export const TypeId = /*#__PURE__*/Symbol.for("@effect/sql-sqlite-node/SqliteClient");
23
+ /**
24
+ * @category tags
25
+ * @since 1.0.0
26
+ */
27
+ export const SqliteClient = /*#__PURE__*/Context.GenericTag("@effect/sql-sqlite-node/SqliteClient");
28
+ /**
29
+ * @category constructor
30
+ * @since 1.0.0
31
+ */
32
+ export const make = options => Effect.gen(function* () {
33
+ const compiler = Statement.makeCompilerSqlite(options.transformQueryNames);
34
+ const transformRows = options.transformResultNames ? Statement.defaultTransforms(options.transformResultNames).array : undefined;
35
+ const makeConnection = Effect.gen(function* () {
36
+ const scope = yield* Effect.scope;
37
+ const db = new Sqlite(options.filename, {
38
+ readonly: options.readonly ?? false
39
+ });
40
+ yield* Scope.addFinalizer(scope, Effect.sync(() => db.close()));
41
+ if (options.disableWAL !== true) {
42
+ db.pragma("journal_mode = WAL");
43
+ }
44
+ const prepareCache = yield* Cache.make({
45
+ capacity: options.prepareCacheSize ?? 200,
46
+ timeToLive: options.prepareCacheTTL ?? Duration.minutes(10),
47
+ lookup: sql => Effect.try({
48
+ try: () => db.prepare(sql),
49
+ catch: cause => new SqlError({
50
+ cause,
51
+ message: "Failed to prepare statement "
52
+ })
53
+ })
54
+ });
55
+ const runStatement = (statement, params, raw) => Effect.withFiberRuntime(fiber => {
56
+ if (Context.get(fiber.currentContext, Client.SafeIntegers)) {
57
+ statement.safeIntegers(true);
58
+ }
59
+ try {
60
+ if (statement.reader) {
61
+ return Effect.succeed(statement.all(...params));
62
+ }
63
+ const result = statement.run(...params);
64
+ return Effect.succeed(raw ? result : []);
65
+ } catch (cause) {
66
+ return Effect.fail(new SqlError({
67
+ cause,
68
+ message: "Failed to execute statement"
69
+ }));
70
+ }
71
+ });
72
+ const run = (sql, params, raw = false) => Effect.flatMap(prepareCache.get(sql), s => runStatement(s, params, raw));
73
+ const runValues = (sql, params) => Effect.acquireUseRelease(prepareCache.get(sql), statement => Effect.try({
74
+ try: () => {
75
+ if (statement.reader) {
76
+ statement.raw(true);
77
+ return statement.all(...params);
78
+ }
79
+ statement.run(...params);
80
+ return [];
81
+ },
82
+ catch: cause => new SqlError({
83
+ cause,
84
+ message: "Failed to execute statement"
85
+ })
86
+ }), statement => Effect.sync(() => statement.reader && statement.raw(false)));
87
+ return identity({
88
+ execute(sql, params, transformRows) {
89
+ return transformRows ? Effect.map(run(sql, params), transformRows) : run(sql, params);
90
+ },
91
+ executeRaw(sql, params) {
92
+ return run(sql, params, true);
93
+ },
94
+ executeValues(sql, params) {
95
+ return runValues(sql, params);
96
+ },
97
+ executeUnprepared(sql, params, transformRows) {
98
+ const effect = runStatement(db.prepare(sql), params ?? [], false);
99
+ return transformRows ? Effect.map(effect, transformRows) : effect;
100
+ },
101
+ executeStream(_sql, _params) {
102
+ return Effect.dieMessage("executeStream not implemented");
103
+ },
104
+ export: Effect.try({
105
+ try: () => db.serialize(),
106
+ catch: cause => new SqlError({
107
+ cause,
108
+ message: "Failed to export database"
109
+ })
110
+ }),
111
+ backup(destination) {
112
+ return Effect.tryPromise({
113
+ try: () => db.backup(destination),
114
+ catch: cause => new SqlError({
115
+ cause,
116
+ message: "Failed to backup database"
117
+ })
118
+ });
119
+ },
120
+ loadExtension(path) {
121
+ return Effect.tap(Effect.try({
122
+ try: () => db.loadExtension(path),
123
+ catch: cause => new SqlError({
124
+ cause,
125
+ message: "Failed to load extension"
126
+ })
127
+ }), () => prepareCache.invalidateAll);
128
+ }
129
+ });
130
+ });
131
+ const semaphore = yield* Effect.makeSemaphore(1);
132
+ const connection = yield* makeConnection;
133
+ const acquirer = semaphore.withPermits(1)(Effect.succeed(connection));
134
+ const transactionAcquirer = Effect.uninterruptibleMask(restore => Effect.as(Effect.zipRight(restore(semaphore.take(1)), Effect.tap(Effect.scope, scope => Scope.addFinalizer(scope, semaphore.release(1)))), connection));
135
+ return Object.assign(yield* Client.make({
136
+ acquirer,
137
+ compiler,
138
+ transactionAcquirer,
139
+ spanAttributes: [...(options.spanAttributes ? Object.entries(options.spanAttributes) : []), [ATTR_DB_SYSTEM_NAME, "sqlite"]],
140
+ transformRows
141
+ }), {
142
+ [TypeId]: TypeId,
143
+ config: options,
144
+ export: Effect.flatMap(acquirer, _ => _.export),
145
+ backup: destination => Effect.flatMap(acquirer, _ => _.backup(destination)),
146
+ loadExtension: path => Effect.flatMap(acquirer, _ => _.loadExtension(path))
147
+ });
148
+ });
149
+ /**
150
+ * @category layers
151
+ * @since 1.0.0
152
+ */
153
+ export const layerConfig = config => Layer.scopedContext(Config.unwrap(config).pipe(Effect.flatMap(make), Effect.map(client => Context.make(SqliteClient, client).pipe(Context.add(Client.SqlClient, client))))).pipe(Layer.provide(Reactivity.layer));
154
+ /**
155
+ * @category layers
156
+ * @since 1.0.0
157
+ */
158
+ export const layer = config => Layer.scopedContext(Effect.map(make(config), client => Context.make(SqliteClient, client).pipe(Context.add(Client.SqlClient, client)))).pipe(Layer.provide(Reactivity.layer));
159
+ //# sourceMappingURL=SqliteClient.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"SqliteClient.js","names":["Reactivity","Client","SqlError","Statement","Sqlite","Cache","Config","Context","Duration","Effect","identity","Layer","Scope","ATTR_DB_SYSTEM_NAME","TypeId","Symbol","for","SqliteClient","GenericTag","make","options","gen","compiler","makeCompilerSqlite","transformQueryNames","transformRows","transformResultNames","defaultTransforms","array","undefined","makeConnection","scope","db","filename","readonly","addFinalizer","sync","close","disableWAL","pragma","prepareCache","capacity","prepareCacheSize","timeToLive","prepareCacheTTL","minutes","lookup","sql","try","prepare","catch","cause","message","runStatement","statement","params","raw","withFiberRuntime","fiber","get","currentContext","SafeIntegers","safeIntegers","reader","succeed","all","result","run","fail","flatMap","s","runValues","acquireUseRelease","execute","map","executeRaw","executeValues","executeUnprepared","effect","executeStream","_sql","_params","dieMessage","export","serialize","backup","destination","tryPromise","loadExtension","path","tap","invalidateAll","semaphore","makeSemaphore","connection","acquirer","withPermits","transactionAcquirer","uninterruptibleMask","restore","as","zipRight","take","release","Object","assign","spanAttributes","entries","config","_","layerConfig","scopedContext","unwrap","pipe","client","add","SqlClient","provide","layer"],"sources":["../../src/SqliteClient.ts"],"sourcesContent":[null],"mappings":"AAAA;;;AAGA,OAAO,KAAKA,UAAU,MAAM,iCAAiC;AAC7D,OAAO,KAAKC,MAAM,MAAM,uBAAuB;AAE/C,SAASC,QAAQ,QAAQ,sBAAsB;AAC/C,OAAO,KAAKC,SAAS,MAAM,uBAAuB;AAClD,OAAOC,MAAM,MAAM,gBAAgB;AACnC,OAAO,KAAKC,KAAK,MAAM,cAAc;AACrC,OAAO,KAAKC,MAAM,MAAM,eAAe;AAEvC,OAAO,KAAKC,OAAO,MAAM,gB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4D,OAAO,CAAC0B,QAAQ,EAAGc,CAAC,IAAKA,CAAC,CAACxB,MAAM,CAACC,WAAW,CAAC,CAAC;IACvFE,aAAa,EAAGC,IAAY,IAAKhF,MAAM,CAAC4D,OAAO,CAAC0B,QAAQ,EAAGc,CAAC,IAAKA,CAAC,CAACrB,aAAa,CAACC,IAAI,CAAC;GACvF,CACF;AACH,CAAC,CAAC;AAEJ;;;;AAIA,OAAO,MAAMqB,WAAW,GACtBF,MAA8C,IAE9CjG,KAAK,CAACoG,aAAa,CACjBzG,MAAM,CAAC0G,MAAM,CAACJ,MAAM,CAAC,CAACK,IAAI,CACxBxG,MAAM,CAAC4D,OAAO,CAAClD,IAAI,CAAC,EACpBV,MAAM,CAACiE,GAAG,CAAEwC,MAAM,IAChB3G,OAAO,CAACY,IAAI,CAACF,YAAY,EAAEiG,MAAM,CAAC,CAACD,IAAI,CACrC1G,OAAO,CAAC4G,GAAG,CAAClH,MAAM,CAACmH,SAAS,EAAEF,MAAM,CAAC,CACtC,CACF,CACF,CACF,CAACD,IAAI,CAACtG,KAAK,CAAC0G,OAAO,CAACrH,UAAU,CAACsH,KAAK,CAAC,CAAC;AAEzC;;;;AAIA,OAAO,MAAMA,KAAK,GAChBV,MAA0B,IAE1BjG,KAAK,CAACoG,aAAa,CACjBtG,MAAM,CAACiE,GAAG,CAACvD,IAAI,CAACyF,MAAM,CAAC,EAAGM,MAAM,IAC9B3G,OAAO,CAACY,IAAI,CAACF,YAAY,EAAEiG,MAAM,CAAC,CAACD,IAAI,CACrC1G,OAAO,CAAC4G,GAAG,CAAClH,MAAM,CAACmH,SAAS,EAAEF,MAAM,CAAC,CACtC,CAAC,CACL,CAACD,IAAI,CAACtG,KAAK,CAAC0G,OAAO,CAACrH,UAAU,CAACsH,KAAK,CAAC,CAAC","ignoreList":[]}
@@ -0,0 +1,59 @@
1
+ /**
2
+ * @since 1.0.0
3
+ */
4
+ import * as Command from "@effect/platform/Command";
5
+ import { FileSystem } from "@effect/platform/FileSystem";
6
+ import { Path } from "@effect/platform/Path";
7
+ import * as Migrator from "@effect/sql/Migrator";
8
+ import * as Effect from "effect/Effect";
9
+ import { pipe } from "effect/Function";
10
+ import * as Layer from "effect/Layer";
11
+ import { SqliteClient } from "./SqliteClient.js";
12
+ /**
13
+ * @since 1.0.0
14
+ */
15
+ export * from "@effect/sql/Migrator";
16
+ /**
17
+ * @since 1.0.0
18
+ */
19
+ export * from "@effect/sql/Migrator/FileSystem";
20
+ /**
21
+ * @category constructor
22
+ * @since 1.0.0
23
+ */
24
+ export const run = /*#__PURE__*/Migrator.make({
25
+ dumpSchema(path, table) {
26
+ const dump = args => Effect.gen(function* () {
27
+ const sql = yield* SqliteClient;
28
+ const dump = yield* pipe(Command.make("sqlite3", sql.config.filename, ...args), Command.string);
29
+ return dump.replace(/^create table sqlite_sequence\(.*$/im, "").replace(/\n{2,}/gm, "\n\n").trim();
30
+ }).pipe(Effect.mapError(error => new Migrator.MigrationError({
31
+ reason: "failed",
32
+ message: error.message
33
+ })));
34
+ const dumpSchema = dump([".schema"]);
35
+ const dumpMigrations = dump(["--cmd", `.mode insert ${table}`, `select * from ${table}`]);
36
+ const dumpAll = Effect.map(Effect.all([dumpSchema, dumpMigrations], {
37
+ concurrency: 2
38
+ }), ([schema, migrations]) => schema + "\n\n" + migrations);
39
+ const dumpFile = file => Effect.gen(function* () {
40
+ const fs = yield* FileSystem;
41
+ const path = yield* Path;
42
+ const dump = yield* dumpAll;
43
+ yield* fs.makeDirectory(path.dirname(file), {
44
+ recursive: true
45
+ });
46
+ yield* fs.writeFileString(file, dump);
47
+ }).pipe(Effect.mapError(error => new Migrator.MigrationError({
48
+ reason: "failed",
49
+ message: error.message
50
+ })));
51
+ return dumpFile(path);
52
+ }
53
+ });
54
+ /**
55
+ * @category constructor
56
+ * @since 1.0.0
57
+ */
58
+ export const layer = options => Layer.effectDiscard(run(options));
59
+ //# sourceMappingURL=SqliteMigrator.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"SqliteMigrator.js","names":["Command","FileSystem","Path","Migrator","Effect","pipe","Layer","SqliteClient","run","make","dumpSchema","path","table","dump","args","gen","sql","config","filename","string","replace","trim","mapError","error","MigrationError","reason","message","dumpMigrations","dumpAll","map","all","concurrency","schema","migrations","dumpFile","file","fs","makeDirectory","dirname","recursive","writeFileString","layer","options","effectDiscard"],"sources":["../../src/SqliteMigrator.ts"],"sourcesContent":[null],"mappings":"AAAA;;;AAGA,OAAO,KAAKA,OAAO,MAAM,0BAA0B;AAEnD,SAASC,UAAU,QAAQ,6BAA6B;AACxD,SAASC,IAAI,QAAQ,uBAAuB;AAC5C,OAAO,KAAKC,QAAQ,MAAM,sBAAsB;AAGhD,OAAO,KAAKC,MAAM,MAAM,eAAe;AACvC,SAASC,IAAI,QAAQ,iBAAiB;AACtC,OAAO,KAAKC,KAAK,MAAM,cAAc;AACrC,SAASC,YAAY,QAAQ,mBAAmB;AAEhD;;;AAGA,cAAc,sBAAsB;AAEpC;;;AAGA,cAAc,iCAAiC;AAE/C;;;;AAIA,OAAO,MAAMC,GAAG,gBAMZL,QAAQ,CAACM,IAAI,CAAC;EAChBC,UAAUA,CAACC,IAAI,EAAEC,KAAK;IACpB,MAAMC,IAAI,GAAIC,IAAmB,IAC/BV,MAAM,CAACW,GAAG,CAAC,aAAS;MAClB,MAAMC,GAAG,GAAG,OAAOT,YAAY;MAC/B,MAAMM,IAAI,GAAG,OAAOR,IAAI,CACtBL,OAAO,CAACS,IAAI,CAAC,SAAS,EAAEO,GAAG,CAACC,MAAM,CAACC,QAAQ,EAAE,GAAGJ,IAAI,CAAC,EACrDd,OAAO,CAACmB,MAAM,CACf;MACD,OAAON,IAAI,CAACO,OAAO,CAAC,sCAAsC,EAAE,EAAE,CAAC,CAC5DA,OAAO,CAAC,UAAU,EAAE,MAAM,CAAC,CAC3BC,IAAI,EAAE;IACX,CAAC,CAAC,CAAChB,IAAI,CACLD,MAAM,CAACkB,QAAQ,CAAEC,KAAK,IAAK,IAAIpB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oC,IAKjCpC,KAAK,CAACqC,aAAa,CAACnC,GAAG,CAACkC,OAAO,CAAC,CAAC","ignoreList":[]}
@@ -0,0 +1,9 @@
1
+ /**
2
+ * @since 1.0.0
3
+ */
4
+ export * as SqliteClient from "./SqliteClient.js";
5
+ /**
6
+ * @since 1.0.0
7
+ */
8
+ export * as SqliteMigrator from "./SqliteMigrator.js";
9
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","names":["SqliteClient","SqliteMigrator"],"sources":["../../src/index.ts"],"sourcesContent":[null],"mappings":"AAAA;;;AAGA,OAAO,KAAKA,YAAY,MAAM,mBAAmB;AAEjD;;;AAGA,OAAO,KAAKC,cAAc,MAAM,qBAAqB","ignoreList":[]}
@@ -0,0 +1,4 @@
1
+ {
2
+ "type": "module",
3
+ "sideEffects": []
4
+ }
@@ -0,0 +1,6 @@
1
+ {
2
+ "sideEffects": [],
3
+ "main": "../dist/cjs/index.js",
4
+ "module": "../dist/esm/index.js",
5
+ "types": "../dist/dts/index.d.ts"
6
+ }
package/package.json ADDED
@@ -0,0 +1,64 @@
1
+ {
2
+ "name": "@ohos-ports/effect-sql-sqlite-node",
3
+ "version": "0.53.0-beta.1",
4
+ "description": "A SQLite toolkit for Effect",
5
+ "license": "MIT",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "https://github.com/ohos-ports/ohos-ports.git",
9
+ "directory": "ports/effect-sql-sqlite-node/0.53.0"
10
+ },
11
+ "sideEffects": [],
12
+ "homepage": "https://github.com/ohos-ports/ohos-ports/tree/main/ports/effect-sql-sqlite-node",
13
+ "dependencies": {
14
+ "better-sqlite3": "npm:@ohos-ports/better-sqlite3@^13.0.3"
15
+ },
16
+ "peerDependencies": {
17
+ "@effect/experimental": "^0.61.0",
18
+ "@effect/platform": "^0.97.0",
19
+ "@effect/sql": "^0.52.0",
20
+ "effect": "^3.22.0"
21
+ },
22
+ "main": "./dist/cjs/index.js",
23
+ "module": "./dist/esm/index.js",
24
+ "types": "./dist/dts/index.d.ts",
25
+ "exports": {
26
+ "./package.json": "./package.json",
27
+ ".": {
28
+ "types": "./dist/dts/index.d.ts",
29
+ "import": "./dist/esm/index.js",
30
+ "default": "./dist/cjs/index.js"
31
+ },
32
+ "./SqliteClient": {
33
+ "types": "./dist/dts/SqliteClient.d.ts",
34
+ "import": "./dist/esm/SqliteClient.js",
35
+ "default": "./dist/cjs/SqliteClient.js"
36
+ },
37
+ "./SqliteMigrator": {
38
+ "types": "./dist/dts/SqliteMigrator.d.ts",
39
+ "import": "./dist/esm/SqliteMigrator.js",
40
+ "default": "./dist/cjs/SqliteMigrator.js"
41
+ },
42
+ "./index": {
43
+ "types": "./dist/dts/index.d.ts",
44
+ "import": "./dist/esm/index.js",
45
+ "default": "./dist/cjs/index.js"
46
+ }
47
+ },
48
+ "typesVersions": {
49
+ "*": {
50
+ "SqliteClient": [
51
+ "./dist/dts/SqliteClient.d.ts"
52
+ ],
53
+ "SqliteMigrator": [
54
+ "./dist/dts/SqliteMigrator.d.ts"
55
+ ],
56
+ "index": [
57
+ "./dist/dts/index.d.ts"
58
+ ]
59
+ }
60
+ },
61
+ "bugs": {
62
+ "url": "https://github.com/ohos-ports/ohos-ports/issues"
63
+ }
64
+ }
@@ -0,0 +1,284 @@
1
+ /**
2
+ * @since 1.0.0
3
+ */
4
+ import * as Reactivity from "@effect/experimental/Reactivity"
5
+ import * as Client from "@effect/sql/SqlClient"
6
+ import type { Connection } from "@effect/sql/SqlConnection"
7
+ import { SqlError } from "@effect/sql/SqlError"
8
+ import * as Statement from "@effect/sql/Statement"
9
+ import Sqlite from "better-sqlite3"
10
+ import * as Cache from "effect/Cache"
11
+ import * as Config from "effect/Config"
12
+ import type { ConfigError } from "effect/ConfigError"
13
+ import * as Context from "effect/Context"
14
+ import * as Duration from "effect/Duration"
15
+ import * as Effect from "effect/Effect"
16
+ import { identity } from "effect/Function"
17
+ import * as Layer from "effect/Layer"
18
+ import * as Scope from "effect/Scope"
19
+
20
+ const ATTR_DB_SYSTEM_NAME = "db.system.name"
21
+
22
+ /**
23
+ * @category type ids
24
+ * @since 1.0.0
25
+ */
26
+ export const TypeId: unique symbol = Symbol.for("@effect/sql-sqlite-node/SqliteClient")
27
+
28
+ /**
29
+ * @category type ids
30
+ * @since 1.0.0
31
+ */
32
+ export type TypeId = typeof TypeId
33
+
34
+ /**
35
+ * @category models
36
+ * @since 1.0.0
37
+ */
38
+ export interface SqliteClient extends Client.SqlClient {
39
+ readonly [TypeId]: TypeId
40
+ readonly config: SqliteClientConfig
41
+ readonly export: Effect.Effect<Uint8Array, SqlError>
42
+ readonly backup: (destination: string) => Effect.Effect<BackupMetadata, SqlError>
43
+ readonly loadExtension: (path: string) => Effect.Effect<void, SqlError>
44
+
45
+ /** Not supported in sqlite */
46
+ readonly updateValues: never
47
+ }
48
+
49
+ /**
50
+ * @category models
51
+ * @since 1.0.0
52
+ */
53
+ export interface BackupMetadata {
54
+ readonly totalPages: number
55
+ readonly remainingPages: number
56
+ }
57
+
58
+ /**
59
+ * @category tags
60
+ * @since 1.0.0
61
+ */
62
+ export const SqliteClient = Context.GenericTag<SqliteClient>("@effect/sql-sqlite-node/SqliteClient")
63
+
64
+ /**
65
+ * @category models
66
+ * @since 1.0.0
67
+ */
68
+ export interface SqliteClientConfig {
69
+ readonly filename: string
70
+ readonly readonly?: boolean | undefined
71
+ readonly prepareCacheSize?: number | undefined
72
+ readonly prepareCacheTTL?: Duration.DurationInput | undefined
73
+ readonly disableWAL?: boolean | undefined
74
+ readonly spanAttributes?: Record<string, unknown> | undefined
75
+
76
+ readonly transformResultNames?: ((str: string) => string) | undefined
77
+ readonly transformQueryNames?: ((str: string) => string) | undefined
78
+ }
79
+
80
+ interface SqliteConnection extends Connection {
81
+ readonly export: Effect.Effect<Uint8Array, SqlError>
82
+ readonly backup: (destination: string) => Effect.Effect<BackupMetadata, SqlError>
83
+ readonly loadExtension: (path: string) => Effect.Effect<void, SqlError>
84
+ }
85
+
86
+ /**
87
+ * @category constructor
88
+ * @since 1.0.0
89
+ */
90
+ export const make = (
91
+ options: SqliteClientConfig
92
+ ): Effect.Effect<SqliteClient, never, Scope.Scope | Reactivity.Reactivity> =>
93
+ Effect.gen(function*() {
94
+ const compiler = Statement.makeCompilerSqlite(options.transformQueryNames)
95
+ const transformRows = options.transformResultNames ?
96
+ Statement.defaultTransforms(
97
+ options.transformResultNames
98
+ ).array :
99
+ undefined
100
+
101
+ const makeConnection = Effect.gen(function*() {
102
+ const scope = yield* Effect.scope
103
+ const db = new Sqlite(options.filename, {
104
+ readonly: options.readonly ?? false
105
+ })
106
+ yield* Scope.addFinalizer(scope, Effect.sync(() => db.close()))
107
+
108
+ if (options.disableWAL !== true) {
109
+ db.pragma("journal_mode = WAL")
110
+ }
111
+
112
+ const prepareCache = yield* Cache.make({
113
+ capacity: options.prepareCacheSize ?? 200,
114
+ timeToLive: options.prepareCacheTTL ?? Duration.minutes(10),
115
+ lookup: (sql: string) =>
116
+ Effect.try({
117
+ try: () => db.prepare(sql),
118
+ catch: (cause) => new SqlError({ cause, message: "Failed to prepare statement " })
119
+ })
120
+ })
121
+
122
+ const runStatement = (
123
+ statement: Sqlite.Statement,
124
+ params: ReadonlyArray<unknown>,
125
+ raw: boolean
126
+ ) =>
127
+ Effect.withFiberRuntime<ReadonlyArray<any>, SqlError>((fiber) => {
128
+ if (Context.get(fiber.currentContext, Client.SafeIntegers)) {
129
+ statement.safeIntegers(true)
130
+ }
131
+ try {
132
+ if (statement.reader) {
133
+ return Effect.succeed(statement.all(...params))
134
+ }
135
+ const result = statement.run(...params)
136
+ return Effect.succeed(raw ? result as unknown as ReadonlyArray<any> : [])
137
+ } catch (cause) {
138
+ return Effect.fail(new SqlError({ cause, message: "Failed to execute statement" }))
139
+ }
140
+ })
141
+
142
+ const run = (
143
+ sql: string,
144
+ params: ReadonlyArray<unknown>,
145
+ raw = false
146
+ ) =>
147
+ Effect.flatMap(
148
+ prepareCache.get(sql),
149
+ (s) => runStatement(s, params, raw)
150
+ )
151
+
152
+ const runValues = (
153
+ sql: string,
154
+ params: ReadonlyArray<unknown>
155
+ ) =>
156
+ Effect.acquireUseRelease(
157
+ prepareCache.get(sql),
158
+ (statement) =>
159
+ Effect.try({
160
+ try: () => {
161
+ if (statement.reader) {
162
+ statement.raw(true)
163
+ return statement.all(...params) as ReadonlyArray<
164
+ ReadonlyArray<unknown>
165
+ >
166
+ }
167
+ statement.run(...params)
168
+ return []
169
+ },
170
+ catch: (cause) => new SqlError({ cause, message: "Failed to execute statement" })
171
+ }),
172
+ (statement) => Effect.sync(() => statement.reader && statement.raw(false))
173
+ )
174
+
175
+ return identity<SqliteConnection>({
176
+ execute(sql, params, transformRows) {
177
+ return transformRows
178
+ ? Effect.map(run(sql, params), transformRows)
179
+ : run(sql, params)
180
+ },
181
+ executeRaw(sql, params) {
182
+ return run(sql, params, true)
183
+ },
184
+ executeValues(sql, params) {
185
+ return runValues(sql, params)
186
+ },
187
+ executeUnprepared(sql, params, transformRows) {
188
+ const effect = runStatement(db.prepare(sql), params ?? [], false)
189
+ return transformRows ? Effect.map(effect, transformRows) : effect
190
+ },
191
+ executeStream(_sql, _params) {
192
+ return Effect.dieMessage("executeStream not implemented")
193
+ },
194
+ export: Effect.try({
195
+ try: () => db.serialize(),
196
+ catch: (cause) => new SqlError({ cause, message: "Failed to export database" })
197
+ }),
198
+ backup(destination) {
199
+ return Effect.tryPromise({
200
+ try: () => db.backup(destination),
201
+ catch: (cause) => new SqlError({ cause, message: "Failed to backup database" })
202
+ })
203
+ },
204
+ loadExtension(path) {
205
+ return Effect.tap(
206
+ Effect.try({
207
+ try: () => db.loadExtension(path),
208
+ catch: (cause) => new SqlError({ cause, message: "Failed to load extension" })
209
+ }),
210
+ () => prepareCache.invalidateAll
211
+ )
212
+ }
213
+ })
214
+ })
215
+
216
+ const semaphore = yield* Effect.makeSemaphore(1)
217
+ const connection = yield* makeConnection
218
+
219
+ const acquirer = semaphore.withPermits(1)(Effect.succeed(connection))
220
+ const transactionAcquirer = Effect.uninterruptibleMask((restore) =>
221
+ Effect.as(
222
+ Effect.zipRight(
223
+ restore(semaphore.take(1)),
224
+ Effect.tap(
225
+ Effect.scope,
226
+ (scope) => Scope.addFinalizer(scope, semaphore.release(1))
227
+ )
228
+ ),
229
+ connection
230
+ )
231
+ )
232
+
233
+ return Object.assign(
234
+ (yield* Client.make({
235
+ acquirer,
236
+ compiler,
237
+ transactionAcquirer,
238
+ spanAttributes: [
239
+ ...(options.spanAttributes ? Object.entries(options.spanAttributes) : []),
240
+ [ATTR_DB_SYSTEM_NAME, "sqlite"]
241
+ ],
242
+ transformRows
243
+ })) as SqliteClient,
244
+ {
245
+ [TypeId]: TypeId as TypeId,
246
+ config: options,
247
+ export: Effect.flatMap(acquirer, (_) => _.export),
248
+ backup: (destination: string) => Effect.flatMap(acquirer, (_) => _.backup(destination)),
249
+ loadExtension: (path: string) => Effect.flatMap(acquirer, (_) => _.loadExtension(path))
250
+ }
251
+ )
252
+ })
253
+
254
+ /**
255
+ * @category layers
256
+ * @since 1.0.0
257
+ */
258
+ export const layerConfig = (
259
+ config: Config.Config.Wrap<SqliteClientConfig>
260
+ ): Layer.Layer<SqliteClient | Client.SqlClient, ConfigError> =>
261
+ Layer.scopedContext(
262
+ Config.unwrap(config).pipe(
263
+ Effect.flatMap(make),
264
+ Effect.map((client) =>
265
+ Context.make(SqliteClient, client).pipe(
266
+ Context.add(Client.SqlClient, client)
267
+ )
268
+ )
269
+ )
270
+ ).pipe(Layer.provide(Reactivity.layer))
271
+
272
+ /**
273
+ * @category layers
274
+ * @since 1.0.0
275
+ */
276
+ export const layer = (
277
+ config: SqliteClientConfig
278
+ ): Layer.Layer<SqliteClient | Client.SqlClient, ConfigError> =>
279
+ Layer.scopedContext(
280
+ Effect.map(make(config), (client) =>
281
+ Context.make(SqliteClient, client).pipe(
282
+ Context.add(Client.SqlClient, client)
283
+ ))
284
+ ).pipe(Layer.provide(Reactivity.layer))
@@ -0,0 +1,90 @@
1
+ /**
2
+ * @since 1.0.0
3
+ */
4
+ import * as Command from "@effect/platform/Command"
5
+ import type { CommandExecutor } from "@effect/platform/CommandExecutor"
6
+ import { FileSystem } from "@effect/platform/FileSystem"
7
+ import { Path } from "@effect/platform/Path"
8
+ import * as Migrator from "@effect/sql/Migrator"
9
+ import type * as Client from "@effect/sql/SqlClient"
10
+ import type { SqlError } from "@effect/sql/SqlError"
11
+ import * as Effect from "effect/Effect"
12
+ import { pipe } from "effect/Function"
13
+ import * as Layer from "effect/Layer"
14
+ import { SqliteClient } from "./SqliteClient.js"
15
+
16
+ /**
17
+ * @since 1.0.0
18
+ */
19
+ export * from "@effect/sql/Migrator"
20
+
21
+ /**
22
+ * @since 1.0.0
23
+ */
24
+ export * from "@effect/sql/Migrator/FileSystem"
25
+
26
+ /**
27
+ * @category constructor
28
+ * @since 1.0.0
29
+ */
30
+ export const run: <R2 = never>(
31
+ options: Migrator.MigratorOptions<R2>
32
+ ) => Effect.Effect<
33
+ ReadonlyArray<readonly [id: number, name: string]>,
34
+ Migrator.MigrationError | SqlError,
35
+ FileSystem | Path | SqliteClient | Client.SqlClient | CommandExecutor | R2
36
+ > = Migrator.make({
37
+ dumpSchema(path, table) {
38
+ const dump = (args: Array<string>) =>
39
+ Effect.gen(function*() {
40
+ const sql = yield* SqliteClient
41
+ const dump = yield* pipe(
42
+ Command.make("sqlite3", sql.config.filename, ...args),
43
+ Command.string
44
+ )
45
+ return dump.replace(/^create table sqlite_sequence\(.*$/im, "")
46
+ .replace(/\n{2,}/gm, "\n\n")
47
+ .trim();
48
+ }).pipe(
49
+ Effect.mapError((error) => new Migrator.MigrationError({ reason: "failed", message: error.message }))
50
+ )
51
+
52
+ const dumpSchema = dump([".schema"])
53
+
54
+ const dumpMigrations = dump([
55
+ "--cmd",
56
+ `.mode insert ${table}`,
57
+ `select * from ${table}`
58
+ ])
59
+
60
+ const dumpAll = Effect.map(
61
+ Effect.all([dumpSchema, dumpMigrations], { concurrency: 2 }),
62
+ ([schema, migrations]) => schema + "\n\n" + migrations
63
+ )
64
+
65
+ const dumpFile = (file: string) =>
66
+ Effect.gen(function*() {
67
+ const fs = yield* FileSystem
68
+ const path = yield* Path
69
+ const dump = yield* dumpAll
70
+ yield* fs.makeDirectory(path.dirname(file), { recursive: true })
71
+ yield* fs.writeFileString(file, dump)
72
+ }).pipe(
73
+ Effect.mapError((error) => new Migrator.MigrationError({ reason: "failed", message: error.message }))
74
+ )
75
+
76
+ return dumpFile(path)
77
+ }
78
+ })
79
+
80
+ /**
81
+ * @category constructor
82
+ * @since 1.0.0
83
+ */
84
+ export const layer = <R>(
85
+ options: Migrator.MigratorOptions<R>
86
+ ): Layer.Layer<
87
+ never,
88
+ SqlError | Migrator.MigrationError,
89
+ SqliteClient | Client.SqlClient | CommandExecutor | FileSystem | Path | R
90
+ > => Layer.effectDiscard(run(options))
package/src/index.ts ADDED
@@ -0,0 +1,9 @@
1
+ /**
2
+ * @since 1.0.0
3
+ */
4
+ export * as SqliteClient from "./SqliteClient.js"
5
+
6
+ /**
7
+ * @since 1.0.0
8
+ */
9
+ export * as SqliteMigrator from "./SqliteMigrator.js"