Relation Map · Level 2 of 8

relations: walk down the hall

The same data, loaded with relations: { posts: true }, first by findOne and then by find.

main.ts
import { Entity, PrimaryGeneratedColumn, Column, OneToMany, ManyToOne, JoinColumn } from "typeorm";import { connect } from "./db"; @Entity()class User {  @PrimaryGeneratedColumn() id!: number;  @Column() name!: string;  @OneToMany(() => Post, (p) => p.author) posts!: Post[];} @Entity()class Post {  @PrimaryGeneratedColumn() id!: number;  @Column() title!: string;  @Column() authorId!: number;  @ManyToOne(() => User, (u) => u.posts)  @JoinColumn({ name: "authorId" }) author!: User;} async function main() {  const db = await connect([User, Post]);  const users = db.getRepository(User);  const posts = db.getRepository(Post);  await users.insert({ name: "Ann" });  await posts.insert({ title: "Hi", authorId: 1 });  const ann = await users.findOne({ where: { id: 1 }, relations: { posts: true } });  console.log("findOne posts: " + ann!.posts.length);  const all = await users.find({ relations: { posts: true } });  console.log("find posts: " + all[0].posts.length);}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. 1…
  2. 2…
  3. 3…
  4. 4…
  5. 5…
  6. 6…
  7. 7…
  8. 8…
  9. 9…