-
Notifications
You must be signed in to change notification settings - Fork 1
/
order-by.ts
83 lines (67 loc) · 2.25 KB
/
order-by.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
import { assert } from '../../error/';
import { OrderByType, Escaper, From } from '../';
/**
* Used by Query classes that can be ordered, like [[Select]] and [[Count]].
*/
export class OrderBy {
// The order of the query.
protected order: OrderByType[] = [];
/**
* Initialize with a From instance.
* @param escaper - An [[Escaper]] matching the database type (e.g.
* [[MySQLEscaper]] or [[MSSQLEscaper]]). Used when escaping column names in
* compiled conditions.
* @param from - A [[From]] instance which holds the base table, all
* joined-in tables, and the where clause.
*/
constructor(
protected escaper: Escaper,
protected from: From) {
}
/**
* Order by one or more columns.
* @param orders - A list of fully-qualified properties in the form
* <table-alias>.<property>, or an array of [[OrderByType]] with
* the fully-qualified property and direction.
*/
orderBy(...orders: OrderByType[] | string[]): this {
// orderBy may only be called once.
assert(!this.isOrdered(), 'orderBy already performed on query.');
for (let i = 0; i < orders.length; ++i) {
const order: OrderByType = typeof orders[i] === 'string' ?
{property: orders[i], dir: 'ASC'} as OrderByType :
orders[i] as OrderByType;
// Make sure the column is available for ordering.
const fromMeta = this.from.getFromMeta();
assert(fromMeta.isColumnAvailable(order.property),
`"${order.property}" is not available for orderBy.`);
this.order.push(order);
}
return this;
}
/**
* Get the ORDER BY portion of the query string, or an empty string if there
* is no order.
*/
getOrderByString(): string {
if (this.isOrdered()) {
const fromMeta = this.from.getFromMeta();
let sql = 'ORDER BY '
sql += this.order
.map(order => {
const colMeta = fromMeta.getFromColumnMetaByProp(order.property);
const colName = this.escaper.escapeFullyQualifiedColumn(colMeta.fqColName);
return `${colName} ${order.dir}`;
})
.join(', ');
return sql;
}
return '';
}
/**
* Returns true if the query is ordered.
*/
isOrdered(): boolean {
return this.order.length !== 0;
}
}