All files / src/query builder.ts

100% Statements 115/115
92.59% Branches 25/27
100% Functions 53/53
100% Lines 108/108
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 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592    1x             1x                         174x                   174x         174x         174x         174x         174x         174x         174x                 4x 4x 4x             3x 3x                                 163x 111x 111x     52x 52x 52x 52x                                             55x 3x     52x 47x 47x     52x 52x                                           3x               17x             17x               1x               3x             3x               1x             6x           6x             1x             1x             1x               5x 5x   5x         5x               1x                                                             11x   11x 11x   11x 2x   9x     11x 11x                                                             1x                                                             1x             3x 2x               5x 5x             1x             2x             35x 33x 33x             20x             1x             5x 5x             10x             42x 41x   41x 41x 54x 27x 27x     27x                 4x 13x             3x             14x             3x             3x             3x             3x             26x 26x   26x 26x 26x             39x 39x 39x               1x 1x 1x             4x 4x 4x             4x 4x 4x               4x             21x             106x             52x         1x
import { JoinType, Operator, OrderDirection, QueryBoolean, WhereQueryClause } from "./types";
import { DatabaseType, KeyedDatabaseResult, Wrapped } from "../base-model";
import Basie from "../index";
 
/**
 * A fluid SQL query builder that is semi-typesafe and supports selecting, inserting, updating
 * and deleting. Obtain an instance using the static methods or one of the methods on wrapped
 * models.
 */
export default class QueryBuilder<T> {
    /**
     * The constructor of the model we are currently querying. If this is non-null,
     * we are still operating on the full model (no narrowed down views) which means
     * that once we have fetched the objects we can assign this prototype to ensure that
     * the returned instance supports any user-defined methods (along with defaults such as save).
     */
    modelConstructor: Function | null;
 
    /**
     * The aggregate function for this query. If this is set, it is assumed
     * that this query selects of format `SELECT fun(columns) AS aggregate`.
     */
    aggregateFunction: string | null = null;
 
    /**
     * Which table we are currently querying.
     */
    table: string;
 
    /**
     * The columns we are currently retrieving.
     */
    columns: string[] = ["*"];
 
    /**
     * If we are only looking for distinct values.
     */
    isDistinct = false;
 
    /**
     * All joins for the current query.
     */
    joins: JoinClause[] = [];
 
    /**
     * All where clauses for the current query.
     */
    wheres: WhereQueryClause[] = [];
 
    /**
     * All the GROUP BY columns for the query.
     */
    groups: string[] = [];
 
    /**
     * All the ORDER BY clauses for the query.
     */
    orders: { column: string, direction: OrderDirection }[] = [];
 
    /**
     * The LIMIT clause for the query, or -1 if not applicable.
     */
    limitCount = -1;
 
    protected constructor() {}
 
    /**
     * Narrows this query down to the specified fields. This erases type-
     * safety since raw SQL queries can be used. Do not use with untrusted input.
     */
    public select(...fields: string[]): QueryBuilder<KeyedDatabaseResult> {
        this.columns = fields;
        this.modelConstructor = null;
        return <any>this;
    }
 
    /**
     * Marks this query as looking for distinct values. Use distinct(false) to undo.
     */
    public distinct(value: boolean = true): this {
        this.isDistinct = value;
        return this;
    }
 
    /**
     * Changes the table this query is currently acting on to the table associated
     * with the specified model.
     */
    public from<A, M extends Wrapped<any, A>>(model: M): QueryBuilder<A>;
 
    /**
     * Changes the table this query is currently acting on to the specified table.
     * An optional type parameter can be used to set the scheme of the table so that
     * further operations are as type-safe as possible.
     */
    public from<M>(table: string): QueryBuilder<M>;
 
    public from<M>(modelOrTable: M | string): QueryBuilder<M> {
        if (typeof modelOrTable === "string") {
            this.table = modelOrTable;
            return <any>this;
        }
 
        this.table = (<any>modelOrTable).tableName;
        this.modelConstructor = <any>modelOrTable;
        this.columns = ["*"];
        return <any>this;
    }
 
