@@ -2,22 +2,31 @@ import { Query, QueryAnd, QueryOr, Order, Predicate, Operator, IsNull } from "./
2
2
3
3
function predicateToSQL < TRow > (
4
4
predicate : Predicate < TRow > ,
5
- resolveName : ( key : keyof TRow ) => string
5
+ resolveName : ( key : keyof TRow ) => string | undefined
6
6
) : string {
7
7
const { column, compare } = predicate ;
8
+ // If we cannot find the column name, we just use the column name as is.
9
+ // It's possible that the column exists but we just don't know it on the client.
10
+ const columnName = resolveName ( column ) ?? String ( column ) ;
8
11
9
12
if ( "other" in predicate ) {
10
13
const { other } = predicate ;
14
+
11
15
// TODO this is a bit too tricky. If the RHS matches a column name, we treat it as such. Otherwise we use it bare.
12
16
const otherColumn = resolveName ( other as keyof TRow ) ;
13
17
if ( otherColumn !== undefined ) {
14
- return `"${ resolveName ( column ) } " ${ compare } "${ otherColumn } "` ;
18
+ return `"${ columnName } " ${ compare } "${ otherColumn } "` ;
15
19
} else {
20
+ // We did not resolve the RHS to a column name, so we treat it as a value.
21
+ // It's possible that this is actually a column that exists in the table,
22
+ // but the client does not know about it.
23
+
24
+ // This quoting is bad – we should require client users to do this.
16
25
const bareValue = typeof other === "string" ? `'${ other } '` : other ;
17
- return `"${ resolveName ( column ) } " ${ compare } ${ String ( bareValue ) } ` ;
26
+ return `"${ columnName } " ${ compare } ${ String ( bareValue ) } ` ;
18
27
}
19
28
}
20
- return `"${ resolveName ( column ) } " ${ compare } ` ;
29
+ return `"${ columnName } " ${ compare } ` ;
21
30
}
22
31
23
32
export class QueryBuilder < TRow , TOmit extends string >
@@ -30,7 +39,9 @@ export class QueryBuilder<TRow, TOmit extends string>
30
39
private _and : Predicate < TRow > [ ] = [ ] ;
31
40
private _or : Predicate < TRow > [ ] = [ ] ;
32
41
33
- constructor ( private props : { table : string ; displayNameToName ( name : keyof TRow ) : string } ) { }
42
+ constructor (
43
+ private props : { table : string ; displayNameToName ( name : keyof TRow ) : string | undefined }
44
+ ) { }
34
45
35
46
public toSQL ( ) : string {
36
47
const { table, displayNameToName } = this . props ;
@@ -46,7 +57,10 @@ export class QueryBuilder<TRow, TOmit extends string>
46
57
47
58
if ( this . _orderBy !== undefined ) {
48
59
const { column, order = "ASC" } = this . _orderBy ;
49
- sql += ` ORDER BY "${ displayNameToName ( column ) } " ${ order } ` ;
60
+ // If we cannot find the column name, we just use the column name as is.
61
+ // It's possible that the column exists but we just don't know it on the client.
62
+ const columnName = displayNameToName ( column ) ?? String ( column ) ;
63
+ sql += ` ORDER BY "${ columnName } " ${ order } ` ;
50
64
}
51
65
52
66
if ( this . _limit !== undefined ) {
0 commit comments