# SQL 标签

> 英文标题：SQL Tag
> 官网原文：https://typeorm.io/docs/guides/sql-tag
> 文档版本：TypeORM v1.1
> 体例：英文原文（EN）与中文译文（ZH）逐块并列，共 31 块

---

<!-- EN -->
# SQL Tag

<!-- ZH -->
# SQL 标签

<!-- EN -->
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.

<!-- ZH -->
TypeORM 提供了一种用模板字符串编写 SQL 查询的方式，它会根据你的数据库类型自动处理参数。该特性有助于防止 SQL 注入，同时让查询更易读。SQL 标签是围绕 `.query` 方法实现的一层包装，提供了另一种接口，而底层功能保持不变。

<!-- EN -->
## Basic Usage

<!-- ZH -->
## 基础用法

<!-- EN -->
The `sql` tag is available on DataSource, EntityManager, Repository and QueryRunner instances:

<!-- ZH -->
`sql` 标签在 DataSource、EntityManager、Repository 和 QueryRunner 实例上都可用：

<!-- EN -->
```typescript
const users = await dataSource.sql`SELECT * FROM users WHERE name = ${"John"}`
```

<!-- ZH -->
```typescript
const users = await dataSource.sql`SELECT * FROM users WHERE name = ${"John"}`
```

<!-- EN -->
## Parameter Handling

<!-- ZH -->
## 参数处理

<!-- EN -->
Parameters are automatically escaped and formatted according to your database type:

<!-- ZH -->
参数会根据你的数据库类型被自动转义和格式化：

<!-- EN -->
* **PostgreSQL**, **CockroachDB**, **Aurora PostgreSQL** uses `$1`, `$2`, etc.:

<!-- ZH -->
* **PostgreSQL**、**CockroachDB**、**Aurora PostgreSQL** 使用 `$1`、`$2` 等：

<!-- EN -->
```typescript
// Query becomes: SELECT * FROM users WHERE name = $1
const users = await dataSource.sql`SELECT * FROM users WHERE name = ${"John"}`
```

<!-- ZH -->
```typescript
// 查询变成：SELECT * FROM users WHERE name = $1
const users = await dataSource.sql`SELECT * FROM users WHERE name = ${"John"}`
```

<!-- EN -->
* **MySQL**, **MariaDB**, **Aurora MySQL**, **SAP**, **SQLite** use `?`:

<!-- ZH -->
* **MySQL**、**MariaDB**、**Aurora MySQL**、**SAP**、**SQLite** 使用 `?`：

<!-- EN -->
```typescript
// Query becomes: SELECT * FROM users WHERE name = ?
const users = await dataSource.sql`SELECT * FROM users WHERE name = ${"John"}`
```

<!-- ZH -->
```typescript
// 查询变成：SELECT * FROM users WHERE name = ?
const users = await dataSource.sql`SELECT * FROM users WHERE name = ${"John"}`
```

<!-- EN -->
* **Oracle** uses `:1`, `:2`, etc.:

<!-- ZH -->
* **Oracle** 使用 `:1`、`:2` 等：

<!-- EN -->
```typescript
// Query becomes: SELECT * FROM users WHERE name = :1
const users = await dataSource.sql`SELECT * FROM users WHERE name = ${"John"}`
```

<!-- ZH -->
```typescript
// 查询变成：SELECT * FROM users WHERE name = :1
const users = await dataSource.sql`SELECT * FROM users WHERE name = ${"John"}`
```

<!-- EN -->
* **MSSQL** uses `@1`, `@2`, etc.:

<!-- ZH -->
* **MSSQL** 使用 `@1`、`@2` 等：

<!-- EN -->
```typescript
// Query becomes: SELECT * FROM users WHERE name = @1
const users = await dataSource.sql`SELECT * FROM users WHERE name = ${"John"}`
```

<!-- ZH -->
```typescript
// 查询变成：SELECT * FROM users WHERE name = @1
const users = await dataSource.sql`SELECT * FROM users WHERE name = ${"John"}`
```

<!-- EN -->
### Multiple Parameters

<!-- ZH -->
### 多个参数

<!-- EN -->
You can use multiple parameters and complex expressions:

<!-- ZH -->
你可以使用多个参数和复杂表达式：

<!-- EN -->
```typescript
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}
`
```

<!-- ZH -->
```typescript
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}
`
```

<!-- EN -->
### Expanding Parameter Lists

<!-- ZH -->
### 展开参数列表

<!-- EN -->
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:

<!-- ZH -->
要把一个值数组转换成模板表达式中的动态参数列表，请把该数组包在一个函数里。这通常用于在 SQL 中编写 `IN (...)` 表达式，其中列表里的每个值都必须作为独立参数提供：

<!-- EN -->
```typescript
// Query becomes: SELECT * FROM users WHERE id IN (?, ?, ?)
const users = await dataSource.sql`
    SELECT * FROM users
    WHERE id IN (${() => [1, 2, 3]})
`
```

<!-- ZH -->
```typescript
// 查询变成：SELECT * FROM users WHERE id IN (?, ?, ?)
const users = await dataSource.sql`
    SELECT * FROM users
    WHERE id IN (${() => [1, 2, 3]})
`
```

<!-- EN -->
### Interpolating Unescaped Expressions

<!-- ZH -->
### 插入未转义的表达式

<!-- EN -->
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.

<!-- ZH -->
当你想插入一个*不应*被转换成数据库参数的模板表达式时，请把字符串包在一个函数里。这可用于动态定义无法参数化的列名、表名或模式名，或在 SQL 中按条件设置子句。

<!-- EN -->
**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.

<!-- ZH -->
**注意！** 以这种方式插入的原生 SQL 不会做任何转义。把它用在来自用户输入的值上是不安全的。

<!-- EN -->
```typescript
// Query becomes: SELECT * FROM dynamic_table_name
const rawData = await dataSource.sql`
    SELECT * FROM ${() => "dynamic_table_name"}
`
```

<!-- ZH -->
```typescript
// 查询变成：SELECT * FROM dynamic_table_name
const rawData = await dataSource.sql`
    SELECT * FROM ${() => "dynamic_table_name"}
`
```

<!-- EN -->
## Features

<!-- ZH -->
## 特性

<!-- EN -->
* **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

<!-- ZH -->
* **防止 SQL 注入**：参数会被正确转义
* **数据库无关**：参数格式化会根据你的数据库类型处理
* **查询更易读**：模板字符串能让查询比参数数组更易读

<!-- EN -->
## Comparison with Query Method

<!-- ZH -->
## 与 query 方法的对比

<!-- EN -->
The traditional `query` method requires manual parameter placeholder handling:

<!-- ZH -->
传统的 `query` 方法需要手动处理参数占位符：

<!-- EN -->
```typescript
// 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}`
```

<!-- ZH -->
```typescript
// 传统 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}`
```

<!-- EN -->
The SQL tag handles parameter formatting automatically, which can reduce potential errors.

<!-- ZH -->
SQL 标签会自动处理参数格式化，这能减少潜在的错误。
