Support order, limit and skip on findAll query

This commit is contained in:
Endeavorance 2025-04-18 11:23:28 -04:00
parent f87b3fcf76
commit 4cee7658b8
2 changed files with 64 additions and 11 deletions

View file

@ -362,8 +362,28 @@ export class Table<RowShape> {
*
* @returns {RowShape[]} An array of all rows in the table.
*/
public findAll(): RowShape[] {
return this._db.prepare<RowShape, []>(`SELECT * FROM ${this}`).all();
public findAll(options?: {
order?: string;
limit?: number;
skip?: number;
}): RowShape[] {
const optionParts: string[] = [];
if (options?.order) {
optionParts.push(`ORDER BY ${options.order}`);
}
if (options?.limit) {
optionParts.push(`LIMIT ${options.limit}`);
if (options?.skip) {
optionParts.push(`OFFSET ${options.skip}`);
}
}
return this._db
.prepare<RowShape, []>(`SELECT * FROM ${this} ${optionParts.join(" ")}`)
.all();
}
/**

View file

@ -183,6 +183,39 @@ test(".findAll() returns the full table", () => {
expect(allUsers[2]).toEqual({ user_id: 3, name: "Sayid" });
});
test(".findAll() can set a limit on returned rows", () => {
const table = makeTestTable();
table.insertPartial({ name: "Jack" });
table.insertPartial({ name: "Kate" });
table.insertPartial({ name: "Sayid" });
const allUsers = table.findAll({ limit: 1 });
expect(allUsers).toHaveLength(1);
expect(allUsers[0]).toEqual({ user_id: 1, name: "Jack" });
});
test(".findAll() can set a skip and limit on returned rows", () => {
const table = makeTestTable();
table.insertPartial({ name: "Jack" });
table.insertPartial({ name: "Kate" });
table.insertPartial({ name: "Sayid" });
const allUsers = table.findAll({ limit: 1, skip: 1 });
expect(allUsers).toHaveLength(1);
expect(allUsers[0]).toEqual({ user_id: 2, name: "Kate" });
});
test(".findAll() can set an order for returned rows", () => {
const table = makeTestTable();
table.insertPartial({ name: "Jack" });
table.insertPartial({ name: "Kate" });
table.insertPartial({ name: "Sayid" });
const allUsers = table.findAll({ order: "user_id DESC" });
expect(allUsers).toHaveLength(3);
expect(allUsers[0]).toEqual({ user_id: 3, name: "Sayid" });
});
test(".query() returns a prepared statement for the table", () => {
const table = makeTestTable();
const query = table.query("SELECT * FROM Users WHERE name = ?");