@flumens/models 0.5.2 → 0.6.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.
@@ -1 +1,221 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("tslib"),t=require("jeep-sqlite/loader"),n=require("@capacitor-community/sqlite"),r=require("@capacitor/core"),i=require("@capacitor/filesystem");function s(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var o=s(require("@flumens/utils/dist/deferred")),a=function(){function s(e){var t=e.name,r=e.debug,i=e.web;this.sqliteConnection=new n.SQLiteConnection(n.CapacitorSQLite),this.name="main",this.debug=!1,this.isWeb=!1,this.ready=new o.default,this.name=t||this.name,this.debug=r||this.debug,this.isWeb=i||this.isWeb}return s.migrateCordova=function(t){var r;return e.__awaiter(this,void 0,void 0,(function(){var i,s,o;return e.__generator(this,(function(e){switch(e.label){case 0:console.log("SQLite: Cordova db migration"),i=new n.SQLiteConnection(n.CapacitorSQLite),e.label=1;case 1:return e.trys.push([1,5,,6]),[4,i.getMigratableDbList(t?"Library/LocalDatabase":void 0)];case 2:return s=e.sent(),(null===(r=s.values)||void 0===r?void 0:r.length)?(console.log("SQLite: migrating",s.values),[4,i.addSQLiteSuffix(t?"Library/LocalDatabase":void 0,s.values)]):(console.log("SQLite: no Cordova db to migrate"),[2]);case 3:return e.sent(),[4,i.deleteOldDatabases(t?"Library/LocalDatabase":void 0,s.values)];case 4:return e.sent(),console.log("SQLite: migrating done",s.values),[3,6];case 5:return o=e.sent(),console.error(o),[3,6];case 6:return[4,i.checkConnectionsConsistency()];case 7:return e.sent(),[4,i.closeAllConnections()];case 8:return e.sent(),[2]}}))}))},Object.defineProperty(s.prototype,"db",{get:function(){return this.connection},enumerable:!1,configurable:!0}),s.prototype.init=function(){return e.__awaiter(this,void 0,void 0,(function(){var n,r;return e.__generator(this,(function(e){switch(e.label){case 0:return this.isWeb?(t.defineCustomElements(window),(n=document.createElement("jeep-sqlite")).setAttribute("autoSave","true"),document.body.appendChild(n),[4,customElements.whenDefined("jeep-sqlite")]):[3,3];case 1:return e.sent(),[4,this.sqliteConnection.initWebStore()];case 2:e.sent(),e.label=3;case 3:return[4,this.sqliteConnection.checkConnectionsConsistency()];case 4:return e.sent(),[4,this.sqliteConnection.closeAllConnections()];case 5:return e.sent(),r=this,[4,this.sqliteConnection.createConnection(this.name,!1,"no-encryption",1,!1)];case 6:return r.connection=e.sent(),[4,this.connection.open()];case 7:return e.sent(),this.ready.resolve(!0),[2]}}))}))},s.prototype.query=function(t){var n,r=t.sql,i=t.params;return e.__awaiter(this,void 0,void 0,(function(){var t;return e.__generator(this,(function(e){switch(e.label){case 0:return[4,this.ready];case 1:return e.sent(),[4,this.db.query(r,i).then((function(e){return e.values||[]}))];case 2:return t=e.sent(),this.debug?(console.groupCollapsed("💾 SQL: ".concat(r.trimStart().replaceAll(/\n/g," ").replaceAll(/\s+/g," ").substring(0,30),"...")),console.debug(r,i,t),console.groupEnd(),[4,null===(n=this.sqliteConnection)||void 0===n?void 0:n.saveToStore(this.name)]):[3,4];case 3:e.sent(),e.label=4;case 4:return[2,t]}}))}))},s.prototype.export=function(){return e.__awaiter(this,void 0,void 0,(function(){var t,n;return e.__generator(this,(function(e){switch(e.label){case 0:return this.isWeb?(t=this.name,[2,new Promise((function(e){indexedDB.open("jeepSqliteStore").onsuccess=function(n){n.target.result.transaction(["databases"],"readwrite").objectStore("databases").get("".concat(t,"SQLite.db")).onsuccess=function(t){var n=new Blob([t.target.result],{type:"application/vnd.sqlite3"});e(n)}}}))]):[4,this.db.getUrl()];case 1:return n=e.sent().url,[4,fetch(r.Capacitor.convertFileSrc(n))];case 2:return[2,e.sent().blob()]}}))}))},s.prototype.import=function(t){return e.__awaiter(this,void 0,void 0,(function(){var n,r,s,o,a;return e.__generator(this,(function(e){switch(e.label){case 0:return this.isWeb?(r=Uint8Array.bind,[4,t.arrayBuffer()]):[3,2];case 1:return n=new(r.apply(Uint8Array,[void 0,e.sent()])),s=this.name,new Promise((function(e){indexedDB.open("jeepSqliteStore").onsuccess=function(t){t.target.result.transaction(["databases"],"readwrite").objectStore("databases").put(n,"".concat(s,"SQLite.db"),0).onsuccess=function(){return e()}}})),[2];case 2:return[4,this.db.getUrl()];case 3:return o=e.sent().url,[4,new Promise((function(e){var n=new FileReader;n.onload=e,n.readAsDataURL(t)})).then((function(e){return e.target.result}))];case 4:return a=e.sent(),[4,i.Filesystem.writeFile({path:o,data:a})];case 5:return e.sent(),[2]}}))}))},s}();exports.default=a;
1
+ 'use strict';
2
+
3
+ Object.defineProperty(exports, '__esModule', { value: true });
4
+
5
+ var tslib = require('tslib');
6
+ var loader = require('jeep-sqlite/loader');
7
+ var sqlite = require('@capacitor-community/sqlite');
8
+ var core = require('@capacitor/core');
9
+ var filesystem = require('@capacitor/filesystem');
10
+ var utils = require('@flumens/utils');
11
+
12
+ var SQLiteDatabase = /** @class */ (function () {
13
+ function SQLiteDatabase(_a) {
14
+ var name = _a.name, debug = _a.debug, web = _a.web;
15
+ this.sqliteConnection = new sqlite.SQLiteConnection(sqlite.CapacitorSQLite);
16
+ this.name = 'main';
17
+ this.debug = false;
18
+ this.isWeb = false;
19
+ this.ready = new utils.Deferred();
20
+ this.name = name || this.name;
21
+ this.debug = debug || this.debug;
22
+ this.isWeb = web || this.isWeb;
23
+ }
24
+ SQLiteDatabase.migrateCordova = function (isIOS) {
25
+ return tslib.__awaiter(this, void 0, void 0, function () {
26
+ var sqliteConnection, res, error_1;
27
+ var _a;
28
+ return tslib.__generator(this, function (_b) {
29
+ switch (_b.label) {
30
+ case 0:
31
+ console.log('SQLite: Cordova db migration');
32
+ sqliteConnection = new sqlite.SQLiteConnection(sqlite.CapacitorSQLite);
33
+ _b.label = 1;
34
+ case 1:
35
+ _b.trys.push([1, 5, , 6]);
36
+ return [4 /*yield*/, sqliteConnection.getMigratableDbList(isIOS ? 'Library/LocalDatabase' : undefined)];
37
+ case 2:
38
+ res = _b.sent();
39
+ if (!((_a = res.values) === null || _a === void 0 ? void 0 : _a.length)) {
40
+ console.log('SQLite: no Cordova db to migrate');
41
+ return [2 /*return*/];
42
+ }
43
+ console.log('SQLite: migrating', res.values);
44
+ return [4 /*yield*/, sqliteConnection.addSQLiteSuffix(isIOS ? 'Library/LocalDatabase' : undefined, res.values)];
45
+ case 3:
46
+ _b.sent();
47
+ return [4 /*yield*/, sqliteConnection.deleteOldDatabases(isIOS ? 'Library/LocalDatabase' : undefined, res.values)];
48
+ case 4:
49
+ _b.sent();
50
+ console.log('SQLite: migrating done', res.values);
51
+ return [3 /*break*/, 6];
52
+ case 5:
53
+ error_1 = _b.sent();
54
+ console.error(error_1);
55
+ return [3 /*break*/, 6];
56
+ case 6: return [4 /*yield*/, sqliteConnection.checkConnectionsConsistency()];
57
+ case 7:
58
+ _b.sent();
59
+ return [4 /*yield*/, sqliteConnection.closeAllConnections()];
60
+ case 8:
61
+ _b.sent();
62
+ return [2 /*return*/];
63
+ }
64
+ });
65
+ });
66
+ };
67
+ Object.defineProperty(SQLiteDatabase.prototype, "db", {
68
+ get: function () {
69
+ return this.connection;
70
+ },
71
+ enumerable: false,
72
+ configurable: true
73
+ });
74
+ SQLiteDatabase.prototype.init = function () {
75
+ return tslib.__awaiter(this, void 0, void 0, function () {
76
+ var jeepSqlite, _a;
77
+ return tslib.__generator(this, function (_b) {
78
+ switch (_b.label) {
79
+ case 0:
80
+ if (!this.isWeb) return [3 /*break*/, 3];
81
+ loader.defineCustomElements(window);
82
+ jeepSqlite = document.createElement('jeep-sqlite');
83
+ jeepSqlite.setAttribute('autoSave', 'true');
84
+ document.body.appendChild(jeepSqlite);
85
+ return [4 /*yield*/, customElements.whenDefined('jeep-sqlite')];
86
+ case 1:
87
+ _b.sent();
88
+ return [4 /*yield*/, this.sqliteConnection.initWebStore()];
89
+ case 2:
90
+ _b.sent();
91
+ _b.label = 3;
92
+ case 3: return [4 /*yield*/, this.sqliteConnection.checkConnectionsConsistency()];
93
+ case 4:
94
+ _b.sent();
95
+ return [4 /*yield*/, this.sqliteConnection.closeAllConnections()];
96
+ case 5:
97
+ _b.sent();
98
+ _a = this;
99
+ return [4 /*yield*/, this.sqliteConnection.createConnection(this.name, false, 'no-encryption', 1, false)];
100
+ case 6:
101
+ _a.connection = _b.sent();
102
+ return [4 /*yield*/, this.connection.open()];
103
+ case 7:
104
+ _b.sent();
105
+ this.ready.resolve(true);
106
+ return [2 /*return*/];
107
+ }
108
+ });
109
+ });
110
+ };
111
+ SQLiteDatabase.prototype.query = function (_a) {
112
+ return tslib.__awaiter(this, arguments, void 0, function (_b) {
113
+ var res;
114
+ var _c;
115
+ var sql = _b.sql, params = _b.params;
116
+ return tslib.__generator(this, function (_d) {
117
+ switch (_d.label) {
118
+ case 0: return [4 /*yield*/, this.ready];
119
+ case 1:
120
+ _d.sent();
121
+ return [4 /*yield*/, this.db.query(sql, params).then(function (r) { return r.values || []; })];
122
+ case 2:
123
+ res = _d.sent();
124
+ if (!this.debug) return [3 /*break*/, 4];
125
+ console.groupCollapsed("\uD83D\uDCBE SQL: ".concat(sql
126
+ .trimStart()
127
+ .replaceAll(/\n/g, ' ')
128
+ .replaceAll(/\s+/g, ' ')
129
+ .substring(0, 30), "..."));
130
+ console.debug(sql, params, res);
131
+ console.groupEnd();
132
+ return [4 /*yield*/, ((_c = this.sqliteConnection) === null || _c === void 0 ? void 0 : _c.saveToStore(this.name))];
133
+ case 3:
134
+ _d.sent();
135
+ _d.label = 4;
136
+ case 4: return [2 /*return*/, res];
137
+ }
138
+ });
139
+ });
140
+ };
141
+ SQLiteDatabase.prototype.export = function () {
142
+ return tslib.__awaiter(this, void 0, void 0, function () {
143
+ var name_1, url, res;
144
+ return tslib.__generator(this, function (_a) {
145
+ switch (_a.label) {
146
+ case 0:
147
+ if (this.isWeb) {
148
+ name_1 = this.name;
149
+ return [2 /*return*/, new Promise(function (resolve) {
150
+ var request = indexedDB.open('jeepSqliteStore');
151
+ request.onsuccess = function (event) {
152
+ var getRequest = event.target.result
153
+ .transaction(['databases'], 'readwrite')
154
+ .objectStore('databases')
155
+ .get("".concat(name_1, "SQLite.db"));
156
+ getRequest.onsuccess = function (e) {
157
+ var blob = new Blob([e.target.result], {
158
+ type: 'application/vnd.sqlite3',
159
+ });
160
+ resolve(blob);
161
+ };
162
+ };
163
+ })];
164
+ }
165
+ return [4 /*yield*/, this.db.getUrl()];
166
+ case 1:
167
+ url = (_a.sent()).url;
168
+ return [4 /*yield*/, fetch(core.Capacitor.convertFileSrc(url))];
169
+ case 2:
170
+ res = _a.sent();
171
+ return [2 /*return*/, res.blob()];
172
+ }
173
+ });
174
+ });
175
+ };
176
+ SQLiteDatabase.prototype.import = function (blob) {
177
+ return tslib.__awaiter(this, void 0, void 0, function () {
178
+ var arr_1, _a, name_2, url, dataURI;
179
+ return tslib.__generator(this, function (_b) {
180
+ switch (_b.label) {
181
+ case 0:
182
+ if (!this.isWeb) return [3 /*break*/, 2];
183
+ _a = Uint8Array.bind;
184
+ return [4 /*yield*/, blob.arrayBuffer()];
185
+ case 1:
186
+ arr_1 = new (_a.apply(Uint8Array, [void 0, _b.sent()]))();
187
+ name_2 = this.name;
188
+ // eslint-disable-next-line no-new
189
+ new Promise(function (resolve) {
190
+ var request = indexedDB.open('jeepSqliteStore');
191
+ request.onsuccess = function (event) {
192
+ var getRequest = event.target.result
193
+ .transaction(['databases'], 'readwrite')
194
+ .objectStore('databases')
195
+ .put(arr_1, "".concat(name_2, "SQLite.db"), 0);
196
+ getRequest.onsuccess = function () { return resolve(); };
197
+ };
198
+ });
199
+ return [2 /*return*/];
200
+ case 2: return [4 /*yield*/, this.db.getUrl()];
201
+ case 3:
202
+ url = (_b.sent()).url;
203
+ return [4 /*yield*/, new Promise(function (r) {
204
+ var a = new FileReader();
205
+ a.onload = r;
206
+ a.readAsDataURL(blob);
207
+ }).then(function (e) { return e.target.result; })];
208
+ case 4:
209
+ dataURI = _b.sent();
210
+ return [4 /*yield*/, filesystem.Filesystem.writeFile({ path: url, data: dataURI })];
211
+ case 5:
212
+ _b.sent();
213
+ return [2 /*return*/];
214
+ }
215
+ });
216
+ });
217
+ };
218
+ return SQLiteDatabase;
219
+ }());
220
+
221
+ exports["default"] = SQLiteDatabase;
@@ -1,9 +1,9 @@
1
1
  import { BuildColumns, ColumnBuilderBase, ColumnBuilderBaseConfig, ColumnDataType, InferModelFromColumns, SQL } from 'drizzle-orm';
2
2
  import { SQLiteSelect, SQLiteDelete, SQLiteTable } from 'drizzle-orm/sqlite-core';
3
- import Deferred from '@flumens/utils/dist/deferred';
3
+ import { Deferred } from '@flumens/utils';
4
4
  import SQLiteDatabase from './SQLiteDatabase';
5
5
  import Store from './Store';
6
- export declare function conflictUpdateAllExcept<T extends SQLiteTable, E extends (keyof T['$inferInsert'])[]>(table: T, except: E): Omit<Record<string | number, SQL<unknown>>, E[number]>;
6
+ export declare function conflictUpdateAllExcept<T extends SQLiteTable, E extends (keyof T['$inferInsert'])[]>(table: T, except: E): Omit<Record<keyof typeof table.$inferInsert, SQL>, E[number]>;
7
7
  export declare const jsonb: <TData>(name: string) => import("drizzle-orm/sqlite-core").SQLiteCustomColumnBuilder<{
8
8
  name: string;
9
9
  dataType: "custom";
@@ -11,7 +11,6 @@ export declare const jsonb: <TData>(name: string) => import("drizzle-orm/sqlite-
11
11
  data: TData;
12
12
  driverParam: string;
13
13
  enumValues: undefined;
14
- generated: undefined;
15
14
  }>;
16
15
  type SQLiteStoreOptions = {
17
16
  db: SQLiteDatabase;
@@ -20,8 +19,8 @@ type SQLiteStoreOptions = {
20
19
  columns?: any;
21
20
  };
22
21
  export declare const defaultCols: () => {
23
- id: import("drizzle-orm/sqlite-core").SQLiteTextBuilderInitial<"", [string, ...string[]]>;
24
- cid: import("drizzle-orm").HasDefault<import("drizzle-orm").NotNull<import("drizzle-orm").IsPrimaryKey<import("drizzle-orm").NotNull<import("drizzle-orm/sqlite-core").SQLiteTextBuilderInitial<"", [string, ...string[]]>>>>>;
22
+ id: import("drizzle-orm/sqlite-core").SQLiteTextBuilderInitial<"", [string, ...string[]], undefined>;
23
+ cid: import("drizzle-orm").HasDefault<import("drizzle-orm").NotNull<import("drizzle-orm").IsPrimaryKey<import("drizzle-orm").NotNull<import("drizzle-orm/sqlite-core").SQLiteTextBuilderInitial<"", [string, ...string[]], undefined>>>>>;
25
24
  data: import("drizzle-orm").NotNull<import("drizzle-orm/sqlite-core").SQLiteCustomColumnBuilder<{
26
25
  name: string;
27
26
  dataType: "custom";
@@ -29,7 +28,6 @@ export declare const defaultCols: () => {
29
28
  data: any;
30
29
  driverParam: string;
31
30
  enumValues: undefined;
32
- generated: undefined;
33
31
  }>>;
34
32
  createdAt: import("drizzle-orm").NotNull<import("drizzle-orm/sqlite-core").SQLiteIntegerBuilderInitial<"created_at">>;
35
33
  updatedAt: import("drizzle-orm").NotNull<import("drizzle-orm/sqlite-core").SQLiteIntegerBuilderInitial<"updated_at">>;
@@ -1 +1,310 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var t=require("tslib"),e=require("drizzle-orm"),r=require("drizzle-orm/casing"),n=require("drizzle-orm/sqlite-core"),i=require("@flumens/utils/dist/deferred"),a=require("./utils.js");function s(t){return t&&"object"==typeof t&&"default"in t?t:{default:t}}var o=s(i);function u(r,n){var i=e.getTableColumns(r);return Object.entries(i).filter((function(t){var e=t[0];return!n.includes(e)})).reduce((function(r,n){var i,a=n[0],s=n[1];return t.__assign(t.__assign({},r),((i={})[a]=e.sql.raw("excluded.".concat(s.name)),i))}),{})}var c=function(t){return n.customType({dataType:function(){return"jsonb"},toDriver:function(t){return JSON.stringify(t)}})(t)},d=new n.SQLiteSyncDialect,l=function(){return{id:n.text(),cid:n.text().primaryKey().notNull().default("id"),data:c("data").notNull(),createdAt:n.integer("created_at").notNull(),updatedAt:n.integer("updated_at").notNull(),syncedAt:n.integer("synced_at")}},f=function(){function i(t){var e=t.db,r=t.name,i=t.debug,a=t.columns,s=void 0===a?l():a;this.ready=new o.default,this.db=e,this.name=r,this.debug=i||!1,this.table=n.sqliteTable(this.name,s),this.init()}return i.prototype.init=function(){return t.__awaiter(this,void 0,void 0,(function(){var e,r;return t.__generator(this,(function(t){switch(t.label){case 0:return[4,this.db.ready];case 1:return t.sent(),e=function(t){return"".concat(t.name," ").concat(t.getSQLType()).concat(t.primary?" primary key":"").concat(t.notNull?" not null":"").concat(t.default?" default ".concat(t.default):"")},r=n.getTableConfig(this.table).columns.map(e).join(",\n"),[4,this.db.query({sql:"CREATE TABLE IF NOT EXISTS ".concat(this.name," (").concat(r,");")})];case 2:return t.sent(),this.ready.resolve(!0),[2]}}))}))},i.prototype.save=function(e){return t.__awaiter(this,void 0,void 0,(function(){var r,i,s;return t.__generator(this,(function(t){switch(t.label){case 0:return[4,this.ready];case 1:return t.sent(),(Array.isArray(e)?e.length:e)?this.debug&&e.cid?[4,this.find({cid:e.cid})]:[3,3]:[2];case 2:r=t.sent(),a.printDiff(r,e,e.cid,this.name),t.label=3;case 3:return i=new n.SQLiteInsertBuilder(this.table,{},d).values(e),(s=this._getPrimaryCol())&&(i=i.onConflictDoUpdate({target:s,set:u(this.table,[])})),[4,this.db.query(i.toSQL())];case 4:return t.sent(),[2]}}))}))},i.prototype.find=function(r){return t.__awaiter(this,void 0,void 0,(function(){var n,i=this;return t.__generator(this,(function(t){switch(t.label){case 0:return[4,this.ready];case 1:return t.sent(),n=function(t){if("function"==typeof r)return r(t).limit(1);if("string"==typeof r){var n=i._getPrimaryCol();if(!n)throw new Error("Primary col is missing");return t.where(e.eq(n,r)).limit(1)}var a=Object.entries(r).map((function(t){var r=t[0],n=t[1];return e.eq(i.table[r],n)}));return t.where(e.and.apply(void 0,a)).limit(1)},[4,this.findAll(n)];case 2:return[2,t.sent()[0]]}}))}))},i.prototype.findAll=function(i){return t.__awaiter(this,void 0,void 0,(function(){var a,s,o,u=this;return t.__generator(this,(function(t){switch(t.label){case 0:return[4,this.ready];case 1:return t.sent(),a=(new n.QueryBuilder).select().from(this.table),i&&(a=i(a)),[4,this.db.query(a.toSQL())];case 2:return s=t.sent(),o=function(t){return Object.entries(t).reduce((function(t,n){var i,a=n[0],s=n[1],o="jsonb"===(null===(i=e.getTableColumns(u.table)[a])||void 0===i?void 0:i.sqlName);return t[r.toCamelCase(a)]=o?JSON.parse(s):s,t}),{})},[2,s.map(o)]}}))}))},i.prototype.delete=function(r){return t.__awaiter(this,void 0,void 0,(function(){var n,i=this;return t.__generator(this,(function(t){switch(t.label){case 0:return[4,this.ready];case 1:return t.sent(),n=function(t){if("function"==typeof r)return r(t);if("string"==typeof r){var n=i._getPrimaryCol();if(!n)throw new Error("Primary col is missing");return t.where(e.eq(n,r))}var a=Object.entries(r).map((function(t){var r=t[0],n=t[1];return e.eq(i.table[r],n)}));return t.where(e.and.apply(void 0,a))},[4,this.deleteAll(n)];case 2:return t.sent(),[2]}}))}))},i.prototype.deleteAll=function(e){return t.__awaiter(this,void 0,void 0,(function(){var r;return t.__generator(this,(function(t){switch(t.label){case 0:return[4,this.ready];case 1:return t.sent(),r=new n.SQLiteDeleteBase(this.table,{},d),e&&(r=e(r)),[4,this.db.query(r.toSQL())];case 2:return t.sent(),[2]}}))}))},i.prototype.export=function(){return t.__awaiter(this,void 0,void 0,(function(){var e;return t.__generator(this,(function(r){switch(r.label){case 0:return[4,this.ready];case 1:return r.sent(),e=function(e,r){var n;return t.__assign(t.__assign({},e),((n={})[r.cid]=r,n))},[4,this.findAll()];case 2:return[2,r.sent().reduce(e,{})]}}))}))},i.prototype.import=function(e){return t.__awaiter(this,void 0,void 0,(function(){var r,n,i=this;return t.__generator(this,(function(a){switch(a.label){case 0:return[4,this.ready];case 1:return a.sent(),[4,this.deleteAll()];case 2:if(a.sent(),"object"!=typeof e)throw new Error("Invalid obj passed to store");return r=function(e){var r,n,i,a,s,o;if(!e.createdAt&&(null===(r=e.metadata)||void 0===r?void 0:r.createdOn)&&(e.createdAt=null===(n=e.metadata)||void 0===n?void 0:n.createdOn),!e.updatedAt&&(null===(i=e.metadata)||void 0===i?void 0:i.updatedOn)&&(e.updatedAt=null===(a=e.metadata)||void 0===a?void 0:a.updatedOn),!e.syncedAt&&(null===(s=e.metadata)||void 0===s?void 0:s.syncedOn)&&(e.syncedAt=null===(o=e.metadata)||void 0===o?void 0:o.syncedOn),e.samples){var u=e.id,c=e.cid,d=e.createdAt,l=e.updatedAt,f=e.syncedAt,h=t.__rest(e,["id","cid","createdAt","updatedAt","syncedAt"]);e={id:u,cid:c,createdAt:d,updatedAt:l,syncedAt:f,data:t.__assign({},h)}}return e},n=Object.entries(e).map((function(t){var e=t[1];return i.save(r(e))})),Promise.all(n),[2]}}))}))},i.prototype._getPrimaryCol=function(){return Object.values(e.getTableColumns(this.table)).find((function(t){return!!t.primary}))},i}();exports.conflictUpdateAllExcept=u,exports.default=f,exports.defaultCols=l,exports.jsonb=c;
1
+ 'use strict';
2
+
3
+ Object.defineProperty(exports, '__esModule', { value: true });
4
+
5
+ var tslib = require('tslib');
6
+ var drizzleOrm = require('drizzle-orm');
7
+ var casing = require('drizzle-orm/casing');
8
+ var sqliteCore = require('drizzle-orm/sqlite-core');
9
+ var utils$1 = require('@flumens/utils');
10
+ var utils = require('./utils.js');
11
+
12
+ // From https://github.com/drizzle-team/drizzle-orm/issues/1728
13
+ function conflictUpdateAllExcept(table, except) {
14
+ var columns = drizzleOrm.getTableColumns(table);
15
+ var updateColumns = Object.entries(columns).filter(function (_a) {
16
+ var col = _a[0];
17
+ return !except.includes(col);
18
+ });
19
+ return updateColumns.reduce(function (acc, _a) {
20
+ var _b;
21
+ var colName = _a[0], tbl = _a[1];
22
+ return (tslib.__assign(tslib.__assign({}, acc), (_b = {}, _b[colName] = drizzleOrm.sql.raw("excluded.".concat(tbl.name)), _b)));
23
+ }, {});
24
+ }
25
+ var jsonb = function (name) {
26
+ return sqliteCore.customType({
27
+ dataType: function () { return 'jsonb'; },
28
+ toDriver: function (value) { return JSON.stringify(value); },
29
+ })(name);
30
+ };
31
+ var dialect = new sqliteCore.SQLiteSyncDialect();
32
+ var defaultCols = function () { return ({
33
+ id: sqliteCore.text(),
34
+ cid: sqliteCore.text().primaryKey().notNull().default('id'),
35
+ data: jsonb('data').notNull(),
36
+ createdAt: sqliteCore.integer('created_at').notNull(),
37
+ updatedAt: sqliteCore.integer('updated_at').notNull(),
38
+ syncedAt: sqliteCore.integer('synced_at'),
39
+ }); };
40
+ var SQLiteStore = /** @class */ (function () {
41
+ function SQLiteStore(_a) {
42
+ var db = _a.db, name = _a.name, debug = _a.debug, _b = _a.columns, columns = _b === void 0 ? defaultCols() : _b;
43
+ this.ready = new utils$1.Deferred();
44
+ this.db = db;
45
+ this.name = name;
46
+ this.debug = debug || false;
47
+ this.table = sqliteCore.sqliteTable(this.name, columns);
48
+ this.init();
49
+ }
50
+ SQLiteStore.prototype.init = function () {
51
+ return tslib.__awaiter(this, void 0, void 0, function () {
52
+ var getColumn, cols;
53
+ return tslib.__generator(this, function (_a) {
54
+ switch (_a.label) {
55
+ case 0: return [4 /*yield*/, this.db.ready];
56
+ case 1:
57
+ _a.sent();
58
+ getColumn = function (col) {
59
+ return "".concat(col.name, " ").concat(col.getSQLType()).concat(col.primary ? ' primary key' : '').concat(col.notNull ? ' not null' : '').concat(col.default ? " default ".concat(col.default) : '');
60
+ };
61
+ cols = sqliteCore.getTableConfig(this.table).columns.map(getColumn).join(',\n');
62
+ return [4 /*yield*/, this.db.query({
63
+ sql: "CREATE TABLE IF NOT EXISTS ".concat(this.name, " (").concat(cols, ");"),
64
+ })];
65
+ case 2:
66
+ _a.sent();
67
+ this.ready.resolve(true);
68
+ return [2 /*return*/];
69
+ }
70
+ });
71
+ });
72
+ };
73
+ SQLiteStore.prototype.save = function (values) {
74
+ return tslib.__awaiter(this, void 0, void 0, function () {
75
+ var hasValues, currentVal, query, primary;
76
+ return tslib.__generator(this, function (_a) {
77
+ switch (_a.label) {
78
+ case 0: return [4 /*yield*/, this.ready];
79
+ case 1:
80
+ _a.sent();
81
+ hasValues = Array.isArray(values) ? values.length : values;
82
+ if (!hasValues)
83
+ return [2 /*return*/];
84
+ if (!(this.debug && values.cid)) return [3 /*break*/, 3];
85
+ return [4 /*yield*/, this.find({ cid: values.cid })];
86
+ case 2:
87
+ currentVal = _a.sent();
88
+ utils.printDiff(currentVal, values, values.cid, this.name);
89
+ _a.label = 3;
90
+ case 3:
91
+ query = new sqliteCore.SQLiteInsertBuilder(this.table, {}, dialect).values(values);
92
+ primary = this._getPrimaryCol();
93
+ if (primary)
94
+ query = query.onConflictDoUpdate({
95
+ target: primary,
96
+ set: conflictUpdateAllExcept(this.table, []),
97
+ });
98
+ return [4 /*yield*/, this.db.query(query.toSQL())];
99
+ case 4:
100
+ _a.sent();
101
+ return [2 /*return*/];
102
+ }
103
+ });
104
+ });
105
+ };
106
+ SQLiteStore.prototype.find = function (q) {
107
+ return tslib.__awaiter(this, void 0, void 0, function () {
108
+ var findOne, value;
109
+ var _this = this;
110
+ return tslib.__generator(this, function (_a) {
111
+ switch (_a.label) {
112
+ case 0: return [4 /*yield*/, this.ready];
113
+ case 1:
114
+ _a.sent();
115
+ findOne = function (query) {
116
+ if (typeof q === 'function')
117
+ return q(query).limit(1);
118
+ if (typeof q === 'string') {
119
+ var primary = _this._getPrimaryCol();
120
+ if (!primary)
121
+ throw new Error('Primary col is missing');
122
+ return query.where(drizzleOrm.eq(primary, q)).limit(1);
123
+ }
124
+ var where = Object.entries(q).map(function (_a) {
125
+ var col = _a[0], val = _a[1];
126
+ return drizzleOrm.eq(_this.table[col], val);
127
+ });
128
+ return query.where(drizzleOrm.and.apply(void 0, where)).limit(1);
129
+ };
130
+ return [4 /*yield*/, this.findAll(findOne)];
131
+ case 2:
132
+ value = (_a.sent())[0];
133
+ return [2 /*return*/, value];
134
+ }
135
+ });
136
+ });
137
+ };
138
+ SQLiteStore.prototype.findAll = function (q) {
139
+ return tslib.__awaiter(this, void 0, void 0, function () {
140
+ var query, values, getCamelCaseAndParseJSON;
141
+ var _this = this;
142
+ return tslib.__generator(this, function (_a) {
143
+ switch (_a.label) {
144
+ case 0: return [4 /*yield*/, this.ready];
145
+ case 1:
146
+ _a.sent();
147
+ query = new sqliteCore.QueryBuilder()
148
+ .select()
149
+ .from(this.table);
150
+ if (q)
151
+ query = q(query);
152
+ return [4 /*yield*/, this.db.query(query.toSQL())];
153
+ case 2:
154
+ values = _a.sent();
155
+ getCamelCaseAndParseJSON = function (val) {
156
+ return Object.entries(val).reduce(function (agg, _a) {
157
+ var _b;
158
+ var key = _a[0], v = _a[1];
159
+ var isJSONType = ((_b = drizzleOrm.getTableColumns(_this.table)[key]) === null || _b === void 0 ? void 0 : _b.sqlName) === 'jsonb';
160
+ if (isJSONType) {
161
+ agg[casing.toCamelCase(key)] = JSON.parse(v);
162
+ }
163
+ else {
164
+ agg[casing.toCamelCase(key)] = v;
165
+ }
166
+ return agg;
167
+ }, {});
168
+ };
169
+ return [2 /*return*/, values.map(getCamelCaseAndParseJSON)];
170
+ }
171
+ });
172
+ });
173
+ };
174
+ SQLiteStore.prototype.delete = function (q) {
175
+ return tslib.__awaiter(this, void 0, void 0, function () {
176
+ var deleteOne;
177
+ var _this = this;
178
+ return tslib.__generator(this, function (_a) {
179
+ switch (_a.label) {
180
+ case 0: return [4 /*yield*/, this.ready];
181
+ case 1:
182
+ _a.sent();
183
+ deleteOne = function (query) {
184
+ // TODO: to delete only one https://stackoverflow.com/questions/1824490/how-do-you-enable-limit-for-delete-in-sqlite
185
+ if (typeof q === 'function')
186
+ return q(query);
187
+ if (typeof q === 'string') {
188
+ var primary = _this._getPrimaryCol();
189
+ if (!primary)
190
+ throw new Error('Primary col is missing');
191
+ return query.where(drizzleOrm.eq(primary, q));
192
+ }
193
+ var where = Object.entries(q).map(function (_a) {
194
+ var col = _a[0], val = _a[1];
195
+ return drizzleOrm.eq(_this.table[col], val);
196
+ });
197
+ return query.where(drizzleOrm.and.apply(void 0, where));
198
+ };
199
+ return [4 /*yield*/, this.deleteAll(deleteOne)];
200
+ case 2:
201
+ _a.sent();
202
+ return [2 /*return*/];
203
+ }
204
+ });
205
+ });
206
+ };
207
+ SQLiteStore.prototype.deleteAll = function (q) {
208
+ return tslib.__awaiter(this, void 0, void 0, function () {
209
+ var query;
210
+ return tslib.__generator(this, function (_a) {
211
+ switch (_a.label) {
212
+ case 0: return [4 /*yield*/, this.ready];
213
+ case 1:
214
+ _a.sent();
215
+ query = new sqliteCore.SQLiteDeleteBase(this.table, {}, dialect);
216
+ if (q)
217
+ query = q(query);
218
+ return [4 /*yield*/, this.db.query(query.toSQL())];
219
+ case 2:
220
+ _a.sent();
221
+ return [2 /*return*/];
222
+ }
223
+ });
224
+ });
225
+ };
226
+ /**
227
+ * Exports all objects from the store.
228
+ */
229
+ SQLiteStore.prototype.export = function () {
230
+ return tslib.__awaiter(this, void 0, void 0, function () {
231
+ var addCIDs;
232
+ return tslib.__generator(this, function (_a) {
233
+ switch (_a.label) {
234
+ case 0: return [4 /*yield*/, this.ready];
235
+ case 1:
236
+ _a.sent();
237
+ addCIDs = function (agg, val) {
238
+ var _a;
239
+ return (tslib.__assign(tslib.__assign({}, agg), (_a = {}, _a[val.cid] = val, _a)));
240
+ };
241
+ return [4 /*yield*/, this.findAll()];
242
+ case 2: return [2 /*return*/, (_a.sent()).reduce(addCIDs, {})];
243
+ }
244
+ });
245
+ });
246
+ };
247
+ /**
248
+ * Imports objects to store.
249
+ */
250
+ SQLiteStore.prototype.import = function (obj) {
251
+ return tslib.__awaiter(this, void 0, void 0, function () {
252
+ var getBackwardsCompVal, savingAll;
253
+ var _this = this;
254
+ return tslib.__generator(this, function (_a) {
255
+ switch (_a.label) {
256
+ case 0: return [4 /*yield*/, this.ready];
257
+ case 1:
258
+ _a.sent();
259
+ return [4 /*yield*/, this.deleteAll()];
260
+ case 2:
261
+ _a.sent();
262
+ if (typeof obj !== 'object')
263
+ throw new Error('Invalid obj passed to store');
264
+ getBackwardsCompVal = function (val) {
265
+ var _a, _b, _c, _d, _e, _f;
266
+ if (!val.createdAt && ((_a = val.metadata) === null || _a === void 0 ? void 0 : _a.createdOn)) {
267
+ val.createdAt = (_b = val.metadata) === null || _b === void 0 ? void 0 : _b.createdOn;
268
+ }
269
+ if (!val.updatedAt && ((_c = val.metadata) === null || _c === void 0 ? void 0 : _c.updatedOn)) {
270
+ val.updatedAt = (_d = val.metadata) === null || _d === void 0 ? void 0 : _d.updatedOn;
271
+ }
272
+ if (!val.syncedAt && ((_e = val.metadata) === null || _e === void 0 ? void 0 : _e.syncedOn)) {
273
+ val.syncedAt = (_f = val.metadata) === null || _f === void 0 ? void 0 : _f.syncedOn;
274
+ }
275
+ if (val.samples) {
276
+ var id = val.id, cid = val.cid, createdAt = val.createdAt, updatedAt = val.updatedAt, syncedAt = val.syncedAt, restVal = tslib.__rest(val, ["id", "cid", "createdAt", "updatedAt", "syncedAt"]);
277
+ val = {
278
+ id: id,
279
+ cid: cid,
280
+ createdAt: createdAt,
281
+ updatedAt: updatedAt,
282
+ syncedAt: syncedAt,
283
+ data: tslib.__assign({}, restVal),
284
+ };
285
+ }
286
+ return val;
287
+ };
288
+ savingAll = Object.entries(obj).map(function (_a) {
289
+ var val = _a[1];
290
+ return _this.save(getBackwardsCompVal(val));
291
+ });
292
+ Promise.all(savingAll);
293
+ return [2 /*return*/];
294
+ }
295
+ });
296
+ });
297
+ };
298
+ SQLiteStore.prototype._getPrimaryCol = function () {
299
+ return Object.values(drizzleOrm.getTableColumns(this.table)).find(function (_a) {
300
+ var primary = _a.primary;
301
+ return !!primary;
302
+ });
303
+ };
304
+ return SQLiteStore;
305
+ }());
306
+
307
+ exports.conflictUpdateAllExcept = conflictUpdateAllExcept;
308
+ exports["default"] = SQLiteStore;
309
+ exports.defaultCols = defaultCols;
310
+ exports.jsonb = jsonb;
@@ -1 +1,11 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=function(){};exports.default=e;
1
+ 'use strict';
2
+
3
+ Object.defineProperty(exports, '__esModule', { value: true });
4
+
5
+ var Store = /** @class */ (function () {
6
+ function Store() {
7
+ }
8
+ return Store;
9
+ }());
10
+
11
+ exports["default"] = Store;
@@ -1 +1,60 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var o=require("deep-diff"),r=require("lodash");exports.printDiff=function(e,n,c,t){void 0===t&&(t="");var a=o.diff(e,n);if(a){var i={},l=0,s="";if(a.forEach((function(o){var e,n,a=((e={})[t]=((n={})[c]={},n),e);if(!o.path)return a[t][c]=o.rhs,console.groupCollapsed("Δ + ".concat(c)),console.log(a),void console.groupEnd();o.path.reduce((function(r,e,n){if(o.path.length-1>n)return r[e]={},r[e];var c=JSON.stringify(o.lhs,null,2),t=JSON.stringify(o.rhs,null,2);if(c===t)return r[e];l++,r[e]="".concat(c," -> ").concat(t),s="".concat(e,": ").concat(c," -> ").concat(t)}),a[t][c]),i=r.merge(i,a)})),l){var f="Δ ".concat(c);1===l&&(f+=" ".concat(s)),console.groupCollapsed(f),console.log(i),console.groupEnd()}}};
1
+ 'use strict';
2
+
3
+ Object.defineProperty(exports, '__esModule', { value: true });
4
+
5
+ var deepDiff = require('deep-diff');
6
+ var lodash = require('lodash');
7
+
8
+ // DEVELOPMENT ONLY
9
+ /* eslint-disable */
10
+ function printDiff(currentVal, val, cid, name) {
11
+ if (name === void 0) { name = ''; }
12
+ var delta = deepDiff.diff(currentVal, val);
13
+ if (!delta) {
14
+ return;
15
+ }
16
+ var allAggs = {};
17
+ var diffDetected = 0;
18
+ var lastDiffStr = '';
19
+ delta.forEach(function (difference) {
20
+ var _a, _b;
21
+ var agg = (_a = {},
22
+ _a[name] = (_b = {},
23
+ _b[cid] = {},
24
+ _b),
25
+ _a);
26
+ if (!difference.path) {
27
+ agg[name][cid] = difference.rhs;
28
+ console.groupCollapsed("\u0394 + ".concat(cid));
29
+ console.log(agg);
30
+ console.groupEnd();
31
+ return;
32
+ }
33
+ difference.path.reduce(function (a, aKey, i) {
34
+ if (difference.path.length - 1 > i) {
35
+ a[aKey] = {};
36
+ return a[aKey];
37
+ }
38
+ var leftStr = JSON.stringify(difference.lhs, null, 2);
39
+ var rightStr = JSON.stringify(difference.rhs, null, 2);
40
+ if (leftStr === rightStr) {
41
+ return a[aKey];
42
+ }
43
+ diffDetected++;
44
+ a[aKey] = "".concat(leftStr, " -> ").concat(rightStr);
45
+ lastDiffStr = "".concat(aKey, ": ").concat(leftStr, " -> ").concat(rightStr);
46
+ }, agg[name][cid]);
47
+ allAggs = lodash.merge(allAggs, agg);
48
+ });
49
+ if (diffDetected) {
50
+ var groudName = "\u0394 ".concat(cid);
51
+ if (diffDetected === 1) {
52
+ groudName += " ".concat(lastDiffStr);
53
+ }
54
+ console.groupCollapsed(groudName);
55
+ console.log(allAggs);
56
+ console.groupEnd();
57
+ }
58
+ }
59
+
60
+ exports.printDiff = printDiff;