修复查询问题

This commit is contained in:
2024-11-29 16:49:52 +08:00
parent fdabf685e8
commit 45919defc6
2 changed files with 51 additions and 15 deletions

View File

@ -1,6 +1,6 @@
{ {
"name": "@yizhi/postgres", "name": "@yizhi/postgres",
"version": "1.0.11", "version": "1.0.12",
"main": "dist/index.js", "main": "dist/index.js",
"types": "typing/index.d.ts", "types": "typing/index.d.ts",
"scripts": {}, "scripts": {},

View File

@ -240,6 +240,7 @@ class SQLBuilderContext {
#nameDict: Record<string, number> = {}; #nameDict: Record<string, number> = {};
#groups: string[] = []; #groups: string[] = [];
#searchs: string[] = []; #searchs: string[] = [];
#hasManyJoin = false;
public genName(name: string) { public genName(name: string) {
this.#nameDict[name] ??= 0; this.#nameDict[name] ??= 0;
@ -254,6 +255,10 @@ class SQLBuilderContext {
public addSearch(search: string) { this.#searchs.push(search); } public addSearch(search: string) { this.#searchs.push(search); }
public get searchs() { return this.#searchs; } public get searchs() { return this.#searchs; }
public set hasManyJoin(val: boolean) { this.#hasManyJoin = val; }
public get hasManyJoin() { return this.#hasManyJoin; }
} }
class SQLBuilder<E extends BasicEntity> { class SQLBuilder<E extends BasicEntity> {
@ -537,6 +542,7 @@ function WithJoin<E extends BasicEntity, B extends Constructor<E>>(Base: B) {
callback = alias; callback = alias;
alias = undefined; alias = undefined;
} }
if (joinConfig.many) this.ctx.hasManyJoin = true;
const joinner = new Joinner(this, name, this.alias, JoinEntity, joinConfig, alias ?? name); const joinner = new Joinner(this, name, this.alias, JoinEntity, joinConfig, alias ?? name);
this.#joinners.push(joinner); this.#joinners.push(joinner);
if (callback) callback(joinner); if (callback) callback(joinner);
@ -672,13 +678,25 @@ export class SelectBuilder<E extends BasicEntity> extends WithGroup(WithJoin(Wit
async findOne() { return this.find().then(res => res[0] ?? null); } async findOne() { return this.find().then(res => res[0] ?? null); }
async count() { async count() {
const sql = `select count(*) as __data_count__ from (\n\t${this.__inner_sql__(false, "\n\t")}\n)`; let sql: string;
if (this.ctx.hasManyJoin) {
sql = `select count(*) as __data_count__ from (\n\t${this.__inner_sql__(false, "\n\t")}\n)`;
}
else {
sql = [
`select count(*) as __data_count__`,
`from ${this.tableSQL} ${escapeID(this.alias)}`,
...this.__joins__, //join
...this.__wheres__.length ? [`where ${this.__wheres__}`] : [], //where条件
...this.ctx.groups.length ? [`group by ${this.ctx.groups.join(",")}`] : [], //分组
].join("\n");
}
// console.log(sql);
const res = await this.#query(sql); const res = await this.#query(sql);
return parseInt(res.rows[0].__data_count__) as number return parseInt(res.rows[0].__data_count__) as number
} }
async findAndCount() { async findAndCount() {
// console.log(this.__sql__(true))
const res = await this.#query(this.__sql__(true)); const res = await this.#query(this.__sql__(true));
const count = res.rows[0]?.__data_count__ ?? 0; const count = res.rows[0]?.__data_count__ ?? 0;
return [this.build(res.rows) as E[], parseInt(count)] as [E[], number]; return [this.build(res.rows) as E[], parseInt(count)] as [E[], number];
@ -736,23 +754,41 @@ export class SelectBuilder<E extends BasicEntity> extends WithGroup(WithJoin(Wit
} }
public __sql__(count: boolean) { public __sql__(count: boolean) {
//外部的SQL if (this.ctx.hasManyJoin) {
const outterSQLItems = [ const groups = [...this.primaryNames.map(p => escapeID(this.alias, p))];
this.#orders?.filter(([name, ord, nulls, group]) => group).forEach(([name, ord, nulls, group]) => groups.push(name));
const buffer = [
`select ${this.__select_columns__}${count ? `, ${escapeID(this.alias)}.__data_count__` : ''}`, //字段列表 `select ${this.__select_columns__}${count ? `, ${escapeID(this.alias)}.__data_count__` : ''}`, //字段列表
`from (\n\t${this.__inner_sql__(count, "\n\t")}\n) ${escapeID(this.alias)}`, //子查询 `from (`,
`\t${this.__inner_sql__(count, "\n\t")}`,
`) ${escapeID(this.alias)}`,
...this.__joins__, //join ...this.__joins__, //join
...this.__wheres__.length ? [`where ${this.__wheres__}`] : [], //where条件 ...this.__wheres__.length ? [`where ${this.__wheres__}`] : [], //where条件
...this.ctx.groups.length ? [`group by ${this.ctx.groups.join(",")}`] : [], //分组 ...this.ctx.groups.length ? [`group by ${this.ctx.groups.join(",")}`] : [], //分组
...this.#orders ? [`order by ${this.#orders.map(([name, ord, nulls]) => `${name} ${ord}${nulls ? ` nulls ${nulls}` : ""}`).join(", ")}`] : [], //排序 ...this.#orders ? [`order by ${this.#orders.map(([name, ord, nulls]) => `${name} ${ord}${nulls ? ` nulls ${nulls}` : ""}`).join(", ")}`] : [], //排序
]; ];
// console.log(buffer.join("\n"));
return outterSQLItems.join("\n"); return buffer.join("\n");
}
else {
const buffer = [
`select ${this.__select_columns__}${count ? `,count(*) over () as __data_count__` : ''}`, //字段列表
`from ${this.tableSQL} ${escapeID(this.alias)}`, //表名
...this.__joins__, //join
...this.__wheres__.length ? [`where ${this.__wheres__}`] : [], //where条件
...this.ctx.groups.length ? [`group by ${this.ctx.groups.join(",")}`] : [], //分组
...this.#orders ? [`order by ${this.#orders.map(([name, ord, nulls]) => `${name} ${ord}${nulls ? ` nulls ${nulls}` : ""}`).join(", ")}`] : [], //排序
...(typeof this.#offset == "number") ? [`offset ${this.#offset}`] : [], //offset
...(typeof this.#limit == "number") ? [`limit ${this.#limit}`] : [], //limit
];
// console.log(buffer.join("\n"));
return buffer.join("\n");
}
} }
public build<D>(data: D[]) { public build<D>(data: D[]) {
return this.__build__(data, this.joinners); return this.__build__(data, this.joinners);
} }
} }
export class InsertBuilder<E extends BasicEntity> extends WithReturning(SQLBuilder)<E> implements IInsertBuilder<E> { export class InsertBuilder<E extends BasicEntity> extends WithReturning(SQLBuilder)<E> implements IInsertBuilder<E> {