微软 SQL 服务器
Microsoft SQL Server 数据源连接器将 Prisma ORM 连接到 微软 SQL 服务器 数据库服务器。
¥The Microsoft SQL Server data source connector connects Prisma ORM to a Microsoft SQL Server database server.
示例
¥Example
要连接到 Microsoft SQL Server 数据库,你需要在 Prisma 架构 中配置 datasource
块:
¥To connect to a Microsoft SQL Server database, you need to configure a datasource
block in your Prisma schema:
datasource db {
provider = "sqlserver"
url = env("DATABASE_URL")
}
传递到 datasource
块的字段是:
¥The fields passed to the datasource
block are:
-
provider
:指定sqlserver
数据源连接器。¥
provider
: Specifies thesqlserver
data source connector. -
url
:指定 Microsoft SQL Server 数据库的 连接网址。在本例中,使用环境变量 提供连接 URL。¥
url
: Specifies the connection URL for the Microsoft SQL Server database. In this case, an environment variable is used to provide the connection URL.
使用 node-mssql
驱动程序
¥Using the node-mssql
driver
从 v5.4.0
开始,你可以将 Prisma ORM 与 JavaScript 生态系统中的数据库驱动程序一起使用(而不是使用 Prisma ORM 的内置驱动程序)。你可以使用 驱动适配器 来完成此操作。
¥As of v5.4.0
, you can use Prisma ORM with database drivers from the JavaScript ecosystem (instead of using Prisma ORM's built-in drivers). You can do this by using a driver adapter.
对于 SQLite,node-mssql
是 JavaScript 生态系统中最流行的驱动程序之一。
¥For SQLite, node-mssql
is one of the most popular drivers in the JavaScript ecosystem.
本节介绍如何将其与 Prisma ORM 和 @prisma/adapter-mssql
驱动程序适配器一起使用。
¥This section explains how you can use it with Prisma ORM and the @prisma/adapter-mssql
driver adapter.
1. 启用 driverAdapters
预览功能标志
¥ Enable the driverAdapters
Preview feature flag
由于驱动程序适配器当前位于 预览 中,因此你需要在 Prisma 架构中的 datasource
块上启用其功能标志:
¥Since driver adapters are currently in Preview, you need to enable its feature flag on the datasource
block in your Prisma schema:
generator client {
provider = "prisma-client-js"
previewFeatures = ["driverAdapters"]
}
datasource db {
provider = "sqlserver"
url = env("DATABASE_URL")
}
将功能标志添加到架构后,重新生成 Prisma 客户端:
¥Once you have added the feature flag to your schema, re-generate Prisma Client:
npx prisma generate
2. 安装依赖
¥ Install the dependencies
接下来,安装 Prisma ORM 的 node-mssql
驱动程序适配器:
¥Next, install Prisma ORM's driver adapter for node-mssql
:
npm install @prisma/adapter-mssql
3. 使用驱动适配器实例化 Prisma Client
¥ Instantiate Prisma Client using the driver adapter
最后,当实例化 Prisma Client 时,需要将 Prisma ORM 的驱动适配器的实例传递给 PrismaClient
构造函数:
¥Finally, when you instantiate Prisma Client, you need to pass an instance of Prisma ORM's driver adapter to the PrismaClient
constructor:
import { PrismaMssql } from '@prisma/adapter-mssql'
import { PrismaClient } from '@prisma/client'
const config = {
server: 'localhost',
port: 1433,
database: 'mydb',
user: 'sa',
password: 'mypassword',
options: {
encrypt: true, // Use this if you're on Windows Azure
trustServerCertificate: true, // Use this if you're using self-signed certificates
},
}
const adapter = new PrismaMssql(config)
const prisma = new PrismaClient({ adapter })
连接详情
¥Connection details
用于连接 Microsoft SQL Server 数据库的连接 URL 位于 JDBC 标准 后面。
¥The connection URL used to connect to an Microsoft SQL Server database follows the JDBC standard.
以下示例使用 SQL 身份验证(用户名和密码)并启用了 TLS 加密连接:
¥The following example uses SQL authentication (username and password) with an enabled TLS encrypted connection:
sqlserver://HOST[:PORT];database=DATABASE;user=USER;password=PASSWORD;encrypt=true
注意:如果你在连接字符串中使用以下任何字符,则 你需要转义它们。
¥Note: If you are using any of the following characters in your connection string, you will need to escape them.
:\=;/[]{} # these are characters that will need to be escaped
要转义这些字符,请在包含特殊字符的值周围使用大括号 {}
。举个例子:
¥To escape these characters, use curly braces {}
around values that contain special characters. As an example:
sqlserver://HOST[:PORT];database=DATABASE;user={MyServer/MyUser};password={ThisIsA:SecurePassword;};encrypt=true
参数
¥Arguments
参数名称 | 必需的 | 默认 | 评论 |
---|---|---|---|
| 不 | master | 要连接到的数据库。 |
| 不 - 看评论 | SQL Server 登录名(例如 sa )或有效的 Windows(Active Directory)用户名(如果 integratedSecurity 设置为 true )(仅限 Windows)。 | |
| 不 - 看评论 | SQL Server 登录密码或 Windows (Active Directory) 用户名(如果 integratedSecurity 设置为 true )(仅限 Windows)。 | |
encrypt | 不 | true | 配置是否始终使用 TLS,还是仅在登录过程中使用 TLS,可能的值:true (始终使用),false (仅用于登录凭据)。 |
integratedSecurity | 不 | 启用 Windows 身份验证(集成安全性),可能的值:true 、false 、yes 、no 。如果设置为 true 或 yes 并且存在 username 和 password ,则通过 Windows Active Directory 执行登录。如果未通过单独的参数给出登录详细信息,则使用当前登录的 Windows 用户登录服务器。 | |
connectionLimit | 不 | num_cpus * 2 + 1 | 连接池 的最大尺寸 |
connectTimeout | 不 | 5 | 等待新连接的最大秒数 |
schema | 不 | dbo | 如果架构名称不是默认名称,则添加为所有查询的前缀。 |
| 不 | 等待登录成功的秒数。 | |
socketTimeout | 不 | 等待每个查询成功的秒数。 | |
isolationLevel | 不 | 设置 事务隔离级别。 | |
poolTimeout | 不 | 10 | 等待池中新连接的最大秒数。如果所有连接都在使用中,则数据库在等待给定时间后将返回 PoolTimeout 错误。 |
| 不 | 设置连接的应用名称。从 2.28.0 版本开始。 | |
trustServerCertificate | 不 | false | 配置是否信任服务器证书。 |
trustServerCertificateCA | 不 | 用于代替系统证书来授权服务器证书的证书颁发机构文件的路径。必须采用 pem 、crt 或 der 格式。不能与 trustServerCertificate 参数一起使用。 |
使用 综合安全(仅限 Windows)
¥Using integrated security (Windows only)
以下示例使用当前登录的 Windows 用户登录 Microsoft SQL Server:
¥The following example uses the currently logged in Windows user to log in to Microsoft SQL Server:
sqlserver://localhost:1433;database=sample;integratedSecurity=true;trustServerCertificate=true;
以下示例使用特定的 Active Directory 用户登录 Microsoft SQL Server:
¥The following example uses a specific Active Directory user to log in to Microsoft SQL Server:
sqlserver://localhost:1433;database=sample;integratedSecurity=true;username=prisma;password=aBcD1234;trustServerCertificate=true;
连接到命名实例
¥Connect to a named instance
以下示例使用集成安全性连接到 Microsoft SQL Server (mycomputer\sql2019
) 的命名实例:
¥The following example connects to a named instance of Microsoft SQL Server (mycomputer\sql2019
) using integrated security:
sqlserver://mycomputer\sql2019;database=sample;integratedSecurity=true;trustServerCertificate=true;
Microsoft SQL Server 到 Prisma 架构之间的类型映射
¥Type mapping between Microsoft SQL Server to Prisma schema
对于按 Prisma ORM 类型组织的类型映射,请参阅 Prisma 架构参考 文档。
¥For type mappings organized by Prisma ORM type, refer to the Prisma schema reference documentation.
支持的版本
¥Supported versions
参见 支持的数据库。
¥See Supported databases.
限制和已知问题
¥Limitations and known issues
Prisma 迁移注意事项
¥Prisma Migrate caveats
Prisma Migrate 在 2.13.0 及更高版本中受支持,但有以下注意事项:
¥Prisma Migrate is supported in 2.13.0 and later with the following caveats:
数据库模式名称
¥Database schema names
SQL Server 没有与 PostgreSQL 中熟悉的 PostgreSQL SET search_path
命令等效的命令。这意味着当你创建迁移时,你必须在生产数据库使用的连接 URL 中定义相同的架构名称。对于大多数用户来说,这是 dbo
(默认值)。但是,如果生产数据库使用其他架构名称,则必须手动编辑所有迁移 SQL 以反映生产,或者必须在创建迁移之前更改连接 URL(例如:schema=name
)。
¥SQL Server does not have an equivalent to the PostgreSQL SET search_path
command familiar from PostgreSQL. This means that when you create migrations, you must define the same schema name in the connection URL that is used by the production database. For most of the users this is dbo
(the default value). However, if the production database uses another schema name, all the migration SQL must be either edited by hand to reflect the production or the connection URL must be changed before creating migrations (for example: schema=name
).
循环引用
¥Cyclic references
当每个模型引用另一个模型时,模型之间可能会发生循环引用,从而创建闭环。使用 Microsoft SQL Server 数据库时,如果关系上的 参考行动 设置为 NoAction
以外的其他值,Prisma ORM 将显示验证错误。
¥Circular references can occur between models when each model references another, creating a closed loop. When using a Microsoft SQL Server database, Prisma ORM will show a validation error if the referential action on a relation is set to something other than NoAction
.
请参阅 SQL Server 中引用操作的特殊规则 了解更多信息。
¥See Special rules for referential actions in SQL Server for more information.
破坏性的改变
¥Destructive changes
某些迁移会导致比你预期更多的变化。例如:
¥Certain migrations will cause more changes than you might expect. For example:
-
添加或删除
autoincrement()
。这无法通过修改列来实现,而是需要重新创建表(包括所有约束、索引和外键)并在表之间移动所有数据。¥Adding or removing
autoincrement()
. This cannot be achieved by modifying the column, but requires recreating the table (including all constraints, indices, and foreign keys) and moving all data between the tables. -
此外,不可能从表中删除所有列(对于 PostgreSQL 或 MySQL 是可能的)。如果迁移需要重新创建所有表列,它也会重新创建表。
¥Additionally, it is not possible to delete all the columns from a table (possible with PostgreSQL or MySQL). If a migration needs to recreate all table columns, it will also re-create the table.
不支持共享默认值
¥Shared default values are not supported
在某些情况下,用户可能希望将默认值定义为共享对象:
¥In some cases, user might want to define default values as shared objects:
CREATE DEFAULT catcat AS 'musti';
CREATE TABLE cats (
id INT IDENTITY PRIMARY KEY,
name NVARCHAR(1000)
);
sp_bindefault 'catcat', 'dbo.cats.name';
使用存储过程 sp_bindefault
,默认值 catcat
可以在多个表中使用。Prisma ORM 管理默认值的方式是针对每个表的:
¥Using the stored procedure sp_bindefault
, the default value catcat
can be used in more than one table. The way Prisma ORM manages default values is per table:
CREATE TABLE cats (
id INT IDENTITY PRIMARY KEY,
name NVARCHAR(1000) CONSTRAINT DF_cat_name DEFAULT 'musti'
);
反思最后一个例子,会得出以下模型:
¥The last example, when introspected, leads to the following model:
model cats {
id Int @id @default(autoincrement())
name String? @default("musti")
}
第一个没有内省默认值:
¥And the first doesn't get the default value introspected:
model cats {
id Int @id @default(autoincrement())
name String?
}
如果将 Prisma Migrate 与共享默认对象一起使用,则必须手动对 SQL 进行更改。
¥If using Prisma Migrate together with shared default objects, changes to them must be done manually to the SQL.
数据模型的限制
¥Data model limitations
无法使用具有 UNIQUE
约束和过滤索引的列作为外键
¥Cannot use column with UNIQUE
constraint and filtered index as foreign key
微软 SQL Server 具有 UNIQUE
约束的列中只允许有一个 NULL
值。例如:
¥Microsoft SQL Server only allows one NULL
value in a column that has a UNIQUE
constraint. For example:
-
用户表有一个名为
license_number
的列¥A table of users has a column named
license_number
-
license_number
字段有UNIQUE
约束¥The
license_number
field has aUNIQUE
constraint -
license_number
字段只允许有一个NULL
值¥The
license_number
field only allows oneNULL
value
解决此问题的标准方法是创建一个排除 NULL
值的筛选唯一索引。这允许你插入多个 NULL
值。如果你没有在数据库中创建索引,那么当你尝试使用 Prisma Client 将多个 null
值插入到列中时,你将收到错误消息。
¥The standard way to get around this issue is to create a filtered unique index that excludes NULL
values. This allows you to insert multiple NULL
values. If you do not create an index in the database, you will get an error if you try to insert more than one null
value into a column with Prisma Client.
但是,创建索引使得无法使用 license_number
作为数据库中的外键(或相应 Prisma Schema 中的关系标量字段)
¥However, creating an index makes it impossible to use license_number
as a foreign key in the database (or a relation scalar field in corresponding Prisma Schema)
原始查询注意事项
¥Raw query considerations
带有 String @db.VarChar(n)
字段/VARCHAR(N)
列的原始查询
¥Raw queries with String @db.VarChar(n)
fields / VARCHAR(N)
columns
原始查询 中的 String
查询参数始终编码为 SQL Server 中的 NVARCHAR(4000)
(如果你的 String
长度为 <= 4000)或 NVARCHAR(MAX)
。如果将 String
查询参数与 String @db.VarChar(N)
/VARCHAR(N)
类型的列进行比较,这可能会导致 SQL Server 上的隐式转换,从而影响你的索引性能并导致高 CPU 使用率。
¥String
query parameters in raw queries are always encoded to SQL Server as NVARCHAR(4000)
(if your String
length is <= 4000) or NVARCHAR(MAX)
. If you compare a String
query parameter to a column of type String @db.VarChar(N)
/VARCHAR(N)
, this can lead to implicit conversion on SQL Server which affects your index performance and can lead to high CPU usage.
这是一个例子:
¥Here is an example:
model user {
id Int @id
name String @db.VarChar(40)
}
此查询将受到影响:
¥This query would be affected:
await prisma.$queryRaw`SELECT * FROM user WHERE name = ${"John"}`
为避免此问题,我们建议你始终在原始查询中手动将 String
查询参数转换为 VARCHAR(N)
:
¥To avoid the problem, we recommend you always manually cast your String
query parameters to VARCHAR(N)
in the raw query:
await prisma.$queryRaw`SELECT * FROM user WHERE name = CAST(${"John"} AS VARCHAR(40))`
这使 SQL Server 能够执行聚集索引查找而不是聚集索引扫描。
¥This enables SQL Server to perform a Clustered Index Seek instead of a Clustered Index Scan.