Skip to content

Commit

Permalink
feat(sql): add separate limit and top api
Browse files Browse the repository at this point in the history
  • Loading branch information
woutervanbakel committed Mar 18, 2021
1 parent a6432a2 commit 1e19aee
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 6 deletions.
17 changes: 12 additions & 5 deletions src/sql/Select.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,8 @@ import { Table } from './Table';
export class Select extends SqlQuery {
protected ordered: List<OrderColumn> = list();
protected grouped: List<Column> = list();
protected top = 0;
protected topped = 0;
protected limited = 0;

constructor(table: Table | Join, readonly columns: List<Column> = list()) {
super(table);
Expand All @@ -28,20 +29,26 @@ export class Select extends SqlQuery {
return this;
}

limit(limit: number): this {
this.top = limit;
top(t: number): this {
this.topped = t;
return this;
}

limit(l: number): this {
this.limited = l;
return this;
}

toString(): string {
return (
`SELECT ` +
ifGet(this.top, `TOP ${this.top} `, '') +
ifGet(this.topped, `TOP ${this.topped} `, '') +
ifGet(this.columns.length, this.columns.join(`, `), '*') +
` FROM ${this.table}` +
ifGet(this.clauses.length, ` WHERE ${this.clauses.join(` AND `)}`, '') +
ifGet(this.grouped.length, ` GROUP BY ${this.grouped.join(`, `)}`, '') +
ifGet(this.ordered.length, ` ORDERED BY ${this.ordered.join(`, `)};`, ';')
ifGet(this.ordered.length, ` ORDERED BY ${this.ordered.join(`, `)}`, '') +
ifGet(this.limited, ` LIMIT ${this.limited};`, ';')
);
}
}
7 changes: 6 additions & 1 deletion test/sql/Select.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -50,8 +50,13 @@ describe('Select', () => {
expect(select).toMatchText('SELECT DevTable.Language, MAX(CodingLevel) AS Level FROM DevTable GROUP BY DevTable.Language;');
});

test('With top', () => {
const select = devs.select(devs.language).top(100);
expect(select).toMatchText('SELECT TOP 100 DevTable.Language FROM DevTable;');
});

test('With limit', () => {
const select = devs.select(devs.language).limit(100);
expect(select).toMatchText('SELECT TOP 100 DevTable.Language FROM DevTable;');
expect(select).toMatchText('SELECT DevTable.Language FROM DevTable LIMIT 100;');
});
});

0 comments on commit 1e19aee

Please sign in to comment.