DBAClientX.SqlServer 1.0.24

dotnet add package DBAClientX.SqlServer --version 1.0.24
                    
NuGet\Install-Package DBAClientX.SqlServer -Version 1.0.24
                    
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="DBAClientX.SqlServer" Version="1.0.24" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="DBAClientX.SqlServer" Version="1.0.24" />
                    
Directory.Packages.props
<PackageReference Include="DBAClientX.SqlServer" />
                    
Project file
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add DBAClientX.SqlServer --version 1.0.24
                    
#r "nuget: DBAClientX.SqlServer, 1.0.24"
                    
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
#:package DBAClientX.SqlServer@1.0.24
                    
#:package directive can be used in C# file-based apps starting in .NET 10 preview 4. Copy this into a .cs file before any lines of code to reference the package.
#addin nuget:?package=DBAClientX.SqlServer&version=1.0.24
                    
Install as a Cake Addin
#tool nuget:?package=DBAClientX.SqlServer&version=1.0.24
                    
Install as a Cake Tool

DBAClientX.SqlServer

SQL Server client for .NET: queries, streaming, bulk copy, GO-batch scripts, Agent jobs, backup and restore, built on Microsoft.Data.SqlClient.

NuGet Downloads

Part of the DbaClientX family. It depends on DBAClientX.Core and Microsoft.Data.SqlClient, and targets net472, net8.0 and net10.0 (net472 builds only on Windows). Source and issues: https://github.com/EvotecIT/DbaClientX

Install

dotnet add package DBAClientX.SqlServer

Quick start

using DBAClientX;

using var sql = new SqlServer();
string connectionString = SqlServer.BuildConnectionString("sql01", "App", integratedSecurity: true);

var count = await sql.ExecuteScalarAsync(connectionString, "SELECT COUNT(*) FROM dbo.Users");

var users = await sql.QueryAsListAsync(connectionString,
    "SELECT Id, Name FROM dbo.Users WHERE Active = @active ORDER BY Id",
    row => (Id: row.GetInt32(0), Name: row.GetString(1)),
    new Dictionary<string, object?> { ["@active"] = true });

foreach (var user in users)
    Console.WriteLine($"{user.Id} {user.Name}");

Every command has an overload that takes serverOrInstance, database and integratedSecurity (plus optional username/password) instead of a connection string.

Connect

SqlServer.BuildConnectionString builds an encrypted, pooled connection string. Optional arguments cover a SQL login, port, trustServerCertificate, connectTimeoutSeconds and applicationName:

var cs = SqlServer.BuildConnectionString("sql01", "App", integratedSecurity: false,
    username: "app_reader", password: password, port: 1433,
    connectTimeoutSeconds: 15, applicationName: "Reports");

Connections are always encrypted: passing ssl: false throws. trustServerCertificate: true skips validating the server certificate, so keep it for test servers with self-signed certificates. The seven-argument overload is kept for binary compatibility.

SqlServerConnectionSettings describes one server (name, database, sign-in, ApplicationIntent, MultiSubnetFailover, timeouts) without holding a connection, so one value can be reused across commands and servers. It also accepts a full connection string. For Microsoft Entra ID, give it a token callback and apply it to the client:

var settings = new SqlServerConnectionSettings("sql01.database.windows.net")
{
    Database = "App",
    AccessTokenCallback = SqlServerConnectionSettings.CreateAccessTokenCallback(accessToken)
};

using var sql = settings.ApplyTo(new SqlServer());
var tables = await sql.QueryAsync(settings.BuildConnectionString(), "SELECT name FROM sys.tables");

CreateAccessTokenCallback reads the expiry from the token (or takes expiresOn) and fails with a clear message once the token has expired. To supply tokens yourself, set ConnectionOptions.AccessTokenCallback on the client; reusing the same delegate keeps SqlClient connection pooling. ConnectionOptions.ConnectionFactory lets you create the SqlConnection yourself, and ConnectionOptions.CompatibilityProfile = SqlServerCompatibilityProfile.FabricWarehouse validates connections and bulk-copy options against Microsoft Fabric Data Warehouse endpoints.

