The same transfer in a basket
The same two updates, this time inside db.transaction.
main.ts
import { Entity, PrimaryGeneratedColumn, Column, Check } from "typeorm";import { connect } from "./db"; @Entity()@Check(`"balance" >= 0`)class Account { @PrimaryGeneratedColumn() id: number; @Column() name: string; @Column() balance: number;} async function main() { const db = await connect([Account]); const repo = db.getRepository(Account); await repo.insert([{ name: "Ann", balance: 100 }, { name: "Bob", balance: 0 }]); try { await db.transaction(async (m) => { await m.increment(Account, { name: "Bob" }, "balance", 150); await m.decrement(Account, { name: "Ann" }, "balance", 150); }); } catch (e) { console.log("caught: " + e.name); } console.log("total: " + (await repo.sum("balance")));}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…
- 8…
- 9…
- 10…