    /**
     * Creates a new nested where clause. The specified callback receives a nested
     * query builder that can be used to build the nested queries.
     */
    public where(handler: (builder: this) => any): this;
 
    /**
     * Adds a new where clause for the specified column, requiring that it matches
     * the specified variable. This is an alias for where(column, "=", value).
     */
    public where<K extends keyof T>(column: K, value: T[K]): this;
 
    /**
     * Adds a new where clause for the specified column, operator and value. Optionally
     * you can provide a QueryBoolean of "OR" instead of "AND", but it is recommended that
     * you use `orWhere` instead.
     */
    public where<K extends keyof T>(column: K, operator: Operator, value: T[K], boolean?: QueryBoolean): this;
 
    public where<K extends keyof T>(column: K | ((builder: this) => any), operatorOrValue?: Operator | T[K], value?: T[K], boolean: QueryBoolean = "AND") {
        if (typeof column === "function") {
            return this.whereNested(column, boolean);
        }
 
        if (typeof value === "undefined") {
            value = <any>operatorOrValue;
            operatorOrValue = "=";
        }
 
        this.wheres.push({ type: "basic", column, operator: <Operator>operatorOrValue, value: <DatabaseType><any>value, boolean });
        return this;
    }
 
    /**
     * Creates a new nested WHERE OR clause. The specified callback receives a nested
     * query builder that can be used to build the nested queries.
     */
    public orWhere(handler: (builder: this) => any): this;
 
    /**
     * Adds a new WHERE OR clause for the specified column, requiring that it matches
     * the specified variable. This is an alias for where(column, "=", value).
     */
    public orWhere<K extends keyof T>(column: K, value: T[K]): this;
 
    /**
     * Adds a new WHERE OR clause for the specified column, operator and value. Use
     * `where` if you want to add a WHERE AND clause instead.
     */
    public orWhere<K extends keyof T>(column: K, operator: Operator, value: T[K]): this;
 
    public orWhere<K extends keyof T>(column: K | ((builder: this) => any), operatorOrValue?: Operator | T[K], value?: T[K]) {
        return (<any>this.where)(column, operatorOrValue, value, "OR");
    }
 
    /**
     * Adds a new where clause comparing two columns of the current query. This uses
     * AND as boolean by default, use `orWhereColumn` if you want OR instead.
     */
    public whereColumn<K1 extends keyof T, K2 extends keyof T>(first: K1, operator: Operator, second: K2, boolean: QueryBoolean = "AND") {
        this.wheres.push({
            type: "column",
            first,
            operator,
            second,
            boolean
        });
        return this;
    }
 
    /**
     * Adds a new WHERE OR clause comparing two columns of the current query. This uses
     * OR, use `whereColumn` if you want AND instead.
     */
    public orWhereColumn<K1 extends keyof T, K2 extends keyof T>(first: K1, operator: Operator, second: K2) {
        return this.whereColumn(first, operator, second, "OR");
    }
 
    /**
     * Adds a new raw where clause for the current query. You can use ? as a substitute for arguments
     * to securely bind parameters.
     */
    public whereRaw(query: string, args: DatabaseType[], boolean: QueryBoolean = "AND"): this {
        this.wheres.push({
            type: "raw",
            sql: query,
            values: args,
            boolean
        });
 
        return this;
    }
 
    /**
     * Adds a new raw WHERE OR clause for the current query. You can use ? as a substitute for arguments
     * to securely bind parameters.
     */
    public orWhereRaw(query: string, args: DatabaseType[]): this {
        return this.whereRaw(query, args, "OR");
    }
 
    /**
     * Adds a new where clause asserting that the specified column is NULL.
     */
    public whereNull<K extends keyof T>(column: K, boolean: QueryBoolean = "AND", negate = false): this {
        this.wheres.push({
            type: "null",
            column,
            boolean,
            negate
        });
        return this;
    }
 
    /**
     * Adds a new WHERE OR clause asserting that the specified column is NULL.
     */
    public orWhereNull<K extends keyof T>(column: K): this {
        return this.whereNull(column, "OR");
    }
 
