Raw SQL
$queryRaw and $executeRaw run statements that the model API cannot express. They accept only tagged templates or sql fragments, never plain strings.
Queries
ts
const email = "alice@example.com";
const rows = await db.$queryRaw<{ id: unknown; email: string }[]>`
SELECT "id", "email" FROM "User" WHERE "email" = ${email}
`;1
2
3
4
2
3
4
The generic parameter is the type of the whole return value, usually an array of records; it does not validate or convert runtime results.
Writes
$executeRaw returns the number of affected rows:
ts
const affected = await db.$executeRaw`
UPDATE "Post" SET "views" = 0 WHERE "published" = ${false}
`;1
2
3
2
3
Composing Fragments
Use sql to build nestable fragments. Parameter placeholders are generated as ? or $n for the current database.
ts
import { sql } from "@ofis/tsorm";
const condition = sql`"email" = ${email}`;
const rows = await db.$queryRaw<{ id: unknown; email: string }[]>(sql`SELECT "id", "email" FROM "User" WHERE ${condition}`);1
2
3
4
2
3
4
Transactions
The tx in a transaction callback provides the same interface:
ts
await db.$transaction(async (tx) => {
await tx.$executeRaw`DELETE FROM "Tag" WHERE "name" = ${"obsolete"}`;
});1
2
3
2
3
Caveats
Interpolation must be a value
Template interpolations bind data values. Use static SQL for table and column names.
- Identifiers: quoting is written by the caller in the database's dialect. PostgreSQL uses double quotes, MySQL uses backticks.
- Result types: records are not decoded through the model, and declared types are not validated at runtime. Adapters normalize bigint values to strings;
datetime, JSON, and similar values follow the adapter's parsing settings. Dateparameters: encoded as instants, see Date & Timezone.- Write guards and soft delete: raw SQL bypasses model visibility, non-empty
wherechecks, andmaxAffected; provide and validate the intended conditions yourself.
Next Steps
- Transactions: run raw statements inside a transaction
- Date & Timezone: how
Dateparameters are encoded - Soft Delete: visibility conditions that raw SQL must add itself