@argos-js/data 0.0.0-stage → 0.1.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 +21 -0
- package/README.md +799 -2
- package/dist/connection/index.d.ts +2 -0
- package/dist/connection/index.d.ts.map +1 -0
- package/dist/connection/index.js +18 -0
- package/dist/connection/index.js.map +1 -0
- package/dist/connection/manager.d.ts +93 -0
- package/dist/connection/manager.d.ts.map +1 -0
- package/dist/connection/manager.js +194 -0
- package/dist/connection/manager.js.map +1 -0
- package/dist/database.d.ts +29 -0
- package/dist/database.d.ts.map +1 -0
- package/dist/database.js +276 -0
- package/dist/database.js.map +1 -0
- package/dist/drivers/base-driver.d.ts +18 -0
- package/dist/drivers/base-driver.d.ts.map +1 -0
- package/dist/drivers/base-driver.js +211 -0
- package/dist/drivers/base-driver.js.map +1 -0
- package/dist/drivers/index.d.ts +11 -0
- package/dist/drivers/index.d.ts.map +1 -0
- package/dist/drivers/index.js +55 -0
- package/dist/drivers/index.js.map +1 -0
- package/dist/drivers/mavedb-edge.d.ts +8 -0
- package/dist/drivers/mavedb-edge.d.ts.map +1 -0
- package/dist/drivers/mavedb-edge.js +18 -0
- package/dist/drivers/mavedb-edge.js.map +1 -0
- package/dist/drivers/mongodb.d.ts +8 -0
- package/dist/drivers/mongodb.d.ts.map +1 -0
- package/dist/drivers/mongodb.js +18 -0
- package/dist/drivers/mongodb.js.map +1 -0
- package/dist/drivers/mssql.d.ts +8 -0
- package/dist/drivers/mssql.d.ts.map +1 -0
- package/dist/drivers/mssql.js +18 -0
- package/dist/drivers/mssql.js.map +1 -0
- package/dist/drivers/mysql.d.ts +8 -0
- package/dist/drivers/mysql.d.ts.map +1 -0
- package/dist/drivers/mysql.js +18 -0
- package/dist/drivers/mysql.js.map +1 -0
- package/dist/drivers/postgres.d.ts +8 -0
- package/dist/drivers/postgres.d.ts.map +1 -0
- package/dist/drivers/postgres.js +18 -0
- package/dist/drivers/postgres.js.map +1 -0
- package/dist/drivers/redis.d.ts +9 -0
- package/dist/drivers/redis.d.ts.map +1 -0
- package/dist/drivers/redis.js +50 -0
- package/dist/drivers/redis.js.map +1 -0
- package/dist/drivers/sqlite.d.ts +8 -0
- package/dist/drivers/sqlite.d.ts.map +1 -0
- package/dist/drivers/sqlite.js +18 -0
- package/dist/drivers/sqlite.js.map +1 -0
- package/dist/index.d.ts +14 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +49 -0
- package/dist/index.js.map +1 -0
- package/dist/migrations/index.d.ts +7 -0
- package/dist/migrations/index.d.ts.map +1 -0
- package/dist/migrations/index.js +23 -0
- package/dist/migrations/index.js.map +1 -0
- package/dist/migrations/migrator.d.ts +79 -0
- package/dist/migrations/migrator.d.ts.map +1 -0
- package/dist/migrations/migrator.js +274 -0
- package/dist/migrations/migrator.js.map +1 -0
- package/dist/migrations/schema-builder.d.ts +318 -0
- package/dist/migrations/schema-builder.d.ts.map +1 -0
- package/dist/migrations/schema-builder.js +957 -0
- package/dist/migrations/schema-builder.js.map +1 -0
- package/dist/migrations/types.d.ts +58 -0
- package/dist/migrations/types.d.ts.map +1 -0
- package/dist/migrations/types.js +3 -0
- package/dist/migrations/types.js.map +1 -0
- package/dist/model.d.ts +107 -0
- package/dist/model.d.ts.map +1 -0
- package/dist/model.js +333 -0
- package/dist/model.js.map +1 -0
- package/dist/plugin.d.ts +38 -0
- package/dist/plugin.d.ts.map +1 -0
- package/dist/plugin.js +83 -0
- package/dist/plugin.js.map +1 -0
- package/dist/query-builder.d.ts +58 -0
- package/dist/query-builder.d.ts.map +1 -0
- package/dist/query-builder.js +534 -0
- package/dist/query-builder.js.map +1 -0
- package/dist/schema-adapter.d.ts +34 -0
- package/dist/schema-adapter.d.ts.map +1 -0
- package/dist/schema-adapter.js +511 -0
- package/dist/schema-adapter.js.map +1 -0
- package/dist/schema.d.ts +104 -0
- package/dist/schema.d.ts.map +1 -0
- package/dist/schema.js +190 -0
- package/dist/schema.js.map +1 -0
- package/dist/seeds/index.d.ts +3 -0
- package/dist/seeds/index.d.ts.map +1 -0
- package/dist/seeds/index.js +19 -0
- package/dist/seeds/index.js.map +1 -0
- package/dist/seeds/seeder.d.ts +27 -0
- package/dist/seeds/seeder.d.ts.map +1 -0
- package/dist/seeds/seeder.js +138 -0
- package/dist/seeds/seeder.js.map +1 -0
- package/dist/seeds/types.d.ts +60 -0
- package/dist/seeds/types.d.ts.map +1 -0
- package/dist/seeds/types.js +3 -0
- package/dist/seeds/types.js.map +1 -0
- package/dist/sync/dump.d.ts +80 -0
- package/dist/sync/dump.d.ts.map +1 -0
- package/dist/sync/dump.js +655 -0
- package/dist/sync/dump.js.map +1 -0
- package/dist/sync/index.d.ts +5 -0
- package/dist/sync/index.d.ts.map +1 -0
- package/dist/sync/index.js +21 -0
- package/dist/sync/index.js.map +1 -0
- package/dist/sync/introspector.d.ts +49 -0
- package/dist/sync/introspector.d.ts.map +1 -0
- package/dist/sync/introspector.js +750 -0
- package/dist/sync/introspector.js.map +1 -0
- package/dist/sync/synchronizer.d.ts +50 -0
- package/dist/sync/synchronizer.d.ts.map +1 -0
- package/dist/sync/synchronizer.js +506 -0
- package/dist/sync/synchronizer.js.map +1 -0
- package/dist/sync/types.d.ts +83 -0
- package/dist/sync/types.d.ts.map +1 -0
- package/dist/sync/types.js +3 -0
- package/dist/sync/types.js.map +1 -0
- package/dist/tenant/sequence.d.ts +36 -0
- package/dist/tenant/sequence.d.ts.map +1 -0
- package/dist/tenant/sequence.js +130 -0
- package/dist/tenant/sequence.js.map +1 -0
- package/dist/types.d.ts +81 -0
- package/dist/types.d.ts.map +1 -0
- package/dist/types.js +3 -0
- package/dist/types.js.map +1 -0
- package/package.json +38 -3
package/dist/plugin.js
ADDED
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.databasePlugin = void 0;
|
|
4
|
+
const schema_1 = require("./schema");
|
|
5
|
+
const database_1 = require("./database");
|
|
6
|
+
const model_1 = require("./model");
|
|
7
|
+
const manager_1 = require("./connection/manager");
|
|
8
|
+
/**
|
|
9
|
+
* Plugin de banco de dados para integração nativa no ciclo de vida do Argos.
|
|
10
|
+
* Suporta tanto conexão única quanto multi-conexões nomeadas.
|
|
11
|
+
*
|
|
12
|
+
* @example
|
|
13
|
+
* // Conexão Única:
|
|
14
|
+
* await app.register(databasePlugin, {
|
|
15
|
+
* driver: 'sqlite',
|
|
16
|
+
* database: ':memory:',
|
|
17
|
+
* });
|
|
18
|
+
*
|
|
19
|
+
* // Multi-Conexão:
|
|
20
|
+
* await app.register(databasePlugin, {
|
|
21
|
+
* default: 'main',
|
|
22
|
+
* connections: {
|
|
23
|
+
* main: { driver: 'sqlite', database: './main.sqlite' },
|
|
24
|
+
* secondary: { driver: 'sqlite', database: './secondary.sqlite' },
|
|
25
|
+
* }
|
|
26
|
+
* });
|
|
27
|
+
*/
|
|
28
|
+
const databasePlugin = async (app, options) => {
|
|
29
|
+
let defaultClient;
|
|
30
|
+
if ('connections' in options && typeof options.connections === 'object') {
|
|
31
|
+
const multiConf = options;
|
|
32
|
+
manager_1.databaseManager.configure(multiConf);
|
|
33
|
+
defaultClient = manager_1.databaseManager.connection();
|
|
34
|
+
await defaultClient.connect();
|
|
35
|
+
}
|
|
36
|
+
else {
|
|
37
|
+
const singleConfig = options;
|
|
38
|
+
defaultClient = new database_1.DatabaseClient(singleConfig);
|
|
39
|
+
await defaultClient.connect();
|
|
40
|
+
manager_1.databaseManager.register('default', singleConfig, defaultClient);
|
|
41
|
+
manager_1.databaseManager.setDefaultConnection('default');
|
|
42
|
+
}
|
|
43
|
+
// Execução do Safe-Sync na Inicialização do Plugin
|
|
44
|
+
const syncOpt = options.sync;
|
|
45
|
+
const shouldSync = Boolean(syncOpt === true ||
|
|
46
|
+
options.mode === 'safe-sync' ||
|
|
47
|
+
(typeof syncOpt === 'object' && syncOpt !== null && (syncOpt.createTables || (syncOpt.tables && syncOpt.tables.length > 0))));
|
|
48
|
+
if (shouldSync) {
|
|
49
|
+
const tableMap = new Map();
|
|
50
|
+
if (typeof syncOpt === 'object' && syncOpt !== null && Array.isArray(syncOpt.tables)) {
|
|
51
|
+
for (const t of syncOpt.tables) {
|
|
52
|
+
if (t && t.tableName) {
|
|
53
|
+
tableMap.set(t.tableName, t);
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
for (const regTable of (0, schema_1.getRegisteredTables)()) {
|
|
58
|
+
if (!tableMap.has(regTable.tableName)) {
|
|
59
|
+
tableMap.set(regTable.tableName, regTable);
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
const tablesToSync = Array.from(tableMap.values());
|
|
63
|
+
if (tablesToSync.length > 0) {
|
|
64
|
+
await defaultClient.syncTables(tablesToSync);
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
app.db = manager_1.db;
|
|
68
|
+
app.database = manager_1.db;
|
|
69
|
+
// Vincula o banco de dados padrão à classe base Model
|
|
70
|
+
model_1.Model.setDatabase(defaultClient);
|
|
71
|
+
// Injeta o proxy de banco de dados no contexto de cada requisição HTTP
|
|
72
|
+
app.use(async (ctx, next) => {
|
|
73
|
+
ctx.db = manager_1.db;
|
|
74
|
+
ctx.database = manager_1.db;
|
|
75
|
+
return next();
|
|
76
|
+
});
|
|
77
|
+
// Desconexão automática de todas as conexões no desligamento gracioso da aplicação
|
|
78
|
+
app.onShutdown(async () => {
|
|
79
|
+
await manager_1.databaseManager.closeAll();
|
|
80
|
+
});
|
|
81
|
+
};
|
|
82
|
+
exports.databasePlugin = databasePlugin;
|
|
83
|
+
//# sourceMappingURL=plugin.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"plugin.js","sourceRoot":"","sources":["../src/plugin.ts"],"names":[],"mappings":";;;AAGA,qCAA+C;AAC/C,yCAA4C;AAC5C,mCAAgC;AAChC,kDAK8B;AAkB9B;;;;;;;;;;;;;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,kBAmEzB"}
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
import type { DatabaseExecutor, PaginationOptions, PaginationResult } from './types';
|
|
2
|
+
import type { UniversalTable } from './schema';
|
|
3
|
+
export declare class FluentTableQueryBuilder<T = any> implements PromiseLike<T[]> {
|
|
4
|
+
private executor;
|
|
5
|
+
private tableName;
|
|
6
|
+
private tableRef;
|
|
7
|
+
private selectedColumns;
|
|
8
|
+
private whereClauses;
|
|
9
|
+
private orderClauses;
|
|
10
|
+
private limitCount?;
|
|
11
|
+
private offsetCount?;
|
|
12
|
+
isSoftDeletes: boolean;
|
|
13
|
+
softDeleteColumn: string;
|
|
14
|
+
softDeleteScope: 'exclude' | 'with' | 'only';
|
|
15
|
+
private hydrator?;
|
|
16
|
+
constructor(executor: DatabaseExecutor, table: string | UniversalTable);
|
|
17
|
+
setHydrator(hydrator: (row: any) => any): this;
|
|
18
|
+
enableSoftDeletes(column?: string): this;
|
|
19
|
+
withTrashed(): this;
|
|
20
|
+
onlyTrashed(): this;
|
|
21
|
+
whereNull(column: string): this;
|
|
22
|
+
whereNotNull(column: string): this;
|
|
23
|
+
select(...columns: string[]): this;
|
|
24
|
+
where(colOrRecord: string | Record<string, unknown>, opOrVal?: string | unknown, val?: unknown): this;
|
|
25
|
+
andWhere(colOrRecord: string | Record<string, unknown>, opOrVal?: string | unknown, val?: unknown): this;
|
|
26
|
+
orWhere(colOrRecord: string | Record<string, unknown>, opOrVal?: string | unknown, val?: unknown): this;
|
|
27
|
+
private addWhere;
|
|
28
|
+
orderBy(column: string, direction?: 'asc' | 'desc' | 'ASC' | 'DESC'): this;
|
|
29
|
+
limit(limit: number): this;
|
|
30
|
+
offset(offset: number): this;
|
|
31
|
+
private nearestClause?;
|
|
32
|
+
nearest(column: string, vector: number[] | string, options?: {
|
|
33
|
+
metric?: 'cosine' | 'l2' | 'inner_product';
|
|
34
|
+
limit?: number;
|
|
35
|
+
}): this;
|
|
36
|
+
whereJson(path: string, value: unknown): this;
|
|
37
|
+
search(columns: string | string[], term: string): this;
|
|
38
|
+
private isPostgres;
|
|
39
|
+
private quoteIdentifier;
|
|
40
|
+
private buildWhereSQL;
|
|
41
|
+
toSql(): {
|
|
42
|
+
sql: string;
|
|
43
|
+
params: unknown[];
|
|
44
|
+
};
|
|
45
|
+
get<Result = T>(): Promise<Result[]>;
|
|
46
|
+
first<Result = T>(): Promise<Result | null>;
|
|
47
|
+
count(): Promise<number>;
|
|
48
|
+
paginate<Result = T>(options?: PaginationOptions): Promise<PaginationResult<Result>>;
|
|
49
|
+
insert<Result = T>(data: Record<string, unknown> | Record<string, unknown>[]): Promise<Result>;
|
|
50
|
+
update(data: Record<string, unknown>): Promise<number>;
|
|
51
|
+
delete(): Promise<number>;
|
|
52
|
+
destroy(): Promise<number>;
|
|
53
|
+
forceDelete(): Promise<number>;
|
|
54
|
+
softDelete(): Promise<number>;
|
|
55
|
+
restore(): Promise<number>;
|
|
56
|
+
then<TResult1 = T[], TResult2 = never>(onfulfilled?: ((value: T[]) => TResult1 | PromiseLike<TResult1>) | null | undefined, onrejected?: ((reason: any) => TResult2 | PromiseLike<TResult2>) | null | undefined): Promise<TResult1 | TResult2>;
|
|
57
|
+
}
|
|
58
|
+
//# sourceMappingURL=query-builder.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"query-builder.d.ts","sourceRoot":"","sources":["../src/query-builder.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,gBAAgB,EAEhB,iBAAiB,EACjB,gBAAgB,EAEjB,MAAM,SAAS,CAAC;AACjB,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,UAAU,CAAC;AAK/C,qBAAa,uBAAuB,CAAC,CAAC,GAAG,GAAG,CAAE,YAAW,WAAW,CAAC,CAAC,EAAE,CAAC;IACvE,OAAO,CAAC,QAAQ,CAAmB;IACnC,OAAO,CAAC,SAAS,CAAS;IAC1B,OAAO,CAAC,QAAQ,CAA0B;IAC1C,OAAO,CAAC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AM,EAAE,OAAO,CAAC,EAAE,GAAG,OAAO,CAAC,MAAM,CAAC;IA8E9F,MAAM,CAAC,IAAI,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,OAAO,CAAC,MAAM,CAAC;IA4BtD,MAAM,IAAI,OAAO,CAAC,MAAM,CAAC;IAOzB,OAAO,IAAI,OAAO,CAAC,MAAM,CAAC;IAI1B,WAAW,IAAI,OAAO,CAAC,MAAM,CAAC;IAc9B,UAAU,IAAI,OAAO,CAAC,MAAM,CAAC;IAmB7B,OAAO,IAAI,OAAO,CAAC,MAAM,CAAC;IAiBhC,IAAI,CAAC,QAAQ,GAAG,CAAC,EAAE,EAAE,QAAQ,GAAG,KAAK,EAC1C,WAAW,CAAC,EAAE,CAAC,CAAC,KAAK,EAAE,CAAC,EAAE,KAAK,QAAQ,GAAG,WAAW,CAAC,QAAQ,CAAC,CAAC,GAAG,IAAI,GAAG,SAAS,EACnF,UAAU,CAAC,EAAE,CAAC,CAAC,MAAM,EAAE,GAAG,KAAK,QAAQ,GAAG,WAAW,CAAC,QAAQ,CAAC,CAAC,GAAG,IAAI,GAAG,SAAS,GAClF,OAAO,CAAC,QAAQ,GAAG,QAAQ,CAAC;CAGhC"}
|
|
@@ -0,0 +1,534 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.FluentTableQueryBuilder = void 0;
|
|
4
|
+
const schema_1 = require("./schema");
|
|
5
|
+
const schema_adapter_1 = require("./schema-adapter");
|
|
6
|
+
const sequence_1 = require("./tenant/sequence");
|
|
7
|
+
class FluentTableQueryBuilder {
|
|
8
|
+
executor;
|
|
9
|
+
tableName;
|
|
10
|
+
tableRef;
|
|
11
|
+
selectedColumns = ['*'];
|
|
12
|
+
whereClauses = [];
|
|
13
|
+
orderClauses = [];
|
|
14
|
+
limitCount;
|
|
15
|
+
offsetCount;
|
|
16
|
+
isSoftDeletes = false;
|
|
17
|
+
softDeleteColumn = 'deleted_at';
|
|
18
|
+
softDeleteScope = 'exclude';
|
|
19
|
+
hydrator;
|
|
20
|
+
constructor(executor, table) {
|
|
21
|
+
this.executor = executor;
|
|
22
|
+
this.tableRef = table;
|
|
23
|
+
this.tableName = typeof table === 'string' ? table : table.tableName;
|
|
24
|
+
if (typeof table === 'object' && table !== null && table.softDeletes) {
|
|
25
|
+
this.isSoftDeletes = true;
|
|
26
|
+
}
|
|
27
|
+
else {
|
|
28
|
+
const registered = (0, schema_1.getRegisteredTables)().find((t) => t.tableName === this.tableName);
|
|
29
|
+
if (registered?.softDeletes) {
|
|
30
|
+
this.isSoftDeletes = true;
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
setHydrator(hydrator) {
|
|
35
|
+
this.hydrator = hydrator;
|
|
36
|
+
return this;
|
|
37
|
+
}
|
|
38
|
+
enableSoftDeletes(column = 'deleted_at') {
|
|
39
|
+
this.isSoftDeletes = true;
|
|
40
|
+
this.softDeleteColumn = column;
|
|
41
|
+
return this;
|
|
42
|
+
}
|
|
43
|
+
withTrashed() {
|
|
44
|
+
this.softDeleteScope = 'with';
|
|
45
|
+
return this;
|
|
46
|
+
}
|
|
47
|
+
onlyTrashed() {
|
|
48
|
+
this.softDeleteScope = 'only';
|
|
49
|
+
return this;
|
|
50
|
+
}
|
|
51
|
+
whereNull(column) {
|
|
52
|
+
this.whereClauses.push({
|
|
53
|
+
column,
|
|
54
|
+
operator: 'IS NULL',
|
|
55
|
+
value: null,
|
|
56
|
+
boolean: 'AND',
|
|
57
|
+
});
|
|
58
|
+
return this;
|
|
59
|
+
}
|
|
60
|
+
whereNotNull(column) {
|
|
61
|
+
this.whereClauses.push({
|
|
62
|
+
column,
|
|
63
|
+
operator: 'IS NOT NULL',
|
|
64
|
+
value: null,
|
|
65
|
+
boolean: 'AND',
|
|
66
|
+
});
|
|
67
|
+
return this;
|
|
68
|
+
}
|
|
69
|
+
select(...columns) {
|
|
70
|
+
if (columns.length > 0) {
|
|
71
|
+
this.selectedColumns = columns;
|
|
72
|
+
}
|
|
73
|
+
return this;
|
|
74
|
+
}
|
|
75
|
+
where(colOrRecord, opOrVal, val) {
|
|
76
|
+
return this.addWhere('AND', colOrRecord, opOrVal, val);
|
|
77
|
+
}
|
|
78
|
+
andWhere(colOrRecord, opOrVal, val) {
|
|
79
|
+
return this.addWhere('AND', colOrRecord, opOrVal, val);
|
|
80
|
+
}
|
|
81
|
+
orWhere(colOrRecord, opOrVal, val) {
|
|
82
|
+
return this.addWhere('OR', colOrRecord, opOrVal, val);
|
|
83
|
+
}
|
|
84
|
+
addWhere(boolean, colOrRecord, opOrVal, val) {
|
|
85
|
+
if (typeof colOrRecord === 'object' && colOrRecord !== null) {
|
|
86
|
+
for (const [column, value] of Object.entries(colOrRecord)) {
|
|
87
|
+
this.whereClauses.push({
|
|
88
|
+
column,
|
|
89
|
+
operator: '=',
|
|
90
|
+
value,
|
|
91
|
+
boolean,
|
|
92
|
+
});
|
|
93
|
+
}
|
|
94
|
+
return this;
|
|
95
|
+
}
|
|
96
|
+
if (val !== undefined) {
|
|
97
|
+
this.whereClauses.push({
|
|
98
|
+
column: colOrRecord,
|
|
99
|
+
operator: String(opOrVal).toUpperCase(),
|
|
100
|
+
value: val,
|
|
101
|
+
boolean,
|
|
102
|
+
});
|
|
103
|
+
}
|
|
104
|
+
else {
|
|
105
|
+
this.whereClauses.push({
|
|
106
|
+
column: colOrRecord,
|
|
107
|
+
operator: '=',
|
|
108
|
+
value: opOrVal,
|
|
109
|
+
boolean,
|
|
110
|
+
});
|
|
111
|
+
}
|
|
112
|
+
return this;
|
|
113
|
+
}
|
|
114
|
+
orderBy(column, direction = 'ASC') {
|
|
115
|
+
this.orderClauses.push({
|
|
116
|
+
column,
|
|
117
|
+
direction: direction.toUpperCase(),
|
|
118
|
+
});
|
|
119
|
+
return this;
|
|
120
|
+
}
|
|
121
|
+
limit(limit) {
|
|
122
|
+
this.limitCount = limit;
|
|
123
|
+
return this;
|
|
124
|
+
}
|
|
125
|
+
offset(offset) {
|
|
126
|
+
this.offsetCount = offset;
|
|
127
|
+
return this;
|
|
128
|
+
}
|
|
129
|
+
nearestClause;
|
|
130
|
+
nearest(column, vector, options) {
|
|
131
|
+
this.nearestClause = {
|
|
132
|
+
column,
|
|
133
|
+
vector,
|
|
134
|
+
metric: options?.metric || 'cosine',
|
|
135
|
+
};
|
|
136
|
+
if (options?.limit !== undefined) {
|
|
137
|
+
this.limit(options.limit);
|
|
138
|
+
}
|
|
139
|
+
return this;
|
|
140
|
+
}
|
|
141
|
+
whereJson(path, value) {
|
|
142
|
+
const segments = path.replace(/->>/g, '.').replace(/->/g, '.').split('.').filter(Boolean);
|
|
143
|
+
const column = segments[0] || 'data';
|
|
144
|
+
const jsonPath = segments.slice(1).join('.');
|
|
145
|
+
const quotedCol = this.quoteIdentifier(column);
|
|
146
|
+
const isPg = this.isPostgres();
|
|
147
|
+
const driver = this.executor.driverName.toLowerCase();
|
|
148
|
+
let expr = '';
|
|
149
|
+
if (isPg) {
|
|
150
|
+
if (segments.length === 2) {
|
|
151
|
+
expr = `${quotedCol}->>'${segments[1]}'`;
|
|
152
|
+
}
|
|
153
|
+
else {
|
|
154
|
+
const intermediate = segments.slice(1, -1).map((s) => `'${s}'`).join('->');
|
|
155
|
+
const last = segments[segments.length - 1];
|
|
156
|
+
expr = `${quotedCol}->${intermediate}->>'${last}'`;
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
else if (driver.includes('sqlite')) {
|
|
160
|
+
expr = `json_extract(${quotedCol}, '$.${jsonPath}')`;
|
|
161
|
+
}
|
|
162
|
+
else if (driver.includes('mysql')) {
|
|
163
|
+
expr = `JSON_UNQUOTE(JSON_EXTRACT(${quotedCol}, '$.${jsonPath}'))`;
|
|
164
|
+
}
|
|
165
|
+
else {
|
|
166
|
+
expr = `JSON_VALUE(${quotedCol}, '$.${jsonPath}')`;
|
|
167
|
+
}
|
|
168
|
+
if (value === null) {
|
|
169
|
+
this.whereClauses.push({
|
|
170
|
+
column,
|
|
171
|
+
operator: 'IS NULL',
|
|
172
|
+
value: null,
|
|
173
|
+
boolean: 'AND',
|
|
174
|
+
isRaw: true,
|
|
175
|
+
rawSql: `${expr} IS NULL`,
|
|
176
|
+
});
|
|
177
|
+
}
|
|
178
|
+
else {
|
|
179
|
+
this.whereClauses.push({
|
|
180
|
+
column,
|
|
181
|
+
operator: '=',
|
|
182
|
+
value,
|
|
183
|
+
boolean: 'AND',
|
|
184
|
+
isRaw: true,
|
|
185
|
+
rawSql: `${expr} = ?`,
|
|
186
|
+
rawParams: [value],
|
|
187
|
+
});
|
|
188
|
+
}
|
|
189
|
+
return this;
|
|
190
|
+
}
|
|
191
|
+
search(columns, term) {
|
|
192
|
+
const cols = Array.isArray(columns) ? columns : [columns];
|
|
193
|
+
const isPg = this.isPostgres();
|
|
194
|
+
const driver = this.executor.driverName.toLowerCase();
|
|
195
|
+
if (isPg) {
|
|
196
|
+
const textExpr = cols.map((c) => `coalesce(${this.quoteIdentifier(c)}, '')`).join(" || ' ' || ");
|
|
197
|
+
this.whereClauses.push({
|
|
198
|
+
column: cols[0],
|
|
199
|
+
operator: '@@',
|
|
200
|
+
value: term,
|
|
201
|
+
boolean: 'AND',
|
|
202
|
+
isRaw: true,
|
|
203
|
+
rawSql: `to_tsvector('simple', ${textExpr}) @@ plainto_tsquery('simple', ?)`,
|
|
204
|
+
rawParams: [term],
|
|
205
|
+
});
|
|
206
|
+
}
|
|
207
|
+
else if (driver.includes('mysql')) {
|
|
208
|
+
const matchCols = cols.map((c) => this.quoteIdentifier(c)).join(', ');
|
|
209
|
+
this.whereClauses.push({
|
|
210
|
+
column: cols[0],
|
|
211
|
+
operator: 'MATCH',
|
|
212
|
+
value: term,
|
|
213
|
+
boolean: 'AND',
|
|
214
|
+
isRaw: true,
|
|
215
|
+
rawSql: `MATCH(${matchCols}) AGAINST(? IN BOOLEAN MODE)`,
|
|
216
|
+
rawParams: [term],
|
|
217
|
+
});
|
|
218
|
+
}
|
|
219
|
+
else {
|
|
220
|
+
// SQLite / Fallback
|
|
221
|
+
const conditions = cols.map((c) => `${this.quoteIdentifier(c)} LIKE ?`).join(' OR ');
|
|
222
|
+
const params = cols.map(() => `%${term}%`);
|
|
223
|
+
this.whereClauses.push({
|
|
224
|
+
column: cols[0],
|
|
225
|
+
operator: 'LIKE',
|
|
226
|
+
value: term,
|
|
227
|
+
boolean: 'AND',
|
|
228
|
+
isRaw: true,
|
|
229
|
+
rawSql: `(${conditions})`,
|
|
230
|
+
rawParams: params,
|
|
231
|
+
});
|
|
232
|
+
}
|
|
233
|
+
return this;
|
|
234
|
+
}
|
|
235
|
+
isPostgres() {
|
|
236
|
+
const d = this.executor.driverName.toLowerCase();
|
|
237
|
+
return d.includes('postgres') || d === 'pg';
|
|
238
|
+
}
|
|
239
|
+
quoteIdentifier(identifier) {
|
|
240
|
+
if (identifier === '*')
|
|
241
|
+
return '*';
|
|
242
|
+
if (identifier.includes('.')) {
|
|
243
|
+
return identifier.split('.').map(part => this.quoteIdentifier(part)).join('.');
|
|
244
|
+
}
|
|
245
|
+
const d = this.executor.driverName.toLowerCase();
|
|
246
|
+
if (d.includes('mysql')) {
|
|
247
|
+
return `\`${identifier}\``;
|
|
248
|
+
}
|
|
249
|
+
return `"${identifier}"`;
|
|
250
|
+
}
|
|
251
|
+
buildWhereSQL(paramOffset = 0) {
|
|
252
|
+
const effectiveClauses = [...this.whereClauses];
|
|
253
|
+
if (this.isSoftDeletes) {
|
|
254
|
+
const hasSoftDeleteConstraint = effectiveClauses.some((c) => c.column === this.softDeleteColumn ||
|
|
255
|
+
c.column === (0, schema_1.toSnakeCase)(this.softDeleteColumn) ||
|
|
256
|
+
c.column === (0, schema_1.toCamelCase)(this.softDeleteColumn));
|
|
257
|
+
if (!hasSoftDeleteConstraint) {
|
|
258
|
+
if (this.softDeleteScope === 'exclude') {
|
|
259
|
+
effectiveClauses.push({
|
|
260
|
+
column: this.softDeleteColumn,
|
|
261
|
+
operator: 'IS NULL',
|
|
262
|
+
value: null,
|
|
263
|
+
boolean: 'AND',
|
|
264
|
+
});
|
|
265
|
+
}
|
|
266
|
+
else if (this.softDeleteScope === 'only') {
|
|
267
|
+
effectiveClauses.push({
|
|
268
|
+
column: this.softDeleteColumn,
|
|
269
|
+
operator: 'IS NOT NULL',
|
|
270
|
+
value: null,
|
|
271
|
+
boolean: 'AND',
|
|
272
|
+
});
|
|
273
|
+
}
|
|
274
|
+
}
|
|
275
|
+
}
|
|
276
|
+
if (effectiveClauses.length === 0) {
|
|
277
|
+
return { sql: '', params: [] };
|
|
278
|
+
}
|
|
279
|
+
const isPg = this.isPostgres();
|
|
280
|
+
const params = [];
|
|
281
|
+
const parts = [];
|
|
282
|
+
effectiveClauses.forEach((clause, index) => {
|
|
283
|
+
const prefix = index === 0 ? '' : ` ${clause.boolean} `;
|
|
284
|
+
if (clause.isRaw && clause.rawSql) {
|
|
285
|
+
let sqlPart = clause.rawSql;
|
|
286
|
+
if (clause.rawParams && clause.rawParams.length > 0) {
|
|
287
|
+
for (const param of clause.rawParams) {
|
|
288
|
+
params.push(param);
|
|
289
|
+
if (isPg) {
|
|
290
|
+
const placeholder = `$${paramOffset + params.length}`;
|
|
291
|
+
sqlPart = sqlPart.replace('?', placeholder);
|
|
292
|
+
}
|
|
293
|
+
}
|
|
294
|
+
}
|
|
295
|
+
parts.push(`${prefix}${sqlPart}`);
|
|
296
|
+
return;
|
|
297
|
+
}
|
|
298
|
+
const colName = /[A-Z]/.test(clause.column) ? (0, schema_1.toSnakeCase)(clause.column) : clause.column;
|
|
299
|
+
const quotedCol = this.quoteIdentifier(colName);
|
|
300
|
+
if (clause.operator === 'IS NULL' || clause.operator === 'IS NOT NULL') {
|
|
301
|
+
parts.push(`${prefix}${quotedCol} ${clause.operator}`);
|
|
302
|
+
}
|
|
303
|
+
else {
|
|
304
|
+
params.push(clause.value);
|
|
305
|
+
const placeholder = isPg ? `$${paramOffset + params.length}` : '?';
|
|
306
|
+
parts.push(`${prefix}${quotedCol} ${clause.operator} ${placeholder}`);
|
|
307
|
+
}
|
|
308
|
+
});
|
|
309
|
+
return { sql: ` WHERE ${parts.join('')}`, params };
|
|
310
|
+
}
|
|
311
|
+
toSql() {
|
|
312
|
+
const cols = this.selectedColumns.map((c) => this.quoteIdentifier(c)).join(', ');
|
|
313
|
+
const fromTable = this.quoteIdentifier(this.tableName);
|
|
314
|
+
let query = `SELECT ${cols} FROM ${fromTable}`;
|
|
315
|
+
const whereData = this.buildWhereSQL();
|
|
316
|
+
query += whereData.sql;
|
|
317
|
+
const params = [...whereData.params];
|
|
318
|
+
const orderParts = [];
|
|
319
|
+
if (this.nearestClause) {
|
|
320
|
+
const col = this.quoteIdentifier(this.nearestClause.column);
|
|
321
|
+
const vecStr = Array.isArray(this.nearestClause.vector)
|
|
322
|
+
? `[${this.nearestClause.vector.join(',')}]`
|
|
323
|
+
: String(this.nearestClause.vector);
|
|
324
|
+
if (this.isPostgres()) {
|
|
325
|
+
const op = this.nearestClause.metric === 'l2'
|
|
326
|
+
? '<->'
|
|
327
|
+
: this.nearestClause.metric === 'inner_product'
|
|
328
|
+
? '<#>'
|
|
329
|
+
: '<=>';
|
|
330
|
+
orderParts.push(`${col} ${op} '${vecStr}' ASC`);
|
|
331
|
+
}
|
|
332
|
+
else {
|
|
333
|
+
orderParts.push(`${col} ASC`);
|
|
334
|
+
}
|
|
335
|
+
}
|
|
336
|
+
if (this.orderClauses.length > 0) {
|
|
337
|
+
for (const o of this.orderClauses) {
|
|
338
|
+
const colName = /[A-Z]/.test(o.column) ? (0, schema_1.toSnakeCase)(o.column) : o.column;
|
|
339
|
+
orderParts.push(`${this.quoteIdentifier(colName)} ${o.direction}`);
|
|
340
|
+
}
|
|
341
|
+
}
|
|
342
|
+
if (orderParts.length > 0) {
|
|
343
|
+
query += ` ORDER BY ${orderParts.join(', ')}`;
|
|
344
|
+
}
|
|
345
|
+
if (this.limitCount !== undefined) {
|
|
346
|
+
query += ` LIMIT ${this.limitCount}`;
|
|
347
|
+
}
|
|
348
|
+
if (this.offsetCount !== undefined) {
|
|
349
|
+
query += ` OFFSET ${this.offsetCount}`;
|
|
350
|
+
}
|
|
351
|
+
return { sql: query, params };
|
|
352
|
+
}
|
|
353
|
+
async get() {
|
|
354
|
+
const { sql, params } = this.toSql();
|
|
355
|
+
const res = await this.executor.execute(sql, params);
|
|
356
|
+
const hydratedRows = res.rows.map((r) => (0, schema_adapter_1.hydrateRow)(r, this.tableRef));
|
|
357
|
+
if (this.hydrator) {
|
|
358
|
+
return hydratedRows.map((r) => this.hydrator(r));
|
|
359
|
+
}
|
|
360
|
+
return hydratedRows;
|
|
361
|
+
}
|
|
362
|
+
async first() {
|
|
363
|
+
const savedLimit = this.limitCount;
|
|
364
|
+
this.limitCount = 1;
|
|
365
|
+
const rows = await this.get();
|
|
366
|
+
this.limitCount = savedLimit;
|
|
367
|
+
return rows.length > 0 ? rows[0] : null;
|
|
368
|
+
}
|
|
369
|
+
async count() {
|
|
370
|
+
const fromTable = this.quoteIdentifier(this.tableName);
|
|
371
|
+
let query = `SELECT COUNT(*) as count FROM ${fromTable}`;
|
|
372
|
+
const whereData = this.buildWhereSQL();
|
|
373
|
+
query += whereData.sql;
|
|
374
|
+
const res = await this.executor.execute(query, whereData.params);
|
|
375
|
+
const row = res.rows[0];
|
|
376
|
+
if (!row)
|
|
377
|
+
return 0;
|
|
378
|
+
return Number(row.count ?? row['count(*)'] ?? 0);
|
|
379
|
+
}
|
|
380
|
+
async paginate(options = {}) {
|
|
381
|
+
const page = Math.max(1, options.page ?? 1);
|
|
382
|
+
const perPage = Math.max(1, options.perPage ?? 15);
|
|
383
|
+
const total = await this.count();
|
|
384
|
+
const offset = (page - 1) * perPage;
|
|
385
|
+
const savedLimit = this.limitCount;
|
|
386
|
+
const savedOffset = this.offsetCount;
|
|
387
|
+
this.limitCount = perPage;
|
|
388
|
+
this.offsetCount = offset;
|
|
389
|
+
const data = await this.get();
|
|
390
|
+
this.limitCount = savedLimit;
|
|
391
|
+
this.offsetCount = savedOffset;
|
|
392
|
+
const lastPage = Math.max(1, Math.ceil(total / perPage));
|
|
393
|
+
return {
|
|
394
|
+
data,
|
|
395
|
+
total,
|
|
396
|
+
page,
|
|
397
|
+
perPage,
|
|
398
|
+
lastPage,
|
|
399
|
+
};
|
|
400
|
+
}
|
|
401
|
+
async insert(data) {
|
|
402
|
+
const records = Array.isArray(data) ? data : [data];
|
|
403
|
+
if (records.length === 0) {
|
|
404
|
+
return [];
|
|
405
|
+
}
|
|
406
|
+
const tableDef = typeof this.tableRef === 'object' && this.tableRef !== null && 'tableName' in this.tableRef
|
|
407
|
+
? this.tableRef
|
|
408
|
+
: (0, schema_1.getRegisteredTables)().find((t) => t.tableName === this.tableName);
|
|
409
|
+
if (tableDef) {
|
|
410
|
+
const seqEntries = Object.entries(tableDef.columns).filter(([_, col]) => col.getDefinition().type === 'sequence');
|
|
411
|
+
if (seqEntries.length > 0) {
|
|
412
|
+
for (const record of records) {
|
|
413
|
+
for (const [key, colBuilder] of seqEntries) {
|
|
414
|
+
const def = colBuilder.getDefinition();
|
|
415
|
+
const colName = def.name || key;
|
|
416
|
+
if (record[key] === undefined && record[colName] === undefined) {
|
|
417
|
+
const byField = def.sequenceOptions?.by;
|
|
418
|
+
let scopeId = undefined;
|
|
419
|
+
if (byField) {
|
|
420
|
+
scopeId =
|
|
421
|
+
record[byField] ??
|
|
422
|
+
record[(0, schema_1.toCamelCase)(byField)] ??
|
|
423
|
+
record[(0, schema_1.toSnakeCase)(byField)];
|
|
424
|
+
}
|
|
425
|
+
const nextVal = await (0, sequence_1.getNextSequence)(this.executor, this.tableName, def.sequenceOptions, scopeId);
|
|
426
|
+
record[key] = nextVal;
|
|
427
|
+
}
|
|
428
|
+
}
|
|
429
|
+
}
|
|
430
|
+
}
|
|
431
|
+
}
|
|
432
|
+
const isPg = this.isPostgres();
|
|
433
|
+
const fromTable = this.quoteIdentifier(this.tableName);
|
|
434
|
+
const rawColumns = Object.keys(records[0]);
|
|
435
|
+
const colNames = rawColumns.map(c => /[A-Z]/.test(c) ? (0, schema_1.toSnakeCase)(c) : c);
|
|
436
|
+
const quotedCols = colNames.map(c => this.quoteIdentifier(c)).join(', ');
|
|
437
|
+
const params = [];
|
|
438
|
+
const valuesRows = [];
|
|
439
|
+
records.forEach(record => {
|
|
440
|
+
const rowPlaceholders = [];
|
|
441
|
+
rawColumns.forEach(col => {
|
|
442
|
+
params.push(record[col]);
|
|
443
|
+
rowPlaceholders.push(isPg ? `$${params.length}` : '?');
|
|
444
|
+
});
|
|
445
|
+
valuesRows.push(`(${rowPlaceholders.join(', ')})`);
|
|
446
|
+
});
|
|
447
|
+
let query = `INSERT INTO ${fromTable} (${quotedCols}) VALUES ${valuesRows.join(', ')}`;
|
|
448
|
+
if (isPg || this.executor.driverName.toLowerCase().includes('sqlite')) {
|
|
449
|
+
query += ` RETURNING *`;
|
|
450
|
+
}
|
|
451
|
+
const result = await this.executor.execute(query, params);
|
|
452
|
+
if (result.rows.length > 0) {
|
|
453
|
+
const normalizedRows = result.rows.map((r) => (0, schema_adapter_1.hydrateRow)(r, this.tableRef));
|
|
454
|
+
return (Array.isArray(data) ? normalizedRows : normalizedRows[0]);
|
|
455
|
+
}
|
|
456
|
+
const normalizedRecords = (Array.isArray(data) ? records : [records[0]]).map((r) => (0, schema_adapter_1.hydrateRow)(r, this.tableRef));
|
|
457
|
+
return (Array.isArray(data) ? normalizedRecords : normalizedRecords[0]);
|
|
458
|
+
}
|
|
459
|
+
async update(data) {
|
|
460
|
+
const isPg = this.isPostgres();
|
|
461
|
+
const fromTable = this.quoteIdentifier(this.tableName);
|
|
462
|
+
const entries = Object.entries(data);
|
|
463
|
+
if (entries.length === 0) {
|
|
464
|
+
return 0;
|
|
465
|
+
}
|
|
466
|
+
const params = [];
|
|
467
|
+
const setParts = [];
|
|
468
|
+
entries.forEach(([col, val]) => {
|
|
469
|
+
const colName = /[A-Z]/.test(col) ? (0, schema_1.toSnakeCase)(col) : col;
|
|
470
|
+
params.push(val);
|
|
471
|
+
const placeholder = isPg ? `$${params.length}` : '?';
|
|
472
|
+
setParts.push(`${this.quoteIdentifier(colName)} = ${placeholder}`);
|
|
473
|
+
});
|
|
474
|
+
let query = `UPDATE ${fromTable} SET ${setParts.join(', ')}`;
|
|
475
|
+
const whereData = this.buildWhereSQL(params.length);
|
|
476
|
+
query += whereData.sql;
|
|
477
|
+
params.push(...whereData.params);
|
|
478
|
+
const result = await this.executor.execute(query, params);
|
|
479
|
+
return result.rowCount;
|
|
480
|
+
}
|
|
481
|
+
async delete() {
|
|
482
|
+
if (this.isSoftDeletes) {
|
|
483
|
+
return this.softDelete();
|
|
484
|
+
}
|
|
485
|
+
return this.forceDelete();
|
|
486
|
+
}
|
|
487
|
+
async destroy() {
|
|
488
|
+
return this.delete();
|
|
489
|
+
}
|
|
490
|
+
async forceDelete() {
|
|
491
|
+
const fromTable = this.quoteIdentifier(this.tableName);
|
|
492
|
+
let query = `DELETE FROM ${fromTable}`;
|
|
493
|
+
const savedScope = this.softDeleteScope;
|
|
494
|
+
this.softDeleteScope = 'with';
|
|
495
|
+
const whereData = this.buildWhereSQL();
|
|
496
|
+
this.softDeleteScope = savedScope;
|
|
497
|
+
query += whereData.sql;
|
|
498
|
+
const result = await this.executor.execute(query, whereData.params);
|
|
499
|
+
return result.rowCount;
|
|
500
|
+
}
|
|
501
|
+
async softDelete() {
|
|
502
|
+
const isPg = this.isPostgres();
|
|
503
|
+
const fromTable = this.quoteIdentifier(this.tableName);
|
|
504
|
+
const colName = /[A-Z]/.test(this.softDeleteColumn) ? (0, schema_1.toSnakeCase)(this.softDeleteColumn) : this.softDeleteColumn;
|
|
505
|
+
const quotedCol = this.quoteIdentifier(colName);
|
|
506
|
+
const now = new Date().toISOString().replace('T', ' ').slice(0, 19);
|
|
507
|
+
const params = [now];
|
|
508
|
+
const placeholder = isPg ? '$1' : '?';
|
|
509
|
+
let query = `UPDATE ${fromTable} SET ${quotedCol} = ${placeholder}`;
|
|
510
|
+
const whereData = this.buildWhereSQL(params.length);
|
|
511
|
+
query += whereData.sql;
|
|
512
|
+
params.push(...whereData.params);
|
|
513
|
+
const result = await this.executor.execute(query, params);
|
|
514
|
+
return result.rowCount;
|
|
515
|
+
}
|
|
516
|
+
async restore() {
|
|
517
|
+
const fromTable = this.quoteIdentifier(this.tableName);
|
|
518
|
+
const colName = /[A-Z]/.test(this.softDeleteColumn) ? (0, schema_1.toSnakeCase)(this.softDeleteColumn) : this.softDeleteColumn;
|
|
519
|
+
const quotedCol = this.quoteIdentifier(colName);
|
|
520
|
+
let query = `UPDATE ${fromTable} SET ${quotedCol} = NULL`;
|
|
521
|
+
const savedScope = this.softDeleteScope;
|
|
522
|
+
this.softDeleteScope = 'with';
|
|
523
|
+
const whereData = this.buildWhereSQL();
|
|
524
|
+
this.softDeleteScope = savedScope;
|
|
525
|
+
query += whereData.sql;
|
|
526
|
+
const result = await this.executor.execute(query, whereData.params);
|
|
527
|
+
return result.rowCount;
|
|
528
|
+
}
|
|
529
|
+
then(onfulfilled, onrejected) {
|
|
530
|
+
return this.get().then(onfulfilled, onrejected);
|
|
531
|
+
}
|
|
532
|
+
}
|
|
533
|
+
exports.FluentTableQueryBuilder = FluentTableQueryBuilder;
|
|
534
|
+
//# sourceMappingURL=query-builder.js.map
|