@cheetah.js/orm 0.1.146 → 0.1.149
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/dist/SqlBuilder.js +3 -0
- package/dist/decorators/unique.decorator.d.ts +9 -0
- package/dist/decorators/unique.decorator.js +44 -0
- package/dist/domain/entities.d.ts +2 -1
- package/dist/domain/entities.js +28 -0
- package/dist/driver/bun-mysql.driver.d.ts +7 -0
- package/dist/driver/bun-mysql.driver.js +11 -0
- package/dist/driver/bun-pg.driver.d.ts +7 -0
- package/dist/driver/bun-pg.driver.js +11 -0
- package/dist/driver/driver.interface.d.ts +14 -0
- package/dist/index.d.ts +1 -0
- package/dist/index.js +1 -0
- package/dist/query/sql-condition-builder.d.ts +5 -0
- package/dist/query/sql-condition-builder.js +29 -3
- package/dist/query/sql-subquery-builder.d.ts +20 -0
- package/dist/query/sql-subquery-builder.js +119 -0
- package/package.json +2 -2
package/dist/SqlBuilder.js
CHANGED
|
@@ -5,6 +5,7 @@ const entities_1 = require("./domain/entities");
|
|
|
5
5
|
const orm_1 = require("./orm");
|
|
6
6
|
const value_processor_1 = require("./utils/value-processor");
|
|
7
7
|
const sql_condition_builder_1 = require("./query/sql-condition-builder");
|
|
8
|
+
const sql_subquery_builder_1 = require("./query/sql-subquery-builder");
|
|
8
9
|
const model_transformer_1 = require("./query/model-transformer");
|
|
9
10
|
const sql_column_manager_1 = require("./query/sql-column-manager");
|
|
10
11
|
const sql_join_manager_1 = require("./query/sql-join-manager");
|
|
@@ -27,6 +28,8 @@ class SqlBuilder {
|
|
|
27
28
|
return this.joinManager.applyJoin(relationship, value, alias);
|
|
28
29
|
};
|
|
29
30
|
this.conditionBuilder = new sql_condition_builder_1.SqlConditionBuilder(this.entityStorage, applyJoinWrapper, this.statements);
|
|
31
|
+
const subqueryBuilder = new sql_subquery_builder_1.SqlSubqueryBuilder(this.entityStorage, () => this.conditionBuilder);
|
|
32
|
+
this.conditionBuilder.setSubqueryBuilder(subqueryBuilder);
|
|
30
33
|
this.joinManager = new sql_join_manager_1.SqlJoinManager(this.entityStorage, this.statements, this.entity, this.model, this.driver, this.logger, this.conditionBuilder, this.columnManager, this.modelTransformer, () => this.originalColumns, this.getAlias.bind(this));
|
|
31
34
|
}
|
|
32
35
|
initializeCacheManager() {
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
export type UniqueDefinition = {
|
|
2
|
+
name: string;
|
|
3
|
+
properties: string[];
|
|
4
|
+
};
|
|
5
|
+
type UniqueOptions<T> = {
|
|
6
|
+
properties: (keyof T)[];
|
|
7
|
+
} | (keyof T)[] | undefined;
|
|
8
|
+
export declare function Unique<T>(options?: UniqueOptions<T>): ClassDecorator & PropertyDecorator;
|
|
9
|
+
export {};
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.Unique = Unique;
|
|
4
|
+
const core_1 = require("@cheetah.js/core");
|
|
5
|
+
function getCtor(target) {
|
|
6
|
+
return typeof target === "function" ? target : target.constructor;
|
|
7
|
+
}
|
|
8
|
+
function buildFromOptions(options) {
|
|
9
|
+
const props = Array.isArray(options) ? options : options?.properties;
|
|
10
|
+
if (!props || props.length === 0) {
|
|
11
|
+
return null;
|
|
12
|
+
}
|
|
13
|
+
const keys = props;
|
|
14
|
+
return {
|
|
15
|
+
name: `${keys.join('_')}_unique`,
|
|
16
|
+
properties: keys,
|
|
17
|
+
};
|
|
18
|
+
}
|
|
19
|
+
function buildFromProperty(propertyKey) {
|
|
20
|
+
const name = String(propertyKey);
|
|
21
|
+
return {
|
|
22
|
+
name: `${name}_unique`,
|
|
23
|
+
properties: [name],
|
|
24
|
+
};
|
|
25
|
+
}
|
|
26
|
+
function resolveUnique(options, propertyKey) {
|
|
27
|
+
const fromOptions = buildFromOptions(options);
|
|
28
|
+
if (fromOptions) {
|
|
29
|
+
return fromOptions;
|
|
30
|
+
}
|
|
31
|
+
if (!propertyKey) {
|
|
32
|
+
throw new Error("@Unique on class requires properties option");
|
|
33
|
+
}
|
|
34
|
+
return buildFromProperty(propertyKey);
|
|
35
|
+
}
|
|
36
|
+
function Unique(options) {
|
|
37
|
+
return (target, propertyKey) => {
|
|
38
|
+
const ctor = getCtor(target);
|
|
39
|
+
const uniques = [...(core_1.Metadata.get("uniques", ctor) || [])];
|
|
40
|
+
const unique = resolveUnique(options, propertyKey);
|
|
41
|
+
uniques.push(unique);
|
|
42
|
+
core_1.Metadata.set("uniques", uniques, ctor);
|
|
43
|
+
};
|
|
44
|
+
}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { PropertyOptions } from "../decorators/property.decorator";
|
|
2
|
-
import { Relationship, SnapshotIndexInfo, SnapshotTable } from "../driver/driver.interface";
|
|
2
|
+
import { Relationship, SnapshotIndexInfo, SnapshotTable, SnapshotUniqueInfo } from "../driver/driver.interface";
|
|
3
3
|
export type Property = {
|
|
4
4
|
options: PropertyOptions;
|
|
5
5
|
type: Function;
|
|
@@ -10,6 +10,7 @@ export type Options = {
|
|
|
10
10
|
};
|
|
11
11
|
hideProperties: string[];
|
|
12
12
|
indexes?: SnapshotIndexInfo[];
|
|
13
|
+
uniques?: SnapshotUniqueInfo[];
|
|
13
14
|
relations: Relationship<any>[];
|
|
14
15
|
tableName: string;
|
|
15
16
|
hooks?: {
|
package/dist/domain/entities.js
CHANGED
|
@@ -77,6 +77,31 @@ function buildIndexWhere(where, columnMap) {
|
|
|
77
77
|
const builder = new index_condition_builder_1.IndexConditionBuilder(columnMap);
|
|
78
78
|
return builder.build(where);
|
|
79
79
|
}
|
|
80
|
+
function mapUniqueDefinitions(uniques, entityName, columnMap) {
|
|
81
|
+
return uniques.map((unique) => toSnapshotUnique(unique, entityName, columnMap));
|
|
82
|
+
}
|
|
83
|
+
function toSnapshotUnique(unique, entityName, columnMap) {
|
|
84
|
+
const columns = resolveUniqueColumns(unique, columnMap);
|
|
85
|
+
const uniqueName = resolveUniqueName(unique.name, entityName, columns);
|
|
86
|
+
return {
|
|
87
|
+
table: entityName,
|
|
88
|
+
uniqueName,
|
|
89
|
+
columnName: columns.join(","),
|
|
90
|
+
};
|
|
91
|
+
}
|
|
92
|
+
function resolveUniqueColumns(unique, columnMap) {
|
|
93
|
+
return unique.properties.map((propName) => resolveUniqueColumn(propName, columnMap));
|
|
94
|
+
}
|
|
95
|
+
function resolveUniqueColumn(propName, columnMap) {
|
|
96
|
+
const mapped = columnMap[propName];
|
|
97
|
+
if (mapped) {
|
|
98
|
+
return mapped;
|
|
99
|
+
}
|
|
100
|
+
return (0, utils_1.toSnakeCase)(propName);
|
|
101
|
+
}
|
|
102
|
+
function resolveUniqueName(name, entityName, columns) {
|
|
103
|
+
return `${columns.join("_")}_unique`;
|
|
104
|
+
}
|
|
80
105
|
let EntityStorage = EntityStorage_1 = class EntityStorage {
|
|
81
106
|
constructor() {
|
|
82
107
|
this.entities = new Map();
|
|
@@ -85,6 +110,7 @@ let EntityStorage = EntityStorage_1 = class EntityStorage {
|
|
|
85
110
|
add(entity, properties, relations, hooks) {
|
|
86
111
|
const entityName = entity.options?.tableName || (0, utils_1.toSnakeCase)(entity.target.name);
|
|
87
112
|
const indexes = core_1.Metadata.get("indexes", entity.target) || [];
|
|
113
|
+
const uniques = core_1.Metadata.get("uniques", entity.target) || [];
|
|
88
114
|
const columnMap = buildIndexColumnMap(properties, relations);
|
|
89
115
|
this.entities.set(entity.target, {
|
|
90
116
|
properties: properties,
|
|
@@ -93,6 +119,7 @@ let EntityStorage = EntityStorage_1 = class EntityStorage {
|
|
|
93
119
|
.map(([key]) => key),
|
|
94
120
|
relations,
|
|
95
121
|
indexes: mapIndexDefinitions(indexes, entityName, columnMap),
|
|
122
|
+
uniques: mapUniqueDefinitions(uniques, entityName, columnMap),
|
|
96
123
|
hooks,
|
|
97
124
|
tableName: entityName,
|
|
98
125
|
...entity.options,
|
|
@@ -116,6 +143,7 @@ let EntityStorage = EntityStorage_1 = class EntityStorage {
|
|
|
116
143
|
tableName: values.tableName,
|
|
117
144
|
schema: values.schema || "public",
|
|
118
145
|
indexes: values.indexes || [],
|
|
146
|
+
uniques: values.uniques || [],
|
|
119
147
|
columns: this.snapshotColumns(values),
|
|
120
148
|
};
|
|
121
149
|
}
|
|
@@ -26,6 +26,13 @@ export declare class BunMysqlDriver extends BunDriverBase implements DriverInter
|
|
|
26
26
|
name: string;
|
|
27
27
|
properties?: string[];
|
|
28
28
|
}, schema: string | undefined, tableName: string): string;
|
|
29
|
+
getCreateUniqueConstraint(unique: {
|
|
30
|
+
name: string;
|
|
31
|
+
properties?: string[];
|
|
32
|
+
}, schema: string | undefined, tableName: string): string;
|
|
33
|
+
getDropUniqueConstraint(unique: {
|
|
34
|
+
name: string;
|
|
35
|
+
}, schema: string | undefined, tableName: string): string;
|
|
29
36
|
getAlterTableType(schema: string | undefined, tableName: string, colName: string, colDiff: ColDiff): string;
|
|
30
37
|
getAlterTableDefaultInstruction(schema: string | undefined, tableName: string, colName: string, colDiff: ColDiff): string;
|
|
31
38
|
getAlterTablePrimaryKeyInstruction(schema: string | undefined, tableName: string, colName: string, colDiff: ColDiff): string;
|
|
@@ -141,6 +141,17 @@ class BunMysqlDriver extends bun_driver_base_1.BunDriverBase {
|
|
|
141
141
|
getDropIndex(index, schema, tableName) {
|
|
142
142
|
return `ALTER TABLE \`${schema}\`.\`${tableName}\` DROP INDEX \`${index.name}\`;`;
|
|
143
143
|
}
|
|
144
|
+
getCreateUniqueConstraint(unique, schema, tableName) {
|
|
145
|
+
const properties = unique.properties || [];
|
|
146
|
+
if (properties.length === 0) {
|
|
147
|
+
throw new Error("Unique properties are required.");
|
|
148
|
+
}
|
|
149
|
+
const columns = properties.map((prop) => `\`${prop}\``).join(', ');
|
|
150
|
+
return `ALTER TABLE \`${schema}\`.\`${tableName}\` ADD CONSTRAINT \`${unique.name}\` UNIQUE (${columns});`;
|
|
151
|
+
}
|
|
152
|
+
getDropUniqueConstraint(unique, schema, tableName) {
|
|
153
|
+
return `ALTER TABLE \`${schema}\`.\`${tableName}\` DROP INDEX \`${unique.name}\`;`;
|
|
154
|
+
}
|
|
144
155
|
getAlterTableType(schema, tableName, colName, colDiff) {
|
|
145
156
|
return `ALTER TABLE \`${schema}\`.\`${tableName}\` MODIFY COLUMN \`${colName}\` ${colDiff.colType}${colDiff.colLength ? `(${colDiff.colLength})` : ''};`;
|
|
146
157
|
}
|
|
@@ -25,6 +25,13 @@ export declare class BunPgDriver extends BunDriverBase implements DriverInterfac
|
|
|
25
25
|
name: string;
|
|
26
26
|
properties?: string[];
|
|
27
27
|
}, schema: string | undefined, tableName: string): string;
|
|
28
|
+
getCreateUniqueConstraint(unique: {
|
|
29
|
+
name: string;
|
|
30
|
+
properties?: string[];
|
|
31
|
+
}, schema: string | undefined, tableName: string): string;
|
|
32
|
+
getDropUniqueConstraint(unique: {
|
|
33
|
+
name: string;
|
|
34
|
+
}, schema: string | undefined, tableName: string): string;
|
|
28
35
|
getAlterTableType(schema: string | undefined, tableName: string, colName: string, colDiff: ColDiff): string;
|
|
29
36
|
getAlterTableDefaultInstruction(schema: string | undefined, tableName: string, colName: string, colDiff: ColDiff): string;
|
|
30
37
|
getAlterTablePrimaryKeyInstruction(schema: string | undefined, tableName: string, colName: string, colDiff: ColDiff): string;
|
|
@@ -114,6 +114,17 @@ class BunPgDriver extends bun_driver_base_1.BunDriverBase {
|
|
|
114
114
|
getDropIndex(index, schema, tableName) {
|
|
115
115
|
return this.getDropConstraint(index, schema, tableName);
|
|
116
116
|
}
|
|
117
|
+
getCreateUniqueConstraint(unique, schema, tableName) {
|
|
118
|
+
const properties = unique.properties || [];
|
|
119
|
+
if (properties.length === 0) {
|
|
120
|
+
throw new Error("Unique properties are required.");
|
|
121
|
+
}
|
|
122
|
+
const columns = properties.map((prop) => `"${prop}"`).join(', ');
|
|
123
|
+
return `ALTER TABLE "${schema}"."${tableName}" ADD CONSTRAINT "${unique.name}" UNIQUE (${columns});`;
|
|
124
|
+
}
|
|
125
|
+
getDropUniqueConstraint(unique, schema, tableName) {
|
|
126
|
+
return this.getDropConstraint(unique, schema, tableName);
|
|
127
|
+
}
|
|
117
128
|
getAlterTableType(schema, tableName, colName, colDiff) {
|
|
118
129
|
return `ALTER TABLE "${schema}"."${tableName}" ALTER COLUMN "${colName}" TYPE ${colDiff.colType}${colDiff.colLength ? `(${colDiff.colLength})` : ''};`;
|
|
119
130
|
}
|
|
@@ -20,6 +20,8 @@ export interface DriverInterface {
|
|
|
20
20
|
getAddColumn(schema: string | undefined, tableName: string, colName: string, colDiff: ColDiff, colDiffInstructions: string[]): void;
|
|
21
21
|
getDropColumn(colDiffInstructions: string[], schema: string | undefined, tableName: string, colName: string): void;
|
|
22
22
|
getDropIndex(index: IndexStatement, schema: string | undefined, tableName: string): string;
|
|
23
|
+
getCreateUniqueConstraint(unique: UniqueStatement, schema: string | undefined, tableName: string): string;
|
|
24
|
+
getDropUniqueConstraint(unique: UniqueStatement, schema: string | undefined, tableName: string): string;
|
|
23
25
|
getAlterTableType(schema: string | undefined, tableName: string, colName: string, colDiff: ColDiff): string;
|
|
24
26
|
getAlterTableDefaultInstruction(schema: string | undefined, tableName: string, colName: string, colDiff: ColDiff): string;
|
|
25
27
|
getAlterTablePrimaryKeyInstruction(schema: string | undefined, tableName: string, colName: string, colDiff: ColDiff): string;
|
|
@@ -136,6 +138,7 @@ export type SnapshotTable = {
|
|
|
136
138
|
schema?: string;
|
|
137
139
|
columns: ColumnsInfo[];
|
|
138
140
|
indexes: SnapshotIndexInfo[];
|
|
141
|
+
uniques?: SnapshotUniqueInfo[];
|
|
139
142
|
foreignKeys?: ForeignKeyInfo[];
|
|
140
143
|
};
|
|
141
144
|
export type SnapshotIndexInfo = {
|
|
@@ -144,11 +147,20 @@ export type SnapshotIndexInfo = {
|
|
|
144
147
|
columnName: string;
|
|
145
148
|
where?: string;
|
|
146
149
|
};
|
|
150
|
+
export type SnapshotUniqueInfo = {
|
|
151
|
+
table: string;
|
|
152
|
+
uniqueName: string;
|
|
153
|
+
columnName: string;
|
|
154
|
+
};
|
|
147
155
|
export type IndexStatement = {
|
|
148
156
|
name: string;
|
|
149
157
|
properties?: string[];
|
|
150
158
|
where?: string;
|
|
151
159
|
};
|
|
160
|
+
export type UniqueStatement = {
|
|
161
|
+
name: string;
|
|
162
|
+
properties?: string[];
|
|
163
|
+
};
|
|
152
164
|
export type ForeignKeyInfo = {
|
|
153
165
|
referencedTableName: string;
|
|
154
166
|
referencedColumnName: string;
|
|
@@ -236,6 +248,8 @@ export type OperatorMap<T> = {
|
|
|
236
248
|
$lt?: ExpandScalar<T>;
|
|
237
249
|
$lte?: ExpandScalar<T>;
|
|
238
250
|
$like?: string;
|
|
251
|
+
$exists?: FilterQuery<ExpandProperty<T>>;
|
|
252
|
+
$nexists?: FilterQuery<ExpandProperty<T>>;
|
|
239
253
|
};
|
|
240
254
|
export type ExcludeFunctions<T, K extends keyof T> = T[K] extends Function ? never : K extends symbol ? never : K;
|
|
241
255
|
export type Scalar = boolean | number | string | bigint | symbol | Date | RegExp | Uint8Array | {
|
package/dist/index.d.ts
CHANGED
|
@@ -3,6 +3,7 @@ export * from './decorators/property.decorator';
|
|
|
3
3
|
export * from './decorators/primary-key.decorator';
|
|
4
4
|
export * from './decorators/one-many.decorator';
|
|
5
5
|
export * from './decorators/index.decorator';
|
|
6
|
+
export * from './decorators/unique.decorator';
|
|
6
7
|
export * from './decorators/event-hook.decorator';
|
|
7
8
|
export * from './decorators/enum.decorator';
|
|
8
9
|
export * from './decorators/computed.decorator';
|
package/dist/index.js
CHANGED
|
@@ -20,6 +20,7 @@ __exportStar(require("./decorators/property.decorator"), exports);
|
|
|
20
20
|
__exportStar(require("./decorators/primary-key.decorator"), exports);
|
|
21
21
|
__exportStar(require("./decorators/one-many.decorator"), exports);
|
|
22
22
|
__exportStar(require("./decorators/index.decorator"), exports);
|
|
23
|
+
__exportStar(require("./decorators/unique.decorator"), exports);
|
|
23
24
|
__exportStar(require("./decorators/event-hook.decorator"), exports);
|
|
24
25
|
__exportStar(require("./decorators/enum.decorator"), exports);
|
|
25
26
|
__exportStar(require("./decorators/computed.decorator"), exports);
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { FilterQuery, Relationship, Statement } from '../driver/driver.interface';
|
|
2
2
|
import { EntityStorage } from '../domain/entities';
|
|
3
|
+
import { SqlSubqueryBuilder } from './sql-subquery-builder';
|
|
3
4
|
type ApplyJoinCallback = (relationship: Relationship<any>, value: FilterQuery<any>, alias: string) => string;
|
|
4
5
|
export declare class SqlConditionBuilder<T> {
|
|
5
6
|
private entityStorage;
|
|
@@ -7,10 +8,13 @@ export declare class SqlConditionBuilder<T> {
|
|
|
7
8
|
private statements;
|
|
8
9
|
private readonly OPERATORS;
|
|
9
10
|
private lastKeyNotOperator;
|
|
11
|
+
private subqueryBuilder?;
|
|
10
12
|
constructor(entityStorage: EntityStorage, applyJoinCallback: ApplyJoinCallback, statements: Statement<T>);
|
|
13
|
+
setSubqueryBuilder(subqueryBuilder: SqlSubqueryBuilder): void;
|
|
11
14
|
build(condition: FilterQuery<T>, alias: string, model: Function): string;
|
|
12
15
|
private processConditions;
|
|
13
16
|
private processEntry;
|
|
17
|
+
private hasExistsOperator;
|
|
14
18
|
private handleRelationship;
|
|
15
19
|
private handleScalarValue;
|
|
16
20
|
private handleObjectValue;
|
|
@@ -39,6 +43,7 @@ export declare class SqlConditionBuilder<T> {
|
|
|
39
43
|
private isLogicalOperator;
|
|
40
44
|
private extractLogicalOperator;
|
|
41
45
|
private trackLastNonOperatorKey;
|
|
46
|
+
private buildExistsCondition;
|
|
42
47
|
private resolveColumnName;
|
|
43
48
|
private resolveRelationColumn;
|
|
44
49
|
}
|
|
@@ -8,15 +8,19 @@ class SqlConditionBuilder {
|
|
|
8
8
|
this.entityStorage = entityStorage;
|
|
9
9
|
this.applyJoinCallback = applyJoinCallback;
|
|
10
10
|
this.statements = statements;
|
|
11
|
-
this.OPERATORS = ['$eq', '$ne', '$in', '$nin', '$like', '$gt', '$gte', '$lt', '$lte', '$and', '$or'];
|
|
11
|
+
this.OPERATORS = ['$eq', '$ne', '$in', '$nin', '$like', '$gt', '$gte', '$lt', '$lte', '$and', '$or', '$exists', '$nexists'];
|
|
12
12
|
this.lastKeyNotOperator = '';
|
|
13
13
|
}
|
|
14
|
+
setSubqueryBuilder(subqueryBuilder) {
|
|
15
|
+
this.subqueryBuilder = subqueryBuilder;
|
|
16
|
+
}
|
|
14
17
|
build(condition, alias, model) {
|
|
15
18
|
const sqlParts = this.processConditions(condition, alias, model);
|
|
16
19
|
if (sqlParts.length === 0) {
|
|
17
20
|
return '';
|
|
18
21
|
}
|
|
19
|
-
|
|
22
|
+
const result = this.wrapWithLogicalOperator(sqlParts, 'AND');
|
|
23
|
+
return result;
|
|
20
24
|
}
|
|
21
25
|
processConditions(condition, alias, model) {
|
|
22
26
|
const sqlParts = [];
|
|
@@ -32,7 +36,7 @@ class SqlConditionBuilder {
|
|
|
32
36
|
processEntry(key, value, alias, model) {
|
|
33
37
|
this.trackLastNonOperatorKey(key, model);
|
|
34
38
|
const relationship = this.findRelationship(key, model);
|
|
35
|
-
if (relationship) {
|
|
39
|
+
if (relationship && !this.hasExistsOperator(value)) {
|
|
36
40
|
return this.handleRelationship(relationship, value, alias);
|
|
37
41
|
}
|
|
38
42
|
if (this.isScalarValue(value)) {
|
|
@@ -43,6 +47,9 @@ class SqlConditionBuilder {
|
|
|
43
47
|
}
|
|
44
48
|
return this.handleObjectValue(key, value, alias, model);
|
|
45
49
|
}
|
|
50
|
+
hasExistsOperator(value) {
|
|
51
|
+
return typeof value === 'object' && value !== null && ('$exists' in value || '$nexists' in value);
|
|
52
|
+
}
|
|
46
53
|
handleRelationship(relationship, value, alias) {
|
|
47
54
|
const sql = this.applyJoinCallback(relationship, value, alias);
|
|
48
55
|
if (this.statements.strategy === 'joined') {
|
|
@@ -100,6 +107,10 @@ class SqlConditionBuilder {
|
|
|
100
107
|
case '$and':
|
|
101
108
|
case '$or':
|
|
102
109
|
return this.buildNestedLogicalCondition(operator, value, alias, model);
|
|
110
|
+
case '$exists':
|
|
111
|
+
return this.buildExistsCondition(key, value, alias, model, false);
|
|
112
|
+
case '$nexists':
|
|
113
|
+
return this.buildExistsCondition(key, value, alias, model, true);
|
|
103
114
|
default:
|
|
104
115
|
return '';
|
|
105
116
|
}
|
|
@@ -202,6 +213,21 @@ class SqlConditionBuilder {
|
|
|
202
213
|
this.lastKeyNotOperator = key;
|
|
203
214
|
}
|
|
204
215
|
}
|
|
216
|
+
buildExistsCondition(key, filters, alias, model, negate) {
|
|
217
|
+
const relationship = this.findRelationship(key, model);
|
|
218
|
+
if (!relationship) {
|
|
219
|
+
const entity = this.entityStorage.get(model);
|
|
220
|
+
const availableRelations = entity?.relations
|
|
221
|
+
?.map((r) => r.propertyKey)
|
|
222
|
+
.join(', ') || 'none';
|
|
223
|
+
throw new Error(`Cannot use $${negate ? 'nexists' : 'exists'} on non-relationship field '${key}'. ` +
|
|
224
|
+
`Available relationships: ${availableRelations}`);
|
|
225
|
+
}
|
|
226
|
+
if (!this.subqueryBuilder) {
|
|
227
|
+
throw new Error('SqlSubqueryBuilder not initialized. This is an internal error.');
|
|
228
|
+
}
|
|
229
|
+
return this.subqueryBuilder.buildExistsSubquery(relationship, filters, alias, negate, model);
|
|
230
|
+
}
|
|
205
231
|
resolveColumnName(property, model) {
|
|
206
232
|
if (property.startsWith('$')) {
|
|
207
233
|
return property;
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import { FilterQuery, Relationship } from '../driver/driver.interface';
|
|
2
|
+
import { EntityStorage } from '../domain/entities';
|
|
3
|
+
import { SqlConditionBuilder } from './sql-condition-builder';
|
|
4
|
+
export declare class SqlSubqueryBuilder {
|
|
5
|
+
private entityStorage;
|
|
6
|
+
private getConditionBuilder;
|
|
7
|
+
private aliasCounter;
|
|
8
|
+
constructor(entityStorage: EntityStorage, getConditionBuilder: () => SqlConditionBuilder<any>);
|
|
9
|
+
buildExistsSubquery(relationship: Relationship<any>, filters: FilterQuery<any>, outerAlias: string, negate: boolean, outerModel?: Function): string;
|
|
10
|
+
private buildSubquery;
|
|
11
|
+
private buildWhereClause;
|
|
12
|
+
private buildCorrelation;
|
|
13
|
+
private getOuterPrimaryKey;
|
|
14
|
+
private buildFilterConditions;
|
|
15
|
+
private combineConditions;
|
|
16
|
+
private resolveTableName;
|
|
17
|
+
private generateAlias;
|
|
18
|
+
private getFkKey;
|
|
19
|
+
private getRelatedPrimaryKey;
|
|
20
|
+
}
|
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.SqlSubqueryBuilder = void 0;
|
|
4
|
+
class SqlSubqueryBuilder {
|
|
5
|
+
constructor(entityStorage, getConditionBuilder) {
|
|
6
|
+
this.entityStorage = entityStorage;
|
|
7
|
+
this.getConditionBuilder = getConditionBuilder;
|
|
8
|
+
this.aliasCounter = 1;
|
|
9
|
+
}
|
|
10
|
+
buildExistsSubquery(relationship, filters, outerAlias, negate, outerModel) {
|
|
11
|
+
const prefix = negate ? 'NOT EXISTS' : 'EXISTS';
|
|
12
|
+
const subquery = this.buildSubquery(relationship, filters, outerAlias, outerModel);
|
|
13
|
+
return `${prefix} (${subquery})`;
|
|
14
|
+
}
|
|
15
|
+
buildSubquery(relationship, filters, outerAlias, outerModel) {
|
|
16
|
+
const subqueryAlias = this.generateAlias();
|
|
17
|
+
const tableName = this.resolveTableName(relationship);
|
|
18
|
+
const whereClause = this.buildWhereClause(relationship, filters, outerAlias, subqueryAlias, outerModel);
|
|
19
|
+
return `SELECT 1 FROM ${tableName} ${subqueryAlias} WHERE ${whereClause}`;
|
|
20
|
+
}
|
|
21
|
+
buildWhereClause(relationship, filters, outerAlias, subqueryAlias, outerModel) {
|
|
22
|
+
const correlation = this.buildCorrelation(relationship, outerAlias, subqueryAlias, outerModel);
|
|
23
|
+
const filterSql = this.buildFilterConditions(filters, subqueryAlias, relationship);
|
|
24
|
+
return this.combineConditions(correlation, filterSql);
|
|
25
|
+
}
|
|
26
|
+
buildCorrelation(relationship, outerAlias, subqueryAlias, outerModel) {
|
|
27
|
+
const fkKey = this.getFkKey(relationship);
|
|
28
|
+
const outerPkKey = this.getOuterPrimaryKey(relationship, outerModel);
|
|
29
|
+
const relatedPkKey = this.getRelatedPrimaryKey(relationship);
|
|
30
|
+
if (relationship.relation === 'one-to-many') {
|
|
31
|
+
return `${subqueryAlias}."${fkKey}" = ${outerAlias}."${outerPkKey}"`;
|
|
32
|
+
}
|
|
33
|
+
const outerFk = relationship.columnName;
|
|
34
|
+
return `${outerAlias}."${outerFk}" = ${subqueryAlias}."${relatedPkKey}"`;
|
|
35
|
+
}
|
|
36
|
+
getOuterPrimaryKey(relationship, outerModel) {
|
|
37
|
+
if (!outerModel) {
|
|
38
|
+
return 'id';
|
|
39
|
+
}
|
|
40
|
+
const entity = this.entityStorage.get(outerModel);
|
|
41
|
+
if (!entity) {
|
|
42
|
+
return 'id';
|
|
43
|
+
}
|
|
44
|
+
for (const prop in entity.properties) {
|
|
45
|
+
if (entity.properties[prop].options.isPrimary) {
|
|
46
|
+
return prop;
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
return 'id';
|
|
50
|
+
}
|
|
51
|
+
buildFilterConditions(filters, alias, relationship) {
|
|
52
|
+
if (!filters || Object.keys(filters).length === 0) {
|
|
53
|
+
return '';
|
|
54
|
+
}
|
|
55
|
+
const conditionBuilder = this.getConditionBuilder();
|
|
56
|
+
const entity = relationship.entity();
|
|
57
|
+
return conditionBuilder.build(filters, alias, entity);
|
|
58
|
+
}
|
|
59
|
+
combineConditions(correlation, filterSql) {
|
|
60
|
+
if (!filterSql) {
|
|
61
|
+
return correlation;
|
|
62
|
+
}
|
|
63
|
+
return `${correlation} AND ${filterSql}`;
|
|
64
|
+
}
|
|
65
|
+
resolveTableName(relationship) {
|
|
66
|
+
const entity = this.entityStorage.get(relationship.entity());
|
|
67
|
+
if (!entity) {
|
|
68
|
+
const name = relationship.entity().name.toLowerCase();
|
|
69
|
+
return `public.${name}`;
|
|
70
|
+
}
|
|
71
|
+
const schema = entity.schema || 'public';
|
|
72
|
+
const tableName = entity.tableName || relationship.entity().name.toLowerCase();
|
|
73
|
+
return `${schema}."${tableName}"`;
|
|
74
|
+
}
|
|
75
|
+
generateAlias() {
|
|
76
|
+
const alias = `sq${this.aliasCounter}`;
|
|
77
|
+
this.aliasCounter++;
|
|
78
|
+
return alias;
|
|
79
|
+
}
|
|
80
|
+
getFkKey(relationship) {
|
|
81
|
+
if (typeof relationship.fkKey === 'undefined') {
|
|
82
|
+
return 'id';
|
|
83
|
+
}
|
|
84
|
+
if (typeof relationship.fkKey === 'string') {
|
|
85
|
+
return relationship.fkKey;
|
|
86
|
+
}
|
|
87
|
+
const match = /\.(?<propriedade>[\w]+)/.exec(relationship.fkKey.toString());
|
|
88
|
+
const propertyKey = match ? match.groups.propriedade : '';
|
|
89
|
+
const entity = this.entityStorage.get(relationship.entity());
|
|
90
|
+
if (!entity) {
|
|
91
|
+
throw new Error(`Entity not found in storage for relationship. ` +
|
|
92
|
+
`Make sure the entity ${relationship.entity().name} is decorated with @Entity()`);
|
|
93
|
+
}
|
|
94
|
+
const property = Object.entries(entity.properties).find(([key, _value]) => key === propertyKey)?.[1];
|
|
95
|
+
if (property) {
|
|
96
|
+
return property.options.columnName;
|
|
97
|
+
}
|
|
98
|
+
const relation = entity.relations.find((rel) => rel.propertyKey === propertyKey);
|
|
99
|
+
if (relation && relation.columnName) {
|
|
100
|
+
return relation.columnName;
|
|
101
|
+
}
|
|
102
|
+
throw new Error(`Property or relation "${propertyKey}" not found in entity "${entity.tableName}". ` +
|
|
103
|
+
`Available properties: ${Object.keys(entity.properties).join(', ')}. ` +
|
|
104
|
+
`Available relations: ${entity.relations.map((r) => r.propertyKey).join(', ')}`);
|
|
105
|
+
}
|
|
106
|
+
getRelatedPrimaryKey(relationship) {
|
|
107
|
+
const entity = this.entityStorage.get(relationship.entity());
|
|
108
|
+
if (!entity) {
|
|
109
|
+
return 'id';
|
|
110
|
+
}
|
|
111
|
+
for (const prop in entity.properties) {
|
|
112
|
+
if (entity.properties[prop].options.isPrimary) {
|
|
113
|
+
return prop;
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
return 'id';
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
exports.SqlSubqueryBuilder = SqlSubqueryBuilder;
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@cheetah.js/orm",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.149",
|
|
4
4
|
"description": "A simple ORM for Cheetah.js.",
|
|
5
5
|
"type": "commonjs",
|
|
6
6
|
"main": "dist/index.js",
|
|
@@ -55,5 +55,5 @@
|
|
|
55
55
|
"bun",
|
|
56
56
|
"value-object"
|
|
57
57
|
],
|
|
58
|
-
"gitHead": "
|
|
58
|
+
"gitHead": "a683593a24301375a1cb97b6523f35f6fafed85c"
|
|
59
59
|
}
|