Skip to content

Commit 8c75f83

Browse files
feat(driver-sql): SQL Server as a federation-only dialect (#31381)
<!-- claude-projects-attribution: {"github_login":"marchtian"} --> _Requested by **田騏** · [project thread](https://claude.ai/code/project/chan_01VmuUhXU9SSUzqJYyXSmYSi?thread=cmsg_01VmuUhXU9SSUzqJYyXSmYSi7ghxnTm51PSygb4ygX2wUJ)_ Fixes #31327 Clause-②: yes (widening) Metadata-protocol: added Skills-docs: generated only — `skills/objectstack-data/references/_index.md` gains the `driver/mssql.zod.ts` row (`gen:skill-refs`); no hand-written skill text changes. ## 维护者速读 - **改了什么**:外部数据源新增 SQL Server(`driver: 'mssql'`,别名 `sqlserver` / `tedious`),只做联邦:能读写已有的 SQL Server 表,Studio 能列出 `dbo.Orders` 这类表并导入为对象;平台永不在 SQL Server 上建表或改表,managed 数据源声明它会在解析时被拒。 - **为什么改**:企业客户的业务数据大量在 SQL Server(ERP、财务库)。没有这个方言之前,driver-sql 把它当 `unknown`,文本匹配在 SQL Server 默认不区分大小写的排序规则下答错,分页语法也不合法。 - **风险与回滚**:新增驱动行与新方言分支,其余驱动行为不变。已与先落地的 Oracle(#31351)对齐成一套名字和机制:联邦专用判断、选择面类型、managed 拒绝消息、DDL 拒绝渲染都用 Oracle 的;两边的 lossy 规则合成一张表 `DIALECT_LOSSY_RULES`,Oracle 的结果不变。另改了一个检查脚本:`check-driver-conformance` 把联邦套件(SQL Server 和 Oracle)单列报告,不计入托管矩阵覆盖。回滚即整体 revert。 - **先看**:① `packages/spec/src/data/driver/config-registry.zod.ts`(federationOnly 列与选择面类型)② `packages/drivers/driver-sql/src/sql-driver-predicate-emitters.ts` 的 mssql 文本匹配分支(BIN2 + TRANSLATE)③ `scripts/check-driver-conformance.mjs` 的 federation 立场(新语义)。 - **两分钟验证**:`pnpm --filter @objectstack/driver-sql exec vitest run src/sql-driver-mssql-dialect.test.ts`,预期 15 条全过;有 SQL Server 时设 `OS_TEST_MSSQL_URL` 跑联邦一致性套件,预期 227/227。 - **需要你做的**:ADR-0015 §4.6 改动属受管面(Tier H),需要你批准;contract review owed(Fable 不可用,按默认档)。 ## What changes - **`@objectstack/spec`**: the driver vocabulary gains `mssql` (aliases `sqlserver`, `tedious`), a second `federationOnly` row after Oracle's (#31351), with `hasLocalDefault: false`. #31351's `FEDERATION_ONLY_DRIVER_IDS`, `isFederationOnlyDriver()`, `FederationOnlyDriverId` and `DatabaseSelectionDriverId` now answer both drivers, and a `managed` datasource declaring `mssql` meets the same parse-time refusal as `oracle` (`federationOnlyDriverOnManagedRefusal`, which names the drivers that can be managed from `DATABASE_DRIVER_SELECTION_IDS`). `MssqlConfigSchema` is the closed config (`host`, `port` 1433, `instanceName`, `database`, `username`, `ssl`); an inline password, a URL and `autoMigrate` are refused with the reason. The boot-host selection tables are built without federation-only rows, so the withdrawal holds by the column, not by the row's empty `aliases`. `type-compat` gains `SqlDialect` `'mssql'` and `DIALECT_ALIASES.mssql`. Oracle's exact-to-lossy demotion (`DIALECT_DEMOTED_TO_LOSSY`) and this PR's added lossy pairing are now ONE table, `DIALECT_LOSSY_RULES`, one rule per (dialect, canonical type) with `demoteExact` and `addLossy`, both only ever toward `'lossy'`: `oracle` / `uuid` keeps its demotion unchanged, and on `mssql` a text column backs a `json`, `tags` or `multiselect` field as `'lossy'`, because SQL Server keeps JSON in `nvarchar(max)` and the driver stores those fields there. A self-signed server is documented as the datasource-level `ssl: { enabled: true, rejectUnauthorized: false }`: the block's `enabled` defaults to false, and a block without it turns encryption off. ADR-0015 §4.6 lists the dialect and the one lossy table, and §5.1's federation-only arm (from #31351) names both drivers and that no boot host selects either. - **`@objectstack/driver-sql`**: `dialectName` reads `'mssql'`. Paging is `OFFSET … FETCH` with an ORDER BY (the caller's keys, else the table's single-column primary key read from the catalog, else `(SELECT NULL)`), and `limit: 0` is `TOP (0)`. Identifiers are `[]`-quoted. Text predicates keep the #6518 contract on case-insensitive collations: case-exact through `Latin1_General_100_BIN2`, folded with `TRANSLATE`, `%` `_` `[` escaped with a bound ESCAPE. A `bit` aggregand is cast for SUM/AVG/MIN/MAX. Writes use `OUTPUT inserted.*` through a temp table, so a table with triggers accepts them. A `uniqueidentifier` reads back in the canonical lower-case form (tedious `lowerCaseGuids`, unless the host sets it), so the `uniqueidentifier` to `uuid` type-compat row holds: a GUID written as a string reads back as that string and filters by it in either case. Dates bind as ISO text against `nvarchar` columns. JSON text columns read back. Introspection lists user tables as `schema.table` with primary keys, foreign keys, single-column uniques and indexes. Managed DDL is refused (`SQL_DIALECT_EMISSION_UNSUPPORTED`) through #31351's `'federation-only'` reason and its renderer, which names the client it refuses; this PR's own vendor-named renderer is gone. `coreSqlDialectOf` maps `mssql` to `'unknown'` as it does `oracle`. Paging falls back from the caller's keys to the column the binding's `columnMap` maps to `id` (#31378), then to the catalog key. And `$contains` / `$empty` on a multi-value field is refused instead of approximated. - **`@objectstack/service-datasource`**: the factory builds `SqlDriver` with the `tedious` connection (server, port, database, user, the bound secret as password, encrypt / trustServerCertificate / instanceName / CA from config and the datasource `ssl` block) and reports `@@VERSION`. `resolveSslOption` moves unchanged to the leaf module `datasource-ssl-option.ts`, so the connection pins load no driver; the liveness ledger's five citations of it are repointed. The Studio connection form does not offer `mssql`; it is declared in code (optional `tedious` peer, federation-only). - **Docs**: `content/docs/data-modeling/external-datasources.mdx` gains "8. SQL Server (federation only)", after Oracle's §7; `drivers.mdx` lists it next to Oracle; the reference page `references/data/driver-mssql.mdx` is generated. - **`scripts/check-driver-conformance.mjs`**: a suite that names `MSSQL_FEDERATION_CELL` or `ORACLE_CELL` is a federation suite. It is listed on its own line under the dialect axis and is never counted as managed-matrix coverage, so it cannot discharge a managed DEBT entry (driver-sql's `UNIQUE_NULL_DISTINCT` debt stays) or trip MATRIXED. `FEDERATION_CELL_SYMBOLS` is the list a further federation-only dialect appends to. Self-test gains three assertions. ## Tests - `sql-driver-mssql-dialect.test.ts`: 15 offline pins, one per emitter arm (OUTPUT, emission refusal, the lower-case GUID connection option, each text operator, JSON-array refusals, paging, aggregands, qualified-name split). Runs everywhere, no server. - `sql-driver-mssql-federation-conformance.test.ts`: the shared case-sets FILTER_LOGIC, FILTER_TEXT, FILTER_COMPARAND_TYPE, TEMPORAL, TEMPORAL_TIME, PAGINATION (incl. unordered and zero-limit), AGGREGATION, VALUE_ROUNDTRIP, UNIQUE_NULL_DISTINCT (filtered unique indexes), READABLE_IDS, plus a write block on a table with a trigger and a default, and a `uniqueidentifier` block (create answers the GUIDs as written; equality and `$in` match in either case; update by a GUID id lands); CROSS_FIELD is asserted as the federated-object refusal. Built with raw DDL plus `registerExternalObject` in a per-file schema. - The live cell is opt-in: `OS_TEST_MSSQL_URL` provisions it, `OS_EXPECT_MSSQL_FEDERATION=1` makes an unprovisioned run fail. No CI job hosts SQL Server, so in CI it is a declared skip, and the live-dialect coverage report prints `live sql server (federation) NOT RUN`. - `mssql-connection.test.ts` (service-datasource, 6 tests, two of them the datasource `ssl` block through the spec parse, `resolveSslOption` and `buildMssqlConnection`: `enabled: true` keeps `encrypt` on with `trustServerCertificate`, and a block without it is `encrypt: false`), a table-wide pin that no spelling of a federation-only row resolves on the selection face, the CLI driver-vocabulary parity pin (a federation-only driver resolves its contract, and `os start` refuses it in dev and prod even with a URL), the credential-slot pin and the analytics echo-bucket roster gain `mssql`. - Tests that used `mssql` as the stand-in for an unmodelled dialect now use `UnmodelledKnexClient` (`unmodelled-knex-client.testkit.ts`). ## Acceptance notes Known gaps, stated so nobody reads them as covered: - Column-map handling on `update()` / `delete()` / `bulkDelete()` / `aggregate()` / `distinct()` landed on main with #31349 and is merged in here; this PR does not touch those paths. - A table whose key is an IDENTITY column cannot be written through the platform (the insert names the key); keep such a datasource read-only. - JSON-array membership (`$contains` on a multi-value field) and `$empty` on one are refused on mssql. - Date buckets run in memory: the dialect advertises no native date granularity. - service-analytics' native-SQL face still uses plain LIKE for mssql: #31394. - A table with no single-column primary key pages in an order SQL Server does not guarantee; the driver warns. - Cross-field `$field` comparisons are refused on federated objects on every dialect (existing behaviour). - SQL Server 2017 is the floor (`TRANSLATE`). - Substring operators on a `uniqueidentifier` column compare against SQL Server's own upper-case text form of the GUID; filter a GUID by equality (documented in the SQL Server section): #31395. - The Studio connection form does not offer `mssql` yet: #31389 tracks offering it there as federation-only. - The spec API surface widens by 4 exports, all `MssqlConfig*` (listed in `api-surface/data.json`); the federation-only names are #31351's. ## Verification Head `b22da50f83`, merged with `origin/main` at `b91dc73d33` (after #31351). The contract review of `dfc8a224c5` was answered on `194571ae2f` (delta PASS); this head carries the reconcile, should-fix 5. <details><summary>Live SQL Server (local container, SQL Server 2022 image, TZ=America/New_York)</summary> `OS_TEST_MSSQL_URL=... OS_EXPECT_MSSQL_FEDERATION=1 vitest run sql-driver-mssql-federation-conformance.test.ts sql-driver-mssql-dialect.test.ts`: 2 files, 227 passed on this head. Coverage reporter: `live sql server (federation) RAN`. </details> <details><summary>Package suites and typechecks</summary> - `@objectstack/driver-sql` full suite: 241 files passed, 13 skipped; 3899 tests passed, 219 skipped (no live server env). `tsc --noEmit` clean. - `@objectstack/spec` full suite: 821 files, 25977 passed, 1 todo (before the refusal-message change; the config-registry and datasource files re-run after it, 556 passed). `check:test-typecheck` OK. `check:generated` OK after a spec build. - `@objectstack/service-datasource` full suite on this head: 74 files, 1291 passed. `tsc --noEmit` clean. - `@objectstack/spec` `src/data` on this head: 163 files, 6064 passed. `check:generated` 14 of 14 current, `check:llms-txt` OK. - `@objectstack/driver-sql` full suite on this head: 244 files passed, 13 skipped; 4085 tests passed, 220 skipped (the Oracle dialect pins included). `tsc --noEmit` clean. - `@objectstack/service-analytics` echo-bucket enumeration: 236 passed. - `@objectstack/cli` driver-vocabulary parity: 131 passed; database-driver flag derivation: 11 passed. `tsc --noEmit` clean. - `@objectstack/runtime` dev-auto-migrate: 7 passed. `tsc --noEmit` clean. - ESLint (`--no-inline-config`) over every changed `.ts`/`.mjs` file: clean. </details> <details><summary>dispatch-gates</summary> On `f8388ce29e`: `node scripts/pm/dispatch-gates.mjs --ran` 146 derived families, 146 run, 0 NOT-MEASURED, every exit code 0; the 60 artifact-roster and wide-population families also run, all 0 except the four that need the workflow's PR context (closing-target, Part-of, single-claim paths, governed queue guard), which CI ran green. CI then found `check:facade-delegation-only` (a roster family) and the dropped-refinements header count; both fixed here. The sweep on each new head is posted as a separate comment. </details> Not run here: SQL Server in CI (no job provisions it; the cell is a declared skip there). Full dogfood is not owed (Clause-② is a widening and the title carries no `!`). ## Human Minimum - [x] 1. Schemas start as Zod; `packages/spec` holds no runtime logic. - [x] 2. Every name I added uses the casing for its kind. - [x] 3. No formatter ran; `pnpm lint` passes. - [x] 4. One issue, one branch off an up-to-date `main`, one pull request. - [x] 5. A change that publishes carries a changeset, and both declaration lines are filled in here and in the changeset. - [x] 6. `packages/spec` touched: its generated artifacts are regenerated and committed. - [x] 7. No hand edits to `content/docs/references/`, `packages/*/CHANGELOG.md` or `content/docs/releases/`. - [x] 8. Title, body and comments are in English. - [x] The *Before Submitting* list in CONTRIBUTING.md is done. 🤖 Generated with [Claude Code](https://claude.com/claude-code) https://claude.ai/code/session_017ihL2g4TsRRELWgXKEF8H3 <!-- signed: epic:#27261#1 · marchtian · session_017ihL2g4TsRRELWgXKEF8H3 --> --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent e3ab0aa commit 8c75f83

60 files changed

Lines changed: 2603 additions & 170 deletions

File tree

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.
Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
---
2+
'@objectstack/spec': minor
3+
'@objectstack/driver-sql': minor
4+
'@objectstack/service-datasource': minor
5+
---
6+
7+
feat(spec, driver-sql, service-datasource): SQL Server as a federation-only dialect — an `external` datasource over Microsoft SQL Server reads live, and with the double opt-in writes live
8+
9+
Clause-②: yes (widening)
10+
Metadata-protocol: added
11+
Skills-docs: generated only — `skills/objectstack-data/references/_index.md` gains the `driver/mssql.zod.ts` row (`gen:skill-refs`); no hand-written skill text enumerates a datasource driver-id roster or teaches per-dialect federation behaviour. `content/docs/data-modeling/external-datasources.mdx` gains the SQL Server section (§8, after Oracle's) (config shape, federation-only scope, schema-qualified tables, the 2017 floor), and `content/docs/references/data/driver-mssql.mdx` is generated.
12+
13+
- **`@objectstack/spec`**: the driver vocabulary gains `mssql` (aliases `sqlserver`, `tedious`), a second `federationOnly` row after `oracle`, with `hasLocalDefault: false`: no boot host offers it, and a `managed` datasource declaring it is refused at parse, at `schemaMode`, by the same refusal as `oracle`. `FEDERATION_ONLY_DRIVER_IDS` and `isFederationOnlyDriver()` now answer both drivers, and `DatabaseSelectionDriverId` excludes both. The boot-host selection tables are now built without the federation-only rows, so the withdrawal holds by the column rather than by each row's empty `aliases`. `MssqlConfigSchema` is the closed config: `host`, `port` (1433), `instanceName`, `database`, `username`, `ssl`; an inline password, a connection URL and `autoMigrate` are refused with the reason. Its `ssl` docblock documents a self-signed server as the datasource-level `ssl: { enabled: true, rejectUnauthorized: false }`, because a block without `enabled: true` turns encryption off. `type-compat`'s `SqlDialect` gains `'mssql'`, and `DIALECT_ALIASES.mssql` maps SQL Server's types (`nvarchar`/`nchar`/`ntext`/`xml` → text, `bit` → boolean, `datetime2`/`datetimeoffset`/`smalldatetime` → datetime, `uniqueidentifier` → uuid, `money`/`decimal`/`numeric` → decimal, `timestamp`/`rowversion` → binary). Oracle's exact-to-lossy demotion and SQL Server's added lossy pairing are now one table, `DIALECT_LOSSY_RULES` (`demoteExact` / `addLossy`, only ever toward `'lossy'`): on `mssql`, a text column backs a `json`, `tags` or `multiselect` field as `'lossy'`, because SQL Server keeps JSON in `nvarchar(max)`; Oracle's answers are unchanged. ADR-0015 §4.6 lists the dialect, and §5.1's federation-only arm names both drivers.
14+
- **`@objectstack/driver-sql`**: `dialectName` reads `'mssql'` for knex's `mssql` client, so nothing falls to `'unknown'`. Text predicates keep the #6518 contract on SQL Server's case-insensitive default collations (a `Latin1_General_100_BIN2` comparison, `TRANSLATE` for the ASCII fold, `[` escaped); a `bit` aggregand is cast for SUM/AVG/MIN/MAX; writes use `INSERT … OUTPUT inserted.*` through a temp table, so a table with triggers accepts them; a `uniqueidentifier` reads back in the canonical lower-case form (tedious `lowerCaseGuids`, unless the host sets it), so a GUID written as a string reads back as that string and filters by it in either case; an unsorted page of a federated table is ordered by its own single-column primary key, read from the catalog; `limit: 0` compiles to `TOP (0)`; JSON fields read back from `nvarchar`; introspection lists every user table as `schema.table` (`dbo.Orders`) with its primary key, foreign keys, unique columns and indexes. Managed DDL is refused as federation-only (`SQL_DIALECT_EMISSION_UNSUPPORTED`, through the same `'federation-only'` reason and message renderer as Oracle), and `$contains` / `$empty` on a multi-value field is refused rather than approximated.
15+
- **`@objectstack/service-datasource`**: the datasource driver factory builds an `mssql` datasource on `SqlDriver` with the `tedious` connection (`server`, `port`, `database`, `user`, the bound secret as password, `encrypt` / `trustServerCertificate` / `instanceName` from the config and the datasource `ssl` block), and reports `@@VERSION`. The `ssl` block's resolution moves, unchanged, to its own leaf module (`datasource-ssl-option.ts`).
16+
17+
Nothing existing changes for the other drivers.

‎content/docs/data-modeling/drivers.mdx‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -81,6 +81,7 @@ libSQL data stayed untouched. Pass the token with `--database-auth-token`
8181
| **Turso / libSQL** | `@objectstack/driver-turso` (optional install — see the callout above) | `TursoDriver` | `turso` \| `libsql` |
8282
| **Memory** | `@objectstack/driver-memory` | `InMemoryDriver` | none — not a boot store (see [Memory Driver](#memory-driver)) |
8383
| **Oracle Database** | `@objectstack/driver-sql` (peer: `oracledb`, Thin mode) | `SqlDriver` | none — federation only, an external datasource (see [External datasources](/docs/data-modeling/external-datasources#7-oracle-database)) |
84+
| **SQL Server** | `@objectstack/driver-sql` (peer: `tedious`) | `SqlDriver` | none — federation only: an `external` datasource reads (and, opted in, writes) existing tables; see [SQL Server](/docs/data-modeling/external-datasources#8-sql-server-federation-only) |
8485

8586
> All SQL flavours (PostgreSQL / MySQL / SQLite) are served by a single
8687
> `@objectstack/driver-sql` package — there is no separate
@@ -104,6 +105,7 @@ driver ships that contract as a zod schema, exported from `@objectstack/spec/dat
104105
| `mongodb` | `MongoConfigSchema` | `url`, `host`, `port`, `database`, `username`, `password`, `authSource`, `options` |
105106
| `memory` \| `in-memory` \| `mingo` | `MemoryConfigSchema` | `initialData`, `strictMode`, `persistence` |
106107
| `oracle` \| `oracledb` | `OracleConfigSchema` | `connectString`, `host`, `port`, `serviceName`, `username` (federation only; TLS by a `tcps://` connect string) |
108+
| `mssql` \| `sqlserver` \| `tedious` | `MssqlConfigSchema` | `host`, `port`, `instanceName`, `database`, `username`, `ssl` (federation only; the password comes from `external.credentialsRef`) |
107109

108110
`mongo` was a second spelling of `mongodb` until 18. It is retired: an authored
109111
`driver: 'mongo'` is refused with the prescription naming `mongodb`, and

‎content/docs/data-modeling/external-datasources.mdx‎

Lines changed: 86 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -583,6 +583,92 @@ the process's own time zone. Run the server with `TZ=UTC` and there is no such h
583583
That column breaks ties after the caller's own sort. Without a mapped key, a paged
584584
read has no unique order, and the server logs a warning once per object.
585585

586+
## 8. SQL Server (federation only)
587+
588+
Microsoft SQL Server is a **federation-only** driver: point an `external` (or
589+
`validate-only`) datasource at it and its tables become objects, read live — and,
590+
with the double opt-in above, written live. The usual reason is an older
591+
line-of-business system (an ERP, a MES, a HIS) whose database is federated in place
592+
rather than migrated. It is served by `@objectstack/driver-sql` over knex's `mssql`
593+
client, so install its optional peer `tedious` next to it.
594+
595+
{/* os:check */}
596+
```typescript
597+
import { defineDatasource } from '@objectstack/spec/data';
598+
599+
export const LegacyErp = defineDatasource({
600+
name: 'legacy_erp',
601+
label: 'Legacy ERP (SQL Server)',
602+
driver: 'mssql', // aliases: 'sqlserver', 'tedious'
603+
schemaMode: 'external', // required — see below
604+
config: {
605+
host: 'erp-db.internal',
606+
port: 1433, // ignored when instanceName is set
607+
database: 'ERP',
608+
username: 'objectstack_ro',
609+
// instanceName: 'SQLEXPRESS', // a named instance, via SQL Server Browser
610+
ssl: true, // tedious `encrypt`; required by Azure SQL
611+
},
612+
external: {
613+
credentialsRef: 'sys_secret:7c1e…', // the password — never written inline
614+
validation: { onMismatch: 'fail', checkOnBoot: true },
615+
},
616+
active: true,
617+
});
618+
```
619+
620+
What is different from the other SQL drivers:
621+
622+
- **Federation only.** The platform never builds its own schema on SQL Server, so a
623+
`managed` datasource on this driver is refused when the stack is parsed, with a
624+
message naming the scope, and no boot host offers it as the platform database. If
625+
you need ObjectStack's own tables on SQL Server, that is a separate feature request.
626+
- **Discrete fields, no URL.** `tedious` reads no connection-string grammar, so the
627+
config takes `host` / `port` / `database` / `username` / `instanceName` and
628+
refuses a `url` / `connectionString`. The password is refused inline: bind it
629+
through the connection form or `external.credentialsRef`.
630+
- **TLS.** `config.ssl` is tedious's `encrypt`. For an on-premises server with a
631+
self-signed certificate, set the datasource-level
632+
`ssl: { enabled: true, rejectUnauthorized: false }` (tedious's `encrypt` plus
633+
`trustServerCertificate`); a CA goes in the same block. Write `enabled: true`:
634+
the block's `enabled` defaults to `false`, and a block without it turns
635+
encryption off.
636+
- **Schemas.** A SQL Server database is usually several schemas. The Studio Tables
637+
tab, `list_remote_tables` and `import_object` list every user table as
638+
`schema.table` (`dbo.Orders`, `Sales.Customers`) with its primary key and foreign
639+
keys, and an imported object gets `external.remoteSchema` / `remoteName` from it.
640+
A bound object without `remoteSchema` resolves in the login's default schema.
641+
- **Types.** `nvarchar` / `nchar` / `ntext` / `xml` read as text (`nvarchar(max)`
642+
included), `bit` as boolean, `datetime2` / `datetimeoffset` / `smalldatetime` as
643+
datetime, `uniqueidentifier` as uuid, `money` / `decimal` as decimal. SQL Server's
644+
`timestamp` is `rowversion` — a binary row counter, not a date. A `json`,
645+
`tags` or `multiselect` field over an `nvarchar(max)` column is accepted as a
646+
lossy match (the driver keeps it as JSON text); JSON-array membership
647+
(`$contains`) and `$empty` on a multi-value field are refused on SQL Server.
648+
- **GUIDs.** A `uniqueidentifier` reads back in the lower-case form
649+
(`3f2504e0-4f89-…`), so a GUID written as a string reads back as that string, and
650+
an equality or `$in` filter matches it in either case. Substring operators
651+
(`$contains`, `$startsWith`) compare against SQL Server's own upper-case text form
652+
of the GUID; filter a GUID by equality
653+
([#31395](https://github.com/objectstack-ai/objectstack/issues/31395) tracks it).
654+
- **Text matching** follows the platform's contract, not the database's collation:
655+
`$contains` / `$startsWith` / `$endsWith` / `$like` are case-exact even on SQL
656+
Server's case-insensitive default collations, and `$icontains` folds A–Z only.
657+
This uses `TRANSLATE`, so the floor is **SQL Server 2017**.
658+
- **Paging.** `OFFSET … FETCH` needs an `ORDER BY` on SQL Server. An unsorted page
659+
is ordered by the column the object's `columnMap` maps to `id` when there is one,
660+
else by the table's own single-column primary key, read from the catalog; a table
661+
with neither (a heap, a composite key) pages without a stable order, and the
662+
driver logs that once per object.
663+
- **Writes** use `INSERT … OUTPUT inserted.*` (routed through a temp table, so a
664+
table with triggers accepts it too), and a created record comes back with the
665+
values SQL Server filled in. The remote table needs a column the object reads as
666+
`id`, and the platform supplies its value: an `IDENTITY` key cannot be inserted
667+
into, so keep a table keyed that way read-only.
668+
- **Not on SQL Server:** `$contains` / `$empty` on a multi-value (JSON-array) field is
669+
refused rather than approximated, and date buckets in reports are computed by the
670+
engine rather than pushed down.
671+
586672
## Multi-tenant hosts
587673

588674
A self-hosted single-environment runtime connects external datasources out of the
Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
---
2+
title: Driver Mssql schema — Data Protocol reference
3+
navTitle: Driver Mssql
4+
description: "Microsoft SQL Server driver configuration — the config slot of a datasource whose driver resolves to mssql (sqlserver / tedious)."
5+
---
6+
7+
{/* ⚠️ AUTO-GENERATED — DO NOT EDIT. Run build-docs.ts to regenerate. Hand-written docs live in the module folders under content/docs/. */}
8+
9+
Microsoft SQL Server driver configuration — the `config` slot of a
10+
`datasource` whose `driver` resolves to `mssql` (`sqlserver` / `tedious`).
11+
12+
FEDERATION ONLY. SQL Server is served by `@objectstack/driver-sql` over
13+
knex's `mssql` client (the `tedious` binding) for an ADR-0015 external
14+
datasource — `schemaMode: 'external'` or `'validate-only'` — whose tables
15+
already exist and are read (and, with `external.allowWrites`, written) in
16+
place. The platform does not build its own schema on SQL Server, so a
17+
`managed` datasource declaring this driver is refused at parse
18+
(`DriverVocabularyEntry.federationOnly`), and no boot host offers it as the
19+
platform database. The usual reason to point a datasource here is an older
20+
line-of-business system (an ERP, a MES, a HIS) whose database is federated
21+
in place rather than migrated.
22+
23+
Every key here is read by `createDefaultDatasourceDriverFactory`
24+
(→ `SqlDriver`, knex `mssql`). There is no `url`: `tedious` reads no
25+
connection-string grammar, so a URL key would have to be parsed by a second
26+
grammar the client never sees — the discrete fields are the shape it takes.
27+
There is no `autoMigrate` either: it governs DDL the platform emits, and on
28+
SQL Server it emits none.
29+
30+
<Callout type="info">
31+
**Source:** `packages/spec/src/data/driver/mssql.zod.ts`
32+
</Callout>
33+
34+
## TypeScript Usage
35+
36+
```typescript
37+
import { MssqlConfigSchema } from '@objectstack/spec/data';
38+
import type { MssqlConfig } from '@objectstack/spec/data';
39+
40+
// Validate data
41+
const result = MssqlConfigSchema.parse(data);
42+
```
43+
44+
---
45+
46+
## MssqlConfig
47+
48+
Microsoft SQL Server connection configuration (federation only)
49+
50+
### Properties
51+
52+
| Property | Type | Required | Description |
53+
| :--- | :--- | :--- | :--- |
54+
| **host** | `string` | ✅ | Host address |
55+
| **port** | `integer` | optional (default: `1433`) | Port number |
56+
| **instanceName** | `string` | optional | Named instance, resolved through the SQL Server Browser service (leave unset for the default instance) |
57+
| **database** | `string` | ✅ | Database name |
58+
| **username** | `string` | optional | SQL authentication login |
59+
| **password** | `never` | optional | Set through the connection form's secret field or `external.credentialsRef` — encrypted into `sys_secret`, never stored in `config`. A datasource defined in code (`defineDatasource`) leaves the credential out of the declaration: it is read at connect time from the runtime environment variable derived from the datasource name (`OS_DATASOURCE_WAREHOUSE_PASSWORD` for a datasource named `warehouse`), which `os serve` / `os start` honour by default (`OS_DATASOURCE_ENV_CREDENTIALS=on`). |
60+
| **ssl** | `boolean` | optional | Enable TLS. Certificates go in the datasource-level `ssl` block. |
61+
62+
63+
---
64+

‎content/docs/references/data/index.mdx‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
---
22
title: Data Protocol — complete schema reference
33
navTitle: Data Protocol
4-
description: "The ObjectStack Data Protocol in 33 reference pages: every schema in @objectstack/spec with its properties, types, defaults and a TypeScript example."
4+
description: "The ObjectStack Data Protocol in 34 reference pages: every schema in @objectstack/spec with its properties, types, defaults and a TypeScript example."
55
---
66

77
{/* ⚠️ AUTO-GENERATED — DO NOT EDIT. Run build-docs.ts to regenerate. Hand-written docs live in the module folders under content/docs/. */}
@@ -19,6 +19,7 @@ This section contains all protocol schemas for the data layer of ObjectStack.
1919
<Card href="/docs/references/data/driver-common" title="Driver Common" description="Source: packages/spec/src/data/driver/common.zod.ts" />
2020
<Card href="/docs/references/data/driver-memory" title="Driver Memory" description="Source: packages/spec/src/data/driver/memory.zod.ts" />
2121
<Card href="/docs/references/data/driver-mongo" title="Driver Mongo" description="Source: packages/spec/src/data/driver/mongo.zod.ts" />
22+
<Card href="/docs/references/data/driver-mssql" title="Driver Mssql" description="Source: packages/spec/src/data/driver/mssql.zod.ts" />
2223
<Card href="/docs/references/data/driver-mysql" title="Driver Mysql" description="Source: packages/spec/src/data/driver/mysql.zod.ts" />
2324
<Card href="/docs/references/data/driver-nosql" title="Driver Nosql" description="Source: packages/spec/src/data/driver-nosql.zod.ts" />
2425
<Card href="/docs/references/data/driver-oracle" title="Driver Oracle" description="Source: packages/spec/src/data/driver/oracle.zod.ts" />

‎content/docs/references/data/meta.json‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,7 @@
3030
"driver-common",
3131
"driver-memory",
3232
"driver-mongo",
33+
"driver-mssql",
3334
"driver-mysql",
3435
"driver-oracle",
3536
"driver-postgres",

0 commit comments

Comments
 (0)