@eltjs/elt-sqlserver
v0.13.38
Published
The SQL Server destination of elt: each stream is a typed table in _warehouse, with a reader view in marts that the host names, numbered commits that readers read as of a position, and a checkpoint store and a sync history in the same database.
Maintainers
Readme
@eltjs/elt-sqlserver
The SQL Server destination of elt. It loads each stream of a connection into a SQL Server or Azure SQL database, with typed columns, and it does not block readers while it loads. Each target is a reader view in marts, which the host names, over a raw table in _warehouse. It also keeps the views and computed datasets that the pipeline derives. A computed dataset can keep a vector column as a native VECTOR(n), so Azure SQL searches it with VECTOR_DISTANCE or a DiskANN index. The checkpoints of its copies and the sync history are in the same database.
The destination gives the contract of elt-postgresql: the same declarations, the same columns for readers, the same positions, history, retention and sync history. A host changes its destination and nothing else. Where SQL Server is different, this README says how and why (ADR 0001).
The words in these documents have one meaning each. See the glossary in CONTEXT.md, and the glossary of elt for the words of all of elt.
The map
| Now (first release) | Later | Never |
| -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| SqlServerDestination: the four destination sync modes, evolve, reload, reader views, extended properties | Native VECTOR over TDS, when tedious has it (tedious #1841) | A search API: the retriever of @zukhruf/retrieval searches the vectors (ADR 0019) |
| Numbered commits, positions, history, readings, retention, a clear that forgets | float16 vector columns (HalfVector), for a model of more than 1,998 dimensions, such as text-embedding-3-large (3,072) | System-versioned temporal tables as the history (ADR 0001) |
| View and ComputedDataset, with vector(n) rule columns as VECTOR(n) and declared nonclustered indexes; TableIndexes with diskAnn() for the DiskANN index of a base table in marts | A bulk load through Azure Blob Storage and BULK INSERT, as the bulk mode of Airbyte, when a load is too slow through JSON batches | An ORM, or a query builder over the reader's SQL |
| The checkpoints of the copies, SqlServerSyncHistory (with derived_status, catalog and named readers), readPassStatus | Microsoft Entra ID logins (managed identity), which mssql supports through authentication | An mssql:// URL |
| The prerequisites in other packages: the vector rule column of elt, dimensions on Embedding, and the extraction of the rules that the destinations share (ADR 0012) | SQL Server 2022 and older, which have no VECTOR and no JSON type | A migration of stored data between versions (elt AGENTS.md: stored data is disposable) |
What the first release does
SqlServerDestinationwith the four destination sync modes: the raw table with its_elt_rowidentity key (ADR 0003), the unique index on_elt_key_hashwhen the copy deduplicates or the columns declare a key (ADR 0004), theMERGEof a deduplicating commit (ADR 0005, see "Deduplication" below), the replacement by difference of an overwrite (see "Locks and commits" below), the history table, theMS_Descriptionextended properties, the reader view, andpositions().- The JSON batches through
OPENJSON(ADR 0011), the check of the engine and the row versioning at each load (ADR 0010), the numbering with the rowversion of the commit row and the mark of the database copy (ADR 0002), and the clear that forgets. - The reset and the reload: a
RESETof the stream or of a partition, and an overwrite whose stored table no longer has the shape of its stream, load into a hidden table, which the end of the stream gives to the table by difference or swaps in (see "Shape changes" below). - The checkpoints of the copies, and
SqlServerSyncHistorywith the application locks of ADR 0009. - The evolve: a load that is not an overwrite, whose stored table no longer has the shape of its stream, changes the table in place with
ALTER TABLE, in one commit of its own, and the history follows each widening (see "Shape changes" below). - The file columns: parsed text and references to the files of a storage (see "Files" below).
reading(position?): a session of its own that reads the database as of a position (see "Commit numbers and positions" below), andreadPassStatus(login).View, and its rows ofderived_status(see "Declare a view" and "Derived status" below).ComputedDatasetof aRuleor aTableRule, withtext,blob,integerandvector(n)rule columns, the parts table of aTableRule, declared indexes, and its rows ofderived_status(see "Declare a computed dataset" below).- A failure of the setup of the database is a
SqlServerSetupError. Its failure type isconfig. A login without a permission that a statement of the destination or of its checkpoints needs is alsoconfig: aSqlServerPermissionErrorof sdk-microsoft-sql-server, and the SQL Server errors 229 and 230 (a permission on an object or a column) and 262 (a permission in the database, such asCREATE TABLE). A login that the server refuses (SqlServerLoginError: wrong credentials, a disabled login, a database that it may not open) isconfigtoo, as a wrong password is in elt-postgresql, and so is aSchemaDriftErrorof checkpoint tables that the host did not apply (see Checkpoints). Each other error, for example a server that cannot be reached, issystem.
Load a stream into SQL Server
import { Connection, Copy, Pipeline } from '@eltjs/elt';
import {
SqlServerDestination,
SqlServerSyncHistory,
} from '@eltjs/elt-sqlserver';
const login = {
server: 'datahub.database.windows.net',
database: 'semantic',
user: 'elt_writer',
password: '…',
};
const warehouse = new SqlServerDestination({ login });
await new Pipeline({
history: new SqlServerSyncHistory({ login }),
connections: [
new Connection({
name: 'sharepoint',
source: sharepoint,
destination: warehouse,
steps: [
new Copy(sharepoint.driveItems, warehouse.table('drive_items'), {
id: 'sharepoint:drive-items',
syncMode: 'incremental',
destinationSyncMode: 'append_dedup',
}),
],
}),
],
}).run();SqlServerDestination({ login })loads into the database of the login. Each relation that readers query is a view inmarts, and each table of elt is in_warehouse, as in Postgres (elt-postgresql ADR 0010). The first load makes the two schemas.warehouse.table('drive_items')names the reader viewmarts.drive_items, the reader name. The destination keeps the rows of the target in the raw table_warehouse.raw_drive_items.loginis the parts of a login (server,port,database,user,password,trustServerCertificate) or an ADO.NET connection string, the two forms of@eltjs/sdk-microsoft-sql-server. The destination opens its sessions through theSqlServerDatabaseof the SDK, which gets write sessions for it.- The login holds credentials, so
location(), which checkpoints keep, names only the raw table. A getter gives the login to the views and computed datasets of the destination, so JSON andutil.inspectdo not show it. - The destination checks the declarations with no connection to the database.
- A reader name follows the naming rule, with the 128 characters of a SQL Server name.
table(name)refuses a reader name that the sync history publishes inmarts, such ascatalog. - The database must be SQL Server 2025 (17.x), Azure SQL Database or Azure SQL Managed Instance with the always-up-to-date policy, because the destination uses the
VECTORandJSONtypes. It must keep row versions for readers:READ_COMMITTED_SNAPSHOTandALLOW_SNAPSHOT_ISOLATIONon (ADR 0010). The first load checks both, and fails with the failure typeconfigand theALTER DATABASEstatement that turns them on. - The destination holds one connection of its own for each load, because a
#stagetable belongs to one connection. It does not take connections from a shared pool.
The API
// @eltjs/elt-sqlserver
type SqlServerLogin =
| string // an ADO.NET connection string
| {
server: string;
port?: number;
database: string;
user: string;
password: string;
trustServerCertificate?: boolean;
};
class SqlServerDestination extends Destination<SqlServerTable> {
constructor(options: {
login: SqlServerLogin;
retention?: Temporal.Duration; // 30 days unless set
});
readonly retention: Temporal.Duration;
table(
name: string, // the reader name: marts.<name> over _warehouse.raw_<name>
columns?: (c: SqlServerColumns) => SqlServerColumn[],
): SqlServerTable;
location(target: SqlServerTable): string; // 'raw_<name>'
positions(after?: string): Promise<readonly string[] | { expired: string }>;
reading(position?: string): Promise<SqlServerReading | { expired: string }>;
}
class SqlServerTable {
readonly name: string; // the reader name
readonly raw: string; // raw_<name>
}
class View {
constructor(options: {
into: SqlServerDestination;
name: string;
description: string;
columns: Readonly<Record<string, string>>;
sql: string;
});
}
class ComputedDataset<Input> {
constructor(
options: {
into: SqlServerDestination;
name: string;
description: string;
from: readonly (SqlServerTable | View)[];
indexes?: readonly SqlServerIndex[]; // of _warehouse.raw_<name>
} & (
| { compute: Rule<Input, RuleColumns> }
| {
compute: TableRule<Input, RuleColumns, RuleColumns>;
partIndexes?: readonly SqlServerIndex[]; // of _warehouse.raw_<name>_parts
}
),
);
}
// DatasetIndex and VectorMetric ('cosine' | 'euclidean' | 'dot') are of @eltjs/elt.
type SqlServerTableIndex = DatasetIndex<'nonclustered', { build: DiskAnn }>;
// = { type: 'nonclustered'; columns: readonly [string, ...string[]] }
// | { type: 'vector'; column: string; metric: VectorMetric; build: DiskAnn }
// The indexes of a computed dataset: the nonclustered ones only.
type SqlServerIndex = Exclude<SqlServerTableIndex, { type: 'vector' }>;
type DiskAnn = { method: 'diskann' };
function diskAnn(): DiskAnn; // SQL Server has no options for the build
// The declared indexes of one table, which reconcile makes or drops in place.
class TableIndexes {
constructor(options: {
owner: string; // who declares them, as each refusal names it
table: string; // schema-qualified
columns: readonly { name: string; type: string }[]; // the SQL Server types
indexes: readonly SqlServerTableIndex[];
});
reconcile(connection: SqlServerConnection): Promise<void>;
}
// Removes the view marts.<name> and every view over it, deepest first, in a
// transaction of its own under the lock of marts. connection is outside any
// transaction.
function withdrawView(
connection: SqlServerConnection,
name: string,
): Promise<void>;
class SqlServerSyncHistory {
constructor(options: { login: SqlServerLogin; readers?: readonly string[] });
}
type SqlServerReading = AsyncDisposable & {
readonly sql: SqlServerConnection; // of @eltjs/sdk-microsoft-sql-server: its own session, in a SNAPSHOT transaction
readonly position: string;
readonly at: Temporal.Instant; // when the commit of the position was made
};
function readPassStatus(login: SqlServerLogin): Promise<{
readonly pass: PassStatus | null;
readonly streams: readonly StreamPassStatus[];
}>;What each call does underneath
| Call | What happens |
| ----------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| new SqlServerDestination(…) | Checks the retention. No I/O |
| pipeline.run() → load() | Opens one connection. Checks the engine and the row versioning of the database. Opens a load in _warehouse._elt_loads |
| prepare(…) | Checks _elt_writers and the stored table. Makes a #stage table on the connection of the load. Evolves a stored table that no longer has the shape of the stream, in one commit, when the copy does not overwrite. Publishes no row of the stream |
| each operation | Goes to the stage in batches of at most 1,000 rows or 16 MiB, as one NVARCHAR(MAX) JSON parameter that OPENJSON … WITH (…) reads and casts for each column (ADR 0011) |
| each commit | One transaction: inserts its commit row, takes CAST(inserted.number AS bigint) as its number (ADR 0002), then one INSERT from the stage into the table for append, or one MERGE for append_dedup, whose OUTPUT puts each replaced or removed row into the history. The commit of an overwrite or overwrite_dedup run replaces the rows by difference instead: one DELETE … OUTPUT deleted.* into the history, then one INSERT (ADR 0005) |
| the first commit of a stream | Also makes the table, its clustered _elt_row key (ADR 0003), the unique index on _elt_key_hash (ADR 0004), the extended properties, the reader view and the writer |
| a change of shape or the swap of a reload | SET LOCK_TIMEOUT 3000, ALTER TABLE or two sp_rename calls, then sp_refreshview for each view over the table (ADR 0006) |
| positions(after) | Reads MIN_ACTIVE_ROWVERSION(), then _elt_commits and _elt_loads in one SNAPSHOT transaction |
| reading(position) | Opens a connection, checks the engine and the row versioning, reads the high-water mark, begins a SNAPSHOT transaction, and sets elt.position with sp_set_session_context … @read_only = 1 |
| a refresh of a View | Opens one connection. In one transaction under the lock of marts, reads OBJECT_DEFINITION of the view, and runs CREATE OR ALTER VIEW and sp_refreshview of each view over it only when the text differs. Writes each description whose stored value differs. Writes the row of derived_status |
| a refresh of a ComputedDataset | Opens a load of the dataset. In one transaction, makes the raw table, its history and its reader view, or makes the table again when its declaration changed, and removes the rows whose input is gone. Then reconciles the declared indexes with sys.indexes, one statement at a time outside a transaction. Then calls the rule, and for each settled call runs one transaction: it reads the row hashes of the call's keys, runs one MERGE of the changed rows from OPENJSON, whose OUTPUT the history keeps, and takes the settled inputs off pending. A vector(n) value goes as the JSON text of @zukhruf/vectors/sqlserver and lands through CAST(… AS VECTOR(n)) |
Columns
Inferred columns follow the stream schema, as in Postgres, with the types of SQL Server:
| JSON Schema | SQL Server |
| ----------------------------------------------- | ----------------------------------------------------------------------------- |
| string | NVARCHAR(MAX) |
| string + format: 'date' | DATE |
| string + format: 'date-time', precision ≤ 7 | DATETIMEOFFSET(p) |
| string + format: 'date-time-local', ≤ 7 | DATETIME2(p) |
| string + format: 'time-local', ≤ 7 | TIME(p) |
| any of those three at precision 8–9 | NVARCHAR(MAX), compared with a binary collation |
| string + format: 'int64' | BIGINT |
| string + format: 'decimal', precision ≤ 38 | DECIMAL(precision, scale), or NVARCHAR(MAX) when not declared or above 38 |
| string + contentEncoding: 'base64' | VARBINARY(MAX) |
| integer | BIGINT |
| number | FLOAT (53 bits) |
| boolean | BIT |
| array | JSON, with CHECK (ISJSON(column, ARRAY) = 1) |
| a vector(n) column of a rule | VECTOR(n), float32, n at most 1,998 |
- SQL Server keeps time to 100 nanoseconds. Thus the
datetime2(7)of a SQL Server source loads asDATETIME2(7)with no loss. Postgres keeps it as text. - A
DATETIMEOFFSETkeeps the offset that the value had. A PostgresTIMESTAMPTZdoes not. Readers compare two values by their instant in both. DATEstarts at the year 0001. A value of the year 0000 fails its commit, and the error names the column and the key.- Text is
NVARCHAR(UTF-16), as in the SQL Server destination of Fivetran. A cursor of text compares with the binary order of its UTF-8 bytes, asCOLLATE "C"does in Postgres: the comparison casts toVARCHAR(MAX) COLLATE Latin1_General_100_BIN2_UTF8. The collation of the database applies to the reader's ownWHERE. VECTORhas no comparison operators and cannot be a key column. The row hash counts it, so no SQL compares it (ADR 0004).- Explicit columns are
columns.text,integer,int64,real,boolean,date,timestamp,localTimestamp(field, precision)andblob(field), with.notNull()and.primaryKey(), as in Postgres. - Table, view and column names follow the naming rule. SQL Server keeps 128 characters of a name. A longer name keeps its first 119 characters, then
_and the first 8 hex digits of the SHA-256 of the field or the requested name. The destination compares names without case, as SQLite does, because the default collation of a database does so. It reservesloaded_at,committed_in,replaced_in,_elt_row,_elt_row_hashand_elt_key_hash.
Store vectors
The computed dataset of an Embedding rule keeps its vectors in a VECTOR(n) column. The rule says how many dimensions its model gives, as a pgai vectorizer does (ADR 0007):
import { openai } from '@ai-sdk/openai';
import { ComputedDataset } from '@eltjs/elt-sqlserver';
import { Embedding } from '@eltjs/embedding';
new ComputedDataset({
into: marts,
name: 'staff_passage_vectors',
description: 'The vector of each staff passage.',
from: [passages],
compute: new Embedding({
model: openai.embedding('text-embedding-3-small'),
dimensions: 1536,
clock: globalThis,
key: 'id',
fields: ['text'],
}),
});- The raw table
_warehouse.raw_staff_passage_vectorshas the columnvector VECTOR(1536). A value is the JSON text oftoSqlof@zukhruf/vectors/sqlserver, with 9 significant digits, which keeps each float32 value; the commit casts it withCAST(… AS VECTOR(1536)). - A rule column of more than 1,998 dimensions fails the constructor of
ComputedDatasetwith aTypeErrorthat names the column and the limit of a float32VECTOR. - A computed dataset declares no vector index. Its tables are in
_warehouse, which readers do not read, andVECTOR_SEARCHuses a vector index only when itsTABLEis a base table, not the reader view (ADR 0019). The type ofindexesrefuses one. - The retriever of
@zukhruf/retrievalsearches the vectors, with the filter and the model of the search.
Keep a vector index on a table of marts
A vector index belongs to a base table in marts that its owner keeps, such as the passage vectors that a member of a vectorizer writes. The owner declares the index with TableIndexes and diskAnn(), and calls reconcile when it has made the table:
import { TableIndexes, diskAnn } from '@eltjs/elt-sqlserver';
const indexes = new TableIndexes({
owner: 'Vectorizer docs',
table: 'marts.docs_passage_vectors',
columns: [
{ name: 'id', type: 'nvarchar(450)' },
{ name: 'vector', type: 'vector(1536)' },
],
indexes: [
{ type: 'vector', column: 'vector', metric: 'cosine', build: diskAnn() },
],
});
await indexes.reconcile(connection);- The statement is
CREATE VECTOR INDEX [ix_elt_<hash>] ON marts.docs_passage_vectors ([vector]) WITH (METRIC = 'cosine', TYPE = 'DiskANN').reconciledrops eachix_elt_index that is no longer declared and makes each declared one that is missing, one statement at a time and outside a transaction, since SQL Server makes a vector index only there (error 574). An index of another name stays. - The constructor refuses, with a
TypeErrorthat starts withowner, a column thatcolumnsdoes not have, a vector index on a column that is not a vector, and an index key of a(max)type or a vector (errors 1919 and 1978). - Azure SQL Database makes the index with no preview feature. SQL Server 2025 in Docker makes it only with
PREVIEW_FEATURESon, on a table whose clustered key is oneintcolumn (error 42217), and over at least 100 vectors (error 42266); a table with the index then refuses each write (error 42231) (ADR 0013, probe). - An index made on an empty table starts as an exact index, and Azure SQL builds its graph after the rows come (ADR 0013, Azure probe).
Files
SQL Server takes the same text().from(file).parse(parser) and text().from(file.store(storage)) declarations as SQLite and Postgres. See stored files in elt.
- Parsed content is
NVARCHAR(MAX). A reference to a file of a storage isNVARCHAR(MAX)too. - A plain
blob()column stores an inlineVARBINARY(MAX)value. Its bytes go to the server as base64 text in the JSON batch, whichOPENJSONreads asvarchar(max):BASE64_DECODEdoes not takenvarchar(error 8116, ADR 0011).
destination.files() gives a database file storage: the copy stores each file in the database, and a DocumentText reads it from there, so a writer whose container gets a fresh disk keeps its files.
const documents = destination.table('documents', (c) => [
c.text('id'),
c.text('documentRef').from(source.driveItems.file.store(destination.files())),
]);
new DocumentText({
parser: () => parser,
files: destination.files(),
column: 'documentRef',
});- The table is
_warehouse._elt_files, which readers ofmartsdo not see:[scope] char(64), the SHA-256 of the scope;[name] varchar(128), the SHA-256 of the bytes and the short source extension;[n] bigint, the place of the chunk from 0; and[bytes] varbinary(max), at most 4 MiB. The key is([scope], [name], [n]). The first call of the storage makes the schema and the table. [scope]and[name]compare by their bytes (COLLATE Latin1_General_BIN2), soa.PDFanda.pdfof the same bytes stay two files in a database whose collation ignores case (ADR 0015).- Each chunk goes as base64 in one JSON parameter, as a plain
blob()does. - The ref is
<scope hash>/<name>. TheMS_Descriptionof the ref column begins with thereferenceof the storage: "Name of a copy of the source file bytes in table _warehouse._elt_files of this database: the SHA-256 of its scope, a slash, and the SHA-256 of the bytes with a short source extension. Kept only while a row references it. Not the source file name, a URL or extracted text." - Each call opens a session of its own with the login of the destination. A save commits each chunk on its own, before the rows that name the file commit. The reconcile keeps each file that a row of the target, of its history or of the hidden target of a reload names.
- A ref that the table does not hold fails the row of a
DocumentTextwithTable _warehouse._elt_files has no stored file <ref>. Reload the copy that stored it to store the file again.A login without a permission is aconfigfailure, as for the destination. - Recipe: store files in the database and read their text.
Descriptions
The descriptions of the source become MS_Description extended properties of each table, view and column (sp_addextendedproperty, sp_updateextendedproperty), the property that SQL Server Management Studio and the SQL Server source of elt read. A property whose stored value has the bytes of its description stays as it is, so a start whose declarations did not change writes no property: SQL Server keeps no versions of metadata, and each write fails each SNAPSHOT reading that began before it and reads the object, with error 3961 (ADR 0017). The rules are those of elt-postgresql. An extended property holds at most 7,500 bytes; a longer description fails the declaration of the copy before a connection reads.
Locks and commits
- As in Postgres, a load takes no schema lock, and no transaction stays open between commits. Each commit is one short transaction.
- A session that a pass holds, the load's or the history's, runs
SELECT 1when it ran no statement for a minute, so the gateway of Azure SQL, which ends an idle session, keeps it for the whole pass. The load waits on the clock of the pipeline, the history on real time. When the server or the network ends the session of the history all the same,finishandfailrecord the outcome on a session of their own (ADR 0016). - Readers never wait for a load: with
READ_COMMITTED_SNAPSHOTon, a reader reads the last committed version of each row. ADELETEor aMERGEthat escalates to a table lock does not block them. - Before the commits of a load, the writer makes the tables that the targets of one database share in
_warehouse, when they are not there, in a transaction of its own that holds a transaction lock ofsp_getapplockon_warehouse, as in Postgres. No commit holds that lock. The publication and the withdrawal of a view take the lock ofmarts(ADR 0009). - The open of a load takes a transaction lock of
sp_getapplockon_warehouse._elt_loadsbefore it inserts the row of the load, so the opens of a database take turns. The open closes each open load of its owner with anUPDATE, which reads each row of the table with an update lock, because the owner isNVARCHAR(MAX)and has no index. Without the lock, two connections of one pipeline that open their loads at the same time each hold the row that it inserted and wait for the row of the other, and SQL Server stops one of them with error 1205 (ADR 0009). - A commit applies the retention in its own transaction (see "Commit numbers and positions" below). It deletes the commits before
min_validby a range of the rowversion, which seeks the primary key, so it reads no commit row of another commit. It deletes the closed loads that have no commitWITH (READPAST), so it skips each row of_elt_loadsthat another transaction holds, such as the row that an open inserted; the retention of a later commit deletes a load that it skipped. Without them, two commits that apply the retention at once, or a retention and an open, wait for each other, and SQL Server stops one with error 1205 (ADR 0009). - The history records the checks of a connection in one transaction, with one
UPDATEof_warehouse.stream_checksfor each stream, or anINSERTwhen the row is not there. TheUPDATEfinds its row by the SHA-256 of the connection name and of the stream name, which is the primary key, so it seeks the row and locks only that row, and it needs no lock ofsp_getapplock. AnUPDATEthat compares the names reads each row of the table with an update lock, and two connections of one watch that record their checks at the same time each hold the rows of their own streams and wait for the rows of the other, and SQL Server stops one with error 1205 (ADR 0009). - A deduplicating commit merges the stage of one stream into its table with one
MERGEon_elt_key_hash. Underreplace, the result is the same as when the operations apply one at a time, in the order of the source. Undercursor_newer, the operation with the greatest cursor of each key applies, and only when its cursor is greater than the cursor of the row, as in Postgres (elt ADR 0032). TheOUTPUTof theMERGEgives each row that it updated or deleted, and the same statement inserts them into the history (ADR 0005). See "Deduplication" below. - An overwrite replaces the rows by difference with
DELETE, notTRUNCATE:TRUNCATEtakes a schema modification lock, and readers wait for it. The rows of the table and the records of the commit match as multisets of row hashes: the k-th row with a hash matches the k-th record with that hash, by the order of_elt_rowand of the stage. A row with no match goes, and the same statement keeps it in the history (INSERT INTO <history> SELECT … FROM (DELETE … OUTPUT deleted.*)). A row with a match stays with itscommitted_inand itsloaded_at. A record with no match enters. Anoverwrite_dedupmatches only the record of each key that its reduced stage keeps. A reset deletes its scope in the same way. - A row is told apart by
_elt_row, its identity number, where Postgres usesctidand SQLite uses_rowid_(ADR 0003). - The writer of each table is in
_warehouse._elt_writers, by the target ownership rule.
Shape changes:
- When the columns, types or
NOT NULLs of a stored table do not fit the stream, and the copy does not overwrite, the load evolves the table in place before it reads, in one commit of its own:ALTER TABLE … ADDa nullable column,DROP COLUMN, andALTER COLUMN … type. Before a conversion, each stored value that is not null must convert back to itself (TRY_CAST(TRY_CAST(column AS new) AS old) = columnfor each row), so1.5inFLOATfails the load toBIGINTand names the column. A conversion fromNVARCHAR(MAX)is the parse that the load applies to each new value, so it has no check, and a value that it cannot parse fails theALTER. A failure leaves the table as it was. TheCHECKof an array column goes before anALTERor aDROPof its column, and comes back for a column that is an array after the change.VECTORconverts only to and from text, so a change of the dimensions of a rule column makes the raw table again. - A row with a value in a column that the evolve drops or converts loses or changes the value, so it is a new version in the commit of the evolve: the history keeps the row as it was, and the row hash of the row becomes
NULL, which matches no record until a commit writes the row again. A column that the evolve adds isNULLin each row, which a row hash does not count, so it makes no new version. An evolve that keeps no row and expires no position takes back its commit row. - The history follows the evolve: it takes each new column, nullable, keeps each dropped one, and converts its column for a widening, so each position stays readable. Any other change of type expires each position before the commit of the evolve (see "Commit numbers and positions" below).
- The stored key hashes cannot be made again from the stored rows. Thus an evolve of a table whose key or key types changed fails the copy, with no change to the table; clear the copy to load it again.
- A change waits at most 3 seconds for readers (
SET LOCK_TIMEOUT 3000), becauseALTER COLUMNtakes a schema modification lock, which also blocks readers that use row versions. Then it fails the copy until the next run. - A reload goes into a hidden table
_elt_next_<hash>, which readers do not see, and no commit into it keeps a row in the history. The end of the reload gives its rows to the table by difference when the shapes agree, as an overwrite replaces its rows, and swaps it in when they do not. A reload that fails continues at the next run, and a newRESETstarts it again. - A
RESETof a partition reloads only that partition, as Delta Lake'sreplaceWherereplaces only the rows of its condition (elt ADR 0024). The rows of the reloaded partitions go to the hidden table, the rows of the others go to the table, and a deletion whose key does not name its partition goes to both._warehouse._elt_reloadskeeps the partitions of an open reload, so a run that continues it reloads the same ones. A partition condition compares text in a binary collation, soaandAare two partitions. - The swap is one transaction, and it waits for readers as a change does. It gives the rows of the hidden table the number of the commit, keeps each row of the old table in the history, renames the old table and then the hidden table with
sp_rename, and drops the old table. The history takes each new column, nullable, and converts its column for a widening. Any other change of the type of a column that the history keeps drops the history and expires each position before the swap, because the history holds one type for each column. The swapped-in table takes the grants of the old one, as Snowflake'sCOPY GRANTSdoes, andCREATE OR ALTER VIEWdefines the reader view again over the new columns, with its grants. - The views over the table read the new table after the change: SQL Server finds the tables of a view by name, so the destination only runs
sp_refreshviewfor each of them. A change that a viewWITH SCHEMABINDINGstops, such as a swap, fails, and the destination names the schema-bound views in its error; an added column goes through (ADR 0006).
Deduplication
An append_dedup copy keeps one row for each key, as in elt-postgresql. The key is the key of the stream, or the primaryKey of the copy.
- The stage keeps each operation in the order of the source: a record, or a deletion of its key (
_elt_op). A deletion carries the key values and its key hash, and no row hash. Undercursor_newerit also carries its cursor, in the cursor column. - The rows match by
_elt_key_hash, the SHA-256 of the JSON array of the key values, with a unique index on it. Thus two keys that differ only in case, such asAanda, stay two rows (ADR 0004). - A commit first reduces its stage to one operation for each key hash.
replaceapplies the operations in the order of the source: only the operations after the last deletion of a key count, a deletion with no record after it removes the key, and the last record wins.cursor_newerranks the records and deletions of a key together by their cursors: the greatest cursor wins, and the first on ties. Thus a record wins over an older deletion of its key, and a deletion wins over the older records before and after it (elt ADR 0032). - Then one statement changes the table and keeps the history:
INSERT INTO <history> SELECT … FROM (MERGE <table> USING <reduced stage> … OUTPUT deleted.*) WHERE committed_in IS NOT NULL(ADR 0005). Underreplace, a deletion deletes its row, a record after a deletion of its key replaces the row, and another record replaces the row when its row hash differs. Undercursor_newer, a deletion deletes its row only when its cursor is greater than the cursor of the row, and a record replaces the row only when its row hash differs and its cursor is greater. Thus on a tie the row stays. Only a record updates a row: a deletion that the guard refuses has nulls and no row hash, so theUPDATEclause requires a record. A record of a new key is inserted. An inserted row outputs adeletedrow of nulls, which the history does not keep. - A record with the row hash of the stored row leaves the row, its
loaded_atand itscommitted_inas they are, and the history keeps nothing. A commit that changes no row takes back its commit row, so it gives no position. - A text cursor compares by its UTF-8 bytes:
CONVERT(varchar(max), cursor COLLATE Latin1_General_100_BIN2_UTF8), asCOLLATE "C"does in Postgres. ThusBcomes beforea, andA(U+FF21) comes before an emoji. - The index of the key hash is named after the table, its key and the types of the key (
_elt_key_<hash>). After a change that gives the copy another key, or a change of the type of a key field, the stored hashes are of the old key values, so the table no longer fits, and the copy fails with no change to the table; clear the copy to load it again. - A stored row with a null key or cursor fails the load with
Existing deduplication keys and cursors must be non-null, as in Postgres.
Commit numbers and positions
One numbering orders the commits of the whole database, in the schema _warehouse, as in Postgres. The tables and the rules are those of elt-postgresql: _elt_commits, _elt_loads, _elt_epoch with min_valid and expired_by, positions <epoch>:<number>, the history of each table, the widening rule, retention, and the clear that forgets.
How SQL Server is different:
- A commit number is the
rowversionof the commit's row in_elt_commits, which the commit inserts before it changes a row.MIN_ACTIVE_ROWVERSION()gives the lowest number that a transaction still holds, so each number below it is settled: the high-water mark isMIN_ACTIVE_ROWVERSION() - 1. No lock and no sequence is necessary (ADR 0002). - Numbers are not dense. Writes of other
rowversioncolumns of the database and commits that rolled back are gaps, which a reader skips, as in Postgres. - A transaction that changes no row deletes its commit row before it commits, so it takes no number that a reader sees.
- The widenings of SQL Server, which
ALTER COLUMNconverts with no loss:BIGINT,BIT,DATE,DECIMAL,DATETIME2,DATETIMEOFFSETandTIMEtoNVARCHAR(MAX);BIGINTto aDECIMAL(p, s)with p − s ≥ 19;DATEtoDATETIME2;DATETIME2,DATETIMEOFFSETandTIMEto more digits of a second;DECIMAL(p, s)to aDECIMAL(q, t)with t ≥ s and q − t ≥ p − s.FLOATdoes not widen to text, because the conversion keeps 6 digits;VARBINARYandJSONdo not either.BIGINTdoes not widen toFLOAT, because past 2^53 it loses digits. Any other change of type setsmin_valid, as in Postgres.
A reading as of a position:
- Each reader view reads its table as of the position in
SESSION_CONTEXT(N'elt.position'): the rows of the table withcommitted_in <= P, and the rows of the history withcommitted_in <= P < replaced_in. A session that sets nothing reads the table as it is now. A view built on a reader view reads as of the same position (ADR 0010). await destination.reading(position?)gives{ sql, position, at }or{ expired }, as in Postgres. With no position, it reads the newest position.sqlis aSqlServerConnectionof its own session, in aSNAPSHOTtransaction, so a commit after the reading begins shows in no read. Dispose the reading to end the session.- The position is a read-only key of the session context, so the reader cannot change it: a change fails with error 15664. Below the newest commit that the snapshot sees, the key holds the number of the position. At the newest commit, it holds the largest
bigint, which reads each table as it is now, because a key with no value cannot be read-only (ADR 0010). - A reading fails with error 3961, which ends its transaction, when it reads an object whose metadata changed after the reading began, such as a view that a changed declaration made again. A start of a pipeline whose declarations did not change changes no object of the database, so it fails no reading (ADR 0017).
- A position of another epoch, past the newest commit, or before
min_validgives{ expired }with the reason, such as a clear that forgot the rows. A commit inside a pass, or a text that is not a position, is aTypeError.
Checkpoints
The destination keeps the checkpoints of its incremental copies in the warehouse's schema, in the tables zukhruf_checkpoints and zukhruf_checkpoint_states of SqlServerCheckpointStore of @zukhruf/checkpoint/sqlserver, on the connection of each load. See ADR 0018.
- The store's transaction runs on the load's connection, as a commit of the load does, so a stage's merge runs in the write of the checkpoint commit, and its rows and its checkpoint commit together, exactly once.
- The store keys each row by the SHA-256 of its names, as
binary(32), so a key of any length fits.SqlServerConnection.queryof sdk-microsoft-sql-server takes text, numbers, bytes andnullfor it. - No lease keeps a copy. A second run of a copy claims its checkpoint, and the older run's next commit throws
CheckpointFencedErrorand writes nothing. pipeline.resetandpipeline.clearopen the store on a connection of their own._warehouse._elt_checkpoints,_warehouse._elt_checkpoint_entriesand the lease rows of an earlier version are not read.- The host applies the two tables before the first load.
checkpointTablesis their declaration of@zukhruf/schema-drift/sqlserver, with the schema_warehouseand the ledger in it. A load andcheckpoints()only check the tables, and throwSchemaDriftErrorwhen one is missing or stale:
import { checkpointTables, sqlServerSession } from '@eltjs/elt-sqlserver';
import { SqlServerDatabase } from '@eltjs/sdk-microsoft-sql-server';
{
await using connection = await new SqlServerDatabase(login).connect(
globalThis,
);
await checkpointTables.apply(sqlServerSession(connection), { rows: 'keep' });
}Reader views
As in elt-postgresql: table(name) names the view marts.<name> over _warehouse.raw_<name>. committed_in, _elt_row, _elt_row_hash, _elt_key_hash and replaced_in are internal, and the reader view does not show them.
Declare a view
As in elt-postgresql. The view lives in marts, and the bare names of its SQL are found in marts, as in Postgres. Thus the SQL reads the reader views. SQL Server resolves a bare name inside a view through the schema of the view and then dbo, for each user; the default schema of the user takes no part (probe of 2026-11-20). Name a relation of another schema with its schema, such as _warehouse.raw_drive_items. A missing relation is error 208 (Invalid object name), and the view waits only when the pipeline makes that relation: a reader view or a raw table of a copy into the same database, or a view declared before it. A view over a relation that the pipeline does not make, or over a view declared after it, fails the refresh with the error of SQL Server.
- A refresh compares the stored definition (
OBJECT_DEFINITION) with the new text, from the name of the view to its end: SQL Server keepsCREATE OR ALTER VIEWasCREATE VIEW(probe of 2026-11-20). When they are the same, it leaves the view as it was. When they differ,CREATE OR ALTER VIEWchanges the view in place, so it keeps its object and its grants, andsp_refreshviewrefreshes each view over it, so a view over*shows the new columns (ADR 0006). - A view that the refresh makes again must have exactly the columns that the declaration describes. The descriptions become
MS_Descriptionextended properties. A view over*gets a new column of its table when the change of the table refreshes it, and the next refresh of the view then writes the description of that column. - While a view waits, its refresh drops the view of its name that an earlier declaration made, and each view over it, deepest first, as elt-postgresql drops a view with
CASCADE. SQL Server keeps a view over a dropped view, and each read of it then fails with error 4413, so the refresh drops that view too. A view of the pipeline over it waits, or is made again by its own refresh. A view that someone made over it is gone. - The publication and the withdrawal take the lock of
marts, each in a transaction of its own.
Declare a computed dataset
As in elt-postgresql. A computed dataset keeps one output row for each key, in the table _warehouse.raw_<name>, beside its history. Readers query the view marts.<name>. The columns are the key, input_hash, rule, status, error, and the columns of the rule. A text column of a rule is NVARCHAR(MAX), an integer column is BIGINT, a blob column is VARBINARY(MAX), and a vector(n) column is VECTOR(n). The key is NVARCHAR(MAX), and the table is unique on the hash of the key (ADR 0004). The refresh, its commits, its positions and its status follow elt-postgresql.
- The raw table also has
_elt_row, its clustered key (ADR 0003),committed_in,_elt_row_hashand_elt_key_hash. The constructor refuses a rule column whose name is one of these, the key, an engine column orreplaced_in, or the name of another rule column, without case, as SQL Server compares two names. - Each settled call of the rule is one commit: one
MERGEon_elt_key_hashof the rows whose row hash changed, whoseOUTPUTthe history keeps (ADR 0005). A row whose values did not change keeps its commit, and a call that changes no row takes no commit number. The row hash counts a vector by its JSON text. - When the stored columns of the raw table differ from its declaration, for example a vector of other dimensions, the refresh makes the table again in one commit: the history keeps each old row and takes the new shape,
CREATE OR ALTER VIEWkeeps the reader view, andsp_refreshviewrefreshes each view over it (ADR 0006). A column whose type the history cannot widen, such asVECTOR(3)toVECTOR(4), expires each position before that commit, as a reload of a stream does. - The dataset reads each relation of
fromthrough its reader view in one statement. A table offrommust be loaded by a copy into the same database. qualifiedNameismarts.<name>. AViewdeclared after the dataset that reads it waits while the dataset waits.indexesdeclares the nonclustered indexes of the raw table:{ type: 'nonclustered', columns }(see "Store vectors" above for a vector index). The constructor refuses, with aTypeError, a column that the table does not have, and an index key that SQL Server refuses:NVARCHAR(MAX),VARBINARY(MAX)orVECTOR(errors 1919 and 1978). Thus of the engine columns onlycommitted_incan be a key.- The destination names each index
ix_elt_and the first 16 hex digits of the SHA-256 of its declaration. Each refresh, before it writes a row, reads the indexes of the table with that start fromsys.indexes, drops each one that is no longer declared and makes each declared one that is missing, one statement at a time and outside a transaction, since SQL Server makes a vector index only there. No row is written or computed again, and an index of another name, such as a person's own, stays (ADR 0013). A person's index is gone after a changed declaration makes the table again; a declared one is made again.
A TableRule gives many parts for one input, as in elt-postgresql and elt ADR 0026. The raw table then keeps one output row for each key, with no rule column, and the parts table _warehouse.raw_<name>_parts keeps one row for each part. Readers query the view marts.<name>_parts: the key, seq (INT, from 0), the content columns and the place columns.
- The parts table also has
_elt_row, its clustered key,committed_in,_elt_row_hashand_elt_key_hash. It is unique on_elt_key_hashandseq, because the key isNVARCHAR(MAX)(ADR 0004). The key hash of a part is the key hash of its output row. - The commit of a settled call writes the output rows and their parts. A part whose row hash did not change keeps its commit. The changed parts are one
MERGEon_elt_key_hashandseq, and the parts beyond the new count of their row are oneDELETE; the history keeps each part that they replace or remove. A row that isemptyorfailedhas no parts, and a removed input removes its parts in the commit that removes its output row. - The two tables are one declaration: when either one differs from its declaration, the refresh makes both again in one commit, and
sp_refreshviewrefreshes the views over each. partIndexesdeclares the indexes of the parts table, asindexesdoes for the raw table. Only aTableRuletakes it.- The constructor refuses a column of the rule named
seqas well, in any case.validaterefuses a copy that makes<name>_partsorraw_<name>_parts. derived_statuscounts the output rows, one for each key, not the parts.
Write a kind of derived dataset in another package
A package can declare its own kind of derived dataset for a SQL Server database, for example the passages of @eltjs/vectorizer. elt-sqlserver gives it the parts that its own kinds use, as elt-sqlite does:
connectDestination(destination, clock)opens one session of the database of the destination, outside any transaction and withXACT_ABORT ON, as each writer of the destination does. The caller disposes it (await using). The login stays private.sameDatabase(destination, into)tells whether a destination of a connection loads into the database ofinto: the same server, port and database.ViewandComputedDatasetuse it to find the copies that make their relations.new SqlServerDerivedStatus(session, dataset, kind, clock)writes the row of the dataset in_warehouse.derived_status.datasetis the relation with its schema, for examplemarts.docs_passages.kindis'view'or'computed'. Callrefreshing(counts),current(counts),waiting()orfailed(error)outside a transaction of the session, asViewandComputedDatasetdo.rawTable(name)gives the name of the raw table of the relationnameunder the naming rule, for exampleraw_docs_chunks_partsfor the parts of the computed datasetdocs_chunks.quote(name)quotes a name for T-SQL: in brackets, with each]inside doubled.literal(text)gives a Unicode string literal of T-SQL: inN'', with each'inside doubled, for text that a statement cannot take as a parameter, such as the text of a view or ofEXEC.withdrawView(session, name)removes the viewmarts.<name>and every view over it, deepest first, in a transaction of its own under the lock ofmarts, as aViewdoes when its inputs are gone. Call it outside a transaction of the session. A kind that keeps a base table inmartscalls it when a view stands at the name of its table, for example theViewthat a host declared before the passages of@eltjs/vectorizer:DROP TABLEof a view fails with error 3705.martsandwarehouseare the names of the two schemas ('marts'and'_warehouse').inMarts(name)andinWarehouse(name)give the quoted, schema-qualified name of a relation in each, for example[marts].[docs_passages].- A relation that the kind makes for readers is in
marts. When the kind has aqualifiedNamesuch asmarts.docs_passages, aViewafter it waits while that relation is missing.
When something fails
As in elt-postgresql. Also:
- A database with no row versioning for readers fails the first load with the failure type
config. - An engine older than SQL Server 2025 fails the first load with the failure type
config. - A value that a column refuses fails its commit. The error names the column and the key.
- A vector of other dimensions than its rule column fails its output row, with an error that names both counts. The run and the other rows succeed.
Sync history
SqlServerSyncHistory({ login, readers }) is the sync history of a pipeline that loads into SQL Server, with the tables, views and rules of elt-postgresql: _warehouse.sync_attempts, extraction_coverage, stream_checks and derived_status, and the views sync_attempts, extraction_coverage, sync_status, stream_status, derived_status and catalog in marts. install() makes them in one transaction. readers are database users or roles; each install grants them SELECT on the numbering and nothing else of _warehouse. Each attempt has a session of its own that holds a session lock of sp_getapplock on the attempt, so the next attempt of its connection finds a pass whose process stopped and records it as failed (elt-postgresql ADR 0009). The catalog reads the MS_Description extended properties. It lists each view and each base table of marts with its columns; kind is view, table or column. elt keeps each table of its own in _warehouse, so a base table of marts is one that its owner keeps for readers, such as the passages and passage vectors of a vectorizer (ADR 0019); its owner describes it with MS_Description. The sync history keeps no row versions, so a session that reads as of a position before