PingAsync runs SELECT 1 and returns false instead of throwing.

Run commands

await sql.ExecuteNonQueryAsync(connectionString,
    "UPDATE dbo.Users SET LastLogin = SYSUTCDATETIME() WHERE Id = @Id",
    new Dictionary<string, object?> { ["@Id"] = 1 },
    cancellationToken: ct);

var result = await sql.ExecuteStoredProcedureAsync(connectionString, "dbo.GetRecentUsers",
    new Dictionary<string, object?> { ["@Limit"] = 100 },
    cancellationToken: ct);

Query and QueryAsync return a DataSet, DataTable or DataRow result according to the client's ReturnType. parameterTypes and parameterDirections set SqlDbType and output parameters. SQL Server sends DateTime parameters as datetime; set UseDateTime2ForDateTimeParameters = true to send datetime2.

Stream rows

On net8.0 and net10.0, QueryStreamAsync reads one row at a time. The typed overload maps each record without building a DataTable:

await foreach (var user in sql.QueryStreamAsync(connectionString,
    "SELECT Id, Name FROM dbo.Users ORDER BY Id",
    row => (Id: row.GetInt32(0), Name: row.GetString(1)),
    cancellationToken: ct))
{
    Console.WriteLine(user.Name);
}

The DataRow overload remains for existing code. When another API consumes a reader directly, QueryReaderAsync returns an owned DbaDataReader (available on every target):

await using var reader = await sql.QueryReaderAsync(connectionString,
    "SELECT Id, Name FROM dbo.Users ORDER BY Id", cancellationToken: ct);

while (await reader.ReadAsync(ct))
    Console.WriteLine($"{reader.GetInt32(0)} {reader.GetString(1)}");

Disposing the reader also disposes its command and any connection opened for it. Output parameters are copied back after the provider reader closes.

Read errors and server messages

