> ## Documentation Index
> Fetch the complete documentation index at: https://filament.getgalaxy.io/llms.txt
> Use this file to discover all available pages before exploring further.

# Microsoft SQL Server source connector

> Keyset snapshot, incremental watermark, and CDC reads from SQL Server 2017+

Connector ID `sqlserver`

The SQL Server source reads from self-managed SQL Server 2017 and later, on
premises or on a VM, with resumable keyset snapshots, incremental watermark
reads and change data capture. It is in preview.

For Azure SQL Database and Azure SQL Managed Instance use the
[Azure SQL source](https://filament.getgalaxy.io/pages/connectors/sources/azuresql.md). It runs the same reader
with connection settings for Azure and Microsoft Entra sign-in.

## Configuration

| Field | Scope | Default | Description |
| - | - | - | - |
| `connection_method` | Connection | `fields` | `fields` or `url`. Unset with a `dsn` present implies `url`. |
| `dsn` | Connection | | A `sqlserver://` URL in the go-mssqldb format. Required in `url` mode. Without an `encrypt` parameter the session is encrypted and the certificate verified, as in `fields` mode. Secret. |
| `host` | Connection | | Server hostname. Required in `fields` mode. |
| `port` | Connection | `1433` | Server port. |
| `instance` | Connection | | Named instance, found through the SQL Server Browser service instead of the port. |
| `auth.type` | Connection | `sql` | `sql`, a SQL Server login and password. |
| `auth.username` | Connection | | SQL Server login. Required. |
| `auth.password` | Connection | | Required. Secret. |
| `database_name` | Connection | | Database to connect to. Required in `fields` mode. |
| `encrypt` | Connection | `true` | `true` encrypts the session, `strict` uses TDS 8.0, `false` encrypts the login only, `disable` turns TLS off. |
| `trust_server_certificate` | Connection | `false` | Accept the server certificate without verifying it. |
| `replication` | Connection | `standard` | `standard` reads tables with queries. `cdc` reads changes from SQL Server change tables. |
| `manage_capture` | Connection | `true` | With `cdc`, enable capture on a selected table that has no capture instance. Needs `db_owner`. |
| `capture_role` | Connection | | Gating role for capture instances the source enables. Empty means none. |
| `snapshot_mode` | Pipeline | `initial` | With `cdc`, `initial` reads a table in full before streaming its changes. `none` streams from the current position only. |
| `schema` | Pipeline | `dbo` | Schema to read tables from. |
| `shard_rows` | Pipeline | `1000000` | Rows per parallel shard. `0` reads each table on one connection. |
| `max_conns` | Pipeline | | Maximum source connections. Set it to at least the run's parallelism. With `cdc` it is also how many shards the initial snapshot reads at once, 4 when unset. |
| `isolation` | Pipeline | `auto` | `auto` uses snapshot isolation when the database allows it and read committed otherwise. `snapshot` requires it. `read_committed` never uses it. |

Connections use a 32 KiB TDS packet unless the URL sets `packet size`.

## Snapshot reads

Tables with a primary key are read in key order. SQL Server stores a table in
its clustered index, which is normally the primary key, so each read is a
sequential range scan. Filament saves the last key each shard delivered, so an
interrupted read resumes where it stopped.

A table larger than `shard_rows` splits into as many as 64 ranges over its
leading key column, each read on its own connection by one streaming query.
Integer keys split by arithmetic over the key range. Other keys split at
sampled boundaries with roughly equal row counts. Composite keys are
supported.

Each range reads inside its own transaction. Under snapshot isolation a range
sees one point in time without taking shared locks, but parallel ranges may
see the table at slightly different moments, because SQL Server cannot share a
snapshot between sessions. Enable snapshot isolation on the source database
for consistent, non-blocking reads.

```sql theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
ALTER DATABASE app SET ALLOW_SNAPSHOT_ISOLATION ON;
```

A table without a primary key is read in a single streaming pass. That pass is
not resumable, so a resume re-reads the whole table. A table whose primary key
includes a `sql_variant` column is read the same way, because a saved key of
that type cannot be compared reliably on resume.

## Types

| SQL Server | Filament |
| - | - |
| `bit` | bool |
| `tinyint`, `smallint`, `int`, `bigint` | int16, int16, int32, int64 |
| `real`, `float` | float32, float64 |
| `decimal`, `numeric` | decimal at the column's precision and scale |
| `money`, `smallmoney` | decimal(19,4), decimal(10,4) |
| `date`, `time` | date, time |
| `datetime`, `smalldatetime`, `datetime2` | timestamp |
| `datetimeoffset` | timestamp in UTC |
| `char`, `varchar`, `text`, `nchar`, `nvarchar`, `ntext`, `xml` | string |
| `binary`, `varbinary`, `image`, `rowversion` | bytes |
| `uniqueidentifier` | uuid |
| `hierarchyid` | string, the path form such as `/1/2/` |
| `geometry`, `geography` | bytes in well-known binary, with Z and M |
| `json` | json |
| `sql_variant`, `vector` | string |

Times and timestamps carry microseconds, so the 100 ns digit of a `time(7)`,
`datetime2(7)` or `datetimeoffset(7)` value is truncated. `datetime2` is scale
7 unless declared otherwise. Two rows whose key differs only in that digit
would reach the destination with the same key, so a table whose primary key
includes one of these columns at scale 7 is not offered for selection and a
run of it fails. Declare the column at scale 6 or lower to read it.
Non-Unicode text is decoded by its column's collation.

Well-known binary has no spatial reference ID. To keep it, add a computed
column such as `location.STSrid` to the table.

## Incremental reads

Incremental resources need a primary key without `sql_variant` columns and a
non-null cursor column, which is a `datetime`, `datetime2`, `smalldatetime`,
`datetimeoffset`, integer or `rowversion` column. Filament suggests a datetime
with a conventional name such as `updated_at` or `ModifiedDate`, then a
`rowversion` column, then a table's only eligible column, and uses it when no
cursor is set. Any eligible column can be chosen per pipeline resource
instead.

An integer cursor such as an identity column picks up only rows whose value
grows. Use one on an append-only table, or when every update also raises the
value. An integer cursor takes no lookback.

An integer cursor also needs values to become visible in order. An identity
or sequence hands out values when rows are inserted, not when they commit, so
with concurrent writers `id = 11` can commit while `id = 10` is still open. A
run that reads `11` first moves the watermark past `10`, which is then never
read. Use an integer cursor only when writers commit in value order. A
`rowversion` cursor or CDC covers concurrent writers.

The first incremental run captures the current `(cursor, primary key...)`
high watermark, then performs a resumable primary-key backfill. Later runs
read the rows after the watermark up to a high watermark taken when the run
starts.

A `rowversion` cursor is exact. The server advances it on every insert and
update, and a run never reads past `MIN_ACTIVE_ROWVERSION()` taken before its
read starts, so a transaction still open then cannot later commit below the
watermark. A `rowversion` cursor takes no lookback.

A timestamp cursor depends on the application to advance it on every change.
A transaction that commits after the high watermark was read, with an older
timestamp, is missed unless a lookback covers it. Configure a positive
per-resource lookback to re-read a recent window, and use incremental upsert
with it, since those rows are read again. An index beginning with the cursor
and followed by the primary key keeps incremental reads from sorting.

```sql theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
CREATE INDEX users_incremental ON dbo.users (updated_at, id);
```

### Start value

A resource can set a start value. The first run then reads only the rows
whose cursor is greater than it and skips the backfill. The value is any text
that converts to the cursor's type, such as `2026-01-01` or `1500000`. A
`rowversion` start is hex such as `0x00000000000007D1` or an integer. Changing
the start value or the column restarts the resource from the new setting.

A cursor must be a `NOT NULL` column. When `updated_at` is `NULL` until a
row's first update, add a persisted computed column that falls back to
`created_at` and use it as the cursor. An index on it keeps reads fast.

```sql theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
ALTER TABLE dbo.users ADD changed_at AS ISNULL(updated_at, created_at) PERSISTED NOT NULL;
CREATE INDEX users_changed_at ON dbo.users (changed_at, id);
```

`PERSISTED NOT NULL` makes the column `NOT NULL` even when `created_at`
allows `NULL`. The `ALTER TABLE` then fails if a row has both columns `NULL`,
so fill those rows first.

```sql theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
UPDATE dbo.users SET created_at = SYSUTCDATETIME() WHERE updated_at IS NULL AND created_at IS NULL;
```

## Change data capture

With `replication` set to `cdc` the source reads the change tables SQL Server
CDC maintains. The capture process copies committed changes from the
transaction log into one change table per capture instance. On SQL Server that
process is a SQL Agent job, so SQL Agent must be running. The source reads only
database-scoped objects and never touches `msdb` or Agent tables.

CDC must be enabled on the database before the first run, which takes
`sysadmin`.

```sql theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
EXEC sys.sp_cdc_enable_db;
```

With `manage_capture` on, the source enables capture on each selected table
that has none, which needs `db_owner`. With it off, enable each table
yourself.

```sql theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
EXEC sys.sp_cdc_enable_table @source_schema = N'dbo', @source_name = N'orders', @role_name = NULL;
```

Each table needs a primary key, and tables without one are not offered for
selection. A run is a bounded catch-up. It replays every
change committed after each table's checkpoint up to the newest captured
change, then saves the position it reached. A table without a checkpoint is
read in full first, unless `snapshot_mode` is `none`.

Change tables hold NULL for computed columns, so CDC reads leave computed
columns out of the table, in the snapshot as well as in changes. A table
whose primary key includes a computed column cannot be read with CDC and is
not selectable. Full refresh still reads it.

### Ordering

Every selected table's changes are read by one query that the server merges
in commit order, so changes reach the destination in the order they committed,
across tables and within a transaction, also while a table moves to a new
capture instance. A run's row limit stops on a transaction boundary, never
inside one. A run that snapshots a table replays to the end regardless of the
limit, so the snapshot is brought up to date. An update that changes a primary key
arrives as a delete of the old row and an insert of the new one.

### Initial snapshot

The snapshot uses the same sharded keyset reads as a full refresh, reading up
to `max_conns` shards at once, or 4 when it is unset. Changes that commit while
it runs are replayed afterwards, which the merge policy absorbs.
Change tables trail the log by the capture process's polling interval, so
after the snapshot the source waits for capture to reach the log position the
snapshot ended at before it replays. That wait reads
`sys.dm_db_log_stats`, which needs a server permission, and
`sys.dm_cdc_log_scan_sessions`, which needs a database one. The
[permissions](#permissions) section lists them by version. Without them, or on
a readable secondary, which does not report its log end, the source replays
what capture holds so far and the next run catches up the rest.

### Retention

A change table holds no log on the source's behalf. The cleanup process
deletes changes older than the database's retention, three days by default,
whether or not they were read. Schedule runs well inside that window. If a
checkpoint falls behind the oldest retained change, before or during a read,
the run fails instead of skipping changes, and the table needs a new snapshot.

```sql theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
EXEC sys.sp_cdc_change_job @job_type = N'cleanup', @retention = 10080; -- minutes
```

### Schema changes

A capture instance captures the columns the table had when it was created. A
column added later is not captured, and a run fails while a selected column is
missing. SQL Server allows two capture instances per table, so add a second one
that captures the new column. The source reads the old instance up to the
point the new one starts, then moves to the new one in the same run. Disable
the old instance once every pipeline has moved past it.

Create the new instance right after adding the column. A change made in
between is held only by the old instance, which has no value for the new
column. The run then fails rather than write NULL over the row's value, and
the table needs a new snapshot.

```sql theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
EXEC sys.sp_cdc_enable_table @source_schema = N'dbo', @source_name = N'orders',
  @role_name = NULL, @capture_instance = N'dbo_orders_v2';
```

Change tables are shared by every reader. Removing a pipeline never disables
capture on a table.

## Permissions

The login needs `SELECT` on the tables it reads and permission to see their
metadata, which `SELECT` grants. CDC also needs `SELECT` on the `cdc` schema.

```sql theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
GRANT SELECT ON SCHEMA::cdc TO filament;
```

The capture wait after an initial snapshot needs two more permissions. They are
optional, and without them the next run catches up instead.

| SQL Server | Server permission, granted in `master` | Database permission |
| - | - | - |
| 2022 and later | `VIEW SERVER PERFORMANCE STATE` | `VIEW DATABASE PERFORMANCE STATE` |
| 2017 and 2019 | `VIEW SERVER STATE` | `VIEW DATABASE STATE` |

```sql theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
-- SQL Server 2022 and later
USE master;
GRANT VIEW SERVER PERFORMANCE STATE TO filament;
USE app;
GRANT VIEW DATABASE PERFORMANCE STATE TO filament;
```

## Roadmap

Continuous CDC execution, partition selection for snapshots and resumable CDC
snapshots are planned.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.