take() pages authors, limit() cuts rows
Two authors with their posts, once with take(2) and once with limit(2). Ann has 3 posts.
main.ts
import { Entity, PrimaryGeneratedColumn, Column, ManyToOne, OneToMany } from "typeorm";import { connect } from "./db"; @Entity()class Author { @PrimaryGeneratedColumn() id: number; @Column() name: string; @OneToMany(() => Post, (p) => p.author) posts: Post[];} @Entity()class Post { @PrimaryGeneratedColumn() id: number; @Column() title: string; @ManyToOne(() => Author, (a) => a.posts) author: Author;} async function main() { const db = await connect([Author, Post]); await db.query(`INSERT INTO "author" (name) VALUES ('Ann'), ('Bob'), ('Cat')`); await db.query(`INSERT INTO "post" (title, authorId) VALUES ('a1', 1), ('a2', 1), ('a3', 1), ('b1', 2), ('c1', 3)`); const repo = db.getRepository(Author); const take = await repo.createQueryBuilder("a") .leftJoinAndSelect("a.posts", "p") .orderBy("a.id") .take(2) .getMany(); console.log("take: " + take.map((a) => a.name + " " + a.posts.length).join(", ")); const limit = await repo.createQueryBuilder("a") .leftJoinAndSelect("a.posts", "p") .orderBy("a.id") .limit(2) .getMany(); console.log("limit: " + limit.map((a) => a.name + " " + a.posts.length).join(", "));}main();db.ts 38 lines
import "reflect-metadata";import { DataSource } from "typeorm"; let show = false; /** One short line per statement: the verb and the table, enough to count what a call costs. */function short(sql: string): string { const s = sql.replace(/\s+/g, " ").trim(); if (/last_insert_rowid/i.test(s)) return "SELECT new id"; if (/^SELECT DISTINCT "distinctAlias"/i.test(s)) return "SELECT ids (paging)"; const verb = (s.match(/^(SELECT|INSERT INTO|UPDATE|DELETE FROM|BEGIN TRANSACTION|COMMIT|ROLLBACK)/i)?.[0] ?? s.split(" ")[0]).toUpperCase(); const table = s.match(/(?:FROM|INTO|UPDATE)\s+"(\w+)"/i)?.[1]; return table ? verb + " " + table + (/ JOIN /i.test(s) ? " JOIN" : "") : verb;} /** An in-memory SQLite database that prints one line for every SQL statement it runs. */export async function connect(entities: Function[]): Promise<DataSource> { const db = new DataSource({ type: "sqljs", entities, synchronize: true, logging: true, logger: { logQuery: (q: string) => { if (show) console.log("SQL " + short(q)); }, logQueryError: () => {}, logQuerySlow: () => {}, logSchemaBuild: () => {}, logMigration: () => {}, log: () => {}, }, }); await db.initialize(); show = true; return db;} 1. Predict the output
Tap the lines in the order you think they print.
- 1…
- 2…
- 3…
- 4…
- 5…
- 6…
- 7…