A failed query, scalar, non-query or stored procedure call throws DBAClientX.DbaQueryExecutionException. ProviderMessages carries what SQL Server reported (number, level, state, line, procedure and text, formatted like SQL Server Management Studio's Msg 137, Level 15, State 2, Line 2), and ProviderErrorKind classifies the failure, for example SyntaxError, UndeclaredVariable or CertificateValidationFailed. Set RedactProviderMessages = true on the client to keep server text, which can include data values, out of exceptions that get logged. This covers DbaQueryExecutionException only; the provider exceptions that streams throw are not changed.

PRINT output and other informational messages (severity 10 and below) arrive through ProviderMessageReceived:

sql.ProviderMessageReceived += (_, e) => Console.WriteLine(e.Message.Message);

try
{
    await sql.ExecuteNonQueryAsync(connectionString, "PRINT 'Starting cleanup'; EXEC dbo.Cleanup;");
}
catch (DbaQueryExecutionException ex)
{
    Console.WriteLine(ex.ProviderErrorKind);
    foreach (var message in ex.ProviderMessages)
        Console.WriteLine(message);
}

Handlers run on the thread that reads the server response, so keep them short. The streaming APIs (QueryStreamAsync and its typed variant) throw the provider's own SqlException instead of DbaQueryExecutionException, and report cancellation as OperationCanceledException.

Run scripts with GO batches

SqlServer.SplitBatches splits a script on GO lines the way SQL Server Management Studio and sqlcmd do: GO inside strings, quoted identifiers and comments is ignored, and GO n repeats the batch. SqlServerScriptRunner runs those batches against several servers. For each server, a multi-batch script shares one session connection, so temp tables, SET options and USE carry from batch to batch, and a failing batch stops that server's script:

var batches = SqlServerScriptRunner.ReadScriptFiles(new[] { @"C:\Scripts\Deploy.sql" });
var servers = new[] { new SqlServerConnectionSettings("sql01"), new SqlServerConnectionSettings("sql02") };

var runner = new SqlServerScriptRunner(() => new SqlServer())
{
    ServerFailed = (server, ex) => Console.WriteLine($"{server}: {ex.Message}")
};

await runner.RunAsync(servers, batches, async batch =>
{
    try
    {
        await batch.Client.ExecuteNonQueryAsync(batch.ConnectionString, batch.Text, cancellationToken: ct);
        return true;
    }
    catch (DbaQueryExecutionException ex)
    {
        Console.WriteLine($"{batch.Server} batch {batch.Number}/{batch.Count}: {ex.Message}");
        return false;
    }
}, ct);

ConfirmScript can decline a multi-batch script for a server before anything connects, and ShareSession = false gives every batch its own client. To keep session state across your own calls without the runner, use BeginSession/BeginSessionAsync and EndSession on a client.

Start an Agent job and wait

StartSqlServerAgentJobAsync starts a job by exact name, optionally at a given step, and with wait: true polls until the run finishes and reads its outcome from job history:

using DBAClientX.SqlServerManagement;

var run = await sql.StartSqlServerAgentJobAsync(connectionString, "Nightly ETL",
    wait: true, pollInterval: TimeSpan.FromSeconds(5), cancellationToken: ct);

Console.WriteLine($"{run.Name}: {run.Outcome} in {run.Duration} {run.Message}");

Outcome is Succeeded, Failed, Retry or Canceled for a finished run, Started when not waiting, and Unknown when SQL Server Agent restarted or another run of the job started before the outcome was read. A missing job throws ArgumentException. Cancelling while waiting leaves the job running on the server. GetSqlServerLogins and GetSqlServerDatabaseUsers list logins and database users.

Transactions

await sql.RunInTransactionAsync(connectionString, async (tx, token) =>
{
    await tx.ExecuteNonQueryAsync(connectionString,
        "DELETE FROM dbo.Logs WHERE Level = 'Debug'", useTransaction: true, cancellationToken: token);
}, cancellationToken: ct);

BeginTransaction/BeginTransactionAsync, Commit and Rollback are available for manual control; pass useTransaction: true to run a command inside the active transaction.

Session-locked transactions

Use a dedicated application-lock session when the lock and the database writes must remain on the same SQL Server connection:

await using var held = await sql.AcquireSessionLockAsync(
    connectionString, "inventory-refresh", cancellationToken: ct);
await held.ExecuteInTransactionAsync(async (scope, token) =>
{
    await scope.ExecuteNonQueryAsync(
        "UPDATE dbo.Inventory SET CheckedAt = @at WHERE Id = @id;",
        new Dictionary<string, object?> { ["@at"] = DateTime.UtcNow, ["@id"] = 42 }, token);
}, cancellationToken: ct);

The callback must await each scope command. Do not keep the scope after the callback, switch databases, or change connection, transaction or application-lock lifetime through SQL. A lock does not fence writes made through other clients. Commands are not retried or reconnected. A command failure prevents commit even when the callback catches it; cancellation or connection loss invalidates the handle. A commit failure can have an uncertain durable outcome and requires reconciliation before another operation.

The scope's QueryAsync returns the first table after completing all result sets. Additional result sets are materialized to expose later SQL failures before commit.

Bulk insert

var table = new DataTable();
table.Columns.Add("Id", typeof(int));
table.Columns.Add("Name", typeof(string));
table.Rows.Add(1, "Example");

sql.BulkInsert(connectionString, table, "dbo.ImportUsers",
    new SqlServerBulkInsertOptions { AutoCreateTable = true },
    batchSize: 1000);

BulkInsert also accepts an IDataReader. SqlServerBulkInsertOptions carries column mappings, table auto-creation, column defaults for nulls, progress (NotifyAfter, RowsCopied) and native SqlBulkCopyOptions flags such as KeepIdentity and TableLock.

Streaming table transfers

SqlServer.TransferTableAsync appends a SQL Server table directly through an owned reader and native streaming bulk copy. It avoids materializing pages and returns the provider's row count and operation identifier:

var result = await SqlServer.TransferTableAsync(new SqlServerTableTransferRequest
{
    SourceConnectionString = sourceConnectionString,
    DestinationConnectionString = destinationConnectionString,
    SourceTable = "dbo.Users",
    DestinationTable = "staging.Users",
    SourceColumns = new[] { "Name", "Email" },
    BatchSize = 5000
}, ct);

Tables must be local user tables. Names can be schema-qualified; an omitted schema means dbo. Select the database through its connection string. SourceColumns contains literal column names and can omit generated destination columns. The source projection follows native destination column order so sequential streaming supports reordered schemas and mappings. Destination mappings use native bulk-copy name matching, including bracketed names. BulkOptions supplies the existing name mappings, identity and progress controls, and explicit staging-table creation. Constraint checking is enabled when BulkOptions is omitted; an explicitly supplied options object controls its native flags.

Budget destination transaction-log space separately from client memory and data-file growth. One atomic transfer can require substantially more log capacity than a copy with small committed batches. CommitEachBatch narrows the commit window and permits partial writes after a failure; it does not reserve space or guarantee a maximum log size. Native bulk flags such as TableLock remain explicit options and follow SQL Server's logging rules.

Native SQL decimal values retain their provider representation, including values outside the CLR decimal range. Reader auto-creation preserves declared decimal precision and scale; readers without those schema facets require an explicitly created destination and AutoCreateTable = false, or the DataTable overload. DataTable auto-creation selects a decimal schema that fits every current value and rejects a mixture that exceeds SQL Server's 38-digit limit. Empty or all-null decimal columns retain the decimal(38,18) default; subsequent writes must fit the resulting schema. Quoted table and column names retain spaces inside their delimiters.

Default writes use one destination transaction, completed after the source reader and transaction. Existing rows remain. CommitEachBatch = true explicitly permits earlier native batches and created schema/table to remain after failure or cancellation. Both modes own non-pooled, non-enlisted connections and do not replay the transfer. SourceConnectionOptions and DestinationConnectionOptions can supply a token callback or a connection factory; a factory must return a closed connection using the supplied connection string. Fabric Warehouse is not supported by this transactional workflow.

The source defaults to ReadCommitted. SourceIsolationLevel = IsolationLevel.Snapshot requires snapshot isolation already enabled on the source database; Serializable uses native locks. The API does not change database settings. A source and destination that identify the same native table are rejected.

This transfer has no checkpoint, transformation or content verification. Use DbaProviderTableCopyRunner from DBAClientX.Core for verified, resumable copies. Native copied-row counts do not establish checksum equality, and caller-requested triggers can change destination contents.

Estimated query plans

ExplainQueryPlanAsync captures SQL Server's estimated plan for one SELECT, INSERT, UPDATE, DELETE or MERGE statement without running that statement. It uses a separate non-pooled connection outside the client's active transaction and ambient enlistment. The login needs statement permissions and SHOWPLAN permission in each referenced database.

using DBAClientX;
using DBAClientX.QueryPlans;
using System.Data;

using var client = new SqlServer();
var plan = await client.ExplainQueryPlanAsync(connectionString,
    "SELECT Payload FROM dbo.Events WHERE Id = @id",
    new Dictionary<string, SqlServerQueryPlanParameter> {
        ["@id"] = new(SqlDbType.Int)
    });

foreach (var step in plan.Steps) {
    Console.WriteLine($"{step.Detail}: {step.Schema}.{step.Table}, output={step.Estimates?.OutputRows}, read={step.Estimates?.RowsRead}");
}

Parameter types create unassigned local variables. These are generic estimates, recorded as plan.Provenance.ParameterMode == TypedVariables; parameter values are never interpolated or bound. Names must match the SQL spelling exactly, with ASCII letters, digits and underscores. Character/binary declarations require an explicit size, such as new(SqlDbType.NVarChar, size: 200); use -1 for MAX. Decimal and temporal declarations accept precision/scale facets. Table-valued, UDT and legacy LOB declarations are unsupported.

Native Estimates keep fractional output rows, estimated rows read and table cardinality separate. Missing estimates remain null. ScanOperations lists scan access methods: TOP/MAX can stop after one row, so the operation label alone does not establish a full traversal. QueryPlanAssert, QueryPlanRules and FullScans use SQLite semantics and reject native SQL Server plans. SQL Server's SELECT WITHOUT QUERY classification is retained with an empty operator list for constant-only statements.

SqlServerQueryPlanParser.Parse(sql, showPlanXml) reads an existing estimated SHOWPLAN document with the same model. Capture and parsing accept at most 16,777,216 document characters and 4096 operators. Actual runtime plans, procedural batches and multiple statement plans are unsupported. Capture uses the client's CommandTimeout; cancellation still attempts SHOWPLAN cleanup with a separate five-second deadline. Custom connection factories must return a closed connection with pooling and enlistment disabled.

Database workload diagnostics

Read Query Store configuration and a bounded rowstore table-index observation for one database:

var snapshot = await sql.GetMonitoringSnapshotAsync(
    new DBAClientX.SqlServerMonitoring.SqlServerMonitoringTarget
    {
        ServerOrInstance = "sql01",
        Database = "App",
        IntegratedSecurity = true
    },
    new DBAClientX.SqlServerMonitoring.SqlServerMonitoringOptions
    {
        Scope = DBAClientX.SqlServerMonitoring.SqlServerMonitoringScope.Workload,
        MaximumIndexUsageRows = 500
    },
    cancellationToken: ct);

if (snapshot.QueryStore is { } store)
    Console.WriteLine($"Query Store: {store.ActualState}, requested {store.DesiredState}");

if (snapshot.IndexUsage is { } usage)
    Console.WriteLine($"Visible indexes: {usage.Indexes.Count}, truncated: {usage.IsTruncated}");

foreach (var error in snapshot.Errors)
    Console.WriteLine(error);

GetQueryStoreStateAsync and GetIndexUsageAsync also collect these sections individually. Query Store reports actual/desired state, capture mode, storage and the complete read-only reason bitmask. Collection does not enable Query Store, alter capture policy, update statistics or return captured query text. Index usage retains primary-key/uniqueness roles, nullable read/write counters and index statistics properties. The default continuous-monitoring scope remains Baseline. All retains its published value and original sections; use All | Workload to collect them together.

The index limit is between 1 and 10,000. IsTruncated reports additional visible indexes; catalog permissions can hide objects even when it is false. This collector includes rowstore table indexes and excludes indexed views, heaps, columnstore, hypothetical and memory-optimized indexes. Missing usage rows or statistics properties remain null. A zero or absent counter does not prove that an index is unused. Counters can reset on instance restart, database detach/shutdown and index changes, so ServerStartTime gives restart context rather than a complete observation window. Server-reported timestamps retain their local clock values with an unspecified DateTime.Kind; CollectedUtc is the collector's UTC completion time.

Query Store needs SQL Server 2016 or later and the applicable database-state/performance-state permission. A disabled database reports OFF; master and tempdb report unsupported. Missing configuration metadata reports metadata-unavailable rather than being interpreted as OFF. Index/statistics collection needs SQL Server 2014 or later and the applicable server-state/performance-state permission; statistics/catalog visibility also depends on the caller's grants. A failed optional section remains null and appears in Errors, including permission-denied and unsupported classifications. Cancellation propagates to the caller. Collection makes no automatic index-removal recommendation.

The DbaClientX PowerShell module forwards the same scope and row bound:

Get-DbaXSqlServerMonitoring -Server sql01 -Database App -Scope Workload -MaximumIndexUsageRows 1000

Export review plans

GetSqlServerExportPlan captures table and module scripts, database permission metadata and known dependencies in an immutable manifest. It reuses the database management readers and requires database VIEW DEFINITION plus SELECT on sys.sql_expression_dependencies. It omits instance metadata reads. Freeze source DDL when consistency is required; capture uses several catalog reads rather than an atomic DDL snapshot.

using var sql = new SqlServer();
var plan = sql.GetSqlServerExportPlan(connectionString);
foreach (var issue in plan.Issues)
    Console.WriteLine($"{issue.Kind}: {issue.ObjectName} - {issue.Detail}");
foreach (var script in plan.OrderedScripts)
    Console.WriteLine($"{script.Id}: {script.ContentFingerprint}");
Console.WriteLine(plan.Fingerprint);

Scripts retains all available supported scripts. OrderedScripts places resolved local prerequisites before their dependents, including post-create constraints, and excludes scripts blocked by dependency cycles. Issues identify unavailable definitions, unsupported objects, missing prerequisites and unresolved or external references. Optional schema and name filters use native database comparisons; dependencies outside the selected scripts remain explicit prerequisites. Permission metadata covers the database regardless of these filters.

For existing reader results, use DBAClientX.SqlServerManagement.SqlServerExportPlan.Create(scripts, dependencies, permissions, sourceDatabaseName). Offline inputs require exact catalog schema/name identities; matching is ordinal and preserves case-sensitive names. Fingerprints use SHA-256 over exact UTF-8 script text and framed manifest metadata. They retain SQL literal line endings and exclude timestamps and runtime culture.

PowerShell exposes the same plan through Get-DbaXSqlServerManagement -Type ExportPlan -ConnectionString $connectionString. Review Issues and Limitations before storing or using scripts. The plan does not execute DDL, write files, create users or grants, export data or secrets, or establish migration readiness. Backing schemas, user types, assemblies, filegroups and other deployment prerequisites remain caller responsibilities. Dynamic SQL can have dependencies absent from catalog metadata. Captured definitions can contain sensitive application literals.

Back up, restore and check a database

Backup paths and relocation paths are evaluated on the SQL Server host under its service account. Supply existing directories that the service can read and write. The SQL login needs backup permission on the source, permission to create the restored database, and permission to run CHECKDB. These operations use an owned connection to master outside ambient transactions.

using var sql = new SqlServer();
var backup = await sql.BackupDatabaseCopyOnlyToDiskAsync(
    connectionString, "App", serverBackupDirectory, cancellationToken: ct);

// Retain this identity with the recovery record, separately from the backup file.
var identity = backup.Header.Identity;
var files = await sql.ReadDiskBackupFileListAsync(
    connectionString, backup.ServerBackupPath, cancellationToken: ct);
string targetName = "App_Recovery_" + Guid.NewGuid().ToString("N");
var destinations = new Dictionary<string, string>();
for (int index = 0; index < files.Count; index++)
{
    var file = files[index];
    string directory = file.FileType switch
    {
        "D" => serverDataDirectory,
        "L" => serverLogDirectory,
        _ => throw new NotSupportedException("Assign an explicit destination for this file type.")
    };
    destinations.Add(file.LogicalName, directory.TrimEnd('\\', '/') + "/"
        + targetName + "_" + index + (file.FileType == "L" ? ".ldf" : ".mdf"));
}

var plan = await sql.PrepareRestoreAsNewAsync(connectionString,
    backup.ServerBackupPath, targetName, identity, destinations, cancellationToken: ct);
// Review plan.Header, plan.Files, plan.FileDestinations and plan.RequiredFileBytes.
await sql.RestoreDatabaseAsNewAsync(connectionString, plan, cancellationToken: ct);
var integrity = await sql.CheckDatabaseIntegrityAsync(
    connectionString, targetName, cancellationToken: ct);
if (!integrity.Succeeded)
    throw new InvalidOperationException("CHECKDB reported integrity issues.");

Preparation reads the backup identity and file metadata, refuses an existing target or assigned paths, and runs RESTORE VERIFYONLY with the complete MOVE mapping and checksums. Its immutable result records the allocated file sizes; that sum excludes growth, CHECKDB and other temporary space. Native free-space verification varies by server and platform: a successful plan can still precede a restore failure on a full volume. Independently confirm capacity on each destination volume. Preparation does not reserve names, files or free space. Execution revalidates the plan and coordinates library callers with a target application lock. It never uses REPLACE. Keep other restore tools away from the target and protect the backup media from modification; the pinned media identity is not an authenticity signature.

Verification proves readability and checksums. A restore followed by full CHECKDB provides separate database integrity evidence. Application readiness still needs application checks. PrepareRestoreAsNewAsync and RestoreDatabaseAsNewAsync accept one dedicated full backup. No recovery command is replayed, including when command retries are enabled.

Canceling a running backup or restore propagates OperationCanceledException with the caller token when SQL Server acknowledges cancellation. Native abort and termination messages accompanying that acknowledgement are accepted; unrelated failures remain errors. Cancellation does not roll back a restore or remove its database and server files. Inspect the target state and arrange explicit cleanup before reusing its name or paths.

CHECKDB returns a typed result with a total issue count and at most MaxIssues retained records (default 1,000). Message text is excluded unless IncludeDiagnosticMessages is true. PhysicalOnly = true narrows the check and is recorded in the result; full checks are the default. CHECKDB can consume substantial CPU, I/O and temporary space. Execution failures throw the library's redacted query exception, and cancellation preserves the caller token.

The restored database remains available for application checks. The caller owns its eventual deletion and the backup file's retention policy. A cancelled or failed restore may leave a database in RESTORING state; confirm the target name and relocated files belong to the attempted restore before deleting it. A failed backup can leave an incomplete file in the supplied directory. The library does not delete caller-named databases or server files automatically.

Full, differential and log chains

BackupToDedicatedDiskAsync creates a dedicated full, differential or log backup. Its required copyOnly argument makes the source policy explicit: a conventional full establishes a differential base, and a conventional log backup can permit log truncation. Use BackupDatabaseCopyOnlyToDiskAsync for the copy-only full workflow above. Every generated backup uses checksums and is verified before its identity is returned.

Prepare an explicitly ordered chain from retained backup results. Each disk file must contain one backup set and one media family:

// full, differential and log are previously verified SqlServerDiskBackupResult values.
var sources = new[] {
    new SqlServerRestoreChainSource(full.ServerBackupPath, full.Header.Identity),
    new SqlServerRestoreChainSource(differential.ServerBackupPath, differential.Header.Identity),
    new SqlServerRestoreChainSource(log.ServerBackupPath, log.Header.Identity)
};
// Supply one new service-visible relocation path per logical file, as in the example above.
var chain = await sql.PrepareRestoreChainAsNewAsync(
    connectionString, sources, targetName, destinations, cancellationToken: ct);
Console.WriteLine($"Recorded file allocation: {chain.RequiredFileBytes} bytes");
await sql.RestoreChainAsNewAsync(connectionString, chain, cancellationToken: ct);
var checkedDatabase = await sql.CheckDatabaseIntegrityAsync(
    connectionString, targetName, cancellationToken: ct);
if (!checkedDatabase.Succeeded)
    throw new InvalidOperationException("CHECKDB reported integrity issues.");

The full backup comes first, followed by at most one differential and then contiguous log backups. The differential must identify its conventional full base; a copy-only full cannot serve as that base. Native log ranges may overlap the previous ending LSN, but must cover and advance it. Sequence numbers retain SQL Server's full precision. Preparation rejects changed database families, recovery forks, snapshot backups, incomplete metadata and changed file identities, including a file recreated under the same logical name.

The immutable plan pins every backup identity and relocation. Execution revalidates the chain, holds one target application lock on an owned non-pooled connection, applies each step with NORECOVERY, and issues a separate final RECOVERY. It refuses an existing target and never uses REPLACE. It does not discover or reorder backups, cross recovery forks, resume a partial restore, restore to a point in time, or cut over an application.

RequiredFiles records each file's maximum allocation across the supplied headers; RequiredFileBytes sums those allocations. Native relocation preflight checks the full backup; its success does not establish free-space availability. Independently check each destination volume and budget later growth, CHECKDB and temporary space separately; the plan reserves neither capacity nor files. Cancellation can retain a RESTORING database and server files for explicit inspection and cleanup.

Live SQL Server tests

The repository's SQL Server integration tests skip unless their variables are set. Point them only at a disposable local instance:

  • DBACLIENTX_SQLSERVER_TEST_CONNECTION: general provider tests.
  • DBACLIENTX_SQLSERVER_SESSION_LOCK_TEST_CONNECTION: an isolated test database for the locking and rollback tests.
  • DBACLIENTX_SQL_EXPORT_TEST_CONNECTION and DBACLIENTX_SQL_EXPORT_TEST_DIRECTORY: export replay tests (Category=LiveSqlExport, Windows localhost, needs sqlcmd).
  • DBACLIENTX_SQL_BACKUP_TEST_CONNECTION, DBACLIENTX_SQL_BACKUP_TEST_DIRECTORY and DBACLIENTX_SQL_BACKUP_TEST_RESTORE_DIRECTORY: backup, restore and CHECKDB tests (Category=LiveSqlRecovery). The directories must be writable by both the test process and the SQL Server service.
  • DBACLIENTX_SQL_CORRUPTION_TEST=1, DBACLIENTX_SQL_LARGE_RECOVERY_TEST=1, DBACLIENTX_SQL_WORKLOAD_TEST=1 and DBACLIENTX_SQL_POPULATED_RECOVERY_TEST=1: Windows localhost probes for page corruption (needs sysadmin), a 10 GiB allocated restore (32 GiB free), file growth and MAXSIZE limits, and a populated restore of more than 10 GiB (48 GiB free).

The tests create uniquely named databases and remove their own databases and files. Running the live database tests describes each probe.

See also

Product Compatible and additional computed target framework versions.
.NET net8.0 is compatible.  net8.0-android was computed.  net8.0-browser was computed.  net8.0-ios was computed.  net8.0-maccatalyst was computed.  net8.0-macos was computed.  net8.0-tvos was computed.  net8.0-windows was computed.  net9.0 was computed.  net9.0-android was computed.  net9.0-browser was computed.  net9.0-ios was computed.  net9.0-maccatalyst was computed.  net9.0-macos was computed.  net9.0-tvos was computed.  net9.0-windows was computed.  net10.0 is compatible.  net10.0-android was computed.  net10.0-browser was computed.  net10.0-ios was computed.  net10.0-maccatalyst was computed.  net10.0-macos was computed.  net10.0-tvos was computed.  net10.0-windows was computed. 
.NET Framework net472 is compatible.  net48 was computed.  net481 was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages (2)

Showing the top 2 NuGet packages that depend on DBAClientX.SqlServer:

Package Downloads
FabricClientX.OfficeIMO

Optional OfficeIMO tabular-artifact workflows for Microsoft Fabric and Power BI

GraphEssentialsX.Monitoring

Caller-invoked Conditional Access evaluation and DbaClientX record-store adapters. Hosting, scheduling and presentation belong to consumers.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
1.0.24 53 12/3/2026
1.0.23 105 12/1/2026
1.0.22 107 11/30/2026
1.0.21 122 11/30/2026
1.0.20 399 11/20/2026
1.0.19 120 11/16/2026
1.0.18 679 10/31/2026
1.0.17 802 10/23/2026
1.0.16 221 10/23/2026
1.0.15 506 10/15/2026
1.0.14 135 10/12/2026
1.0.13 109 10/12/2026
1.0.12 110 10/10/2026
1.0.11 115 10/10/2026
1.0.10 133 9/30/2026
1.0.9 1,183 9/21/2026
1.0.8 4,842 8/21/2026
0.16.0 131 8/20/2026
0.15.0 531 8/14/2026
0.14.0 142 8/2/2026
Loading failed