SQL 标签
TypeORM 提供了一种用模板字符串编写 SQL 查询的方式,它会根据你的数据库类型自动处理参数。该特性有助于防止 SQL 注入,同时让查询更易读。SQL 标签是围绕 .query 方法实现的一层包装,提供了另一种接口,而底层功能保持不变。
基础用法
sql 标签在 DataSource、EntityManager、Repository 和 QueryRunner 实例上都可用:
const users = await dataSource.sql`SELECT * FROM users WHERE name = ${"John"}`参数处理
参数会根据你的数据库类型被自动转义和格式化:
- PostgreSQL、CockroachDB、Aurora PostgreSQL 使用
$1、$2等:
// 查询变成:SELECT * FROM users WHERE name = $1
const users = await dataSource.sql`SELECT * FROM users WHERE name = ${"John"}`- MySQL、MariaDB、Aurora MySQL、SAP、SQLite 使用
?:
// 查询变成:SELECT * FROM users WHERE name = ?
const users = await dataSource.sql`SELECT * FROM users WHERE name = ${"John"}`- Oracle 使用
:1、:2等:
// 查询变成:SELECT * FROM users WHERE name = :1
const users = await dataSource.sql`SELECT * FROM users WHERE name = ${"John"}`- MSSQL 使用
@1、@2等:
// 查询变成:SELECT * FROM users WHERE name = @1
const users = await dataSource.sql`SELECT * FROM users WHERE name = ${"John"}`多个参数
你可以使用多个参数和复杂表达式:
const name = "John"
const age = 30
const active = true
const users = await dataSource.sql`
SELECT * FROM users
WHERE name LIKE ${name + "%"}
AND age > ${age}
AND is_active = ${active}
`展开参数列表
要把一个值数组转换成模板表达式中的动态参数列表,请把该数组包在一个函数里。这通常用于在 SQL 中编写 IN (...) 表达式,其中列表里的每个值都必须作为独立参数提供:
// 查询变成:SELECT * FROM users WHERE id IN (?, ?, ?)
const users = await dataSource.sql`
SELECT * FROM users
WHERE id IN (${() => [1, 2, 3]})
`插入未转义的表达式
当你想插入一个不应被转换成数据库参数的模板表达式时,请把字符串包在一个函数里。这可用于动态定义无法参数化的列名、表名或模式名,或在 SQL 中按条件设置子句。
注意! 以这种方式插入的原生 SQL 不会做任何转义。把它用在来自用户输入的值上是不安全的。
// 查询变成:SELECT * FROM dynamic_table_name
const rawData = await dataSource.sql`
SELECT * FROM ${() => "dynamic_table_name"}
`特性
- 防止 SQL 注入:参数会被正确转义
- 数据库无关:参数格式化会根据你的数据库类型处理
- 查询更易读:模板字符串能让查询比参数数组更易读
与 query 方法的对比
传统的 query 方法需要手动处理参数占位符:
// 传统 query 方法
await dataSource.query("SELECT * FROM users WHERE name = $1 AND age > $2", [
"John",
30,
])
// SQL 标签替代方案
await dataSource.sql`SELECT * FROM users WHERE name = ${"John"} AND age > ${30}`SQL 标签会自动处理参数格式化,这能减少潜在的错误。
TypeORM provides a way to write SQL queries using template literals with automatic parameter handling based on your database type. This feature helps prevent SQL injection while making queries more readable. The SQL tag is implemented as a wrapper around the .query method, providing an alternative interface while maintaining the same underlying functionality.
Basic Usage
The sql tag is available on DataSource, EntityManager, Repository and QueryRunner instances:
const users = await dataSource.sql`SELECT * FROM users WHERE name = ${"John"}`Parameter Handling
Parameters are automatically escaped and formatted according to your database type:
- PostgreSQL, CockroachDB, Aurora PostgreSQL uses
$1,$2, etc.:
// Query becomes: SELECT * FROM users WHERE name = $1
const users = await dataSource.sql`SELECT * FROM users WHERE name = ${"John"}`- MySQL, MariaDB, Aurora MySQL, SAP, SQLite use
?:
// Query becomes: SELECT * FROM users WHERE name = ?
const users = await dataSource.sql`SELECT * FROM users WHERE name = ${"John"}`- Oracle uses
:1,:2, etc.:
// Query becomes: SELECT * FROM users WHERE name = :1
const users = await dataSource.sql`SELECT * FROM users WHERE name = ${"John"}`- MSSQL uses
@1,@2, etc.:
// Query becomes: SELECT * FROM users WHERE name = @1
const users = await dataSource.sql`SELECT * FROM users WHERE name = ${"John"}`Multiple Parameters
You can use multiple parameters and complex expressions:
const name = "John"
const age = 30
const active = true
const users = await dataSource.sql`
SELECT * FROM users
WHERE name LIKE ${name + "%"}
AND age > ${age}
AND is_active = ${active}
`Expanding Parameter Lists
To transform an array of values into a dynamic list of parameters in a template expression, wrap the array in a function. This is commonly used to write an IN (...) expression in SQL, where each value in the list must be supplied as a separate parameter:
// Query becomes: SELECT * FROM users WHERE id IN (?, ?, ?)
const users = await dataSource.sql`
SELECT * FROM users
WHERE id IN (${() => [1, 2, 3]})
`Interpolating Unescaped Expressions
When you want to insert a template expression which should not be transformed into a database parameter, wrap the string in a function. This can be used to dynamically define column, table or schema names which can't be parameterized, or to conditionally set clauses in the SQL.
Caution! No escaping is performed on raw SQL inserted in this way. It is not safe to use this with values sourced from user input.
// Query becomes: SELECT * FROM dynamic_table_name
const rawData = await dataSource.sql`
SELECT * FROM ${() => "dynamic_table_name"}
`Features
- SQL Injection Prevention: Parameters are properly escaped
- Database Agnostic: Parameter formatting is handled based on your database type
- Readable Queries: Template literals can make queries more readable than parameter arrays
Comparison with Query Method
The traditional query method requires manual parameter placeholder handling:
// Traditional query method
await dataSource.query("SELECT * FROM users WHERE name = $1 AND age > $2", [
"John",
30,
])
// SQL tag alternative
await dataSource.sql`SELECT * FROM users WHERE name = ${"John"} AND age > ${30}`The SQL tag handles parameter formatting automatically, which can reduce potential errors.