    /**
     * Adds a new where clause asserting that the specified column is NOT NULL.
     */
    public whereNotNull<K extends keyof T>(column: K): this {
        return this.whereNull(column, "AND", true);
    }
 
    /**
     * Adds a new WHERE OR clause asserting that the specified column is NOT NULL.
     */
    public orWhereNotNull<K extends keyof T>(column: K): this {
        return this.whereNull(column, "OR", true);
    }
 
    /**
     * Adds a new nested where query. The handler receives a new QueryBuilder that
     * can be used to enter the where clauses of the nested where.
     */
    public whereNested(handler: (builder: QueryBuilder<T>) => void, boolean: QueryBoolean = "AND") {
        const builder = this.createNew().from<T>(this.table);
        handler(builder);
 
        this.wheres.push({
            type: "nested",
            builder,
            boolean
        });
        return this;
    }
 
    /**
     * Adds a new nested WHERE OR query. The handler receives a new QueryBuilder that
     * can be used to enter the where clauses of the nested where.
     */
    public orWhereNested(handler: (builder: QueryBuilder<T>) => void) {
        return this.whereNested(handler, "OR");
    }
 
    /**
     * Adds a new INNER JOIN with the specified table on the specified columns and operators.
     * This operation loses type-safety since it is impossible to determine the return type
     * of the join statically.
     */
    public join(table: string, first: string, operator: Operator, second: string, type?: JoinType): QueryBuilder<KeyedDatabaseResult>;
 
    /**
     * Adds a new nested INNER JOIN with the specified table. The handler receives a JoinClause
     * which it can use to build the new join.
     */
    public join(table: string, handler: (clause: JoinClause) => any): QueryBuilder<KeyedDatabaseResult>;
 
    /**
     * Adds a new INNER JOIN with the specified model and the specified columns and operator.
     * This operation is type safe and returns a union of the current fields and the fields of
     * the specified model.
     */
    public join<A, M extends Wrapped<any, A>>(model: M, first: string, operator: Operator, second: string, type?: JoinType): QueryBuilder<T & A>;
 
    /**
     * Adds a new nested INNER JOIN with the specified model. The handler receives a JoinClause
     * which it can use to build the new join. This operation is type safe and returns a union
     * of the current fields and the fields of the specified model.
     */
    public join<A, M extends Wrapped<any, A>>(model: M, handler: (clause: JoinClause) => any): QueryBuilder<T & A>;
 
    public join<M>(tableOrModel: string | M, first: string | ((clause: JoinClause) => any), operator?: Operator, second?: string, type: JoinType = "INNER") {
        this.modelConstructor = null;
 
        const table = typeof tableOrModel === "string" ? tableOrModel : (<any>tableOrModel).tableName;
        const clause = new JoinClause(type, table);
 
        if (typeof first === "function") {
            first(clause);
        } else {
            clause.on(first, operator!, second!);
        }
 
        this.joins.push(clause);
        return <any>this;
    }
 
    /**
     * Adds a new LEFT JOIN with the specified table on the specified columns and operators.
     * This operation loses type-safety since it is impossible to determine the return type
     * of the join statically.
     */
    public leftJoin(table: string, first: string, operator: Operator, second: string): QueryBuilder<KeyedDatabaseResult>;
 
    /**
     * Adds a new nested LEFT JOIN with the specified table. The handler receives a JoinClause
     * which it can use to build the new join.
     */
    public leftJoin(table: string, handler: (clause: JoinClause) => any): QueryBuilder<KeyedDatabaseResult>;
 
    /**
     * Adds a new LEFT JOIN with the specified model and the specified columns and operator.
     * This operation is type safe and returns a union of the current fields and the fields of
     * the specified model.
     */
    public leftJoin<A, M extends Wrapped<any, A>>(model: M, first: string, operator: Operator, second: string): QueryBuilder<T & A>;
 
    /**
     * Adds a new nested LEFT JOIN with the specified model. The handler receives a JoinClause
     * which it can use to build the new join. This operation is type safe and returns a union
     * of the current fields and the fields of the specified model.
     */
    public leftJoin<A, M extends Wrapped<any, A>>(model: M, handler: (clause: JoinClause) => any): QueryBuilder<T & A>;
 
