Microsoft SQL Server
安装
npm install mssql数据源选项
通用数据源选项请参阅数据源选项。
基于 tedious 的 MSSQL 实现。暴露属性的细节请参见 SqlServerDataSourceOptions.ts。
url- 建立连接的连接 url。请注意,其他数据源选项会覆盖从 url 中设置的参数。host- 数据库主机。port- 数据库主机端口。mssql 默认端口是1433。username- 数据库用户名。password- 数据库密码。database- 数据库名。schema- 模式名。默认是 "dbo"。domain- 一旦设置了 domain,驱动就会使用域登录连接 SQL Server。connectionTimeout- 连接超时,单位毫秒(默认:15000)。requestTimeout- 请求超时,单位毫秒(默认:15000)。注意:msnodesqlv8 驱动不支持小于 1 秒的超时。stream- 以流方式处理记录集 / 行,而不是把它们一次性作为回调参数返回(默认:false)。你也可以为每个请求单独启用流式处理(request.stream = true)。如果你打算处理大量行,请始终设为true。pool.max- 连接池中可存在的最大连接数(默认:10)。pool.min- 连接池中可存在的最小连接数(默认:0)。pool.maxWaitingClients- 允许排队的最大请求数,超出的 acquire 调用会在事件循环的下一轮以错误回调。pool.acquireTimeoutMillis-acquire调用在超时前等待资源的最长毫秒数。(默认不限制),如果提供应为非零正整数。pool.fifo- 为 true 时最先分配最旧的资源。为 false 时最先分配最近释放的资源。这实际上把连接池的行为从队列变成了栈。布尔值,(默认true)。pool.priorityRange- 1 到 x 之间的整数——设置后,在没有可用资源时借用者可以在队列中指定自己的相对优先级。参见示例。(默认1)。pool.evictionRunIntervalMillis- 多久运行一次清理检查。默认:0(不运行)。pool.numTestsPerRun- 每次清理运行要检查的资源数。默认:3。pool.softIdleTimeoutMillis- 对象在池中空闲多久后才有资格被空闲对象清理器清理(如果有),额外条件是池中至少保留 "min idle" 个对象实例。默认-1(不会被清理)。pool.idleTimeoutMillis- 对象在池中空闲多久后才有资格因空闲时间被清理。会取代softIdleTimeoutMillis。默认:30000。pool.errorHandler- 当底层连接池触发'error'事件时调用的函数。它接收一个参数(error 实例),默认以warn级别记录日志。options.fallbackToDefaultDb- 默认情况下,如果options.database请求的数据库无法访问,连接会以错误失败。不过,如果options.fallbackToDefaultDb设为true,则改用该用户的默认数据库(默认:false)。options.instanceName- 要连接的实例名。数据库服务器上必须运行 SQL Server Browser 服务,并且数据库服务器上的 UDP 端口 1434 必须可达。与port互斥。(无默认值)。options.enableAnsiNullDefault- 为 true 时,初始 SQL 中会设置SET ANSI_NULL_DFLT_ON ON。这意味着新列默认可空。更多细节参见 T-SQL 文档。(默认:true)。options.cancelTimeout- 请求的取消(中止)被视为失败前的毫秒数(默认:5000)。options.packetSize- TDS 数据包大小(需与服务端协商)。应为 2 的幂。(默认:4096)。options.useUTC- 一个布尔值,决定以 UTC 还是本地时间传递时间值。(默认:false)。options.abortTransactionOnError- 一个布尔值,决定在给定事务执行期间遇到任何错误时是否自动回滚事务。它会在连接的初始 SQL 阶段设置SET XACT_ABORT的值(文档)。options.localAddress- 一个字符串,指示连接 SQL Server 时使用哪个网络接口(ip 地址)。options.useColumnNames- 一个布尔值,决定把行返回为数组还是键值集合。(默认:false)。options.camelCaseColumns- 一个布尔值,控制返回的列名是否把首字母转为小写(true)。如果你提供了columnNameReplacer,该值会被忽略。(默认:false)。options.isolationLevel- 事务运行时使用的默认隔离级别。参见已知问题 > 连接池不会重置隔离级别。READ UNCOMMITTEDREAD COMMITTEDREPEATABLE READSERIALIZABLESNAPSHOT
(默认:
READ COMMITTED)options.connectionIsolationLevel- 新连接的默认隔离级别。所有事务外的查询都以该设置执行。参见已知问题 > 连接池不会重置隔离级别。READ UNCOMMITTEDREAD COMMITTEDREPEATABLE READSERIALIZABLESNAPSHOT
(默认:
READ COMMITTED)options.readOnlyIntent- 一个布尔值,决定连接是否会向 SQL Server 可用性组请求只读访问。更多信息参见此处。(默认:false)。options.encrypt- 一个布尔值,决定连接是否会被加密。如果你在 Windows Azure 上请设为 true。(默认:true)。options.cryptoCredentialsDetails- 使用加密时,可以提供一个对象,它会被用作调用 tls.createSecurePair 时的第一个参数(默认:{})。options.rowCollectionOnDone- 一个布尔值,为 true 时会在 Request 的done*事件中暴露接收到的行。参见 done、doneInProc 和 doneProc。(默认:false)注意:如果接收到很多行,启用该选项可能导致内存占用过高。
options.rowCollectionOnRequestCompletion- 一个布尔值,为 true 时会在 Request 的完成回调中暴露接收到的行。参见 new Request。(默认:false)注意:如果接收到很多行,启用该选项可能导致内存占用过高。
options.tdsVersion- 要使用的 TDS 版本。如果服务器不支持指定版本,则改用协商后的版本。可用版本来自require('tedious').TDS_VERSION。7_17_27_3_A7_3_B7_4
(默认:
7_4)options.appName- 应用名,用于在 SQL Server 的分析、日志或追踪工具中标识某个特定应用。(默认:node-mssql)options.trustServerCertificate- 一个布尔值,控制在没有可验证的服务器证书时是否仍进行加密。(默认:false)options.multiSubnetFailover- 一个布尔值,控制驱动是否应并行连接 DNS 返回的所有 IP。(默认:false)options.debug.packet- 一个布尔值,控制是否触发带数据包细节文本描述的debug事件(默认:false)。options.debug.data- 一个布尔值,控制是否触发带数据包数据细节文本描述的debug事件(默认:false)。options.debug.payload- 一个布尔值,控制是否触发带数据包载荷细节文本描述的debug事件(默认:false)。options.debug.token- 一个布尔值,控制是否触发带 token 流 token 文本描述的debug事件(默认:false)。
列类型
int、bigint、bit、decimal、money、numeric、smallint、smallmoney、tinyint、float、real、date、datetime2、datetime、datetimeoffset、smalldatetime、time、char、varchar、text、nchar、nvarchar、ntext、binary、image、varbinary、hierarchyid、sql_variant、timestamp、uniqueidentifier、xml、geometry、geography、rowversion、vector
向量类型(vector)
vector 数据类型在 SQL Server 中可用于存储高维向量,常用于:
- 基于嵌入的语义搜索
- 推荐系统
- 相似性匹配
- 机器学习应用
注意:通用的 halfvec 类型支持不可用,因为该特性仍处于预览阶段。参见 Microsoft 文档:Vector data type。
用法
@Entity()
export class DocumentChunk {
@PrimaryGeneratedColumn()
id: number
@Column("varchar")
content: string
// 1998 维的向量列
@Column("vector", { length: 1998 })
embedding: number[]
}向量相似性搜索
SQL Server 提供了 VECTOR_DISTANCE 函数来计算向量之间的距离:
const queryEmbedding = [/* 你的查询向量 */]
const results = await dataSource.query(
`
DECLARE @question AS VECTOR (1998) = @0;
SELECT TOP (10) dc.*,
VECTOR_DISTANCE('cosine', @question, embedding) AS distance
FROM document_chunk dc
ORDER BY VECTOR_DISTANCE('cosine', @question, embedding)
`,
[JSON.stringify(queryEmbedding)],
)距离度量:
'cosine'- 余弦距离(语义搜索中最常用)'euclidean'- 欧氏(L2)距离'dot'- 负点积
要求:
- 已启用向量支持的 SQL Server 版本
- 必须用
length选项指定向量维度
已知问题
连接池不会重置隔离级别
驱动专属的 options.isolationLevel 和 options.connectionIsolationLevel 数据源选项,在底层 node-mssql 驱动首次创建连接时会被正确应用。然而,node-mssql 在把连接归还连接池时并不会调用 connection.reset()。这意味着如果某个操作改变了池化连接上的隔离级别(例如以不同级别显式开启的事务),该改动会一直保留并泄漏给该连接的下一个使用者。
实际中,这使得 options.isolationLevel 和 options.connectionIsolationLevel 对那些同时使用按事务隔离级别的应用来说并不可靠。
推荐替代方案: 改用顶层的 isolationLevel DataSource 选项(所有驱动都可用)。它会在每次事务开始时显式应用隔离级别,从而完全绕开连接池的限制。参见事务 > 默认隔离级别。
这是上游限制,追踪于 tediousjs/node-mssql#1483。
Installation
npm install mssqlData Source Options
See Data Source Options for the common data source options.
Based on tedious MSSQL implementation. See SqlServerDataSourceOptions.ts for details on exposed attributes.
url- Connection url where the connection is performed. Please note that other data source options will override parameters set from url.host- Database host.port- Database host port. Default mssql port is1433.username- Database username.password- Database password.database- Database name.schema- Schema name. Default is "dbo".domain- Once you set domain, the driver will connect to SQL Server using domain login.connectionTimeout- Connection timeout in ms (default:15000).requestTimeout- Request timeout in ms (default:15000). NOTE: msnodesqlv8 driver doesn't support timeouts < 1 second.stream- Stream record sets/rows instead of returning them all at once as an argument of callback (default:false). You can also enable streaming for each request independently (request.stream = true). Always set totrueif you plan to work with a large number of rows.pool.max- The maximum number of connections there can be in the pool (default:10).pool.min- The minimum of connections there can be in the pool (default:0).pool.maxWaitingClients- maximum number of queued requests allowed, additional acquire calls will be called back with an error in a future cycle of the event loop.pool.acquireTimeoutMillis- max milliseconds anacquirecall will wait for a resource before timing out. (default no limit), if supplied should non-zero positive integer.pool.fifo- if true the oldest resources will be first to be allocated. If false, the most recently released resources will be the first to be allocated. This, in effect, turns the pool's behaviour from a queue into a stack. boolean, (defaulttrue).pool.priorityRange- int between 1 and x - if set, borrowers can specify their relative priority in the queue if no resources are available. see example. (default1).pool.evictionRunIntervalMillis- How often to run eviction checks. Default:0(does not run).pool.numTestsPerRun- Number of resources to check each eviction run. Default:3.pool.softIdleTimeoutMillis- amount of time an object may sit idle in the pool before it is eligible for eviction by the idle object evictor (if any), with the extra condition that at least "min idle" object instances remain in the pool. Default-1(nothing can get evicted).pool.idleTimeoutMillis- the minimum amount of time that an object may sit idle in the pool before it is eligible for eviction due to idle time. SupersedessoftIdleTimeoutMillis. Default:30000.pool.errorHandler- A function that gets called when the underlying pool emits'error'event. Takes a single parameter (error instance) and defaults to logging withwarnlevel.options.fallbackToDefaultDb- By default, if the database requested byoptions.databasecannot be accessed, the connection will fail with an error. However, ifoptions.fallbackToDefaultDbis set totrue, then the user's default database will be used instead (Default:false).options.instanceName- The instance name to connect to. The SQL Server Browser service must be running on the database server, and UDP port 1434 on the database server must be reachable. Mutually exclusive withport. (no default).options.enableAnsiNullDefault- If true,SET ANSI_NULL_DFLT_ON ONwill be set in the initial SQL. This means new columns will be nullable by default. See the T-SQL documentation for more details. (Default:true).options.cancelTimeout- The number of milliseconds before the cancel (abort) of a request is considered failed (default:5000).options.packetSize- The size of TDS packets (subject to negotiation with the server). Should be a power of 2. (default:4096).options.useUTC- A boolean determining whether to pass time values in UTC or local time. (default:false).options.abortTransactionOnError- A boolean determining whether to roll back a transaction automatically if any error is encountered during the given transaction's execution. This sets the value forSET XACT_ABORTduring the initial SQL phase of a connection (documentation).options.localAddress- A string indicating which network interface (ip address) to use when connecting to SQL Server.options.useColumnNames- A boolean determining whether to return rows as arrays or key-value collections. (default:false).options.camelCaseColumns- A boolean, controlling whether the column names returned will have the first letter converted to lower case (true) or not. This value is ignored if you provide acolumnNameReplacer. (default:false).options.isolationLevel- The default isolation level that transactions will be run with. See Known Issues > Connection pool does not reset isolation level.READ UNCOMMITTEDREAD COMMITTEDREPEATABLE READSERIALIZABLESNAPSHOT
(default:
READ COMMITTED)options.connectionIsolationLevel- The default isolation level for new connections. All out-of-transaction queries are executed with this setting. See Known Issues > Connection pool does not reset isolation level.READ UNCOMMITTEDREAD COMMITTEDREPEATABLE READSERIALIZABLESNAPSHOT
(default:
READ COMMITTED)options.readOnlyIntent- A boolean, determining whether the connection will request read-only access from a SQL Server Availability Group. For more information, see here. (default:false).options.encrypt- A boolean determining whether the connection will be encrypted. Set to true if you're on Windows Azure. (default:true).options.cryptoCredentialsDetails- When encryption is used, an object may be supplied that will be used for the first argument when calling tls.createSecurePair (default:{}).options.rowCollectionOnDone- A boolean, that when true will expose received rows in Requests'done*events. See done, doneInProc and doneProc. (default:false)Caution: If many rows are received, enabling this option could result in excessive memory usage.
options.rowCollectionOnRequestCompletion- A boolean, that when true will expose received rows in Requests' completion callback. See new Request. (default:false)Caution: If many rows are received, enabling this option could result in excessive memory usage.
options.tdsVersion- The version of TDS to use. If the server doesn't support the specified version, a negotiated version is used instead. The versions are available fromrequire('tedious').TDS_VERSION.7_17_27_3_A7_3_B7_4
(default:
7_4)options.appName- Application name used for identifying a specific application in profiling, logging or tracing tools of SQL Server. (default:node-mssql)options.trustServerCertificate- A boolean, controlling whether encryption occurs if there is no verifiable server certificate. (default:false)options.multiSubnetFailover- A boolean, controlling whether the driver should connect to all IPs returned from DNS in parallel. (default:false)options.debug.packet- A boolean, controlling whetherdebugevents will be emitted with text describing packet details (default:false).options.debug.data- A boolean, controlling whetherdebugevents will be emitted with text describing packet data details (default:false).options.debug.payload- A boolean, controlling whetherdebugevents will be emitted with text describing packet payload details (default:false).options.debug.token- A boolean, controlling whetherdebugevents will be emitted with text describing token stream tokens (default:false).
Column Types
int, bigint, bit, decimal, money, numeric, smallint, smallmoney, tinyint, float, real, date, datetime2, datetime, datetimeoffset, smalldatetime, time, char, varchar, text, nchar, nvarchar, ntext, binary, image, varbinary, hierarchyid, sql_variant, timestamp, uniqueidentifier, xml, geometry, geography, rowversion, vector
Vector Type (vector)
The vector data type is available in SQL Server for storing high-dimensional vectors, commonly used for:
- Semantic search with embeddings
- Recommendation systems
- Similarity matching
- Machine learning applications
NOTE: general halfvec type support is unavailable because this feature is still in preview. See the Microsoft docs: Vector data type.
Usage
@Entity()
export class DocumentChunk {
@PrimaryGeneratedColumn()
id: number
@Column("varchar")
content: string
// Vector column with 1998 dimensions
@Column("vector", { length: 1998 })
embedding: number[]
}Vector Similarity Search
SQL Server provides the VECTOR_DISTANCE function for calculating distances between vectors:
const queryEmbedding = [/* your query vector */]
const results = await dataSource.query(
`
DECLARE @question AS VECTOR (1998) = @0;
SELECT TOP (10) dc.*,
VECTOR_DISTANCE('cosine', @question, embedding) AS distance
FROM document_chunk dc
ORDER BY VECTOR_DISTANCE('cosine', @question, embedding)
`,
[JSON.stringify(queryEmbedding)],
)Distance Metrics:
'cosine'- Cosine distance (most common for semantic search)'euclidean'- Euclidean (L2) distance'dot'- Negative dot product
Requirements:
- SQL Server version with vector support enabled
- Vector dimensions must be specified using the
lengthoption
Known Issues
Connection pool does not reset isolation level
The driver-specific options.isolationLevel and options.connectionIsolationLevel data source options are correctly applied when a connection is first created by the underlying node-mssql driver. However, node-mssql does not call connection.reset() when returning connections to the pool. This means that if any operation changes the isolation level on a pooled connection (e.g., an explicit transaction at a different level), the change persists and leaks to the next consumer of that connection.
In practice, this makes options.isolationLevel and options.connectionIsolationLevel unreliable for applications that also use per-transaction isolation levels.
Recommended alternative: Use the top-level isolationLevel DataSource option (available on all drivers) instead. This applies the isolation level explicitly on each transaction start, bypassing the pool limitation entirely. See Transactions > Default Isolation Level.
This is an upstream limitation tracked in tediousjs/node-mssql#1483.