1
1
import type { QueryParams } from "@clickhouse/client" ;
2
2
import type { Client } from "." ;
3
- import { AllExpressions } from "../expressions" ;
3
+ import { AllExpressions , OrderByExpression } from "../expressions" ;
4
4
import * as conditions from "../expressions/conditions" ;
5
5
import { ColumnBuilder } from "../schema/builder" ;
6
6
import { ClickhouseJSONResponse , ExtractPropsFromTable } from "../types/clickhouse" ;
@@ -11,7 +11,9 @@ import { SQLParser, sql } from "../utils/sql";
11
11
12
12
type GenericParams < T extends Table > = {
13
13
where : ( columns : T [ "columns" ] , conditions : AllExpressions ) => SQLParser ;
14
- orderBy ?: ( columns : T [ "columns" ] , conditions : AllExpressions ) => string ;
14
+ orderBy ?: ( columns : T [ "columns" ] , conditions : OrderByExpression ) => string ;
15
+ limit ?: number ;
16
+ offset ?: number ;
15
17
} ;
16
18
17
19
export class Query < T extends Table > {
@@ -25,13 +27,20 @@ export class Query<T extends Table> {
25
27
this . table = table ;
26
28
}
27
29
28
- public async findFirst ( params : GenericParams < T > ) {
30
+ public async findFirst ( params : Omit < GenericParams < T > , "limit" > ) {
29
31
const { template, queryParams : query_params } = parseQuery (
30
32
params . where ( this . table . columns , conditions ) ,
31
33
) ;
32
34
33
35
const queriedData = await this . client . query ( {
34
- query : `SELECT * FROM ${ this . database } .${ this . table . name } WHERE ${ template } LIMIT 1` ,
36
+ query : `SELECT * FROM ${ this . database } .${ this . table . name } WHERE ${ template } ${
37
+ params . orderBy
38
+ ? `ORDER BY ${ params . orderBy ( this . table . columns , {
39
+ asc : conditions . asc ,
40
+ desc : conditions . desc ,
41
+ } ) } `
42
+ : ""
43
+ } LIMIT 1 OFFSET ${ params . offset ?? 0 } `,
35
44
query_params,
36
45
} ) ;
37
46
@@ -46,7 +55,14 @@ export class Query<T extends Table> {
46
55
) ;
47
56
48
57
const queriedData = await this . client . query ( {
49
- query : `SELECT * FROM ${ this . database } .${ this . table . name } WHERE ${ template } ` ,
58
+ query : `SELECT * FROM ${ this . database } .${ this . table . name } WHERE ${ template } ${
59
+ params . orderBy
60
+ ? `ORDER BY ${ params . orderBy ( this . table . columns , {
61
+ asc : conditions . asc ,
62
+ desc : conditions . desc ,
63
+ } ) } `
64
+ : ""
65
+ } LIMIT ${ params . limit ?? 100 } OFFSET ${ params . offset ?? 0 } `,
50
66
query_params,
51
67
} ) ;
52
68
0 commit comments