    public leftJoin<M>(tableOrModel: string | M, first: string | ((clause: JoinClause) => any), operator?: Operator, second?: string) {
        return (<any>this.join)(tableOrModel, first, operator, second, "LEFT");
    }
 
    /**
     * Adds a new RIGHT JOIN with the specified table on the specified columns and operators.
     * This operation loses type-safety since it is impossible to determine the return type
     * of the join statically.
     */
    public rightJoin(table: string, first: string, operator: Operator, second: string): QueryBuilder<KeyedDatabaseResult>;
 
    /**
     * Adds a new nested RIGHT JOIN with the specified table. The handler receives a JoinClause
     * which it can use to build the new join.
     */
    public rightJoin(table: string, handler: (clause: JoinClause) => any): QueryBuilder<KeyedDatabaseResult>;
 
    /**
     * Adds a new RIGHT JOIN with the specified model and the specified columns and operator.
     * This operation is type safe and returns a union of the current fields and the fields of
     * the specified model.
     */
    public rightJoin<A, M extends Wrapped<any, A>>(model: M, first: string, operator: Operator, second: string): QueryBuilder<T & A>;
 
    /**
     * Adds a new nested RIGHT JOIN with the specified model. The handler receives a JoinClause
     * which it can use to build the new join. This operation is type safe and returns a union
     * of the current fields and the fields of the specified model.
     */
    public rightJoin<A, M extends Wrapped<any, A>>(model: M, handler: (clause: JoinClause) => any): QueryBuilder<T & A>;
 
    public rightJoin<M>(tableOrModel: string | M, first: string | ((clause: JoinClause) => any), operator?: Operator, second?: string) {
        return (<any>this.join)(tableOrModel, first, operator, second, "RIGHT");
    }
 
    /**
     * Marks the query to group the results by the provided column names.
     */
    public groupBy<K extends keyof T>(...groups: K[]) {
        this.groups = [...groups, ...this.groups].filter((e, i, a) => a.indexOf(e) === i);
        return this;
    }
 
    /**
     * Marks the query to order the results by the specified column in the specified
     * direction, or ASC (ascending) by default.
     */
    public orderBy<K extends keyof T>(column: K, direction: OrderDirection = "ASC") {
        this.orders.push({ column, direction });
        return this;
    }
 
    /**
     * Marks the query to order the results by the specified column in ascending direction.
     */
    public orderByAsc<K extends keyof T>(column: K) {
        return this.orderBy(column, "ASC");
    }
 
    /**
     * Marks the query to order the results by the specified column in descending direction.
     */
    public orderByDesc<K extends keyof T>(column: K) {
        return this.orderBy(column, "DESC");
    }
 
    /**
     * Limits the amount of rows this query targets to the specified amount. Must be positive non-null.
     */
    public limit(count: number) {
        if (count < 1) throw new Error("limit() expects a positive integer.");
        this.limitCount = count;
        return this;
    }
 
    /**
     * Returns the first row matching this query.
     */
    public first(): Promise<T | undefined> {
        return this.limit(1).get().then(x => x[0]);
    }
 
    /**
     * Finds the first row with the specified ID. Alias for where("id", id).first()
     */
    public find(id: number): Promise<T | undefined> {
        return this.where(<any>"id", <any>id).first();
    }
 
    /**
     * Returns the specified column of the first result returned by this query.
     */
    public async value<K extends keyof T>(column: K): Promise<T[K]> {
        const entries = await this.limit(1).get();
        return entries[0][column];
    }
 
    /**
     * Alias for get().
     */
    public all(): Promise<T[]> {
        return this.get();
    }
 
    /**
     * Returns all rows matching the current query.
     */
    public get(): Promise<T[]> {
        const compiler = Basie.getEngine().getGrammarCompiler();
        const query = compiler.compileSelect(this);
 
        return Basie.getEngine().get(query.sql, query.args).then(rows => {
            return rows.map(row => {
                if (this.modelConstructor) {
                    const instance = new (<any>this.modelConstructor)();
                    return Object.assign(instance, row);
                }
 
                return row;
            });
        }).then(Object.freeze);
    }
 
