npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@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.

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

  • SqlServerDestination with the four destination sync modes: the raw table with its _elt_row identity key (ADR 0003), the unique index on _elt_key_hash when the copy deduplicates or the columns declare a key (ADR 0004), the MERGE of a deduplicating commit (ADR 0005, see "Deduplication" below), the replacement by difference of an overwrite (see "Locks and commits" below), the history table, the MS_Description extended properties, the reader view, and positions().
  • 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 RESET of 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 SqlServerSyncHistory with 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), and readPassStatus(login).
  • View, and its rows of derived_status (see "Declare a view" and "Derived status" below).
  • ComputedDataset of a Rule or a TableRule, with text, blob, integer and vector(n) rule columns, the parts table of a TableRule, declared indexes, and its rows of derived_status (see "Declare a computed dataset" below).
  • A failure of the setup of the database is a SqlServerSetupError. Its failure type is config. A login without a permission that a statement of the destination or of its checkpoints needs is also config: a SqlServerPermissionError of 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 as CREATE TABLE). A login that the server refuses (SqlServerLoginError: wrong credentials, a disabled login, a database that it may not open) is config too, as a wrong password is in elt-postgresql, and so is a SchemaDriftError of checkpoint tables that the host did not apply (see Checkpoints). Each other error, for example a server that cannot be reached, is system.

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 in marts, 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 view marts.drive_items, the reader name. The destination keeps the rows of the target in the raw table _warehouse.raw_drive_items.
  • login is 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 the SqlServerDatabase of 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 and util.inspect do 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 in marts, such as catalog.
  • 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 VECTOR and JSON types. It must keep row versions for readers: READ_COMMITTED_SNAPSHOT and ALLOW_SNAPSHOT_ISOLATION on (ADR 0010). The first load checks both, and fails with the failure type config and the ALTER DATABASE statement that turns them on.
  • The destination holds one connection of its own for each load, because a #stage table 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 as DATETIME2(7) with no loss. Postgres keeps it as text.
  • A DATETIMEOFFSET keeps the offset that the value had. A Postgres TIMESTAMPTZ does not. Readers compare two values by their instant in both.
  • DATE starts 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, as COLLATE "C" does in Postgres: the comparison casts to VARCHAR(MAX) COLLATE Latin1_General_100_BIN2_UTF8. The collation of the database applies to the reader's own WHERE.
  • VECTOR has 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) and blob(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 reserves loaded_at, committed_in, replaced_in, _elt_row, _elt_row_hash and _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_vectors has the column vector VECTOR(1536). A value is the JSON text of toSql of @zukhruf/vectors/sqlserver, with 9 significant digits, which keeps each float32 value; the commit casts it with CAST(… AS VECTOR(1536)).
  • A rule column of more than 1,998 dimensions fails the constructor of ComputedDataset with a TypeError that names the column and the limit of a float32 VECTOR.
  • A computed dataset declares no vector index. Its tables are in _warehouse, which readers do not read, and VECTOR_SEARCH uses a vector index only when its TABLE is a base table, not the reader view (ADR 0019). The type of indexes refuses one.
  • The retriever of @zukhruf/retrieval searches 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'). reconcile drops each ix_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 TypeError that starts with owner, a column that columns does 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_FEATURES on, on a table whose clustered key is one int column (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 is NVARCHAR(MAX) too.
  • A plain blob() column stores an inline VARBINARY(MAX) value. Its bytes go to the server as base64 text in the JSON batch, which OPENJSON reads as varchar(max): BASE64_DECODE does not take nvarchar (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 of marts do 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), so a.PDF and a.pdf of 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>. The MS_Description of the ref column begins with the reference of 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 DocumentText with Table _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 a config failure, 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 1 when 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, finish and fail record the outcome on a session of their own (ADR 0016).
  • Readers never wait for a load: with READ_COMMITTED_SNAPSHOT on, a reader reads the last committed version of each row. A DELETE or a MERGE that 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 of sp_getapplock on _warehouse, as in Postgres. No commit holds that lock. The publication and the withdrawal of a view take the lock of marts (ADR 0009).
  • The open of a load takes a transaction lock of sp_getapplock on _warehouse._elt_loads before 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 an UPDATE, which reads each row of the table with an update lock, because the owner is NVARCHAR(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_valid by 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 commit WITH (READPAST), so it skips each row of _elt_loads that 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 UPDATE of _warehouse.stream_checks for each stream, or an INSERT when the row is not there. The UPDATE finds 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 of sp_getapplock. An UPDATE that 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 MERGE on _elt_key_hash. Under replace, the result is the same as when the operations apply one at a time, in the order of the source. Under cursor_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). The OUTPUT of the MERGE gives 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, not TRUNCATE: TRUNCATE takes 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_row and 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 its committed_in and its loaded_at. A record with no match enters. An overwrite_dedup matches 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 uses ctid and 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 … ADD a nullable column, DROP COLUMN, and ALTER 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) = column for each row), so 1.5 in FLOAT fails the load to BIGINT and names the column. A conversion from NVARCHAR(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 the ALTER. A failure leaves the table as it was. The CHECK of an array column goes before an ALTER or a DROP of its column, and comes back for a column that is an array after the change. VECTOR converts 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 is NULL in 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), because ALTER COLUMN takes 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 new RESET starts it again.
  • A RESET of a partition reloads only that partition, as Delta Lake's replaceWhere replaces 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_reloads keeps 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, so a and A are 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's COPY GRANTS does, and CREATE OR ALTER VIEW defines 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_refreshview for each of them. A change that a view WITH SCHEMABINDING stops, 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. Under cursor_newer it 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 as A and a, stay two rows (ADR 0004).
  • A commit first reduces its stage to one operation for each key hash. replace applies 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_newer ranks 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). Under replace, 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. Under cursor_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 the UPDATE clause requires a record. A record of a new key is inserted. An inserted row outputs a deleted row of nulls, which the history does not keep.
  • A record with the row hash of the stored row leaves the row, its loaded_at and its committed_in as 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), as COLLATE "C" does in Postgres. Thus B comes before a, and A (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 rowversion of 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 is MIN_ACTIVE_ROWVERSION() - 1. No lock and no sequence is necessary (ADR 0002).
  • Numbers are not dense. Writes of other rowversion columns 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 COLUMN converts with no loss: BIGINT, BIT, DATE, DECIMAL, DATETIME2, DATETIMEOFFSET and TIME to NVARCHAR(MAX); BIGINT to a DECIMAL(p, s) with p − s ≥ 19; DATE to DATETIME2; DATETIME2, DATETIMEOFFSET and TIME to more digits of a second; DECIMAL(p, s) to a DECIMAL(q, t) with t ≥ s and q − t ≥ p − s. FLOAT does not widen to text, because the conversion keeps 6 digits; VARBINARY and JSON do not either. BIGINT does not widen to FLOAT, because past 2^53 it loses digits. Any other change of type sets min_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 with committed_in <= P, and the rows of the history with committed_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. sql is a SqlServerConnection of its own session, in a SNAPSHOT transaction, 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_valid gives { 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 a TypeError.

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.query of sdk-microsoft-sql-server takes text, numbers, bytes and null for it.
  • No lease keeps a copy. A second run of a copy claims its checkpoint, and the older run's next commit throws CheckpointFencedError and writes nothing.
  • pipeline.reset and pipeline.clear open the store on a connection of their own.
  • _warehouse._elt_checkpoints, _warehouse._elt_checkpoint_entries and the lease rows of an earlier version are not read.
  • The host applies the two tables before the first load. checkpointTables is their declaration of @zukhruf/schema-drift/sqlserver, with the schema _warehouse and the ledger in it. A load and checkpoints() only check the tables, and throw SchemaDriftError when 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 keeps CREATE OR ALTER VIEW as CREATE VIEW (probe of 2026-11-20). When they are the same, it leaves the view as it was. When they differ, CREATE OR ALTER VIEW changes the view in place, so it keeps its object and its grants, and sp_refreshview refreshes 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_Description extended 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_hash and _elt_key_hash. The constructor refuses a rule column whose name is one of these, the key, an engine column or replaced_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 MERGE on _elt_key_hash of the rows whose row hash changed, whose OUTPUT the 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 VIEW keeps the reader view, and sp_refreshview refreshes each view over it (ADR 0006). A column whose type the history cannot widen, such as VECTOR(3) to VECTOR(4), expires each position before that commit, as a reload of a stream does.
  • The dataset reads each relation of from through its reader view in one statement. A table of from must be loaded by a copy into the same database.
  • qualifiedName is marts.<name>. A View declared after the dataset that reads it waits while the dataset waits.
  • indexes declares the nonclustered indexes of the raw table: { type: 'nonclustered', columns } (see "Store vectors" above for a vector index). The constructor refuses, with a TypeError, a column that the table does not have, and an index key that SQL Server refuses: NVARCHAR(MAX), VARBINARY(MAX) or VECTOR (errors 1919 and 1978). Thus of the engine columns only committed_in can 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 from sys.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_hash and _elt_key_hash. It is unique on _elt_key_hash and seq, because the key is NVARCHAR(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 MERGE on _elt_key_hash and seq, and the parts beyond the new count of their row are one DELETE; the history keeps each part that they replace or remove. A row that is empty or failed has 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_refreshview refreshes the views over each.
  • partIndexes declares the indexes of the parts table, as indexes does for the raw table. Only a TableRule takes it.
  • The constructor refuses a column of the rule named seq as well, in any case. validate refuses a copy that makes <name>_parts or raw_<name>_parts.
  • derived_status counts 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 with XACT_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 of into: the same server, port and database. View and ComputedDataset use 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. dataset is the relation with its schema, for example marts.docs_passages. kind is 'view' or 'computed'. Call refreshing(counts), current(counts), waiting() or failed(error) outside a transaction of the session, as View and ComputedDataset do.
  • rawTable(name) gives the name of the raw table of the relation name under the naming rule, for example raw_docs_chunks_parts for the parts of the computed dataset docs_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: in N'', with each ' inside doubled, for text that a statement cannot take as a parameter, such as the text of a view or of EXEC.
  • withdrawView(session, name) removes the view marts.<name> and every view over it, deepest first, in a transaction of its own under the lock of marts, as a View does when its inputs are gone. Call it outside a transaction of the session. A kind that keeps a base table in marts calls it when a view stands at the name of its table, for example the View that a host declared before the passages of @eltjs/vectorizer: DROP TABLE of a view fails with error 3705.
  • marts and warehouse are the names of the two schemas ('marts' and '_warehouse'). inMarts(name) and inWarehouse(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 a qualifiedName such as marts.docs_passages, a View after 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