    /**
     * Returns only the specified column of all rows this query currently targets.
     */
    public pluck<K extends keyof T>(column: K): Promise<T[K][]> {
        this.columns = [column];
        return this.get().then(x => x.map(y => y[column]));
    }
 
    /**
     * Checks if any rows exist that match the current query. Alias for count > 0.
     */
    public exists(): Promise<boolean> {
        return this.count().then(count => count > 0);
    }
 
    /**
     * Counts the amount of rows matching.
     */
    public count(): Promise<number> {
        return this.aggregate("COUNT");
    }
 
    /**
     * Returns the average of the specified column, or the current column by default.
     */
    public avg(column?: string): Promise<number> {
        return this.aggregate("AVG", column);
    }
 
    /**
     * Returns the sum of the specified column, or the current column by default.
     */
    public sum(column?: string): Promise<number> {
        return this.aggregate("SUM", column);
    }
 
    /**
     * Returns the minimum value of the specified column, or the current column by default.
     */
    public min(column?: string): Promise<number> {
        return this.aggregate("MIN", column);
    }
 
    /**
     * Returns the maximum value of the specified column, or the current column by default.
     */
    public max(column?: string): Promise<number> {
        return this.aggregate("MAX", column);
    }
 
    /**
     * Runs the specified aggregate function and returns the result.
     */
    public aggregate(fn: string, column?: string): Promise<number> {
        this.columns = column ? [column] : this.columns;
        this.aggregateFunction = fn;
 
        const compiler = Basie.getEngine().getGrammarCompiler();
        const query = compiler.compileSelect(this);
        return Basie.getEngine().get(query.sql, query.args).then(x => <number>x[0]["aggregate"]);
    }
 
    /**
     * Inserts the specified entries in the current table.
     */
    public insert(...entries: Partial<T>[]): Promise<void> {
        const compiler = Basie.getEngine().getGrammarCompiler();
        const query = compiler.compileInsert(this, entries);
        return Basie.getEngine().query(query.sql, query.args);
    }
 
    /**
     * Essentially the same as `insert()`, but returns the ID of the inserted
     * row and only supports inserting a single row at a time.
     */
    public insertAndGetId(entry: Partial<T>): Promise<number> {
        const compiler = Basie.getEngine().getGrammarCompiler();
        const query = compiler.compileInsert(this, [entry]);
        return Basie.getEngine().insertAndGetId(this.table, query.sql, query.args);
    }
 
    /**
     * Updates the specified values for all rows matching the current query.
     */
    public update(values: Partial<T>): Promise<void> {
        const compiler = Basie.getEngine().getGrammarCompiler();
        const query = compiler.compileUpdate(this, values);
        return Basie.getEngine().query(query.sql, query.args);
    }
 
    /**
     * Deletes all rows matching the current query.
     */
    public delete(): Promise<void> {
        const compiler = Basie.getEngine().getGrammarCompiler();
        const query = compiler.compileDelete(this);
        return Basie.getEngine().query(query.sql, query.args);
    }
 
    /**
     * Used as a helper function to create a new instance of ourselves. Mainly
     * used in nested where/on clauses. Must be overridden by subclasses.
     */
    protected createNew(): this {
        return <this>new QueryBuilder<T>();
    }
 
    /**
     * Executes the specified raw query.
     */
    public static execute(sql: string, args?: any[]): Promise<void> {
        return Basie.getEngine().query(sql, args || []);
    }
 
    /**
     * Creates a new QueryBuilder referencing the specified table.
     */
    public static table<T extends object>(table: string): QueryBuilder<T> {
        return new QueryBuilder().from<T>(table);
    }
 
    /**
     * Creates a new QueryBuilder referencing the specified model.
     */
    public static model<A, T extends Wrapped<any, A>>(model: T): QueryBuilder<A> {
        return new QueryBuilder().from<A, T>(model);
    }
}
 
// This needs to be here (below QueryBuilder) to prevent a cyclic dependency.
import JoinClause from "./join-clause";