gosmo

package module
v0.0.13 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Sep 15, 2026 License: MIT Imports: 33 Imported by: 0

README

gosmo

SQLServer Management Objects Library A Go library that mimics Microsoft SQL Server Management Objects (SMO) — without WMI, COM, or Windows-only dependencies.

go get github.com/radix29/gosmo

Go version note: The module requires Go 1.27

Supported SQL Server versions

SQL Server 2016 SP1 (13.0.4001) and later, on Windows and on Linux. gosmo.MinimumServerVersion states the floor in code.

The floor is SP1 rather than 2016 RTM for one reason: CREATE OR ALTER arrived in 13.0.4001, and Database.CreateStoredProcedure emits it unconditionally (procedure.go) — the only statement gosmo builds that 2016 RTM cannot parse. Every catalog read gosmo makes would run on RTM. Supporting it means rewriting that one statement as IF EXISTS … ALTER … ELSE CREATE; that is a deliberate decision, not an oversight, and TestOnlyKnownSitesEmitCreateOrAlter fails if a second such statement appears without one.

Scripter's module scripting is not a second site: alterModuleDefinition recognises a CREATE OR ALTER that the server's own stored definition already contains and passes it through unchanged. That text is the author's, not gosmo's.

Azure SQL Managed Instance is supported and is version-gated separately. It reports a frozen ProductVersion — 12.0.2000.8, SQL Server 2014 — while running an 18.x engine that has every catalog column gosmo gates on 2016 through 2022, so ServerInfo.IsAzure() routes it past VersionMajor and into the "treat as newest" branch. Info().VersionMajor keeps the 12 the server actually said, for callers that display a version.

Columns and syntax added after the floor are gated rather than assumed, and every gate is pinned three ways — see ARCHITECTURE.md.


Quick start

import "github.com/radix29/gosmo"

srv, err := gosmo.Connect(gosmo.ConnectionOptions{
    Server:                 "localhost:1433",
    User:                   "sa",
    Password:               "YourPassword",
    TrustServerCertificate: true,
})
if err != nil { log.Fatal(err) }
defer srv.Close()

fmt.Println(srv.Info().ProductVersion)

Connect opens the pool itself. Where the pool is not gosmo's to open — one shared with the rest of an application, a driver wrapped for tracing or retries, or a fake driver in a test — gosmo.NewServer(ctx, db) wraps an existing *sql.DB and loads the same metadata. It is the inverse of srv.DB(), and ownership passes to the Server, whose Close closes the pool.


What it covers

Every object family SSMS shows, read and — where it makes sense — written:

  • Server — info, configuration, logins and server roles, permissions and the connected login's capabilities, sessions, Database Mail, linked servers, the error log, the server filesystem, memory and processor DMVs.
  • Database — files and filegroups, ALTER DATABASE options, scoped configurations, space and disk usage, change tracking, users, roles, schemas, permissions down to column scope, detach/attach, snapshots.
  • Objects — tables (with system, FileTable, external and graph tables as their own listings), columns, indexes, keys, constraints, statistics, partitions, views, procedures, functions, sequences, synonyms, triggers at all three scopes.
  • Programmability — user-defined types, XML schema collections, rules, defaults, CLR assemblies, plan guides, external data sources, file formats and libraries.
  • Backup & restore — to disk, to a logical device, or to Azure Storage, with headers, history, file lists and progress callbacks.
  • SQL Server Agent — jobs, steps, schedules, alerts, operators, categories.
  • Always On — availability groups, replicas, databases, listeners, the mirroring endpoints beneath them and the certificates that authenticate them.
  • Security — audits and audit specifications at both scopes, credentials at both scopes, endpoints, certificates, asymmetric keys, column encryption.
  • Query Store — its options and all seven report views.
  • Azure SQL Managed Instance — supported, not merely reachable: its own version gating, resource history and governance limits at instance and database scope, and backup to URL.
  • Scripting — a Scripter that generates CREATE/ALTER/DROP DDL for any of the above, and WithScript, which collects the statements a write would run instead of running them.

Every collection method has a FooSeq(ctx) iterator beside it, and every method that touches the database comes as a Foo/FooContext pair.

The full API map — nineteen Mermaid class diagrams in diagram/ under a master map, and a feature map giving gosmo's name for each SMO one — is in ARCHITECTURE.md.


Authentication

ConnectionOptions.Auth selects the method: SQL Server logins, Windows and Kerberos, and thirteen Microsoft Entra ID flows — managed identity, service principal, the Azure and Azure Developer CLI credentials, interactive, device code, on-behalf-of and Azure Pipelines OIDC among them. gosmo builds the Entra credential itself rather than leaving it to the driver, which would sign in once per physical connection; an EntraCache signs in once per identity and a whole pool shares it.

Required fields are checked before anything is dialled, and the error names the gosmo field rather than a driver parameter the caller never wrote. Each method's fields, and the Kerberos, proxy-dialer and connection-string options beside them, are in ARCHITECTURE.md.


Security

Passwords are escaped and never spliced in raw; every keyword or literal DDL cannot parameterize is validated by shape or allowlist before it reaches a statement; identifier and literal quoting goes through one implementation wrapping the driver's own. The detail is in ARCHITECTURE.md.


Documentation

Document
ARCHITECTURE.md The API map, the feature map, errors, authentication and the connection internals
diagram/ The class map — 00-map.mmd plus nineteen Mermaid class diagrams, one per group of types
RELEASE.md What changed in the current release
CHANGELOG.md The full history, from v0.0.4
examples/README.md What each runnable example covers

Packages

Path Purpose
/ All SMO types and logic
examples/ Nine runnable programs — see examples/README.md

Running the examples

export MSSQL_SERVER="localhost:1433"
export MSSQL_USER="sa"
export MSSQL_PASSWORD="YourPassword"
export MSSQL_TRUST_CERT="true"     # self-signed dev cert

go run ./examples                  # guided tour of the whole library

Eight more programs go deeper on one subject each:

Program Covers
go run ./examples/backup BACKUP/RESTORE, backup headers and history, progress callbacks, relocating files
go run ./examples/bulkcopy BulkInsert from a slice, a generator, and a streaming CSV
go run ./examples/diagnostic AsSQLError, IsRetryable, ExecProc, execution plans, search, dependencies, DMV reads
go run ./examples/iterators The *Seq API and what its deferred-fetch semantics do and don't buy you
go run ./examples/jobs SQL Server Agent jobs, steps, schedules, operators, alerts
go run ./examples/maintain Files, fragmentation, index rebuilds, statistics, Query Store, change tracking
go run ./examples/scripting The Scripter, and WithScript's collect-instead-of-execute mode
go run ./examples/security Logins, users, roles, and permissions from both directions

Each creates its own throwaway database and drops it afterwards; nothing already on the instance is modified. Authentication and the full environment variable list are documented in examples/README.md.


Features intentionally excluded (require WMI / COM / OS APIs)

  • Hardware enumeration (disk, NIC, CPU details beyond what sys.dm_os_sys_info provides)
  • SQL Server service start/stop/restart
  • Performance counters via Windows PDH
  • SQL Server Browser service interaction — enumerating instances, reading its configuration. The dual-stack Browser dialer is not an exception: it fixes how the driver's own port lookup reaches the service, and asks it nothing gosmo does not already need in order to connect.
  • Windows Event Log reading
  • Registry reads through a Windows API. xp_instance_regread, which the server itself runs, is not one — it is how Info().DefaultBackupPath is recovered on instances where SERVERPROPERTY does not report it — but nothing here opens a registry from the client side.
  • WMI and performance-condition SQL Server Agent alerts — these are listed by srv.Alerts() but not creatable or editable, since they depend on a WMI provider or Windows performance counters. Alert.IsEventAlert() and srv.EventAlerts() identify the manageable subset.
  • Multi-server Agent administration (master/target servers) — jobs are created as LOCAL, enlisted on (local)

All of the above require WMI or Windows-only APIs and are out of scope for a cross-platform Go library.


Contributing

The codebase is currently unstable and going through regular refactoring, so I'm not accepting pull requests at this time — please open an issue instead. I'll start accepting PRs once the project reaches a released, more stable state. In the near future I'm planning to update the project regularly.

Documentation

Overview

Package gosmo provides a Go library that mimics Microsoft SQL Server Management Objects (SMO). It allows you to connect to SQL Server instances and programmatically manage databases, tables, schemas, users, logins, indexes, stored procedures, and more.

Index

Constants

View Source
const (
	WeekdaySunday    = 1
	WeekdayMonday    = 2
	WeekdayTuesday   = 4
	WeekdayWednesday = 8
	WeekdayThursday  = 16
	WeekdayFriday    = 32
	WeekdaySaturday  = 64
)

Weekday bitmask values for a FreqWeekly schedule's FreqInterval.

View Source
const (
	RelativeDaySunday     = 1
	RelativeDayMonday     = 2
	RelativeDayTuesday    = 3
	RelativeDayWednesday  = 4
	RelativeDayThursday   = 5
	RelativeDayFriday     = 6
	RelativeDaySaturday   = 7
	RelativeDayDay        = 8
	RelativeDayWeekday    = 9
	RelativeDayWeekendDay = 10
)

Single-value day codes for a FreqMonthlyRelative schedule's FreqInterval. Unlike FreqWeekly's bitmask above, these are sequential (1=Sunday through 7=Saturday), not powers of two, plus three special values.

View Source
const (
	RelativeFirst  = 1
	RelativeSecond = 2
	RelativeThird  = 4
	RelativeFourth = 8
	RelativeLast   = 16
)

FreqRelativeInterval values for a FreqMonthlyRelative schedule.

View Source
const (
	AuditToFile           = "FILE"
	AuditToApplicationLog = "APPLICATION LOG"
	AuditToSecurityLog    = "SECURITY LOG"
)

Audit destinations, as sys.server_audits.type_desc records them. The T-SQL keyword differs for the two log destinations — APPLICATION LOG is written TO APPLICATION_LOG — so never build a statement out of these directly; auditDestinationKeyword does the translation.

View Source
const (
	AuditFailureContinue = "CONTINUE"
	AuditFailureShutdown = "SHUTDOWN SERVER INSTANCE"
	AuditFailureFailOp   = "FAIL OPERATION"
)

Audit on-failure actions, as sys.server_audits.on_failure_desc records them. As with the destinations, the description is not the keyword: SHUTDOWN SERVER INSTANCE is written ON_FAILURE = SHUTDOWN.

View Source
const (
	RowsFileGroup            = "ROWS_FILEGROUP"
	FileStreamFileGroup      = "FILESTREAM_DATA_FILEGROUP"
	MemoryOptimizedFileGroup = "MEMORY_OPTIMIZED_DATA_FILEGROUP"
)

Filegroup type_desc values, as sys.filegroups reports them.

View Source
const AuditUnlimited = 2147483647

AuditUnlimited is what sys.server_file_audits stores for MAX_ROLLOVER_FILES = UNLIMITED, which is also the default. MaxFileSize uses 0 for UNLIMITED instead; the two columns do not agree on a sentinel, and this is the one place that difference is written down.

View Source
const MinimumServerVersion = SQLServer2016

MinimumServerVersion is the oldest instance gosmo supports: SQL Server 2016 SP1 (13.0.4001), the build that introduced CREATE OR ALTER.

Exactly one statement gosmo builds needs SP1 — Database.CreateStoredProcedureContext's CREATE OR ALTER PROCEDURE (procedure.go). Every catalog read would run on 2016 RTM, so this one statement is the whole of the gap; supporting RTM means rewriting it as IF EXISTS ... ALTER ... ELSE CREATE, which is a decision to take rather than an oversight to fix. TestOnlyKnownSitesEmitCreateOrAlter fails if a second such statement appears without one.

scripter.go is not a second site, though it names the keywords: alterModuleDefinition recognises a CREATE OR ALTER the server's own stored definition already contains and returns it unchanged.

View Source
const QSDefaultTop = 25

QSDefaultTop is how many rows a report returns when Options.Top is zero.

Variables

View Source
var ErrNotFound = errors.New("not found")

ErrNotFound is the sentinel every by-name lookup that reports absence as an error wraps, so a caller can tell "this object does not exist" from "the lookup itself failed" with errors.Is(err, gosmo.ErrNotFound) instead of matching on message text.

Making that distinction matters: a caller that treats any error as absence will go on to create an object it never established was missing, and report the creation's failure instead of the permission or connection error that actually stopped it.

Three not-found conventions exist across the package, and the difference is deliberate rather than an oversight:

  • Most by-name lookups — LoginByName, DatabaseByName, TableByName, UserByName, RoleByName, AgentJobByName, AlertByName, OperatorByName, ScheduleByName, ServerRoleByName, ConfigurationByName, AvailabilityGroupByName and the scripter's view/procedure/function lookups — return an error wrapping ErrNotFound.
  • CertificateByName returns (nil, nil), because its callers branch on absence as the ordinary case rather than the exceptional one.
  • AgentStatus reports an unreachable Agent as a populated value (StatusText "Unknown"), not an error.

AvailabilityGroupByName's not-found error additionally still satisfies errors.Is(err, sql.ErrNoRows), which it promised before ErrNotFound existed.

View Source
var ErrSystemEndpoint = errors.New("endpoint is a built-in system endpoint")

ErrSystemEndpoint is returned by Endpoint.SetState and Endpoint.Drop for one of the built-in endpoints (endpoint_id < 65536): the Dedicated Admin Connection, TSQL Local Machine, TSQL Named Pipes, TSQL Default TCP and TSQL Default VIA. SQL Server refuses those writes with a message that names neither the endpoint nor the reason, so the refusal happens here instead, where a caller can present it.

View Source
var ErrUnsupportedVersion = errors.New("unsupported server version")

ErrUnsupportedVersion reports a call gosmo refused because the connected instance is older than the feature it names — a refusal decided here, before any statement is sent, because the server's own answer would be a parse error naming syntax the caller never wrote.

Every such refusal wraps it, so a caller (or a sweep across an old instance) can tell "this server is too old for this feature" from "this read is broken". The message text is unchanged by the sentinel.

View Source
var ProbedAvailabilityGroupPermissions = []string{
	"ALTER",
}

ProbedAvailabilityGroupPermissions are the AVAILABILITY GROUP-scope (class 108) permissions Capabilities probes, once per availability group on the instance.

This scope is asked with HAS_PERMS_BY_NAME and not read out of the catalog, which is the opposite of every other explicit-permission block here, and the reason is that the catalog cannot answer: class 108's major_id is an internal availability-group id that **no supported view maps back to a name** — sys.availability_groups exposes only the group_id GUID, and the internal table behind it exposes nothing more. A catalog read at this class produces rows nothing can be matched to.

HAS_PERMS_BY_NAME can be asked per group because there are single digits of them, where there are hundreds of logins, and it answers the question this scope actually needs: a login holding the server-wide ALTER ANY AVAILABILITY GROUP reads 1 on each group and 0 on one carrying DENY ALTER — verified live on the two-node cluster, 2026-09-05. That is the distinction sys.server_permissions had to be read for at class 101, and here the probe makes it directly.

View Source
var ProbedDatabasePermissions = []string{
	"CONTROL",
	"ALTER",
	"VIEW DEFINITION",
	"VIEW DATABASE STATE",
	"BACKUP DATABASE",
	"BACKUP LOG",
	"CREATE TABLE",
	"CREATE VIEW",
	"CREATE PROCEDURE",
	"CREATE FUNCTION",
	"CREATE SCHEMA",
	"ALTER ANY USER",
	"ALTER ANY ROLE",
	"ALTER ANY SCHEMA",
	"ALTER ANY DATASPACE",
	"ALTER ANY COLUMN MASTER KEY",
	"ALTER ANY COLUMN ENCRYPTION KEY",
	"ALTER ANY SECURITY POLICY",
	"ALTER ANY DATABASE AUDIT",
	"ALTER ANY DATABASE DDL TRIGGER",
	"ALTER ANY ASSEMBLY",
	"ALTER ANY EXTERNAL DATA SOURCE",
	"ALTER ANY EXTERNAL FILE FORMAT",

	"ALTER ANY EXTERNAL LIBRARY",
	"SELECT",
	"INSERT",
	"UPDATE",
	"DELETE",
	"EXECUTE",
	"SHOWPLAN",
}

ProbedDatabasePermissions are the database-scope permissions DatabaseCapabilities probes — again a working subset, not the grantable catalog DatabasePermissionNames returns.

These are checked against the DATABASE securable class, not the server: HAS_PERMS_BY_NAME(NULL, NULL, 'ALTER') asks about the *server* and answers NULL, which is how a database-scope name mistakenly probed at server scope disappears without an error.

View Source
var ProbedDatabaseRoles = []string{
	"db_owner",
	"db_securityadmin",
	"db_accessadmin",
	"db_backupoperator",
	"db_ddladmin",
	"db_datawriter",
	"db_datareader",
	"db_denydatawriter",
	"db_denydatareader",
	"SQLAgentUserRole",
	"SQLAgentReaderRole",
	"SQLAgentOperatorRole",
}

ProbedDatabaseRoles are the fixed database roles DatabaseCapabilities probes.

The three SQLAgent* roles exist only in msdb; elsewhere IS_ROLEMEMBER returns NULL for them and they read as false. They are probed for every database rather than only msdb because doing so costs nothing and keeps one code path.

View Source
var ProbedObjectPermissions = []string{
	"ALTER",
}

ProbedObjectPermissions are the OBJECT-scope permissions DatabaseCapabilities probes, for every object the login has been granted one on or owns outright.

This block is read out of the catalog rather than asked with HAS_PERMS_BY_NAME, which answers for one securable per call and so would cost a query per object. The consequence is that it reports only what is *explicit*: an object carrying no grant and no distinct owner has no row at all, which is why the answer is additive — see HasOnObject.

Each name is probed at column scope as well, into ColumnPermissions. Only a column-grantable permission can produce a row there — ALTER and CONTROL are not among them — so the block is empty for this list as it stands, and correct the moment SELECT, UPDATE or REFERENCES joins it.

View Source
var ProbedPrincipalPermissions = []string{
	"ALTER",
}

ProbedPrincipalPermissions are the DATABASE_PRINCIPAL-scope (class 4) permissions DatabaseCapabilities probes, for every user or database role the login has one explicitly recorded on.

Only the DENY direction is worth reading here, and that is a fact about SQL Server rather than a choice — verified live on majors 13, 14 and 17 (2026-09-04, identical on all three):

  • GRANT ALTER ON USER::x answers HAS_PERMS_BY_NAME 1 on the user and still permits nothing: both ALTER USER ... WITH NAME and DROP USER are refused. Those statements require ALTER ANY USER at database scope, so unlike an object- or schema-scope grant there is no narrow grant for a wider map to miss.
  • DENY ALTER ON USER::x *does* withhold both, over a database-wide ALTER ANY USER, so only the catalog can say what a gate needs to know.

One name is enough for the same reason it is at schema scope, and CONTROL is matched alongside it in the query: DENY CONTROL ON USER::x withholds the same two statements and is recorded under its own permission_name.

View Source
var ProbedSchemaPermissions = []string{
	"ALTER",
}

ProbedSchemaPermissions are the SCHEMA-scope permissions DatabaseCapabilities probes, once per schema in the database.

One name is enough: HAS_PERMS_BY_NAME folds in the permissions that imply the one it is asked about, so a principal holding CONTROL on the schema, or ALTER ANY SCHEMA, or db_owner, answers 1 for ALTER without any of them being asked separately.

View Source
var ProbedSecurablePermissions = []string{
	"CONTROL",
}

ProbedSecurablePermissions are the permissions DatabaseCapabilities probes on every assembly (class 5), user-defined type (class 6) and XML schema collection (class 10) in the database, once per securable.

This block is asked with HAS_PERMS_BY_NAME, as class 108 is, rather than read out of the catalog, and the answer it gives is the one no catalog row can: the *effective* permission, folding in ownership of the securable, ownership of or CONTROL on its schema, and CONTROL on the database. These families hold a handful of rows each, so one call per securable costs little.

CONTROL is the one name worth asking, and what it answers was probed live on majors 13, 14 and 17 (2026-09-11, identical on all three) with a WITHOUT LOGIN user per case:

  • ALTER SCHEMA ... TRANSFER of a type or a collection goes through exactly when CONTROL reads 1 — under CONTROL on the securable, its ownership, CONTROL on or ownership of the source schema, or CONTROL on the database. ALTER on the database, ALTER ANY SCHEMA, db_ddladmin and ALTER on the source schema all read 0 and are all refused (Msg 15151), with ALTER on the target schema held throughout.
  • DROP goes through when CONTROL reads 1, *and* under the wider rights that read 0 here: ALTER ANY ASSEMBLY for an assembly, ALTER on the schema for a type or a collection, ALTER on the database for all three. So for a drop this is an additional reason to permit, never the whole test.
  • ALTER is not worth asking. GRANT ALTER on the securable alone reads 1 for ALTER and permits neither statement, and DENY ALTER reads 0 while the drop goes through.

There is no catalog block for the DENY direction, and that is SQL Server's doing rather than an omission: DENY CONTROL on any of the three — to the user or to public — withholds VIEW DEFINITION with it, and the securable disappears from sys.assemblies, sys.types and sys.xml_schema_collections for that principal (verified on the same three majors). A listing built from those views never shows it, so there is nothing for a gate to withhold.

View Source
var ProbedServerPermissions = []string{
	"CONTROL SERVER",
	"ALTER SETTINGS",
	"SHUTDOWN",
	"ALTER TRACE",
	"ADMINISTER BULK OPERATIONS",
	"VIEW ANY DATABASE",
	"VIEW ANY DEFINITION",
	"VIEW SERVER STATE",
	"VIEW SERVER PERFORMANCE STATE",
	"VIEW SERVER SECURITY STATE",
	"CREATE ANY DATABASE",
	"ALTER ANY DATABASE",
	"ALTER ANY LOGIN",
	"ALTER ANY SERVER ROLE",
	"ALTER ANY CONNECTION",
	"ALTER ANY CREDENTIAL",
	"ALTER ANY SERVER AUDIT",
	"ALTER ANY ENDPOINT",
	"ALTER ANY LINKED SERVER",
	"ALTER ANY EVENT SESSION",
	"ALTER ANY AVAILABILITY GROUP",
}

ProbedServerPermissions are the server-scope permissions Capabilities probes: the handful the application layer gates on, not the whole grantable catalog ServerPermissionNames returns. Every name here was checked against a live instance; a name with a typo would report CapabilityUnknown forever rather than failing.

VIEW SERVER PERFORMANCE STATE and VIEW SERVER SECURITY STATE are the two narrower rights SQL Server 2022 split VIEW SERVER STATE into, and are what a modern instance names in its denial. All three are probed because holding the wide one grants both narrow ones, but not the reverse.

View Source
var ProbedServerRoles = []string{
	"sysadmin",
	"serveradmin",
	"securityadmin",
	"processadmin",
	"setupadmin",
	"bulkadmin",
	"diskadmin",
	"dbcreator",
	"public",
}

ProbedServerRoles are the fixed server roles Capabilities probes.

Membership in sysadmin does not imply membership in any other role, so a caller testing for a role must test for sysadmin too — see Capabilities.InServerRole.

View Source
var ProbedServerSecurablePermissions = []string{
	"ALTER",
}

ProbedServerSecurablePermissions are the permissions Capabilities reads explicit server-scope DENY rows for, once per securable the login has one recorded on: SERVER_PRINCIPAL (class 101 — logins and server roles alike) and ENDPOINT (class 105).

One name is enough for the reason it is at schema and class-4 scope: CONTROL is matched alongside it in the query, and nothing narrower than ALTER is what these gates ask about.

Only the DENY direction is read, and that is a fact about SQL Server rather than a choice — probed live on majors 13 and 17 (2026-09-04, identical on both). HAS_PERMS_BY_NAME cannot answer here at all: it reads 0 for a denied ALTER *and* for one never granted, which is the ordinary state of a login working through the server-wide ALTER ANY LOGIN, so only the catalog can say a DENY row exists. See Capabilities.ExplicitServerPermissions for what each class's DENY actually withholds — the two do not agree, and a caller that treats them alike is wrong about one of them.

Functions

func BuildBackupStatement added in v0.0.4

func BuildBackupStatement(opts BackupOptions) (string, error)

BuildBackupStatement returns the T-SQL BACKUP statement opts describes, without executing it — for callers that want to show or hand off the script (e.g. an editor pane) rather than run it immediately. BackupContext validates and builds the statement the same way, then runs what this returns.

func BuildRestoreStatement added in v0.0.5

func BuildRestoreStatement(opts RestoreOptions) (string, error)

BuildRestoreStatement returns the T-SQL RESTORE statement opts describes, without executing it — the RESTORE counterpart of BuildBackupStatement. RestoreContext validates and builds the statement the same way, then runs what this returns.

The statement is laid out over several lines — the target, the devices, then one WITH option per line — because a restore that relocates files carries a MOVE clause per database file, each holding two full paths. On one line that runs to several hundred columns, and a caller scripting it for review (goSSMS's Restore dialog does) sees the RESTORE with every MOVE off the right edge of the editor, which reads as the MOVE clauses being missing entirely. Whitespace is not significant to SQL Server here, so the executed statement is unchanged.

func ColumnKey added in v0.0.11

func ColumnKey(schema, object, column string) string

ColumnKey is the key ColumnPermissions is indexed by: the schema, object and column joined with dots, unquoted, exactly as the probe records them.

func ColumnPermissionNames added in v0.0.8

func ColumnPermissionNames() []string

ColumnPermissionNames returns every permission name GRANT/DENY/REVOKE accepts on a column, sorted — the catalog a column-permissions grid enumerates, the way ObjectPermissionNames is the catalog for the whole object.

func ColumnTypeString added in v0.0.5

func ColumnTypeString(col *Column) string

ColumnTypeString returns the T-SQL data-type fragment for a Column read from sys.columns.

func DatabasePermissionNames added in v0.0.5

func DatabasePermissionNames() []string

DatabasePermissionNames returns every database-scoped permission name GRANT/DENY/REVOKE accepts, sorted — see ServerPermissionNames for what it's used for.

func DatabaseSecurableKey added in v0.0.13

func DatabaseSecurableKey(kind DatabaseSecurableKind, schema, name string) string

DatabaseSecurableKey is the key SecurablePermissions is indexed by: the kind and the securable joined with "::", the securable being "schema.name" for a type or a collection and the bare name for an assembly, whose schema is "".

The kind is part of the key for ServerSecurableKey's reason: types and XML schema collections live in separate namespaces, so dbo.x can be both, and the two answers must not be reachable through each other.

func IsBackupURL added in v0.0.12

func IsBackupURL(device string) bool

IsBackupURL reports whether device names a backup blob in Azure Storage rather than a path on the server's filesystem — an http:// or https:// URL.

The distinction decides the device keyword: a blob is BACKUP ... TO URL / RESTORE ... FROM URL, and a filesystem path is TO DISK / FROM DISK. It is not cosmetic on Azure SQL Managed Instance, which answers any TO DISK or FROM DISK with

Msg 41902 ... SQL Database Managed Instance supports database restore
from URI backup device only.

and whose SERVERPROPERTY('InstanceDefaultBackupPath') is itself a blob container URL, so a caller that builds a default destination out of it arrives here holding a URL without ever having decided to.

The test is the scheme alone. A UNC path (\\host\share\db.bak) and a drive-letter path are both DISK devices, and neither has one.

func IsRetryable added in v0.0.4

func IsRetryable(err error) bool

IsRetryable reports whether err represents a transient failure worth retrying — the driver's RetryableError; a dropped pooled connection (driver.ErrBadConn), including when wrapped; or one of the raw connection-level failures the driver itself uses to flag a connection dead (see mssql.Conn.checkBadConn): a network error, a corrupted TDS byte stream (mssql.StreamError), a fatal server-side error that severs the connection (mssql.ServerError), or io.EOF. Those last few surface unwrapped rather than as RetryableError whenever the driver decided retrying the exact in-flight call wasn't safe (its own mayRetry=false) — that restriction is about automatically retrying the *same* call, not about whether the connection itself is salvageable, so a caller retrying its own idempotent operation on a fresh connection is still safe to do so. It is exported so callers that run their own statements (e.g. an ad-hoc query runner) can decide whether a failure is worth another attempt; note that only idempotent operations are safe to retry blindly.

A context error is never retryable. context.DeadlineExceeded has to be rejected explicitly because it implements net.Error, so the net.Error test below would otherwise report a caller's own expired deadline as a transient failure and have them wait out three attempts on a deadline that has already passed. context.Canceled fails that test anyway and is named alongside it so the two can't drift apart.

func ObjectKey added in v0.0.11

func ObjectKey(schema, object string) string

ObjectKey is the key ObjectPermissions is indexed by: the schema and object name joined with a dot, unquoted, exactly as the probe records them.

func ObjectPermissionNames added in v0.0.5

func ObjectPermissionNames() []string

ObjectPermissionNames returns every object-scoped permission name GRANT/DENY/REVOKE accepts on a table or view, sorted — see ServerPermissionNames for what it's used for.

func ParseServerAddress added in v0.0.4

func ParseServerAddress(server string) (host, instance string, port int)

ParseServerAddress splits a user-supplied server address into its host, named-instance, and port components, accepting every form SSMS itself accepts in its "Server name" field:

host                    host:port                host,port
host\instance           host\instance,port

An IPv6 literal is accepted bare (fe80::1), bracketed ([fe80::1]), or with a port as [fe80::1]:1433 or fe80::1,1433. A colon is read as a port separator only when what precedes it is a host that can carry one — a name, an IPv4 address or a bracketed literal — so the last group of a bare literal is never mistaken for a port ("2001:db8::5" is a host, not "2001:db8:" on port 5). A bracketed host is returned with its brackets.

Exported so callers (e.g. a UI layer building its own address/DSN preview, or resolving a separate "port" field against a Server string that may already carry its own) can reuse the same parsing buildDSN relies on, instead of duplicating it.

A malformed trailing port (non-numeric) is left as part of host rather than rejected outright — the caller surfaces connection failures via the driver's own error, not a separate parse error here.

func QuoteLiteral added in v0.0.4

func QuoteLiteral(s string) string

QuoteLiteral renders s as a T-SQL string literal, including the surrounding single quotes and doubling any embedded quote — safe to embed in SQL text where a parameter placeholder is not accepted (DDL, dynamic SQL). Prefer a query parameter for ordinary values.

Use QuoteLiteral where the whole literal is being produced. Where the quotes are already part of a format string — the common shape in this package, e.g. "@name = N'%s'" — use the unexported escapeSingle (helpers.go) instead, which escapes without adding quotes of its own. QuoteLiteral also does not emit the N prefix.

Neither one quotes an *identifier*. An identifier that ends up inside a string literal — the argument to OBJECT_ID, DBCC SHOW_STATISTICS, fn_listextendedproperty, and similar — needs QuoteName/qualifiedName applied first and escapeSingle on top of that:

escapeSingle(qualifiedName(schema, name))  // -> [dbo].[Sales.Archive]
escapeSingle(t.FullName())                 // same, for a *Table

Skipping the bracket-quoting is not cosmetic. A name containing '.' then parses as a multi-part name and resolves to the wrong object or to NULL, and a NULL object_id means "every object in the database" to sys.dm_db_index_physical_stats — so the wrong form returns plausible stats for the wrong tables instead of failing. See identifier_quoting_test.go, which pins all of this.

func QuoteName added in v0.0.4

func QuoteName(name string) string

QuoteName wraps a SQL Server identifier (schema, table, column, ...) in square brackets, doubling any embedded closing bracket — the equivalent of T-SQL's QUOTENAME(). Use it to build object names safely; note it quotes the whole string as one identifier, so pass each part of a multi-part name separately.

func SchemaPermissionNames added in v0.0.5

func SchemaPermissionNames() []string

SchemaPermissionNames returns every schema-scoped permission name GRANT/DENY/REVOKE accepts ON SCHEMA::x, sorted — see ObjectPermissionNames for what it's used for.

func Scripting added in v0.0.7

func Scripting(ctx context.Context) bool

Scripting reports whether ctx came from WithScript — that is, whether write methods invoked with it record their statement instead of running it.

A caller that mirrors a write into its own state needs to know: under WithScript a write returns success without the server ever seeing it, so state derived from "it worked" is wrong. The case this exists for is a rename — an editor that renames an object and then re-reads it by the new name finds nothing, because the old name is still what the server has. Reads are unaffected by WithScript and go to the real server either way.

func ServerPermissionNames added in v0.0.5

func ServerPermissionNames() []string

ServerPermissionNames returns every server-scoped permission name GRANT/DENY/REVOKE accepts, sorted — the catalog SSMS's Server Properties > Permissions page enumerates for a principal regardless of whether it already has an explicit GRANT/DENY entry.

func ServerSecurableKey added in v0.0.12

func ServerSecurableKey(kind ServerSecurableKind, name string) string

ServerSecurableKey is the key ExplicitServerPermissions is indexed by: the securable kind and its name joined with "::", exactly as the probe records them and as the DENY statement spells them.

The kind is part of the key rather than a separate map because the answer differs by kind — a class-101 DENY withholds everything on a login and only membership edits on a server role — and a caller must not be able to reach one kind's answer while asking about another's.

func SliceRows added in v0.0.4

func SliceRows(rows [][]any) iter.Seq2[[]any, error]

SliceRows adapts an in-memory slice of rows to the sequence BulkInsert consumes, for callers that already hold every row in memory.

Types

type ActiveSession

type ActiveSession struct {
	SessionID         int
	LoginName         string
	HostName          string
	ProgramName       string
	DatabaseName      string
	Status            string
	CPUTime           int64
	MemoryUsage       int64
	TotalElapsedMS    int64
	LastRequestStart  string
	CommandText       string
	BlockingSessionID int
	WaitType          string
	WaitTimeMS        int64
}

ActiveSession holds information about one session from sys.dm_exec_sessions.

type AgentStatus added in v0.0.6

type AgentStatus struct {
	Running    bool
	StatusText string
	// LastStartupTime is the zero Time if the DMV has no matching row (the
	// Agent service isn't registered under this instance, or the DMV isn't
	// queryable in this edition/deployment).
	LastStartupTime time.Time
}

AgentStatus reports whether SQL Server Agent is currently running, based only on SQL-visible state (sys.dm_server_services, or the Agent's own sessions on Azure) — no Windows Service Control, WMI, or registry access, matching the SQL-only scope of the rest of this file.

type Alert added in v0.0.6

type Alert struct {
	ID      int
	Name    string
	Enabled bool
	// EventSource is "MSSQLSERVER" for a plain SQL Server event alert, or
	// "WMI" for a WMI alert — see IsEventAlert.
	EventSource string
	// ErrorNumber is sysalerts.message_id — mutually exclusive in practice
	// with Severity (SQL Server Agent triggers on whichever is nonzero).
	ErrorNumber           int
	Severity              int
	DatabaseName          string
	DelayBetweenResponses time.Duration
	NotificationMessage   string
	// IncludeEventDescriptionIn is sysalerts.include_event_description —
	// msdb's own bitmask for which notification channel(s) get the event
	// description text appended (0=None, 1=Email, 2=Pager, 4=NetSend,
	// 7=All). Named "...In" after sp_add_alert/sp_update_alert's
	// @include_event_description_in parameter; the column itself has no
	// "_in" suffix, the two names genuinely diverge.
	IncludeEventDescriptionIn int
	EventDescriptionKeyword   string
	Category                  string
	// JobName is the job executed in response to this alert, or "" if none.
	JobName              string
	PerformanceCondition string
	OccurrenceCount      int
	LastOccurrence       time.Time
	LastResponse         time.Time
	// contains filtered or unexported fields
}

Alert represents a SQL Server Agent alert (msdb.dbo.sysalerts).

func (*Alert) Disable added in v0.0.6

func (a *Alert) Disable() error

Disable disables the alert.

func (*Alert) DisableContext added in v0.0.6

func (a *Alert) DisableContext(ctx context.Context) error

DisableContext is the context-aware variant of Disable.

func (*Alert) Drop added in v0.0.6

func (a *Alert) Drop() error

Drop deletes the alert via sp_delete_alert.

func (*Alert) DropContext added in v0.0.6

func (a *Alert) DropContext(ctx context.Context) error

DropContext is the context-aware variant of Drop.

func (*Alert) Enable added in v0.0.6

func (a *Alert) Enable() error

Enable enables the alert.

func (*Alert) EnableContext added in v0.0.6

func (a *Alert) EnableContext(ctx context.Context) error

EnableContext is the context-aware variant of Enable.

func (*Alert) IsEventAlert added in v0.0.6

func (a *Alert) IsEventAlert() bool

IsEventAlert reports whether this is a plain SQL Server event alert (an error-number-or-severity trigger) rather than a WMI alert or a performance-condition alert — the SQL-only-implementable subset of SQL Server Agent alerts (no WMI provider, no performance counter access). See Server.EventAlerts. Only EventSource and PerformanceCondition are checked — sysalerts.wmi_query/wmi_namespace, WMI's own supplementary columns, don't exist on every build (they're absent on SQL Server on Linux, where WMI doesn't apply at all), so gosmo doesn't select them; event_source = 'WMI' is the reliable, always-present discriminator SQL Server itself sets for a WMI alert.

func (*Alert) NotificationSeq added in v0.0.6

func (a *Alert) NotificationSeq(ctx context.Context) iter.Seq2[*AlertNotification, error]

NotificationSeq returns an iterator over every operator notified by this alert.

func (*Alert) Notifications added in v0.0.6

func (a *Alert) Notifications() ([]*AlertNotification, error)

Notifications returns every operator notified by this alert.

func (*Alert) NotificationsContext added in v0.0.6

func (a *Alert) NotificationsContext(ctx context.Context) ([]*AlertNotification, error)

NotificationsContext is the context-aware variant of Notifications.

func (*Alert) Notify added in v0.0.6

func (a *Alert) Notify(operatorName string, method NotificationMethod) error

Notify configures the alert to notify an operator via sp_add_notification.

func (*Alert) NotifyContext added in v0.0.6

func (a *Alert) NotifyContext(ctx context.Context, operatorName string, method NotificationMethod) error

NotifyContext is the context-aware variant of Notify.

func (*Alert) RemoveNotify added in v0.0.6

func (a *Alert) RemoveNotify(operatorName string) error

RemoveNotify removes an operator's notification link from the alert.

func (*Alert) RemoveNotifyContext added in v0.0.6

func (a *Alert) RemoveNotifyContext(ctx context.Context, operatorName string) error

RemoveNotifyContext is the context-aware variant of RemoveNotify.

func (*Alert) Rename added in v0.0.6

func (a *Alert) Rename(newName string) error

Rename changes the alert's name.

func (*Alert) RenameContext added in v0.0.6

func (a *Alert) RenameContext(ctx context.Context, newName string) error

RenameContext is the context-aware variant of Rename.

func (*Alert) SetCategory added in v0.0.6

func (a *Alert) SetCategory(category string) error

SetCategory reassigns the alert's category. category == "" clears it — sent as the real [Uncategorized] category, since sp_update_alert rejects an empty name outright ("The specified @category_name (”) does not exist") and [Uncategorized] is what an alert created with no category actually holds in msdb.dbo.syscategories.

func (*Alert) SetCategoryContext added in v0.0.6

func (a *Alert) SetCategoryContext(ctx context.Context, category string) error

SetCategoryContext is the context-aware variant of SetCategory.

func (*Alert) SetDatabase added in v0.0.6

func (a *Alert) SetDatabase(dbName string) error

SetDatabase scopes the alert to a single database, or "" for all databases.

func (*Alert) SetDatabaseContext added in v0.0.6

func (a *Alert) SetDatabaseContext(ctx context.Context, dbName string) error

SetDatabaseContext is the context-aware variant of SetDatabase.

func (*Alert) SetDelay added in v0.0.6

func (a *Alert) SetDelay(d time.Duration) error

SetDelay sets the minimum delay between repeated responses to the alert.

func (*Alert) SetDelayContext added in v0.0.6

func (a *Alert) SetDelayContext(ctx context.Context, d time.Duration) error

SetDelayContext is the context-aware variant of SetDelay.

func (*Alert) SetJobResponse added in v0.0.6

func (a *Alert) SetJobResponse(jobName string) error

SetJobResponse sets the job executed in response to this alert, or "" to clear it.

func (*Alert) SetJobResponseContext added in v0.0.6

func (a *Alert) SetJobResponseContext(ctx context.Context, jobName string) error

SetJobResponseContext is the context-aware variant of SetJobResponse.

func (*Alert) SetNotificationMessage added in v0.0.6

func (a *Alert) SetNotificationMessage(msg string) error

SetNotificationMessage sets the extra text appended to the alert's notification.

func (*Alert) SetNotificationMessageContext added in v0.0.6

func (a *Alert) SetNotificationMessageContext(ctx context.Context, msg string) error

SetNotificationMessageContext is the context-aware variant of SetNotificationMessage.

func (*Alert) SetTrigger added in v0.0.6

func (a *Alert) SetTrigger(errorNumber, severity int) error

SetTrigger sets what raises the alert: a specific SQL Server error number, or a severity level. SQL Server treats these as mutually exclusive — pass 0 for whichever one isn't in use.

func (*Alert) SetTriggerContext added in v0.0.6

func (a *Alert) SetTriggerContext(ctx context.Context, errorNumber, severity int) error

SetTriggerContext is the context-aware variant of SetTrigger.

type AlertNotification added in v0.0.6

type AlertNotification struct {
	OperatorName string
	Method       NotificationMethod
}

AlertNotification describes one operator notified by an alert.

type AlertNotificationRef added in v0.0.6

type AlertNotificationRef struct {
	AlertName string
	Method    NotificationMethod
}

AlertNotificationRef describes one alert configured to notify an operator.

type Assembly added in v0.0.13

type Assembly struct {
	Name       string
	AssemblyID int

	// Owner is the database principal that owns the assembly, empty when
	// principal_id is NULL or names a principal that no longer exists.
	Owner string

	// ClrName is the full .NET strong name — "name, version=…, culture=…,
	// publickeytoken=…, processorarchitecture=…". Empty on an assembly the
	// server could not read one from, and on one the caller lacks VIEW
	// DEFINITION on.
	ClrName string

	// PermissionSet is the host policy, as permission_set_desc reports it.
	PermissionSet AssemblyPermissionSet

	// IsVisible reports whether the assembly's routines can be bound to by
	// CREATE PROCEDURE/FUNCTION/TYPE. A referenced-only dependency is
	// registered with is_visible = 0.
	IsVisible bool

	// IsUserDefined is 0 on the assemblies SQL Server ships (Microsoft.
	// SqlServer.Types and friends), which are present in every database.
	IsUserDefined bool

	CreateDate time.Time
	ModifyDate time.Time
	// contains filtered or unexported fields
}

Assembly mirrors a sys.assemblies row.

func (*Assembly) Database added in v0.0.13

func (a *Assembly) Database() *Database

Database returns the database the assembly belongs to.

func (*Assembly) Drop added in v0.0.13

func (a *Assembly) Drop() error

Drop drops the assembly.

func (*Assembly) DropContext added in v0.0.13

func (a *Assembly) DropContext(ctx context.Context) error

DropContext is the context-aware variant of Drop.

func (*Assembly) FileContent added in v0.0.13

func (a *Assembly) FileContent(fileID int) ([]byte, error)

FileContent returns the bytes of one of the assembly's files. fileID 1 is the assembly binary.

func (*Assembly) FileContentContext added in v0.0.13

func (a *Assembly) FileContentContext(ctx context.Context, fileID int) ([]byte, error)

FileContentContext is the context-aware variant of FileContent.

func (*Assembly) Files added in v0.0.13

func (a *Assembly) Files() ([]*AssemblyFile, error)

Files returns the files registered with the assembly, without their contents.

func (*Assembly) FilesContext added in v0.0.13

func (a *Assembly) FilesContext(ctx context.Context) ([]*AssemblyFile, error)

FilesContext is the context-aware variant of Files.

func (*Assembly) Modules added in v0.0.13

func (a *Assembly) Modules() ([]*AssemblyModule, error)

Modules returns the CLR routines bound to the assembly.

func (*Assembly) ModulesContext added in v0.0.13

func (a *Assembly) ModulesContext(ctx context.Context) ([]*AssemblyModule, error)

ModulesContext is the context-aware variant of Modules.

assembly_method is NULL for a CLR aggregate, which has a class and no single entry point, so it comes back as the empty string rather than failing the scan.

type AssemblyFile added in v0.0.13

type AssemblyFile struct {
	Name string

	// FileID is the file's id within the assembly. 1 is the assembly binary
	// itself.
	FileID int

	// ContentLength is the payload size in bytes, from DATALENGTH.
	ContentLength int64
}

AssemblyFile is one file registered with an assembly — the assembly's own DLL (file_id 1) plus any debug symbols or source files added with ALTER ASSEMBLY … ADD FILE.

Content is deliberately not a field: an assembly binary runs to megabytes, and a listing that carried every payload would make reading the *names* cost the whole set. Fetch one with Assembly.FileContent.

type AssemblyModule added in v0.0.13

type AssemblyModule struct {
	ObjectID int
	Schema   string
	Name     string

	// Type is the sys.objects type code, trimmed: "P" for a CLR procedure,
	// "FS"/"FT" for a scalar or table-valued function, "TA" for a trigger,
	// "AF" for an aggregate.
	Type string

	AssemblyClass  string
	AssemblyMethod string
}

AssemblyModule is one T-SQL object bound to an assembly — a CLR stored procedure, function, trigger or aggregate, and the .NET class and method it runs.

func (*AssemblyModule) FullName added in v0.0.13

func (m *AssemblyModule) FullName() string

FullName returns the schema-qualified, bracket-quoted name.

type AssemblyPermissionSet added in v0.0.13

type AssemblyPermissionSet string

AssemblyPermissionSet is the CLR host policy an assembly runs under.

const (
	AssemblySafe           AssemblyPermissionSet = "SAFE"
	AssemblyExternalAccess AssemblyPermissionSet = "EXTERNAL_ACCESS"
	AssemblyUnsafe         AssemblyPermissionSet = "UNSAFE"
)

The three permission sets CREATE ASSEMBLY accepts. UNSAFE and EXTERNAL_ACCESS additionally require the database to be trustworthy or the assembly to be signed.

type AsymmetricKey added in v0.0.11

type AsymmetricKey struct {
	Name        string
	KeyID       int
	PrincipalID int

	// Algorithm is the key algorithm's description — "RSA_2048" and the like.
	Algorithm string

	// KeyLength is the key length in bits.
	KeyLength int

	// PvtKeyEncryptionType is how the private key is protected —
	// "ENCRYPTED_BY_MASTER_KEY", "ENCRYPTED_BY_PASSWORD", or "NO_PRIVATE_KEY"
	// for a key imported from its public half alone.
	PvtKeyEncryptionType string

	// Thumbprint is the SHA-1 hash of the public key.
	Thumbprint []byte
	// contains filtered or unexported fields
}

AsymmetricKey mirrors a row of sys.asymmetric_keys.

func (*AsymmetricKey) HasPrivateKey added in v0.0.11

func (k *AsymmetricKey) HasPrivateKey() bool

HasPrivateKey reports whether this instance holds the key's private half, i.e. can sign with it rather than only verify against it.

type AttachSpec added in v0.0.11

type AttachSpec struct {
	// Name is what the database is attached as. It need not be the name it
	// was detached under — DetachedDatabase.Name reports that one.
	Name string

	// Files are the physical paths of the database's files on the server's
	// own filesystem, primary data file first. Every file must be listed:
	// SQL Server only finds the others by itself when they sit at the paths
	// recorded inside the primary file, which is exactly what stops being
	// true the moment a database is moved — the case Attach exists for.
	Files []string

	// Owner, if set, is the principal the attached database's ownership is
	// transferred to. Left empty, the database is owned by the login that
	// attached it, which is what CREATE DATABASE ... FOR ATTACH does on its
	// own.
	Owner string

	// RebuildLog attaches without a log file and builds a new one
	// (FOR ATTACH_REBUILD_LOG). It is for a database whose log was lost or
	// deliberately not copied, and it is not free: an unclean database
	// cannot be recovered without its log, so the attach fails rather than
	// silently losing the transactions in it.
	RebuildLog bool
}

AttachSpec describes one database to attach.

type AuthMethod

type AuthMethod int

AuthMethod selects the authentication strategy for Connect().

const (
	// AuthSQLServer uses a SQL Server login and password.
	// Set ConnectionOptions.User and ConnectionOptions.Password.
	AuthSQLServer AuthMethod = iota

	// AuthWindows uses the Windows/Active Directory identity (on-premises,
	// domain-joined host). On Windows it uses native SSPI. On every other
	// platform it authenticates via Kerberos: with no credentials it uses the
	// ambient kinit credential cache (single sign-on); set ConnectionOptions.
	// Kerberos for a keytab, an explicit realm, or a non-default krb5.conf,
	// or set User+Password for a username/password Kerberos login.
	AuthWindows

	// AuthEntraDefault uses DefaultAzureCredential (env vars -> MSI -> AzCLI).
	// Ideal for code that must work both locally and in Azure without changes.
	AuthEntraDefault

	// AuthEntraPassword uses an Entra user UPN + password.
	// Set ConnectionOptions.User (UPN) and ConnectionOptions.Password;
	// ConnectionOptions.ApplicationClientID optionally names the public client
	// app to sign in through (default: 04b07795-8ddb-461a-bbee-02f9e1bf7b46,
	// the public client azidentity itself defaults to).
	//
	// It cannot satisfy multifactor authentication, so it fails for any user
	// MFA applies to; azidentity deprecates the underlying credential for that
	// reason. Prefer AuthEntraInteractive or AuthEntraDeviceCode for people.
	AuthEntraPassword

	// AuthEntraMSI uses a system-assigned Managed Identity.
	// Set ConnectionOptions.ClientID to select a user-assigned identity.
	AuthEntraMSI

	// AuthEntraServicePrincipal uses an app registration client-secret or cert.
	// Set ConnectionOptions.User to the application (client) ID,
	// ConnectionOptions.TenantID, and either:
	//   - ConnectionOptions.Password (client secret), or
	//   - ConnectionOptions.ClientCertPath + optionally ClientCertPassword (cert).
	AuthEntraServicePrincipal

	// AuthEntraServicePrincipalAccessToken presents a pre-acquired bearer token.
	// Set ConnectionOptions.AccessToken.
	AuthEntraServicePrincipalAccessToken

	// AuthEntraIntegrated is meant for Windows SSO federated with Entra, but
	// go-mssqldb has no such credential: it runs the same
	// DefaultAzureCredential chain as AuthEntraDefault. No credentials needed.
	AuthEntraIntegrated

	// AuthEntraInteractive opens a browser for interactive sign-in (human only).
	// ConnectionOptions.User is an optional login hint (the user's UPN).
	// ConnectionOptions.ApplicationClientID optionally names the public client
	// app to sign in through (default: 04b07795-8ddb-461a-bbee-02f9e1bf7b46,
	// the public client azidentity itself defaults to).
	AuthEntraInteractive

	// AuthEntraDeviceCode prints a device code for human sign-in on another
	// device. ConnectionOptions.ApplicationClientID optionally names the public
	// client app (azidentity defaults it to the same public client as
	// AuthEntraInteractive). The code goes to ConnectionOptions.DeviceCodePrompt,
	// or to the process's standard output when that is nil.
	AuthEntraDeviceCode

	// AuthEntraAzCLI uses the credential from "az login".
	AuthEntraAzCLI

	// AuthEntraAzureDeveloperCLI uses the credential from "azd auth login".
	AuthEntraAzureDeveloperCLI

	// AuthEntraAzurePipelines uses Azure DevOps OIDC federated credentials
	// (an Azure Resource Manager service connection).
	// Set ConnectionOptions.User to the service connection's client ID and
	// ConnectionOptions.TenantID to its tenant, or leave both empty to use
	// AZURESUBSCRIPTION_CLIENT_ID / AZURESUBSCRIPTION_TENANT_ID. The service
	// connection ID and the pipeline's System.AccessToken come from the
	// "serviceconnectionid" and "systemtoken" ExtraParams, or else from
	// AZURESUBSCRIPTION_SERVICE_CONNECTION_ID and SYSTEM_ACCESSTOKEN. The
	// OIDC request URL comes from SYSTEM_OIDCREQUESTURI, which Azure Pipelines
	// sets on every job.
	AuthEntraAzurePipelines

	// AuthEntraOnBehalfOf uses the OAuth 2.0 on-behalf-of flow: a middle-tier
	// app exchanges the token it received from a user for one to SQL Server.
	// Set ConnectionOptions.User to the app's client ID, optionally
	// ConnectionOptions.TenantID, ConnectionOptions.AccessToken to the inbound
	// user assertion, and the app's credential: ConnectionOptions.Password (a
	// client secret) or ConnectionOptions.ClientCertPath (+ ClientCertPassword),
	// or a "clientassertion" ExtraParams entry.
	AuthEntraOnBehalfOf
)

func (AuthMethod) String added in v0.0.13

func (m AuthMethod) String() string

String returns the constant's Go name ("AuthEntraPassword"), or "AuthMethod(<n>)" for a value that names no method.

type AvailabilityDatabase added in v0.0.9

type AvailabilityDatabase struct {
	GroupID           string
	ReplicaID         string
	ReplicaServerName string
	DatabaseName      string
	GroupDatabaseID   string

	IsLocal          bool
	IsPrimaryReplica bool

	SynchronizationState  string
	SynchronizationHealth string
	DatabaseState         string

	IsSuspended   bool
	SuspendReason string

	LogSendQueueKB  int64
	LogSendRateKBps int64
	RedoQueueKB     int64
	RedoRateKBps    int64

	// SecondaryLagSeconds is how far this secondary trails the primary.
	// SQL Server 2016+; 0 on older versions and on the primary itself.
	SecondaryLagSeconds int64

	LastSentTime     time.Time
	LastReceivedTime time.Time
	LastHardenedTime time.Time
	LastRedoneTime   time.Time
	LastCommitTime   time.Time
}

AvailabilityDatabase is one database's synchronization state on one replica. A group with two databases and three replicas yields six rows, of which the local instance can normally only populate the queue/rate/LSN detail for its own.

The queue and rate figures are in kilobytes and kilobytes per second, as SQL Server reports them; they are left at zero for a replica whose state this instance cannot see.

type AvailabilityGroup added in v0.0.9

type AvailabilityGroup struct {
	ID              string
	Name            string
	ResourceID      string
	ResourceGroupID string

	// ClusterType is WSFC, EXTERNAL or NONE. It is empty before SQL Server
	// 2017, which had no cluster_type column and only ever meant WSFC.
	// Upper-cased by agColumns, which is what makes those spellings true —
	// SQL Server reports this one in lower case.
	//
	// This is the field that decides whether a failover can be performed
	// through T-SQL at all: under EXTERNAL the cluster manager owns failover
	// and SQL Server rejects both ALTER AVAILABILITY GROUP ... FAILOVER and
	// ... FORCE_FAILOVER_ALLOW_DATA_LOSS with error 47104.
	ClusterType string

	AutomatedBackupPreference string
	FailureConditionLevel     int
	HealthCheckTimeout        int
	Version                   int

	// BasicFeatures reports a Basic availability group (Standard edition):
	// one database, two replicas, no readable secondary. SQL Server 2016+.
	BasicFeatures bool
	DTCSupport    bool
	DBFailover    bool
	IsDistributed bool

	// RequiredSynchronizedSecondariesToCommit is SQL Server 2017+; it is 0 on
	// older versions, which is also a legitimate value, so it cannot be used
	// to detect support.
	RequiredSynchronizedSecondariesToCommit int

	// IsContained reports a contained availability group, which carries its
	// own master and msdb. SQL Server 2022+.
	IsContained bool

	PrimaryReplicaServerName string
	PrimaryRecoveryHealth    string
	SynchronizationHealth    string
	// contains filtered or unexported fields
}

AvailabilityGroup represents one Always On availability group, as seen from the instance the owning Server is connected to.

The fields sourced from sys.dm_hadr_availability_group_states (PrimaryReplicaServerName, PrimaryRecoveryHealth, SynchronizationHealth) are empty when the local instance has no state row for the group — which happens while the group is resolving, or on an instance that has joined but not yet connected. An empty PrimaryReplicaServerName means "unknown from here", not "no primary exists".

func (*AvailabilityGroup) AddDatabase added in v0.0.9

func (ag *AvailabilityGroup) AddDatabase(name string) error

AddDatabase adds a database on the primary to the availability group.

Run against the primary. The database must already be in the full recovery model with a log backup taken; SQL Server rejects it otherwise. What happens on the secondaries afterwards depends on their seeding mode: an AUTOMATIC replica seeds itself, a MANUAL one needs the database restored there and then JoinDatabase called against it.

func (*AvailabilityGroup) AddDatabaseContext added in v0.0.9

func (ag *AvailabilityGroup) AddDatabaseContext(ctx context.Context, name string) error

AddDatabaseContext is the context-aware variant of AddDatabase.

func (*AvailabilityGroup) AddListener added in v0.0.9

func (ag *AvailabilityGroup) AddListener(spec AvailabilityListenerSpec) error

AddListener creates the group's listener. Run against the primary.

Under an EXTERNAL cluster type this records the listener in SQL Server's own metadata only — the address itself belongs to the external cluster manager (on Linux, a Pacemaker IPaddr2 resource), which has to be configured separately for clients to actually reach it. Unlike failover, the statement itself is accepted.

func (*AvailabilityGroup) AddListenerContext added in v0.0.9

func (ag *AvailabilityGroup) AddListenerContext(ctx context.Context, spec AvailabilityListenerSpec) error

AddListenerContext is the context-aware variant of AddListener.

func (*AvailabilityGroup) AddListenerIP added in v0.0.9

func (ag *AvailabilityGroup) AddListenerIP(dnsName string, ip AvailabilityListenerIPSpec) error

AddListenerIP binds another static address to an existing listener — the second and later subnets of a multi-subnet listener. Run against the primary.

A listener created WITH DHCP cannot be given static addresses this way; SQL Server rejects the statement.

There is no matching REMOVE IP: an address bound here stays for the life of the listener, and correcting one means REMOVE LISTENER and ADD LISTENER.

Under an EXTERNAL cluster type the address is recorded but not brought up — it appears in sys.availability_group_listener_ip_addresses as OFFLINE, because the external cluster manager owns the address, not SQL Server. Verified on SQL Server 2025 under Pacemaker.

func (*AvailabilityGroup) AddListenerIPContext added in v0.0.9

func (ag *AvailabilityGroup) AddListenerIPContext(ctx context.Context, dnsName string, ip AvailabilityListenerIPSpec) error

AddListenerIPContext is the context-aware variant of AddListenerIP.

func (*AvailabilityGroup) AddReplica added in v0.0.9

func (ag *AvailabilityGroup) AddReplica(spec AvailabilityReplicaSpec) error

AddReplica adds a secondary replica to an existing availability group.

This is the first of three statements, and on its own it leaves the new replica disconnected — exactly as CreateAvailabilityGroup does for the replicas it names. Run this against the primary, then, connected to the new replica itself:

  1. Join, which is the only way the replica actually enters the group; and
  2. GrantCreateAnyDatabase, if the spec seeds AUTOMATIC, without which seeding silently copies nothing.

The replica must already have a started database mirroring endpoint that the other replicas can reach, and its FailoverMode has to match what the group's cluster type permits — EXTERNAL requires EXTERNAL, NONE requires MANUAL.

func (*AvailabilityGroup) AddReplicaContext added in v0.0.9

func (ag *AvailabilityGroup) AddReplicaContext(ctx context.Context, spec AvailabilityReplicaSpec) error

AddReplicaContext is the context-aware variant of AddReplica.

func (*AvailabilityGroup) DatabaseSeq added in v0.0.9

DatabaseSeq returns an iterator over the per-replica synchronization state of every database in the availability group.

func (*AvailabilityGroup) Databases added in v0.0.9

func (ag *AvailabilityGroup) Databases() ([]*AvailabilityDatabase, error)

Databases returns the per-replica synchronization state of every database in the group.

The database list comes from sys.availability_databases_cluster, which is cluster-wide metadata, so a database appears even on a replica that has not finished seeding it — with empty state rather than being silently missing.

func (*AvailabilityGroup) DatabasesContext added in v0.0.9

func (ag *AvailabilityGroup) DatabasesContext(ctx context.Context) ([]*AvailabilityDatabase, error)

DatabasesContext is the context-aware variant of Databases.

func (*AvailabilityGroup) DenyCreateAnyDatabase added in v0.0.9

func (ag *AvailabilityGroup) DenyCreateAnyDatabase() error

DenyCreateAnyDatabase revokes what GrantCreateAnyDatabase granted.

func (*AvailabilityGroup) DenyCreateAnyDatabaseContext added in v0.0.9

func (ag *AvailabilityGroup) DenyCreateAnyDatabaseContext(ctx context.Context) error

DenyCreateAnyDatabaseContext is the context-aware variant of DenyCreateAnyDatabase.

func (*AvailabilityGroup) Drop added in v0.0.9

func (ag *AvailabilityGroup) Drop() error

Drop deletes the availability group.

Run against the primary, which drops the group cluster-wide. Running it on a secondary instead removes only that replica's participation and leaves the group running elsewhere — SQL Server does not warn about the difference, so check IsLocalPrimary first if the intent is to delete the group.

The databases survive: the primary's copies stay online and read-write, and each secondary is left with the same unusable copies RemoveDatabase leaves behind.

func (*AvailabilityGroup) DropContext added in v0.0.9

func (ag *AvailabilityGroup) DropContext(ctx context.Context) error

DropContext is the context-aware variant of Drop.

func (*AvailabilityGroup) Failover added in v0.0.9

func (ag *AvailabilityGroup) Failover() error

Failover makes this replica the primary, without data loss.

Run against the secondary that should become primary — not against the current primary. The target must be a synchronous-commit replica in the SYNCHRONIZED state; SQL Server refuses otherwise rather than failing over with loss.

Whether this works at all is decided by ClusterType, and only WSFC allows it. Under EXTERNAL it is rejected with error 47104 ("Use the cluster management tools to perform the operation"), because the external cluster manager owns failover — Pacemaker's `crm resource move`, not SQL Server. Under NONE it is rejected with error 47122, which says only forced failover is supported. Both verified against SQL Server 2025. Check ClusterType before offering this; the statement is sent and refused, not silently ignored.

func (*AvailabilityGroup) FailoverContext added in v0.0.9

func (ag *AvailabilityGroup) FailoverContext(ctx context.Context) error

FailoverContext is the context-aware variant of Failover.

func (*AvailabilityGroup) ForceFailoverAllowDataLoss added in v0.0.9

func (ag *AvailabilityGroup) ForceFailoverAllowDataLoss() error

ForceFailoverAllowDataLoss makes this replica the primary even though it may not hold every committed transaction.

Run against the secondary that should become primary. This is the disaster path: any transaction the target had not hardened is lost, and every other secondary has to be resumed (and may need reseeding) afterwards. Prefer Failover wherever the target is SYNCHRONIZED.

Rejected with error 47104 under an EXTERNAL cluster type, exactly as Failover is. Under NONE it is the *only* failover there is, which is why a read-scale group has no lossless one.

func (*AvailabilityGroup) ForceFailoverAllowDataLossContext added in v0.0.9

func (ag *AvailabilityGroup) ForceFailoverAllowDataLossContext(ctx context.Context) error

ForceFailoverAllowDataLossContext is the context-aware variant of ForceFailoverAllowDataLoss.

func (*AvailabilityGroup) GrantCreateAnyDatabase added in v0.0.9

func (ag *AvailabilityGroup) GrantCreateAnyDatabase() error

GrantCreateAnyDatabase lets the availability group create databases on this instance, which is what automatic seeding needs to materialise a secondary copy.

Run against each secondary. Without it a replica set to SEEDING_MODE = AUTOMATIC seeds nothing, and reports no error for it — the database simply never appears.

func (*AvailabilityGroup) GrantCreateAnyDatabaseContext added in v0.0.9

func (ag *AvailabilityGroup) GrantCreateAnyDatabaseContext(ctx context.Context) error

GrantCreateAnyDatabaseContext is the context-aware variant of GrantCreateAnyDatabase.

func (*AvailabilityGroup) IsLocalPrimary added in v0.0.9

func (ag *AvailabilityGroup) IsLocalPrimary() bool

IsLocalPrimary reports whether the instance this group was read from is currently the group's primary replica. False when the primary is elsewhere *or* unknown from here, so it is safe to branch on but not to invert: !IsLocalPrimary() does not prove a remote primary exists.

func (*AvailabilityGroup) Join added in v0.0.9

func (ag *AvailabilityGroup) Join(clusterType string) error

Join joins the instance this group was read from to it, as a secondary.

Run against the secondary — the primary cannot join anything on its behalf. The group must already name this instance as a replica, which CreateAvailabilityGroup's REPLICA ON list does.

**Under CLUSTER_TYPE = EXTERNAL or NONE the group does not exist on the secondary until this succeeds.** Only a WSFC cluster propagates the metadata ahead of the join, so AvailabilityGroupByName on the secondary comes back "no rows" and there is nothing to call this on — use Server.AvailabilityGroup to build a handle by name instead. Verified against SQL Server 2025.

clusterType is passed rather than read off the group for the same reason: a handle that had to be built by name has no metadata to read. It must match what the group was created with, and EXTERNAL and NONE are rejected when it does not; pass "" or "WSFC" for a Windows cluster, which takes no clause.

func (*AvailabilityGroup) JoinContext added in v0.0.9

func (ag *AvailabilityGroup) JoinContext(ctx context.Context, clusterType string) error

JoinContext is the context-aware variant of Join.

func (*AvailabilityGroup) JoinDatabase added in v0.0.9

func (ag *AvailabilityGroup) JoinDatabase(name string) error

JoinDatabase joins a restored secondary copy of a database to the group.

Run against the secondary holding the copy, after restoring it WITH NORECOVERY from a full and a log backup of the primary's. Only needed for a MANUAL-seeding replica; an AUTOMATIC one joins itself as part of seeding.

func (*AvailabilityGroup) JoinDatabaseContext added in v0.0.9

func (ag *AvailabilityGroup) JoinDatabaseContext(ctx context.Context, name string) error

JoinDatabaseContext is the context-aware variant of JoinDatabase.

func (*AvailabilityGroup) ListenerSeq added in v0.0.9

ListenerSeq returns an iterator over the availability group's listeners.

func (*AvailabilityGroup) Listeners added in v0.0.9

func (ag *AvailabilityGroup) Listeners() ([]*AvailabilityGroupListener, error)

Listeners returns the group's listeners, each with its IP addresses.

func (*AvailabilityGroup) ListenersContext added in v0.0.9

func (ag *AvailabilityGroup) ListenersContext(ctx context.Context) ([]*AvailabilityGroupListener, error)

ListenersContext is the context-aware variant of Listeners.

func (*AvailabilityGroup) RemoveDatabase added in v0.0.9

func (ag *AvailabilityGroup) RemoveDatabase(name string) error

RemoveDatabase removes a database from the availability group.

Run against the primary, which removes the database from the group cluster-wide. The primary's copy stays online and read-write; each secondary is left holding a copy that is no longer in any role, so every connection to it fails with error 983 until it is dropped or restored WITH RECOVERY. sys.databases still reports that copy as ONLINE, so state_desc is not the way to find one — verified against SQL Server 2025.

func (*AvailabilityGroup) RemoveDatabaseContext added in v0.0.9

func (ag *AvailabilityGroup) RemoveDatabaseContext(ctx context.Context, name string) error

RemoveDatabaseContext is the context-aware variant of RemoveDatabase.

func (*AvailabilityGroup) RemoveListener added in v0.0.9

func (ag *AvailabilityGroup) RemoveListener(dnsName string) error

RemoveListener drops the group's listener by DNS name. Run against the primary. Existing connections made through the listener are not dropped.

func (*AvailabilityGroup) RemoveListenerContext added in v0.0.9

func (ag *AvailabilityGroup) RemoveListenerContext(ctx context.Context, dnsName string) error

RemoveListenerContext is the context-aware variant of RemoveListener.

func (*AvailabilityGroup) RemoveReplica added in v0.0.9

func (ag *AvailabilityGroup) RemoveReplica(serverName string) error

RemoveReplica removes a secondary replica from the group.

Run against the primary; a secondary cannot remove itself, and rejects the attempt with error 41190.

The removed instance is not cleaned up by this: it keeps both its copies of the databases and a stale row for the group in its own sys.availability_groups, which only DROP AVAILABILITY GROUP run *there* clears. Removing a replica and then dropping the group on the primary therefore still leaves the group listed on the instance that was removed — verified against SQL Server 2025.

func (*AvailabilityGroup) RemoveReplicaContext added in v0.0.9

func (ag *AvailabilityGroup) RemoveReplicaContext(ctx context.Context, serverName string) error

RemoveReplicaContext is the context-aware variant of RemoveReplica.

func (*AvailabilityGroup) ReplicaSeq added in v0.0.9

ReplicaSeq returns an iterator over the availability group's replicas.

func (*AvailabilityGroup) Replicas added in v0.0.9

func (ag *AvailabilityGroup) Replicas() ([]*AvailabilityReplica, error)

Replicas returns every replica in the group, ordered by server name.

func (*AvailabilityGroup) ReplicasContext added in v0.0.9

func (ag *AvailabilityGroup) ReplicasContext(ctx context.Context) ([]*AvailabilityReplica, error)

ReplicasContext is the context-aware variant of Replicas.

func (*AvailabilityGroup) ResumeDatabase added in v0.0.9

func (ag *AvailabilityGroup) ResumeDatabase(name string) error

ResumeDatabase resumes data movement for one database, on the same scope SuspendDatabase used.

func (*AvailabilityGroup) ResumeDatabaseContext added in v0.0.9

func (ag *AvailabilityGroup) ResumeDatabaseContext(ctx context.Context, name string) error

ResumeDatabaseContext is the context-aware variant of ResumeDatabase.

func (*AvailabilityGroup) Server added in v0.0.9

func (ag *AvailabilityGroup) Server() *Server

Server returns the connection this availability group was read from.

func (*AvailabilityGroup) SetAutomatedBackupPreference added in v0.0.9

func (ag *AvailabilityGroup) SetAutomatedBackupPreference(pref string) error

SetAutomatedBackupPreference chooses where automated backups of this group's databases should run: PRIMARY, SECONDARY_ONLY, SECONDARY (prefer a secondary but fall back to the primary) or NONE (any replica).

The preference is advisory. SQL Server does not enforce it — it is exposed to backup jobs through sys.fn_hadr_backup_is_preferred_replica, which the job has to consult.

func (*AvailabilityGroup) SetAutomatedBackupPreferenceContext added in v0.0.9

func (ag *AvailabilityGroup) SetAutomatedBackupPreferenceContext(ctx context.Context, pref string) error

SetAutomatedBackupPreferenceContext is the context-aware variant of SetAutomatedBackupPreference.

func (*AvailabilityGroup) SetDBFailover added in v0.0.9

func (ag *AvailabilityGroup) SetDBFailover(on bool) error

SetDBFailover turns database-level health detection on or off: with it on, a single database going offline triggers failover of the whole group.

func (*AvailabilityGroup) SetDBFailoverContext added in v0.0.9

func (ag *AvailabilityGroup) SetDBFailoverContext(ctx context.Context, on bool) error

SetDBFailoverContext is the context-aware variant of SetDBFailover.

func (*AvailabilityGroup) SetDTCSupport added in v0.0.9

func (ag *AvailabilityGroup) SetDTCSupport(perDB bool) error

SetDTCSupport turns per-database DTC support on (PER_DB) or off (NONE). SQL Server 2016+.

func (*AvailabilityGroup) SetDTCSupportContext added in v0.0.9

func (ag *AvailabilityGroup) SetDTCSupportContext(ctx context.Context, perDB bool) error

SetDTCSupportContext is the context-aware variant of SetDTCSupport.

func (*AvailabilityGroup) SetFailureConditionLevel added in v0.0.9

func (ag *AvailabilityGroup) SetFailureConditionLevel(level int) error

SetFailureConditionLevel sets how severe a condition must be before an automatic failover is triggered, 1 (server down only) to 5 (any qualifying internal error).

func (*AvailabilityGroup) SetFailureConditionLevelContext added in v0.0.9

func (ag *AvailabilityGroup) SetFailureConditionLevelContext(ctx context.Context, level int) error

SetFailureConditionLevelContext is the context-aware variant of SetFailureConditionLevel.

func (*AvailabilityGroup) SetHealthCheckTimeout added in v0.0.9

func (ag *AvailabilityGroup) SetHealthCheckTimeout(ms int) error

SetHealthCheckTimeout sets how long, in milliseconds, the cluster waits for sp_server_diagnostics before declaring the instance unresponsive. SQL Server enforces a 15000 ms floor.

func (*AvailabilityGroup) SetHealthCheckTimeoutContext added in v0.0.9

func (ag *AvailabilityGroup) SetHealthCheckTimeoutContext(ctx context.Context, ms int) error

SetHealthCheckTimeoutContext is the context-aware variant of SetHealthCheckTimeout.

func (*AvailabilityGroup) SetListenerPort added in v0.0.9

func (ag *AvailabilityGroup) SetListenerPort(dnsName string, port int) error

SetListenerPort changes the port an existing listener answers on. Run against the primary.

Clients already connected through the old port stay connected; only new connections are affected, and any that name the port explicitly will need updating.

func (*AvailabilityGroup) SetListenerPortContext added in v0.0.9

func (ag *AvailabilityGroup) SetListenerPortContext(ctx context.Context, dnsName string, port int) error

SetListenerPortContext is the context-aware variant of SetListenerPort.

func (*AvailabilityGroup) SetRequiredSynchronizedSecondariesToCommit added in v0.0.9

func (ag *AvailabilityGroup) SetRequiredSynchronizedSecondariesToCommit(n int) error

SetRequiredSynchronizedSecondariesToCommit sets how many synchronous secondaries must acknowledge a transaction before it commits on the primary. SQL Server 2017+.

Raising it above the number of healthy synchronous secondaries stops the primary accepting writes, which is the intended trade for guaranteed zero-data-loss failover — it is not a setting to nudge experimentally on a live group.

func (*AvailabilityGroup) SetRequiredSynchronizedSecondariesToCommitContext added in v0.0.9

func (ag *AvailabilityGroup) SetRequiredSynchronizedSecondariesToCommitContext(ctx context.Context, n int) error

SetRequiredSynchronizedSecondariesToCommitContext is the context-aware variant of SetRequiredSynchronizedSecondariesToCommit.

func (*AvailabilityGroup) SuspendDatabase added in v0.0.9

func (ag *AvailabilityGroup) SuspendDatabase(name string) error

SuspendDatabase suspends data movement for one database.

The scope depends on where it runs, and the difference matters: on a secondary it suspends that one secondary, on the primary it suspends the database on *every* secondary. Either way the primary keeps accepting writes and its log cannot be truncated while movement is suspended, so a long suspension fills the log drive.

func (*AvailabilityGroup) SuspendDatabaseContext added in v0.0.9

func (ag *AvailabilityGroup) SuspendDatabaseContext(ctx context.Context, name string) error

SuspendDatabaseContext is the context-aware variant of SuspendDatabase.

func (*AvailabilityGroup) UnjoinDatabase added in v0.0.9

func (ag *AvailabilityGroup) UnjoinDatabase(name string) error

UnjoinDatabase removes this instance's secondary copy of a database from the group, leaving it in the RESTORING state.

Run against the secondary. This is the per-secondary counterpart of RemoveDatabase: it takes one copy out of the group and leaves the database in it on every other replica.

func (*AvailabilityGroup) UnjoinDatabaseContext added in v0.0.9

func (ag *AvailabilityGroup) UnjoinDatabaseContext(ctx context.Context, name string) error

UnjoinDatabaseContext is the context-aware variant of UnjoinDatabase.

type AvailabilityGroupListener added in v0.0.9

type AvailabilityGroupListener struct {
	GroupID    string
	ListenerID string
	DNSName    string
	Port       int

	// IsConformant is false for a listener created outside SQL Server (added
	// directly in the cluster manager), whose configuration SQL Server can
	// report but not fully validate.
	IsConformant bool

	IPConfigurationString    string
	IsDistributedNetworkName bool

	IPAddresses []AvailabilityListenerIP
}

AvailabilityGroupListener is one virtual network name clients connect to. Its addresses are carried inline rather than behind another round trip, since a listener without them tells a caller almost nothing.

type AvailabilityListenerIP added in v0.0.9

type AvailabilityListenerIP struct {
	IPAddress  string
	SubnetMask string
	IsDHCP     bool
	State      string
}

AvailabilityListenerIP is one address bound to a listener. A multi-subnet availability group has one per subnet.

type AvailabilityListenerIPSpec added in v0.0.9

type AvailabilityListenerIPSpec struct {
	IPAddress string

	// SubnetMask is required for IPv4 and must be empty for IPv6.
	SubnetMask string
}

AvailabilityListenerIPSpec is one static address for a listener being created.

type AvailabilityListenerSpec added in v0.0.9

type AvailabilityListenerSpec struct {
	// DNSName is the virtual network name clients connect to. Required.
	DNSName string

	// Port is the TCP port the listener answers on. Zero omits PORT from the
	// statement, which SQL Server defaults to 1433.
	Port int

	// IPAddresses are the static addresses to bind, one per subnet. An entry
	// with an empty SubnetMask is emitted as an IPv6 address, which takes no
	// mask; an IPv4 entry needs one.
	IPAddresses []AvailabilityListenerIPSpec

	// DHCP requests an address from DHCP instead of binding static ones.
	// Mutually exclusive with IPAddresses.
	DHCP bool

	// DHCPSubnet and DHCPSubnetMask optionally name the subnet to take the
	// address from — WITH DHCP ON (N'network', N'mask'). Both or neither.
	DHCPSubnet     string
	DHCPSubnetMask string
}

AvailabilityListenerSpec describes a listener to create with AddListener.

Exactly one addressing mode has to be chosen: either DHCP, or one or more static IPAddresses. A group can have only one listener at a time, so adding a second is an error (19477) rather than a second name to reach it by.

type AvailabilityReplica added in v0.0.9

type AvailabilityReplica struct {
	GroupID string

	// GroupName is the owning group's name. ALTER AVAILABILITY GROUP addresses
	// a replica as "<group> MODIFY REPLICA ON '<replica>'", so every setter on
	// this type needs it; it is filled in by ReplicasContext.
	GroupName string

	ReplicaID         string
	ReplicaServerName string
	EndpointURL       string

	AvailabilityMode string
	FailoverMode     string
	SessionTimeout   int

	PrimaryRoleAllowConnections   string
	SecondaryRoleAllowConnections string

	BackupPriority     int
	ReadOnlyRoutingURL string

	// SeedingMode is AUTOMATIC or MANUAL. SQL Server 2016+; empty on older.
	SeedingMode string

	CreateDate time.Time
	ModifyDate time.Time

	IsLocal               bool
	Role                  string
	OperationalState      string
	ConnectedState        string
	RecoveryHealth        string
	SynchronizationHealth string

	LastConnectErrorNumber      int
	LastConnectErrorDescription string
	LastConnectErrorTimestamp   time.Time
	// contains filtered or unexported fields
}

AvailabilityReplica is one replica's configuration plus, where the local instance can see it, its current state.

The state fields (Role, OperationalState, ConnectedState, RecoveryHealth, SynchronizationHealth) come from sys.dm_hadr_availability_replica_states and are empty for a replica this instance has no state row for. OperationalState in particular is only ever populated for the local replica — SQL Server does not report a remote replica's operational state — so an empty value there is normal rather than a fault.

func (*AvailabilityReplica) Drop added in v0.0.9

func (r *AvailabilityReplica) Drop() error

Drop removes this replica from its availability group — the same statement AvailabilityGroup.RemoveReplica issues, addressed from the replica instead. Run against the primary.

func (*AvailabilityReplica) DropContext added in v0.0.9

func (r *AvailabilityReplica) DropContext(ctx context.Context) error

DropContext is the context-aware variant of Drop.

func (*AvailabilityReplica) ReadOnlyRoutingList added in v0.0.9

func (r *AvailabilityReplica) ReadOnlyRoutingList() ([][]string, error)

ReadOnlyRoutingList returns the read-only routing list this replica uses while it holds the primary role: the secondaries read-intent connections are redirected to, in priority order.

The outer slice is the priority order; each inner slice holds the replicas sharing one priority, which SQL Server load-balances between (2016+). A replica with no routing list configured returns nil, not an error.

func (*AvailabilityReplica) ReadOnlyRoutingListContext added in v0.0.9

func (r *AvailabilityReplica) ReadOnlyRoutingListContext(ctx context.Context) ([][]string, error)

ReadOnlyRoutingListContext is the context-aware variant of ReadOnlyRoutingList.

func (*AvailabilityReplica) SetAvailabilityMode added in v0.0.9

func (r *AvailabilityReplica) SetAvailabilityMode(mode string) error

SetAvailabilityMode switches the replica between SYNCHRONOUS_COMMIT, ASYNCHRONOUS_COMMIT and CONFIGURATION_ONLY.

Only a synchronous-commit replica can be an automatic failover target, so dropping one to asynchronous also silently removes it as a candidate.

func (*AvailabilityReplica) SetAvailabilityModeContext added in v0.0.9

func (r *AvailabilityReplica) SetAvailabilityModeContext(ctx context.Context, mode string) error

SetAvailabilityModeContext is the context-aware variant of SetAvailabilityMode.

func (*AvailabilityReplica) SetBackupPriority added in v0.0.9

func (r *AvailabilityReplica) SetBackupPriority(priority int) error

SetBackupPriority sets this replica's automated-backup priority, 1 (lowest) to 100 (highest). 0 excludes the replica from automated backups altogether — the value behind SSMS's "Exclude Replica" checkbox.

func (*AvailabilityReplica) SetBackupPriorityContext added in v0.0.9

func (r *AvailabilityReplica) SetBackupPriorityContext(ctx context.Context, priority int) error

SetBackupPriorityContext is the context-aware variant of SetBackupPriority.

func (*AvailabilityReplica) SetFailoverMode added in v0.0.9

func (r *AvailabilityReplica) SetFailoverMode(mode string) error

SetFailoverMode switches the replica between AUTOMATIC, MANUAL and EXTERNAL failover. EXTERNAL is the only mode a group with ClusterType EXTERNAL accepts, since the cluster manager owns failover there.

func (*AvailabilityReplica) SetFailoverModeContext added in v0.0.9

func (r *AvailabilityReplica) SetFailoverModeContext(ctx context.Context, mode string) error

SetFailoverModeContext is the context-aware variant of SetFailoverMode.

func (*AvailabilityReplica) SetPrimaryRoleAllowConnections added in v0.0.9

func (r *AvailabilityReplica) SetPrimaryRoleAllowConnections(mode string) error

SetPrimaryRoleAllowConnections sets which connections the replica accepts while it is the primary: ALL, or READ_WRITE (which turns away connections asking for ApplicationIntent=ReadOnly).

func (*AvailabilityReplica) SetPrimaryRoleAllowConnectionsContext added in v0.0.9

func (r *AvailabilityReplica) SetPrimaryRoleAllowConnectionsContext(ctx context.Context, mode string) error

SetPrimaryRoleAllowConnectionsContext is the context-aware variant of SetPrimaryRoleAllowConnections.

func (*AvailabilityReplica) SetReadOnlyRoutingList added in v0.0.9

func (r *AvailabilityReplica) SetReadOnlyRoutingList(list [][]string) error

SetReadOnlyRoutingList sets the routing list this replica uses while it holds the primary role, in the shape ReadOnlyRoutingListContext returns: the outer slice is priority order, and replicas sharing an inner slice are load-balanced between (SQL Server 2016+). An empty list clears the routing list.

func (*AvailabilityReplica) SetReadOnlyRoutingListContext added in v0.0.9

func (r *AvailabilityReplica) SetReadOnlyRoutingListContext(ctx context.Context, list [][]string) error

SetReadOnlyRoutingListContext is the context-aware variant of SetReadOnlyRoutingList.

func (*AvailabilityReplica) SetReadOnlyRoutingURL added in v0.0.9

func (r *AvailabilityReplica) SetReadOnlyRoutingURL(url string) error

SetReadOnlyRoutingURL sets the address read-intent connections are redirected to when this replica is a readable secondary, e.g. "TCP://ubusql2.example.com:1433". An empty url clears it.

The URL is a property of the *secondary* role, while the routing list that points at it is a property of the primary role — see SetReadOnlyRoutingList. Both have to be set for read-only routing to work.

Clearing writes the bare keyword NONE, matching the routing list. Neither NULL nor an empty string works: NULL is a syntax error and N” is rejected as "Invalid usage of the option READ_ONLY_ROUTING_URL" — both verified against SQL Server 2025.

func (*AvailabilityReplica) SetReadOnlyRoutingURLContext added in v0.0.9

func (r *AvailabilityReplica) SetReadOnlyRoutingURLContext(ctx context.Context, url string) error

SetReadOnlyRoutingURLContext is the context-aware variant of SetReadOnlyRoutingURL.

func (*AvailabilityReplica) SetSecondaryRoleAllowConnections added in v0.0.9

func (r *AvailabilityReplica) SetSecondaryRoleAllowConnections(mode string) error

SetSecondaryRoleAllowConnections sets whether the replica is readable while it is a secondary: NO, READ_ONLY (read-intent connections only) or ALL.

func (*AvailabilityReplica) SetSecondaryRoleAllowConnectionsContext added in v0.0.9

func (r *AvailabilityReplica) SetSecondaryRoleAllowConnectionsContext(ctx context.Context, mode string) error

SetSecondaryRoleAllowConnectionsContext is the context-aware variant of SetSecondaryRoleAllowConnections.

func (*AvailabilityReplica) SetSeedingMode added in v0.0.9

func (r *AvailabilityReplica) SetSeedingMode(mode string) error

SetSeedingMode switches the replica between AUTOMATIC (direct seeding) and MANUAL (backup and restore) database seeding. SQL Server 2016+.

func (*AvailabilityReplica) SetSeedingModeContext added in v0.0.9

func (r *AvailabilityReplica) SetSeedingModeContext(ctx context.Context, mode string) error

SetSeedingModeContext is the context-aware variant of SetSeedingMode.

func (*AvailabilityReplica) SetSessionTimeout added in v0.0.9

func (r *AvailabilityReplica) SetSessionTimeout(seconds int) error

SetSessionTimeout sets how many seconds a replica waits for a message from its partner before reporting the connection down. SQL Server enforces a 5-second floor; below about 10 seconds a busy system reports false failures.

func (*AvailabilityReplica) SetSessionTimeoutContext added in v0.0.9

func (r *AvailabilityReplica) SetSessionTimeoutContext(ctx context.Context, seconds int) error

SetSessionTimeoutContext is the context-aware variant of SetSessionTimeout.

type AvailabilityReplicaSpec added in v0.0.9

type AvailabilityReplicaSpec struct {
	// ServerName is the instance name, as @@SERVERNAME reports it there.
	// Required — it is how every later ALTER addresses this replica.
	ServerName string

	// EndpointURL is the replica's database mirroring endpoint address,
	// "tcp://host:port". Required; DatabaseMirroringEndpoint.URL builds it.
	EndpointURL string

	// AvailabilityMode is SYNCHRONOUS_COMMIT, ASYNCHRONOUS_COMMIT or
	// CONFIGURATION_ONLY. Empty means SYNCHRONOUS_COMMIT.
	AvailabilityMode string

	// FailoverMode is MANUAL, AUTOMATIC or EXTERNAL. Empty means MANUAL.
	// EXTERNAL is required — and the only legal value — under
	// CLUSTER_TYPE = EXTERNAL.
	FailoverMode string

	// SeedingMode is AUTOMATIC or MANUAL. Empty omits the clause, which the
	// server defaults to MANUAL.
	SeedingMode string

	// BackupPriority is 0-100; 0 excludes the replica from automated backups.
	// Negative omits the clause, leaving the server's default of 50 — which is
	// why this is not simply "0 means default".
	BackupPriority int

	// SessionTimeout is the seconds a replica waits for a partner before
	// declaring the connection dead. Zero omits the clause (server default 10).
	SessionTimeout int

	// PrimaryRoleAllowConnections is ALL or READ_WRITE; empty omits the clause.
	PrimaryRoleAllowConnections string

	// SecondaryRoleAllowConnections is NO, READ_ONLY or ALL; empty omits it.
	SecondaryRoleAllowConnections string

	// ReadOnlyRoutingURL is this replica's routing address for read-intent
	// redirection, set inside SECONDARY_ROLE. Empty omits it.
	ReadOnlyRoutingURL string
}

AvailabilityReplicaSpec describes one replica of a group being created.

type BackupAction

type BackupAction string

BackupAction mirrors SQL Server backup types.

const (
	BackupActionDatabase     BackupAction = "DATABASE"
	BackupActionLog          BackupAction = "LOG"
	BackupActionFiles        BackupAction = "FILES"
	BackupActionDifferential BackupAction = "DATABASE_DIFFERENTIAL"
)

type BackupDevice added in v0.0.11

type BackupDevice struct {
	Name string

	// Type is the device kind as sys.backup_devices reports it: "DISK",
	// "TAPE", "VIRTUAL_DEVICE", or "PERMANENT DUMP DEVICE" for one carried
	// over from a much older version. It is the catalog's type_desc, not the
	// keyword sp_addumpdevice takes — see BackupDeviceType for that.
	Type string

	// PhysicalName is the path (or tape/virtual device name) the alias
	// stands for.
	PhysicalName string
	// contains filtered or unexported fields
}

BackupDevice mirrors a row of sys.backup_devices — a named alias for a physical backup location, usable anywhere a BACKUP or RESTORE statement takes a device.

func (*BackupDevice) Drop added in v0.0.11

func (d *BackupDevice) Drop(deleteFile bool) error

Drop removes the logical backup device. deleteFile also deletes the physical file behind it.

func (*BackupDevice) DropContext added in v0.0.11

func (d *BackupDevice) DropContext(ctx context.Context, deleteFile bool) error

DropContext is the context-aware variant of Drop.

deleteFile is sp_dropdevice's @delfile: false unregisters the alias and leaves the backup file on disk, true deletes the file too and is not recoverable.

func (*BackupDevice) Headers added in v0.0.11

func (d *BackupDevice) Headers() ([]*BackupHeader, error)

Headers reads the backup sets the device holds (RESTORE HEADERONLY).

func (*BackupDevice) HeadersContext added in v0.0.11

func (d *BackupDevice) HeadersContext(ctx context.Context) ([]*BackupHeader, error)

HeadersContext is the context-aware variant of Headers.

func (*BackupDevice) Target added in v0.0.11

func (d *BackupDevice) Target() BackupTarget

Target returns the device as a BackupTarget, for the RESTORE-side reads (BackupHeadersFrom, BackupFileListForSetFrom, VerifyBackupFrom) that report what a device holds.

type BackupDeviceType added in v0.0.11

type BackupDeviceType string

BackupDeviceType is the device kind sp_addumpdevice takes.

const (
	// BackupDeviceDisk is a file on the server's filesystem.
	BackupDeviceDisk BackupDeviceType = "disk"
	// BackupDeviceTape is a tape device. Tape backup is removed from current
	// SQL Server versions; a tape device is listed and dropped, not created.
	BackupDeviceTape BackupDeviceType = "tape"
)

type BackupFile added in v0.0.5

type BackupFile struct {
	LogicalName   string
	PhysicalName  string
	Type          string // "D" data, "L" log, "F" full-text, "S" FILESTREAM
	FileGroupName string
	Size          int64 // bytes
	MaxSize       int64 // bytes
}

BackupFile describes one database file inside a backup set, as reported by RESTORE FILELISTONLY.

type BackupHeader added in v0.0.5

type BackupHeader struct {
	BackupName           string
	Description          string
	BackupType           BackupAction
	Position             int
	DatabaseName         string
	ServerName           string
	BackupStart          time.Time
	BackupFinish         time.Time
	BackupSize           int64 // bytes
	CompressedSize       int64 // bytes; equals BackupSize when not compressed
	Compressed           bool
	HasChecksums         bool
	IsCopyOnly           bool
	DatabaseVersion      int
	CompatibilityLevel   CompatibilityLevel
	SoftwareVersionMajor int
	RecoveryModel        string
}

BackupHeader describes one backup set on a backup device, as reported by RESTORE HEADERONLY.

type BackupInfo

type BackupInfo struct {
	DatabaseName       string
	BackupSetName      string
	Description        string
	BackupType         BackupAction
	BackupStart        time.Time
	BackupFinish       time.Time
	BackupSize         int64
	DeviceName         string
	UserName           string
	ServerName         string
	DatabaseVersion    int
	CompatibilityLevel CompatibilityLevel
}

BackupInfo holds metadata about a specific database backup.

type BackupOptions

type BackupOptions struct {
	// Database to back up (required).
	Database string
	// Action: DATABASE (default), LOG, or FILES.
	Action BackupAction
	// Files and FileGroups name the logical files / filegroups a
	// BackupActionFiles backup covers. At least one of the two is required
	// for that action and both are ignored for every other one — there is no
	// "BACKUP FILES" verb in T-SQL; a file/filegroup backup is a BACKUP
	// DATABASE carrying FILE = / FILEGROUP = clauses.
	Files      []string
	FileGroups []string
	// Devices is one or more backup device paths, e.g. `C:\Backups\MyDB.bak`.
	Devices []string
	// BackupSetName is the NAME clause.
	BackupSetName string
	// Description is the DESCRIPTION clause.
	Description string
	// MediaDescription is the MEDIADESCRIPTION clause.
	MediaDescription string
	// Compression: nil = server default, new(true) = force on, new(false) = force off.
	Compression *bool
	// CopyOnly marks this as a copy-only backup (does not break the log chain).
	CopyOnly bool
	// Checksum adds WITH CHECKSUM.
	Checksum bool
	// Format reinitialises the media.
	Format bool
	// Init overwrites existing backup sets on the media.
	Init bool
	// Stats controls progress reporting frequency (e.g. 10 = every 10%).
	// If Progress is set and Stats is left at 0, it defaults to 10 so
	// percent-complete messages actually get emitted.
	Stats int
	// Credential names the SQL Server credential a BACKUP ... TO URL
	// authenticates to Azure Storage with (WITH CREDENTIAL = N'name'), the
	// storage-account-key form. Leave it empty for the shared access
	// signature form, which is what Managed Instance uses: there the
	// credential's *name* is the container URL and SQL Server finds it
	// itself, so naming it here is not merely unnecessary but wrong.
	// Ignored for a DISK device, which authenticates as the service account.
	Credential string
	// Progress, if set, is called for every message SQL Server emits while
	// the backup runs, including the "N percent processed" notices STATS
	// produces — pct is -1 for a message that doesn't carry a percentage.
	Progress func(pct int, message string)
}

BackupOptions configures a BACKUP DATABASE or BACKUP LOG operation.

type BackupTarget added in v0.0.11

type BackupTarget struct {
	// contains filtered or unexported fields
}

BackupTarget names where a RESTORE-side read finds a backup: a physical path, a blob URL, or a logical backup device from sys.backup_devices. The three are addressed differently and are not interchangeable — a logical device is named bare, as FROM [devicename], and passing its name as a path produces FROM DISK = N'devicename', which SQL Server reads as a file of that name in the server's default backup directory.

Build one with DiskTarget, URLTarget or DeviceTarget.

func DeviceTarget added in v0.0.11

func DeviceTarget(name string) BackupTarget

DeviceTarget names a backup by the logical backup device holding it — a row of sys.backup_devices, see Server.BackupDevices.

func DiskTarget added in v0.0.11

func DiskTarget(path string) BackupTarget

DiskTarget names a backup by its location on the server: a filesystem path, or — when path is an http/https URL, per IsBackupURL — the blob holding it. The URL case is classified here rather than left to the caller because every RESTORE-side read (VerifyBackup, BackupHeaders, BackupFileList) funnels through this constructor, and a Managed Instance refuses all three as DISK. URLTarget states the same thing outright.

func URLTarget added in v0.0.12

func URLTarget(url string) BackupTarget

URLTarget names a backup by its Azure Storage blob URL, whatever its spelling — DiskTarget already recognises the usual http/https one.

func (BackupTarget) String added in v0.0.11

func (t BackupTarget) String() string

String returns the target's name, for error messages and display.

type BulkCopy added in v0.0.4

type BulkCopy struct {
	// Schema is the destination schema; empty defaults to "dbo".
	Schema string

	// Table is the destination table name (unquoted).
	Table string

	// Columns are the destination columns, in the order each row supplies
	// its values. Required.
	Columns []string

	// Options tunes the load; the zero value is fine.
	Options BulkOptions
}

BulkCopy describes the destination of a bulk-insert load.

type BulkOptions added in v0.0.4

type BulkOptions struct {
	// CheckConstraints enforces CHECK and FOREIGN KEY constraints on the
	// incoming rows. Off by default (as with bcp), which is faster but can
	// admit rows a normal INSERT would reject.
	CheckConstraints bool

	// FireTriggers fires AFTER INSERT triggers on the destination table.
	// Off by default, so triggers do not run during the load.
	FireTriggers bool

	// KeepNulls keeps NULLs supplied by the source instead of substituting
	// the destination column's DEFAULT.
	KeepNulls bool

	// TableLock takes a bulk-update (BU) lock on the table for the duration
	// of the load rather than acquiring row/page locks — faster for a
	// dedicated import.
	TableLock bool

	// RowsPerBatch hints the number of rows per batch sent to the server.
	// Zero lets the server decide.
	RowsPerBatch int

	// KilobytesPerBatch hints the batch size in kilobytes. Zero lets the
	// server decide.
	KilobytesPerBatch int

	// Order names the columns the source rows are already sorted by (each
	// entry a column optionally followed by " ASC"/" DESC"). When it matches
	// the destination's clustered index the server can skip an internal sort.
	Order []string
}

BulkOptions tunes a bulk-copy load, mirroring the WITH options of T-SQL's INSERT BULK. The zero value performs a plain load with server defaults.

type Capabilities added in v0.0.10

type Capabilities struct {
	// ServerRoles maps each name in ProbedServerRoles to membership.
	ServerRoles map[string]bool

	// ServerPermissions maps each name in ProbedServerPermissions to its state.
	ServerPermissions map[string]CapabilityState

	// ExplicitServerPermissions maps a server securable — keyed by
	// ServerSecurableKey, so a login, a server role and an endpoint of the
	// same name stay apart — to the state each name in
	// ProbedServerSecurablePermissions is *explicitly* recorded in for the
	// login, read out of sys.server_permissions rather than asked with
	// HAS_PERMS_BY_NAME. Read it through DeniedOnLogin, DeniedOnServerRole,
	// DeniedOnEndpoint or the kind-taking DeniedOnServerSecurable.
	//
	// It is DatabaseCapabilities.ExplicitPrincipalPermissions' server-scope
	// twin and exists for the same reason: a class-101 DENY overrides the
	// server-wide ALTER ANY LOGIN a gate would otherwise read as permission,
	// and HAS_PERMS_BY_NAME cannot tell that DENY from a permission never
	// granted — it answers 0 for both.
	//
	// Sparse in ObjectPermissions' sense: a securable nobody denied anything
	// on has no row. Only DENY rows are read, for ExplicitDatabasePermissions'
	// reason — the grant direction is already answered, and answered better,
	// by HAS_PERMS_BY_NAME in ServerPermissions.
	//
	// **The three kinds are recorded alike and answer differently, and a
	// caller must not treat them alike.** Probed live on majors 13 and 17
	// (2026-09-04, identical on both), with HAS_PERMS_BY_NAME reading 0 for
	// the denied ALTER in every row including the two the server goes on to
	// allow:
	//
	//   - LOGIN: DENY ALTER ON LOGIN::x withholds ALTER LOGIN — rename and
	//     password alike — and DROP LOGIN, with no exceptions (Msg 15151).
	//   - SERVER ROLE: DENY ALTER ON SERVER ROLE::r withholds
	//     ALTER SERVER ROLE ... ADD MEMBER / DROP MEMBER (Msg 15151) and does
	//     *not* withhold the rename (WITH NAME) or DROP SERVER ROLE. This is
	//     the database role's split, not the login's all-or-nothing: a gate
	//     reading this map over a server role's rename withholds an action the
	//     server allows.
	//   - ENDPOINT: DENY ALTER ON ENDPOINT::e withholds ALTER ENDPOINT, and
	//     the refusal is Msg 6004 rather than 15151.
	//
	// Membership also checks ALTER on the *member*: adding a login carrying a
	// class-101 DENY to a server role nobody denied is refused too, so a
	// membership gate has to ask about both principals.
	ExplicitServerPermissions map[string]map[string]CapabilityState

	// AvailabilityGroupPermissions maps each availability group on the
	// instance to the state of each name in
	// ProbedAvailabilityGroupPermissions on it. Read it through
	// PermitsOnAvailabilityGroup or HasOnAvailabilityGroup.
	//
	// Unlike ExplicitServerPermissions this is a HAS_PERMS_BY_NAME answer, not
	// a catalog read — see ProbedAvailabilityGroupPermissions for why it has
	// to be — so it is *not* sparse: every group on the instance has a row,
	// and a missing group means the probe did not run rather than that nothing
	// was recorded. It is also, for that reason, the one server-scope map that
	// can be read in the Allows direction.
	//
	// What a class-108 DENY withholds, probed live on the two-node cluster
	// (major 17, 2026-09-05) with the server-wide ALTER ANY AVAILABILITY GROUP
	// held throughout: **every ALTER AVAILABILITY GROUP there is** — the
	// options SET, ADD DATABASE, REMOVE DATABASE, MODIFY REPLICA and FAILOVER,
	// each Msg 15151. This is the login's all-or-nothing shape, not the server
	// role's split.
	//
	// It does *not* withhold ALTER DATABASE ... SET HADR SUSPEND / RESUME,
	// which is checked against the database rather than the group and goes
	// through with the DENY in place.
	AvailabilityGroupPermissions map[string]map[string]CapabilityState
}

Capabilities is what the connected login may do at the server scope: its fixed-server-role memberships and the state of each permission in ProbedServerPermissions.

Obtain one with Server.Capabilities. Every method is nil-safe, so a caller that could not probe — or chose not to — can hold a nil *Capabilities and still ask questions of it.

func (*Capabilities) Allows added in v0.0.10

func (c *Capabilities) Allows(name string) bool

Allows reports that the permission is not known to be denied — granted, or unknown. Use it to decide whether to *withhold* something.

The asymmetry with Has is the whole point, and gating on the wrong one is the mistake this pair exists to prevent. A probe that failed, or an instance that does not define the permission, leaves every answer Unknown; gating a menu item on Has would then hide the entire application from a login that may well be a sysadmin. The server remains the authority — withholding is only ever a courtesy, and it must fail open.

func (*Capabilities) AvailabilityGroupPermission added in v0.0.12

func (c *Capabilities) AvailabilityGroupPermission(group, name string) CapabilityState

AvailabilityGroupPermission returns the state of one AVAILABILITY GROUP-scope permission on the named group. A group that does not exist, or a name that was never probed — including every group of a server that was not probed at all — is CapabilityUnknown.

func (*Capabilities) DeniedOnEndpoint added in v0.0.12

func (c *Capabilities) DeniedOnEndpoint(name, permission string) bool

DeniedOnEndpoint is DeniedOnServerSecurable for an endpoint (class 105). Its DENY withholds ALTER ENDPOINT, refused with Msg 6004.

func (*Capabilities) DeniedOnLogin added in v0.0.12

func (c *Capabilities) DeniedOnLogin(name, permission string) bool

DeniedOnLogin is DeniedOnServerSecurable for a login (class 101, type_desc SQL_LOGIN and friends). Its DENY is all-or-nothing: it withholds ALTER LOGIN and DROP LOGIN alike.

func (*Capabilities) DeniedOnServerRole added in v0.0.12

func (c *Capabilities) DeniedOnServerRole(name, permission string) bool

DeniedOnServerRole is DeniedOnServerSecurable for a server role (class 101, type_desc SERVER_ROLE). Its DENY withholds the role's membership edits and *not* its rename or its drop — see ExplicitServerPermissions, where the live result is recorded.

func (*Capabilities) DeniedOnServerSecurable added in v0.0.12

func (c *Capabilities) DeniedOnServerSecurable(kind ServerSecurableKind, name, permission string) bool

DeniedOnServerSecurable reports that the permission is explicitly denied on one server securable — ServerPermissions' withholding counterpart, and the only sound read of ExplicitServerPermissions.

It is sound where an Allows-style read of the sparse map would not be, for DeniedOnObject's reason: it asks for a state that was recorded rather than for the absence of one, so a securable nobody denied reads unknown, which is not a denial.

A caller may withhold on it because SQL Server resolves a server-scope DENY over the server-wide ALTER ANY LOGIN / ALTER ANY SERVER ROLE / ALTER ANY ENDPOINT that would otherwise permit the write — but *which* writes it withholds depends on the kind, and one of the three answers is a split rather than an all-or-nothing. Read ExplicitServerPermissions before gating on this; a gate that assumes the login's answer for a server role withholds a rename the server allows.

One exception belongs to the caller, as at every other scope: a member of sysadmin bypasses the check and must be asked about first, because the probe's principal set includes public and a DENY made to public is recorded for a sysadmin whose write SQL Server still allows.

func (*Capabilities) Has added in v0.0.10

func (c *Capabilities) Has(name string) bool

Has reports that the permission is known to be held. Use it to *offer* something extra.

func (*Capabilities) HasOnAvailabilityGroup added in v0.0.12

func (c *Capabilities) HasOnAvailabilityGroup(group, name string) bool

HasOnAvailabilityGroup reports that the permission is known to be held on the group — the test for offering something extra. See Capabilities.Has.

func (*Capabilities) InServerRole added in v0.0.10

func (c *Capabilities) InServerRole(name string) bool

InServerRole reports whether the login is a member of the named fixed server role.

sysadmin is *not* folded in, because SQL Server does not fold it in either: IS_SRVROLEMEMBER('SQLAgentUserRole') is 0 for sa. Where a feature accepts either, ask for both. Permissions need no such care — HAS_PERMS_BY_NAME already answers 1 for a sysadmin on every server permission.

func (*Capabilities) IsSysadmin added in v0.0.10

func (c *Capabilities) IsSysadmin() bool

IsSysadmin reports membership in the sysadmin fixed server role.

func (*Capabilities) Permission added in v0.0.10

func (c *Capabilities) Permission(name string) CapabilityState

Permission returns the state of one server permission. A name that was never probed — including a misspelt one — is CapabilityUnknown.

func (*Capabilities) PermitsOnAvailabilityGroup added in v0.0.12

func (c *Capabilities) PermitsOnAvailabilityGroup(group, name string) bool

PermitsOnAvailabilityGroup reports that the permission is not known to be denied on the group — the test for withholding something scoped to one availability group. See Capabilities.Allows for why unknown must permit.

It is sound in the withholding direction where the other server-scope maps are not, because this one is not sparse: every group on a probed instance has a row, so a 0 is an answer rather than a silence. What that 0 cannot tell apart is a DENY on the group from a login that holds nothing at this scope at all — and the second is already withheld by the server-wide permission a caller asks about beside this, so the two collapse to the same decision.

func (*Capabilities) Probed added in v0.0.10

func (c *Capabilities) Probed() bool

Probed reports whether these capabilities came from a server that answered.

The zero value and a failed probe are both "nothing known", and every permission accessor already treats that as unknown — but a *role* test cannot: InServerRole answers false for a role that was never asked about, exactly as it does for one the login is not in. A caller that would withhold something on "not a member" must check this first, or an unprobed connection silently loses whatever the role guards.

type CapabilityState added in v0.0.10

type CapabilityState int

CapabilityState is the answer to "does the connected login hold this permission?" — the three-way answer HAS_PERMS_BY_NAME actually gives.

The third state is not padding. HAS_PERMS_BY_NAME returns NULL, without raising an error, for a permission name the instance does not define, so a permission introduced in a later version reads as CapabilityUnknown on an older one rather than as denied. A caller that folds Unknown into Denied hides a feature on every instance that has it under a different name.

const (
	// CapabilityUnknown means the answer is not available: the permission is
	// not one this instance defines, or it was never probed, or the probe
	// itself failed. It is not a denial — see Capabilities.Allows.
	CapabilityUnknown CapabilityState = iota

	// CapabilityGranted means the login holds the permission, whether
	// directly, through a role, or through a wider permission that implies
	// it.
	CapabilityGranted

	// CapabilityDenied means the instance was asked and said no.
	CapabilityDenied
)

func (CapabilityState) String added in v0.0.10

func (s CapabilityState) String() string

type Catalog added in v0.0.5

type Catalog struct {
	Schemas []string
	Objects []CatalogObject
}

Catalog is a bulk snapshot of every user table and view in a database, each with its columns already loaded — see Database.Catalog.

type CatalogColumn added in v0.0.5

type CatalogColumn struct {
	Name       string
	DataType   DataType
	MaxLength  int
	Precision  int
	Scale      int
	IsNullable bool
}

CatalogColumn is one column of a CatalogObject — the subset of Column's fields relevant to identifying and describing a column, without the per-table detail (identity, computed, default, rowguid) that a bulk snapshot has no need for.

type CatalogObject added in v0.0.5

type CatalogObject struct {
	ObjectID int
	Schema   string
	Name     string
	Type     CatalogObjectType
	Columns  []CatalogColumn
}

CatalogObject is one table or view and its columns, in ordinal order.

type CatalogObjectType added in v0.0.5

type CatalogObjectType int

CatalogObjectType distinguishes a Catalog entry's underlying object kind.

const (
	CatalogTable CatalogObjectType = iota
	CatalogView
)

type Category added in v0.0.6

type Category struct {
	ID    int
	Class CategoryClass
	Name  string
}

Category represents a SQL Server Agent job, alert, or operator category (msdb.dbo.syscategories) — Class says which.

type CategoryClass added in v0.0.6

type CategoryClass string

CategoryClass is the msdb.dbo.syscategories.category_class value a Category belongs to — also the literal sp_add_category/sp_delete_category @class parameter.

const (
	CategoryClassJob      CategoryClass = "JOB"
	CategoryClassAlert    CategoryClass = "ALERT"
	CategoryClassOperator CategoryClass = "OPERATOR"
)

type Certificate added in v0.0.9

type Certificate struct {
	Name          string
	CertificateID int
	PrincipalID   int

	// Subject is the certificate's subject as SQL Server decoded it.
	Subject string

	// PvtKeyEncryptionType is how the private key is protected —
	// "ENCRYPTED_BY_MASTER_KEY", "ENCRYPTED_BY_PASSWORD", or "NO_PRIVATE_KEY"
	// for one imported from a public certificate alone. An endpoint's own
	// certificate must be ENCRYPTED_BY_MASTER_KEY, because the private key has
	// to be openable without anyone typing a password.
	PvtKeyEncryptionType string

	StartDate  time.Time
	ExpiryDate time.Time

	Thumbprint []byte
	// contains filtered or unexported fields
}

Certificate mirrors a row of sys.certificates.

func (*Certificate) Drop added in v0.0.9

func (c *Certificate) Drop() error

Drop deletes the certificate.

func (*Certificate) DropContext added in v0.0.9

func (c *Certificate) DropContext(ctx context.Context) error

DropContext is the context-aware variant of Drop.

func (*Certificate) Encoded added in v0.0.9

func (c *Certificate) Encoded() ([]byte, error)

Encoded returns the ASN.1-encoded public certificate — what CreateCertificate's FromBinary takes, and the whole of what one instance needs to give another to authenticate it. The private key is not included and cannot be obtained this way.

func (*Certificate) EncodedContext added in v0.0.9

func (c *Certificate) EncodedContext(ctx context.Context) ([]byte, error)

EncodedContext is the context-aware variant of Encoded.

func (*Certificate) HasPrivateKey added in v0.0.9

func (c *Certificate) HasPrivateKey() bool

HasPrivateKey reports whether this instance holds the certificate's private key, i.e. can present it rather than only verify against it.

type CertificateSpec added in v0.0.9

type CertificateSpec struct {
	Name string

	// Authorization is the database user that will own the certificate. Empty
	// leaves it owned by the caller. An imported peer certificate is normally
	// owned by a user created for it, so that CONNECT on the endpoint can be
	// granted to that user's login.
	Authorization string

	// Subject is the certificate subject for a newly generated certificate.
	Subject string

	// StartDate and ExpiryDate bound a newly generated certificate. Zero
	// values omit the clause, which SQL Server defaults to one year from now.
	StartDate  time.Time
	ExpiryDate time.Time

	// EncryptionPassword protects the new certificate's private key with a
	// password instead of the database master key. Leave it empty for an
	// endpoint certificate: the private key has to open without a password.
	EncryptionPassword string

	// FromBinary is an ASN.1-encoded public certificate, as returned by
	// Certificate.Encoded. Mutually exclusive with Subject.
	FromBinary []byte
}

CertificateSpec describes a certificate to create.

Exactly one origin: either FromBinary, which imports an existing public certificate, or a Subject, which has SQL Server generate a new key pair.

type ChangeTrackingInfo added in v0.0.4

type ChangeTrackingInfo struct {
	Enabled         bool
	AutoCleanup     bool
	RetentionPeriod int
	RetentionUnit   string // e.g. "DAYS", "HOURS", "MINUTES"
}

ChangeTrackingInfo holds database-level change tracking settings.

type CheckConstraint

type CheckConstraint struct {
	Name       string
	Definition string
	IsDisabled bool
	Column     string // empty for table-level checks
}

CheckConstraint represents a CHECK constraint.

type ClrType added in v0.0.13

type ClrType struct {
	Name       string
	Schema     string
	UserTypeID int

	// MaxLength is the serialized length in bytes, -1 for a MAX type.
	MaxLength int
	Precision int
	Scale     int

	// IsNullable is the type's own nullability.
	IsNullable bool

	// Assembly and AssemblyClass name the implementation. Both come from
	// sys.assembly_types, and are empty on the rare row that has none.
	Assembly      string
	AssemblyClass string
	// contains filtered or unexported fields
}

ClrType is a user-defined type implemented by a CLR assembly — a sys.types row with is_assembly_type = 1.

func (*ClrType) Database added in v0.0.13

func (t *ClrType) Database() *Database

Database returns the database the type belongs to.

func (*ClrType) Drop added in v0.0.13

func (t *ClrType) Drop() error

Drop drops the CLR type.

func (*ClrType) DropContext added in v0.0.13

func (t *ClrType) DropContext(ctx context.Context) error

DropContext is the context-aware variant of Drop.

func (*ClrType) FullName added in v0.0.13

func (t *ClrType) FullName() string

FullName returns the schema-qualified, bracket-quoted name.

type Column

type Column struct {
	Name              string
	OrdinalPosition   int
	DataType          DataType
	MaxLength         int // -1 = MAX
	Precision         int
	Scale             int
	IsNullable        bool
	IsIdentity        bool
	IdentitySeed      int64
	IdentityIncrement int64
	IsComputed        bool
	ComputedText      string
	DefaultValue      *ColumnDefault
	IsRowGUID         bool
	Collation         string
	IsPrimaryKey      bool
}

Column mirrors Microsoft.SqlServer.Management.Smo.Column.

type ColumnDefault

type ColumnDefault struct {
	Name       string
	Definition string // e.g. "(getdate())" or "((0))"
}

ColumnDefault represents a column default constraint.

type ColumnDefinition

type ColumnDefinition struct {
	Name         string
	DataType     DataType
	MaxLength    int // char/varchar/nchar/nvarchar: 0 = omit, -1 = MAX
	Precision    int // decimal/numeric
	Scale        int // decimal/numeric / datetime2 / time
	IsNullable   bool
	IsIdentity   bool
	IdentitySeed int64
	IdentityIncr int64
	DefaultValue string // expression, e.g. "sysdatetime()" or "0"
	IsPrimaryKey bool
}

ColumnDefinition describes a column in a CREATE TABLE statement.

type ColumnEncryptionKey

type ColumnEncryptionKey struct {
	Name string
	ID   int
	// MasterKeyName and EncryptionAlgorithm mirror Values[0] — the key's first
	// encrypted value, which is the whole of it in the common case where a key
	// has exactly one. AddValue and DropValue re-seat them, so a caller
	// rendering a summary from the handle it already holds never names a
	// master key the rotation has dropped. Both are empty when Values is.
	MasterKeyName       string
	EncryptionAlgorithm string
	// Values holds every encrypted value of the key, one per column master
	// key it is encrypted under. A key has two while its master key is being
	// rotated, and CREATE COLUMN ENCRYPTION KEY has to restate all of them.
	Values []*ColumnEncryptionKeyValue
	// contains filtered or unexported fields
}

ColumnEncryptionKey mirrors sys.column_encryption_keys.

func (*ColumnEncryptionKey) AddValue added in v0.0.11

func (cek *ColumnEncryptionKey) AddValue(value ColumnEncryptionKeyValue) error

AddValue encrypts the key under one more column master key, the first half of a master-key rotation: both values coexist so clients holding either master key can still decrypt, and the old one is dropped with DropValue once every client has the new master key.

As with CreateColumnEncryptionKey, the encrypted value is produced client-side by something that can reach the new master key — nothing here can generate it, and the server stores it without checking it.

func (*ColumnEncryptionKey) AddValueContext added in v0.0.11

func (cek *ColumnEncryptionKey) AddValueContext(ctx context.Context, value ColumnEncryptionKeyValue) error

AddValueContext is the context-aware variant of AddValue.

func (*ColumnEncryptionKey) Drop

func (cek *ColumnEncryptionKey) Drop() error

Drop drops the column encryption key.

func (*ColumnEncryptionKey) DropContext added in v0.0.5

func (cek *ColumnEncryptionKey) DropContext(ctx context.Context) error

DropContext is the context-aware variant of Drop.

func (*ColumnEncryptionKey) DropValue added in v0.0.11

func (cek *ColumnEncryptionKey) DropValue(masterKeyName string) error

DropValue removes the value encrypted under one column master key — the second half of a rotation.

The data encrypted with this key becomes unreadable to any client that can reach only the dropped master key, so the new value must be in place and distributed first. DROP VALUE names the master key alone; the ciphertext is not restated.

func (*ColumnEncryptionKey) DropValueContext added in v0.0.11

func (cek *ColumnEncryptionKey) DropValueContext(ctx context.Context, masterKeyName string) error

DropValueContext is the context-aware variant of DropValue.

type ColumnEncryptionKeyValue added in v0.0.10

type ColumnEncryptionKeyValue struct {
	MasterKeyName       string
	EncryptionAlgorithm string
	// EncryptedValue is the key material encrypted under the master key.
	// Scripting the key means reproducing these bytes exactly; nothing can
	// regenerate them.
	EncryptedValue []byte
}

ColumnEncryptionKeyValue is one encrypted value of a column encryption key, from sys.column_encryption_key_values.

type ColumnMasterKey

type ColumnMasterKey struct {
	Name                     string
	ID                       int
	KeyStoreProviderName     string
	KeyPath                  string
	AllowEnclaveComputations bool
	// Signature is the digital signature over the key's metadata, required
	// verbatim by CREATE COLUMN MASTER KEY's ENCLAVE_COMPUTATIONS clause —
	// it can't be recomputed from the other fields, so a key that allows
	// enclave computations cannot be scripted without it. Empty for a key
	// that doesn't.
	Signature []byte
	// contains filtered or unexported fields
}

ColumnMasterKey mirrors sys.column_master_keys.

func (*ColumnMasterKey) Drop

func (cmk *ColumnMasterKey) Drop() error

Drop drops the column master key.

func (*ColumnMasterKey) DropContext added in v0.0.5

func (cmk *ColumnMasterKey) DropContext(ctx context.Context) error

DropContext is the context-aware variant of Drop.

type ColumnPermissionEntry added in v0.0.8

type ColumnPermissionEntry struct {
	Principal     string
	PrincipalType string // e.g. "DATABASE_ROLE", "SQL_USER"
	Grantor       string
	Schema        string
	Object        string

	// ObjectType is what the column's parent is — "TABLE" or "VIEW", the
	// same values PrincipalSecurable.SecurableType uses, so a caller can key
	// both against one securable identity. Both types carry column
	// permissions and sys.database_permissions records them identically, so
	// without this a view's grants get mistaken for a table's.
	ObjectType string

	Column     string
	Permission ObjectPermission
	State      PermissionState // "GRANT", "GRANT_WITH_GRANT_OPTION", "DENY"
}

ColumnPermissionEntry is one GRANT/DENY entry recorded on a single column of a table or view — what sys.database_permissions stores as an OBJECT_OR_COLUMN row with a non-zero minor_id. Object-level entries (minor_id 0) are reported by Permissions instead, and the two are genuinely separate grants: a column DENY overrides an object GRANT.

type CompatibilityLevel

type CompatibilityLevel int

CompatibilityLevel mirrors SQL Server database compatibility levels.

const (
	CompatLevel2008 CompatibilityLevel = 100
	CompatLevel2012 CompatibilityLevel = 110
	CompatLevel2014 CompatibilityLevel = 120
	CompatLevel2016 CompatibilityLevel = 130
	CompatLevel2017 CompatibilityLevel = 140
	CompatLevel2019 CompatibilityLevel = 150
	CompatLevel2022 CompatibilityLevel = 160
	CompatLevel2025 CompatibilityLevel = 170
)

type ConfigurationOption

type ConfigurationOption struct {
	ConfigID    int
	Name        string
	Value       int64
	ValueInUse  int64
	Minimum     int64
	Maximum     int64
	IsDynamic   bool // true = change takes effect without a restart
	IsAdvanced  bool
	Description string
	// contains filtered or unexported fields
}

ConfigurationOption mirrors a row from sys.configurations.

func (*ConfigurationOption) SetValue

func (c *ConfigurationOption) SetValue(value int64) error

SetValue changes the option value using sp_configure. For non-dynamic options, call Server.Reconfigure() afterwards.

func (*ConfigurationOption) SetValueContext

func (c *ConfigurationOption) SetValueContext(ctx context.Context, value int64) error

SetValueContext is the context-aware variant of SetValue.

type ConnectionOptions

type ConnectionOptions struct {

	// Server is the host[:port] or host\instance, e.g. "localhost:1433" or
	// "myserver.database.windows.net". Required.
	Server string

	// Database to connect to initially. Defaults to "master".
	Database string

	// Auth selects the authentication strategy. Defaults to AuthSQLServer.
	Auth AuthMethod

	// User is the SQL Server login, Windows UPN, Entra user UPN (the sign-in
	// name for AuthEntraPassword, a login hint for AuthEntraInteractive), or
	// Entra application client ID (service principal, on-behalf-of, Azure
	// Pipelines), depending on the Auth method chosen.
	User string

	// Password is the SQL Server password, Entra user password, or client secret.
	Password string

	// TenantID is the Entra tenant (directory) ID to sign in to, for every
	// Entra method whose credential takes one — all but AuthEntraMSI and
	// AuthEntraServicePrincipalAccessToken, which ignore it. Left empty,
	// AuthEntraServicePrincipal, AuthEntraOnBehalfOf, AuthEntraAzurePipelines,
	// AuthEntraPassword, AuthEntraInteractive and AuthEntraDeviceCode sign in
	// to the tenant the server names at login, as SSMS does; the rest use
	// their credential's own default (the CLI's signed-in tenant, or the
	// environment's). For the first three it also travels in the DSN as the
	// "@tenant" suffix of the client ID.
	TenantID string

	// ClientID selects a user-assigned Managed Identity when Auth=AuthEntraMSI.
	// It is not the application client ID of the other Entra methods: that is
	// User for service principal, on-behalf-of and Azure Pipelines, and
	// ApplicationClientID for the public-client (human) flows.
	ClientID string

	// ClientCertPath is the path to a PEM/PFX certificate for
	// Auth=AuthEntraServicePrincipal certificate-based auth.
	ClientCertPath string

	// ClientCertPassword is the private-key password for ClientCertPath.
	ClientCertPassword string

	// AccessToken is a pre-acquired bearer token for
	// Auth=AuthEntraServicePrincipalAccessToken, or the inbound user assertion
	// for AuthEntraOnBehalfOf. The former is embedded once at connect time;
	// prefer AccessTokenProvider when the token can expire during the
	// connection's lifetime.
	AccessToken string

	// AccessTokenProvider, when set, is called to obtain a bearer token for
	// each new pooled connection, so tokens that expire (e.g. Entra tokens,
	// good for ~1 hour) are refreshed automatically rather than embedded
	// once and going stale. It takes precedence over AccessToken and Auth:
	// the token is presented directly to SQL Server, bypassing the fedauth
	// DSN machinery, so it works for any scenario where the caller mints
	// its own tokens. The error it returns aborts the connection attempt.
	AccessTokenProvider func(ctx context.Context) (string, error)

	// ApplicationClientID is the client ID of the public client application
	// the human sign-in flows go through: AuthEntraPassword,
	// AuthEntraInteractive and AuthEntraDeviceCode. Set it when the tenant
	// requires its own app registration; empty uses the public client
	// azidentity defaults to (04b07795-8ddb-461a-bbee-02f9e1bf7b46). Ignored
	// by every other method.
	ApplicationClientID string

	// ServerSPN overrides the Kerberos service principal name of the target
	// instance (e.g. "MSSQLSvc/host.contoso.com:1433"). Used only with
	// AuthWindows. Leave empty to let the driver derive it from the address,
	// which is correct for most host:port connections.
	ServerSPN string

	// Kerberos configures Active Directory authentication for AuthWindows.
	// It matters mainly on non-Windows hosts, where AuthWindows authenticates
	// via Kerberos rather than native SSPI; see KerberosOptions. The zero
	// value uses the host's ambient Kerberos setup (krb5.conf + kinit cache).
	Kerberos KerberosOptions

	// Encrypt controls the encryption mode.
	// "" - driver default (true for Azure endpoints, false otherwise)
	// "true" / "mandatory" - always encrypt
	// "false" / "optional" - encrypt the login packet only
	// "disable" - no encryption at all, not even the login
	// "strict" - TDS 8.0 strict encryption
	Encrypt string

	// TrustServerCertificate disables TLS certificate validation.
	// Handy for dev/local instances; do not use in production.
	TrustServerCertificate bool

	// HostNameInCertificate overrides the expected server name in the TLS cert.
	// Useful when connecting via IP address or when the cert CN differs.
	HostNameInCertificate string

	// DisableInstanceDiscovery disables OIDC instance discovery.
	// Set true only for disconnected or private clouds (e.g. Azure Stack).
	DisableInstanceDiscovery bool

	// SendCertificateChain controls whether the full certificate chain is sent
	// in token requests (needed for Subject Name/Issuer SNI auth).
	SendCertificateChain bool

	// TokenFilePath is the path to a Kubernetes service account token file
	// for Workload Identity. go-mssqldb reads it only for its
	// ActiveDirectoryWorkloadIdentity workflow, which no AuthMethod selects
	// yet: it is written to the DSN for AuthEntraMSI, and has no effect there.
	TokenFilePath string

	// EntraCache holds the Entra credentials and tokens connections share, so
	// that an Entra method signs in once per identity rather than once per
	// physical connection — the difference between one browser sign-in and one
	// per pooled connection for AuthEntraInteractive. Share one across every
	// Connect that should share a sign-in, and call its Warm first to sign in
	// under a context of your choosing. Nil gives the Server a private cache of
	// its own: its connections share a sign-in, other Servers' do not.
	EntraCache *EntraCache

	// DeviceCodePrompt, when set, is called with the code and URL the user must
	// visit for AuthEntraDeviceCode, in place of azidentity's default of
	// printing them to standard output — which a terminal UI, a GUI or a
	// service cannot show. It runs on the goroutine that is connecting (or
	// warming the cache) and should return promptly; sign-in completes, or
	// times out with that goroutine's context, after it returns. A credential
	// an EntraCache shares uses the prompt of the most recent connection
	// through it that set one.
	DeviceCodePrompt func(ctx context.Context, m DeviceCodeMessage) error

	// ConnectTimeout is the maximum time to wait for the initial connection.
	// Defaults to 30s when zero.
	ConnectTimeout time.Duration

	// ApplicationName is shown in sys.dm_exec_sessions.program_name.
	// Defaults to "gosmo".
	ApplicationName string

	// MaxOpenConns is the maximum number of open connections in the pool.
	// 0 means unlimited.
	MaxOpenConns int

	// MaxIdleConns is the maximum number of idle connections kept in the pool.
	// Defaults to 2.
	MaxIdleConns int

	// ConnMaxLifetime is the maximum lifetime of a pooled connection.
	// 0 means unlimited.
	ConnMaxLifetime time.Duration

	// ConnMaxIdleTime is the maximum time a pooled connection may sit idle
	// before it's closed and evicted rather than handed out again. This is
	// what guards against a connection silently dropped while idle — a
	// firewall/NAT idle timeout, a load balancer, or the server itself
	// closing a long-idle session — sitting in the pool looking usable
	// until something actually tries it and fails. Defaults to 5 minutes
	// when zero.
	ConnMaxIdleTime time.Duration

	// Dialer, when set, is used for every network operation the driver
	// performs — the TDS connection itself and the SQL Server Browser probe
	// that resolves a named instance's port. Use it to route connections
	// through a proxy or an SSH tunnel, or to control address selection.
	// A dialer that also implements mssql.HostDialer has DNS resolved on its
	// own network.
	//
	// Leave it nil for the default, which is the driver's own dialer except
	// when Server names an instance with no port: that case needs a Browser
	// probe, and gosmo substitutes a dialer that sends it to every resolved
	// address rather than only the first, and reuses a reply for up to two
	// minutes rather than probing for every new pooled connection — any
	// failed connection attempt discards it (see dialer.go).
	Dialer mssql.Dialer

	// SessionInitSQL is T-SQL executed on every pooled connection right
	// after it is reset, before the first query runs on it. Use it to apply
	// SET options that must hold for the whole session (the equivalent of
	// SSMS's Query Execution options), e.g. "SET ARITHABORT ON; SET
	// ANSI_NULLS ON". Leave empty for driver defaults.
	SessionInitSQL string

	// ExtraParams carries go-mssqldb connection-string parameters that have
	// no ConnectionOptions field — "packet size", "ApplicationIntent",
	// "MultiSubnetFailover", "dial timeout", "keepalive" and the like. Keys are
	// case-insensitive, as the driver reads them; each key takes exactly one
	// value.
	//
	// A parameter that a ConnectionOptions field controls is refused, never
	// merged: server, port, database, user id and password, app name,
	// connection timeout, the TLS settings, and every authentication
	// parameter (fedauth, authenticator, the krb5-* family, tenant, client and
	// certificate settings), along with their ADO.NET synonyms ("initial
	// catalog", "uid", "trust server certificate", …). Otherwise one of the
	// two would silently override the other, and which one won would depend
	// on the driver's parsing order rather than on anything the caller wrote.
	// A refused key fails Connect and ConnectionString with an error naming it.
	ExtraParams url.Values
}

ConnectionOptions holds every parameter needed to open a connection.

Authentication quick guide:

SQL Server login:

Auth: AuthSQLServer, User: "sa", Password: "..."

Windows / Kerberos (on-premises, domain-joined host):

Auth: AuthWindows (no User/Password needed)

On Linux/macOS this uses Kerberos; run "kinit" first for single sign-on, or set the Kerberos field for a keytab, realm, or custom krb5.conf.

Azure Managed Identity (system-assigned):

Auth: AuthEntraMSI, Server: "myserver.database.windows.net"

Azure Managed Identity (user-assigned):

Auth: AuthEntraMSI, ClientID: "<managed-identity-client-id>"

Service Principal (client secret):

Auth: AuthEntraServicePrincipal
User: "<app-client-id>", TenantID: "<tenant-id>", Password: "<client-secret>"

(or User: "<app-client-id>@<tenant-id>" with no TenantID — not both, unless they name the same tenant).

Service Principal (certificate):

Auth: AuthEntraServicePrincipal
User: "<app-client-id>[@<tenant-id>]", ClientCertPath: "/path/to/cert.pem"

Default credential chain (env vars -> MSI -> AzCLI):

Auth: AuthEntraDefault

Azure CLI credential (az login):

Auth: AuthEntraAzCLI

func (ConnectionOptions) ConnectionString added in v0.0.13

func (o ConnectionOptions) ConnectionString(maskSecrets bool) (string, error)

ConnectionString renders the go-mssqldb connection string Connect would dial for o: the same builder, after the same defaults, so the result carries "database=master", the application name and the connect timeout exactly as they are sent, and fails with the error Connect would fail with for the same options. Use it to show a user what is being dialled, to log it, or to hand it to another go-mssqldb client.

With maskSecrets, every password, client secret, certificate password, access token and user assertion in it is replaced by a fixed placeholder, so the result is safe to display — and no longer connects. Unmasked, it is a live credential. The tokens an AccessTokenProvider mints never appear either way: they are fetched per connection and are not part of the string.

type CreateAlertRequest added in v0.0.6

type CreateAlertRequest struct {
	Name    string
	Enabled bool
	// ErrorNumber and Severity are mutually exclusive triggers — leave
	// whichever isn't in use at 0.
	ErrorNumber               int
	Severity                  int
	DatabaseName              string
	DelayBetweenResponses     time.Duration
	NotificationMessage       string
	IncludeEventDescriptionIn int
	Category                  string
}

CreateAlertRequest describes a new SQL Server event alert.

type CreateAvailabilityGroupRequest added in v0.0.9

type CreateAvailabilityGroupRequest struct {
	// Name is the group's name. Required.
	Name string

	// ClusterType is WSFC, EXTERNAL or NONE. Empty omits the clause, which
	// means WSFC — and fails on an instance with no Windows cluster under it,
	// so Linux callers must set this.
	ClusterType string

	// AutomatedBackupPreference is PRIMARY, SECONDARY_ONLY, SECONDARY or NONE.
	// Empty omits the clause.
	AutomatedBackupPreference string

	// FailureConditionLevel is 1-5; zero omits the clause.
	FailureConditionLevel int

	// HealthCheckTimeout is milliseconds; zero omits the clause.
	HealthCheckTimeout int

	// DBFailover turns on database-level health detection.
	DBFailover bool

	// DTCSupport requests DTC_SUPPORT = PER_DB.
	DTCSupport bool

	// RequiredSynchronizedSecondariesToCommit is SQL Server 2017+. Negative
	// omits the clause; zero is a legitimate value and is written.
	RequiredSynchronizedSecondariesToCommit int

	// Basic creates a Basic availability group (Standard edition): one
	// database, two replicas, no readable secondary.
	Basic bool

	// Contained creates a contained availability group, which carries its own
	// master and msdb. SQL Server 2022+.
	Contained bool

	// Databases are the databases to include. May be empty — a group with no
	// databases is legal and is how the "add them afterwards" flow starts.
	// Each must already be in full recovery with a full backup taken.
	Databases []string

	// Replicas are the group's replicas, primary first: CREATE AVAILABILITY
	// GROUP makes the instance it runs on the primary, so the first entry has
	// to name that instance. At least one is required.
	Replicas []AvailabilityReplicaSpec
}

CreateAvailabilityGroupRequest describes an availability group to create.

type CreateDatabaseOptions

type CreateDatabaseOptions struct {
	Collation     string
	RecoveryModel RecoveryModel
	CompatLevel   CompatibilityLevel

	// PrimaryFile and LogFile customize the database's initial data and
	// log file (name, path, size, growth, max size) via CREATE DATABASE's
	// ON PRIMARY/LOG ON clauses. Leaving either nil lets the server place
	// that file at its own default path/size, exactly like CreateDatabase
	// with a zero-valued CreateDatabaseOptions always has — for a nil
	// PrimaryFile beside a LogFile, by naming that default file explicitly,
	// since SQL Server refuses LOG ON without a data file (see
	// defaultPrimaryFile). FileGroup is
	// ignored on both (PrimaryFile is always PRIMARY; LogFile has none) —
	// additional filegroups and files are added after creation via
	// AddFileGroupContext/AddFileContext, not here.
	PrimaryFile *DatabaseFileSpec
	LogFile     *DatabaseFileSpec
}

CreateDatabaseOptions holds optional parameters for CreateDatabase.

type CreateDatabaseSnapshotRequest added in v0.0.13

type CreateDatabaseSnapshotRequest struct {
	// Name is the new snapshot's database name.
	Name string

	// SourceDatabase is the database to snapshot.
	SourceDatabase string

	// Files is one entry per ROWS file in the source. Leave it nil to have
	// the paths defaulted from the source's own files — see
	// SnapshotFileDefaultsContext, which is what the nil case calls.
	Files []SnapshotFileSpec
}

CreateDatabaseSnapshotRequest describes a snapshot to create.

type CreateIndexRequest

type CreateIndexRequest struct {
	Name       string
	Type       IndexType
	IsUnique   bool
	KeyColumns []IndexColumnDef
	// IncludedColumns are the non-key columns of a nonclustered rowstore
	// index (INCLUDE).
	IncludedColumns []string
	// FilterDefinition is a filtered index's predicate, without the WHERE.
	FilterDefinition string
	FillFactor       int
	PadIndex         bool
	Online           bool
	SortInTempDB     bool
	// DropExisting recreates an index of the same name in place
	// (DROP_EXISTING = ON) instead of failing on the collision.
	DropExisting bool
	// DataCompression is the compression keyword — NONE, ROW or PAGE for a
	// rowstore index, COLUMNSTORE or COLUMNSTORE_ARCHIVE for a columnstore
	// one. Empty leaves it unspecified.
	DataCompression string
	// CompressionDelay is a columnstore index's COMPRESSION_DELAY, in
	// minutes. Zero leaves it unspecified.
	CompressionDelay int
	// FileGroup is the filegroup the index is created on, and
	// PartitionScheme/PartitionColumns the partition scheme it is partitioned
	// by. The two are alternatives — an index has one ON clause.
	FileGroup        string
	PartitionScheme  string
	PartitionColumns []string
	// IsPrimaryXML selects the primary XML index form; PrimaryXMLIndex and
	// SecondaryXMLType describe a secondary one, which is built over the
	// primary index named here.
	IsPrimaryXML     bool
	PrimaryXMLIndex  string
	SecondaryXMLType XMLSecondaryIndexType
	// Tessellation is a spatial index's tessellation scheme (USING).
	Tessellation SpatialTessellation
	// BoundingBox bounds a geometry index's tessellation. Required for the
	// two GEOMETRY_ schemes and rejected for the GEOGRAPHY_ ones, which
	// tessellate the whole globe.
	BoundingBox *SpatialBoundingBox
	// GridLevels is the per-level grid density (GRIDS), which only the two
	// non-automatic schemes accept.
	GridLevels SpatialGridLevels
	// CellsPerObject is the tessellation cell budget per object
	// (CELLS_PER_OBJECT), 1-8192. Zero leaves it unspecified.
	CellsPerObject int
}

CreateIndexRequest describes a new index to create. Which fields apply depends on Type, and CreateIndex refuses a combination the server would reject rather than emitting DDL that fails at the far end:

  • rowstore (CLUSTERED, NONCLUSTERED, and the zero value): key columns, IsUnique, IncludedColumns (nonclustered only), FilterDefinition (nonclustered only), FillFactor/PadIndex, DataCompression NONE/ROW/PAGE.
  • COLUMNSTORE: key columns and FilterDefinition (the filtered NCCI form), DataCompression COLUMNSTORE/COLUMNSTORE_ARCHIVE, CompressionDelay.
  • CLUSTERED COLUMNSTORE: no key columns at all — the index covers every column of the table.
  • XML: one key column (the xml one) plus IsPrimaryXML, or PrimaryXMLIndex and SecondaryXMLType for a secondary index.
  • SPATIAL: one key column (the geometry/geography one) plus Tessellation, and BoundingBox for the two GEOMETRY_ schemes.

type CreateJobRequest

type CreateJobRequest struct {
	Name        string
	Description string
	// Category defaults to [Uncategorized (Local)] when empty.
	Category   string
	OwnerLogin string
	Enabled    bool
}

CreateJobRequest describes a new SQL Server Agent job.

type CreateLoginOptions

type CreateLoginOptions struct {
	DefaultDatabase string
	MustChange      bool

	// Source selects what the login authenticates from. The zero value
	// (LoginSourceAuto) keeps CreateLogin's original behaviour: a SQL login
	// when a password is given, a Windows login when it is empty.
	Source LoginSource

	// CertificateName is the master certificate a LoginSourceCertificate
	// login maps to; required for that source and ignored otherwise.
	CertificateName string

	// AsymmetricKeyName is the master asymmetric key a
	// LoginSourceAsymmetricKey login maps to; required for that source and
	// ignored otherwise.
	AsymmetricKeyName string

	// ObjectID is the Microsoft Entra ID object id (a GUID) a
	// LoginSourceExternalProvider login names explicitly, emitted as
	// CREATE LOGIN ... FROM EXTERNAL PROVIDER WITH OBJECT_ID = '...'.
	// SQL Server 2022 and later. It resolves a display name that is
	// ambiguous in the directory — with no object id the server looks the
	// login name up itself, which is the ordinary case. Naming it for any
	// other source is an error rather than a silently ignored field.
	ObjectID string
}

CreateLoginOptions holds optional parameters for CreateLogin.

type CreateOperatorRequest added in v0.0.6

type CreateOperatorRequest struct {
	Name         string
	Enabled      bool
	EmailAddress string
	Category     string
}

CreateOperatorRequest describes a new SQL Server Agent operator.

type CreatePartitionFunctionRequest

type CreatePartitionFunctionRequest struct {
	Name       string
	InputType  DataType
	IsRight    bool
	Boundaries []string // literal boundary values, e.g. {"100","200","300"}
}

CreatePartitionFunctionRequest describes a partition function to create.

type CreateScheduleRequest added in v0.0.6

type CreateScheduleRequest struct {
	Name                 string
	Enabled              bool
	FreqType             ScheduleFreqType
	FreqInterval         int
	FreqSubdayType       ScheduleSubdayType
	FreqSubdayInterval   int
	FreqRelativeInterval int
	FreqRecurrenceFactor int
	// ActiveStartDate defaults to today if the zero Time.
	ActiveStartDate time.Time
	// ActiveEndDate means "no end date" if the zero Time.
	ActiveEndDate time.Time
	// ActiveStartTime and ActiveEndTime are HHMMSS integers.
	ActiveStartTime int
	ActiveEndTime   int
	OwnerLoginName  string
}

CreateScheduleRequest describes a new shared schedule.

type CreateSequenceRequest

type CreateSequenceRequest struct {
	Schema     string
	Name       string
	DataType   DataType // defaults to bigint
	StartValue int64
	Increment  int64
	MinValue   *int64
	MaxValue   *int64
	Cycle      bool
	Cache      *int // nil = no cache; 0 = NO CACHE; >0 = cache size
}

CreateSequenceRequest describes a new sequence.

type CreateStatisticRequest added in v0.0.10

type CreateStatisticRequest struct {
	Name    string
	Columns []string
	// SamplePercent scans that percentage of the rows (SAMPLE n PERCENT).
	// Zero lets the server pick its own sample, unless FullScan is set.
	SamplePercent int
	// FullScan reads every row (WITH FULLSCAN). An alternative to
	// SamplePercent, not a companion to it.
	FullScan bool
	// FilterDefinition is a filtered statistic's predicate, without the
	// WHERE.
	FilterDefinition string
	// NoRecompute stops the server refreshing this statistic automatically
	// (WITH NORECOMPUTE) — it then only changes when UPDATE STATISTICS runs.
	NoRecompute bool
	// Incremental builds the statistic per partition (WITH INCREMENTAL = ON),
	// which requires a partitioned table.
	Incremental bool
}

CreateStatisticRequest describes a user-defined statistic to create. Columns is ordered: the leading column is the one the histogram is built on, and every column contributes to the density vector.

type CreateTableRequest

type CreateTableRequest struct {
	Schema  string
	Name    string
	Columns []ColumnDefinition
}

CreateTableRequest describes a table to be created.

type Credential added in v0.0.4

type Credential struct {
	CredentialID int
	Name         string
	Identity     string
	CreateDate   time.Time
	ModifyDate   time.Time

	// TargetType is what the credential is bound to: empty for an ordinary
	// credential (sys.credentials.target_type is NULL there) and
	// "CRYPTOGRAPHIC PROVIDER" for one created FOR CRYPTOGRAPHIC PROVIDER.
	TargetType string

	// CryptographicProvider is the provider's name, resolved through
	// sys.cryptographic_providers, and empty for an ordinary credential.
	// It can also be empty for a provider credential the connected login
	// cannot see the provider row for — TargetType is the reliable test of
	// which kind of credential this is.
	CryptographicProvider string
	// contains filtered or unexported fields
}

Credential mirrors a row from sys.credentials — a server-level credential, listed under Security > Credentials and offered in a Login's "Map to credential" dropdown.

Get one from Server.Credential(name) or one of the reads below. A Credential built as a struct literal has no server behind it and will panic on Alter or Drop.

func (*Credential) Alter added in v0.0.11

func (c *Credential) Alter(identity string, secret *string) error

Alter changes the credential's identity, and its secret.

func (*Credential) AlterContext added in v0.0.11

func (c *Credential) AlterContext(ctx context.Context, identity string, secret *string) error

AlterContext is the context-aware variant of Alter.

A nil secret does not leave the stored secret alone — it clears it. ALTER CREDENTIAL resets both halves every time, and SQL Server documents omitting SECRET as setting the stored secret to NULL; there is no T-SQL form that changes the identity while keeping the secret. Since the secret can never be read back, a caller that wants to keep one has to ask the user for it again and pass it here. Both branches are deliberate: pass a pointer to the new secret to set it, and nil only when clearing it is the intent.

func (*Credential) Drop added in v0.0.11

func (c *Credential) Drop() error

Drop deletes the credential.

func (*Credential) DropContext added in v0.0.11

func (c *Credential) DropContext(ctx context.Context) error

DropContext is the context-aware variant of Drop.

type CredentialSpec added in v0.0.11

type CredentialSpec struct {
	Name string

	// Identity is the account the credential presents when connecting
	// outside the server. CREATE CREDENTIAL requires it.
	Identity string

	// Secret is the password half. Empty omits the SECRET clause, creating a
	// credential with a NULL secret — which is legitimate for an identity
	// that needs no password.
	Secret string

	// CryptographicProvider binds the credential to an EKM provider
	// (FOR CRYPTOGRAPHIC PROVIDER). Empty creates an ordinary credential.
	CryptographicProvider string
}

CredentialSpec describes a credential to create.

type CryptographicProvider added in v0.0.11

type CryptographicProvider struct {
	ProviderID int
	Name       string
	GUID       string
	Version    string
	DLLPath    string
	IsEnabled  bool
}

CryptographicProvider mirrors a row of sys.cryptographic_providers — an Extensible Key Management provider registered with CREATE CRYPTOGRAPHIC PROVIDER. It lives here rather than in a file of its own because a credential's FOR CRYPTOGRAPHIC PROVIDER binding is the only thing in gosmo that refers to one.

type DataSpace added in v0.0.10

type DataSpace struct {
	Name              string
	IsPartitionScheme bool
	// IsDefaultFileGroup is true for the database's default filegroup, the
	// one an object with no ON clause lands on. A scripter uses it to leave
	// the clause off where it would say nothing.
	IsDefaultFileGroup bool
	// PartitionColumn is the column the scheme partitions by; set only when
	// IsPartitionScheme.
	PartitionColumn string
}

DataSpace names where a table or index keeps its rows — the ON clause of CREATE TABLE and CREATE INDEX. It is either a filegroup or a partition scheme, and for a partition scheme the partitioning column is part of the clause, so it is carried here too: `ON [scheme]([column])`.

Name is empty for an index with no data space of its own in sys.indexes — a memory-optimized table's, whose rows are not on a filegroup at all.

type DataType

type DataType string

DataType mirrors SQL Server column data types.

const (
	DataTypeBigInt           DataType = "bigint"
	DataTypeBinary           DataType = "binary"
	DataTypeBit              DataType = "bit"
	DataTypeChar             DataType = "char"
	DataTypeDate             DataType = "date"
	DataTypeDatetime         DataType = "datetime"
	DataTypeDatetime2        DataType = "datetime2"
	DataTypeDatetimeOffset   DataType = "datetimeoffset"
	DataTypeDecimal          DataType = "decimal"
	DataTypeFloat            DataType = "float"
	DataTypeGeography        DataType = "geography"
	DataTypeGeometry         DataType = "geometry"
	DataTypeHierarchyID      DataType = "hierarchyid"
	DataTypeImage            DataType = "image"
	DataTypeInt              DataType = "int"
	DataTypeMoney            DataType = "money"
	DataTypeNChar            DataType = "nchar"
	DataTypeNText            DataType = "ntext"
	DataTypeNumeric          DataType = "numeric"
	DataTypeNVarChar         DataType = "nvarchar"
	DataTypeReal             DataType = "real"
	DataTypeRowVersion       DataType = "rowversion"
	DataTypeSmallDatetime    DataType = "smalldatetime"
	DataTypeSmallInt         DataType = "smallint"
	DataTypeSmallMoney       DataType = "smallmoney"
	DataTypeSQLVariant       DataType = "sql_variant"
	DataTypeText             DataType = "text"
	DataTypeTime             DataType = "time"
	DataTypeTinyInt          DataType = "tinyint"
	DataTypeUniqueIdentifier DataType = "uniqueidentifier"
	DataTypeVarBinary        DataType = "varbinary"
	DataTypeVarChar          DataType = "varchar"
	DataTypeXML              DataType = "xml"
)

type Database

type Database struct {
	// contains filtered or unexported fields
}

Database mirrors Microsoft.SqlServer.Management.Smo.Database.

func (*Database) ActualPlan added in v0.0.4

func (d *Database) ActualPlan(sql string) (*ExecutionPlan, error)

ActualPlan executes sql and captures its actual execution plan (SET STATISTICS XML ON) — SSMS's "Include Actual Execution Plan". Unlike EstimatedPlan, this runs the statement.

func (*Database) ActualPlanContext added in v0.0.4

func (d *Database) ActualPlanContext(ctx context.Context, sqlText string) (*ExecutionPlan, error)

ActualPlanContext is the context-aware variant of ActualPlan.

func (*Database) AddExtendedProperty

func (d *Database) AddExtendedProperty(name, value string, level ExtendedPropertyLevel) error

AddExtendedProperty adds a new extended property on an object. Fails if a property with this name already exists at this level — see SetExtendedProperty to update one.

func (*Database) AddExtendedPropertyContext added in v0.0.4

func (d *Database) AddExtendedPropertyContext(ctx context.Context, name, value string, level ExtendedPropertyLevel) error

AddExtendedPropertyContext is the context-aware variant of AddExtendedProperty.

func (*Database) AddFile added in v0.0.4

func (d *Database) AddFile(spec DatabaseFileSpec) error

AddFile adds a new data or log file to the database.

func (*Database) AddFileContext added in v0.0.4

func (d *Database) AddFileContext(ctx context.Context, spec DatabaseFileSpec) error

AddFileContext is the context-aware variant of AddFile.

func (*Database) AddFileGroup added in v0.0.4

func (d *Database) AddFileGroup(name string) error

AddFileGroup adds a new (empty) filegroup to the database.

func (*Database) AddFileGroupContext added in v0.0.4

func (d *Database) AddFileGroupContext(ctx context.Context, name string) error

AddFileGroupContext is the context-aware variant of AddFileGroup.

func (*Database) AddRoleMember

func (d *Database) AddRoleMember(roleName, memberName string) error

AddRoleMember adds a user to a database role.

func (*Database) AddRoleMemberContext

func (d *Database) AddRoleMemberContext(ctx context.Context, roleName, memberName string) error

AddRoleMemberContext is the context-aware variant.

func (*Database) AlterFile added in v0.0.4

func (d *Database) AlterFile(name string, m FileModify) error

AlterFile changes an existing file's name, size, growth, or max size.

func (*Database) AlterFileContext added in v0.0.4

func (d *Database) AlterFileContext(ctx context.Context, name string, m FileModify) error

AlterFileContext is the context-aware variant of AlterFile.

func (*Database) Assemblies added in v0.0.13

func (d *Database) Assemblies() ([]*Assembly, error)

Assemblies returns the CLR assemblies registered in the database.

func (*Database) AssembliesContext added in v0.0.13

func (d *Database) AssembliesContext(ctx context.Context) ([]*Assembly, error)

AssembliesContext is the context-aware variant of Assemblies.

func (*Database) AssemblyByName added in v0.0.13

func (d *Database) AssemblyByName(name string) (*Assembly, error)

AssemblyByName returns one assembly, or a not-found error (errors.Is ErrNotFound) when the database has none by that name.

func (*Database) AssemblyByNameContext added in v0.0.13

func (d *Database) AssemblyByNameContext(ctx context.Context, name string) (*Assembly, error)

AssemblyByNameContext is the context-aware variant of AssemblyByName.

func (*Database) AssemblySeq added in v0.0.13

func (d *Database) AssemblySeq(ctx context.Context) iter.Seq2[*Assembly, error]

AssemblySeq returns an iterator over all CLR assemblies registered in the database.

func (*Database) AsymmetricKeyByName added in v0.0.11

func (d *Database) AsymmetricKeyByName(name string) (*AsymmetricKey, error)

AsymmetricKeyByName returns one asymmetric key, or (nil, nil) when the database has none by that name — matching CertificateByName, whose absent answer this family's callers already branch on.

func (*Database) AsymmetricKeyByNameContext added in v0.0.11

func (d *Database) AsymmetricKeyByNameContext(ctx context.Context, name string) (*AsymmetricKey, error)

AsymmetricKeyByNameContext is the context-aware variant of AsymmetricKeyByName.

func (*Database) AsymmetricKeys added in v0.0.11

func (d *Database) AsymmetricKeys() ([]*AsymmetricKey, error)

AsymmetricKeys returns the database's asymmetric keys, excluding the internal ones SQL Server creates for itself (named ##...##) — the same exclusion Certificates makes.

func (*Database) AsymmetricKeysContext added in v0.0.11

func (d *Database) AsymmetricKeysContext(ctx context.Context) ([]*AsymmetricKey, error)

AsymmetricKeysContext is the context-aware variant of AsymmetricKeys.

func (*Database) BulkInsert added in v0.0.4

func (d *Database) BulkInsert(bc BulkCopy, rows iter.Seq2[[]any, error]) (int64, error)

BulkInsert streams rows into a table using SQL Server's TDS bulk-copy protocol — the same fast path bcp and SSMS "Import Data" use, far faster than row-by-row INSERTs. It returns the number of rows copied.

rows yields one []any per row, its values ordered to match bc.Columns; a nil element becomes SQL NULL. Yielding a non-nil error aborts the load and that error is returned (wrapped), so a streaming source such as a CSV reader can surface a read failure. Use SliceRows for an in-memory slice.

func (*Database) BulkInsertContext added in v0.0.4

func (d *Database) BulkInsertContext(ctx context.Context, bc BulkCopy, rows iter.Seq2[[]any, error]) (int64, error)

BulkInsertContext is the context-aware variant of BulkInsert. Cancelling ctx stops the load; the count of rows copied before cancellation is returned alongside the error.

func (*Database) Capabilities added in v0.0.10

func (d *Database) Capabilities() (*DatabaseCapabilities, error)

Capabilities reports what the connected login may do inside d.

func (*Database) CapabilitiesContext added in v0.0.10

func (d *Database) CapabilitiesContext(ctx context.Context) (*DatabaseCapabilities, error)

CapabilitiesContext is the context-aware variant of Capabilities.

Accessibility is settled first, at the *server* scope, and an inaccessible database returns early with Accessible false and no error. That ordering is required rather than tidy: the role and permission probe runs inside the database, and Database.query opens with a USE, which is itself what fails for a login that cannot connect there.

func (*Database) Catalog added in v0.0.5

func (d *Database) Catalog() (*Catalog, error)

Catalog returns a bulk snapshot of every user table and view in the database, each with its columns, sorted by schema then name.

func (*Database) CatalogContext added in v0.0.5

func (d *Database) CatalogContext(ctx context.Context) (*Catalog, error)

CatalogContext is the context-aware variant of Catalog.

func (*Database) CertificateByName added in v0.0.9

func (d *Database) CertificateByName(name string) (*Certificate, error)

CertificateByName returns one certificate, or (nil, nil) when the database has none by that name — an absent certificate is the ordinary case for a caller about to create one, not an error.

func (*Database) CertificateByNameContext added in v0.0.9

func (d *Database) CertificateByNameContext(ctx context.Context, name string) (*Certificate, error)

CertificateByNameContext is the context-aware variant of CertificateByName.

func (*Database) CertificateSeq added in v0.0.9

func (d *Database) CertificateSeq(ctx context.Context) iter.Seq2[*Certificate, error]

CertificateSeq returns an iterator over all certificates in the database.

func (*Database) Certificates added in v0.0.9

func (d *Database) Certificates() ([]*Certificate, error)

Certificates returns the database's certificates, excluding the internal ones SQL Server creates for itself (named ##...##).

func (*Database) CertificatesContext added in v0.0.9

func (d *Database) CertificatesContext(ctx context.Context) ([]*Certificate, error)

CertificatesContext is the context-aware variant of Certificates.

func (*Database) ChangeTracking added in v0.0.4

func (d *Database) ChangeTracking() (*ChangeTrackingInfo, error)

ChangeTracking returns the database's change tracking settings. Enabled is false (with the rest zero-valued) when change tracking has never been turned on for this database — there's simply no row for it in sys.change_tracking_databases, not an error.

func (*Database) ChangeTrackingContext added in v0.0.4

func (d *Database) ChangeTrackingContext(ctx context.Context) (*ChangeTrackingInfo, error)

ChangeTrackingContext is the context-aware variant of ChangeTracking.

func (*Database) ClearQueryStore added in v0.0.5

func (d *Database) ClearQueryStore() error

ClearQueryStore discards all captured Query Store data (SSMS's "Clear Query Store" action) without changing its configuration.

func (*Database) ClearQueryStoreContext added in v0.0.5

func (d *Database) ClearQueryStoreContext(ctx context.Context) error

ClearQueryStoreContext is the context-aware variant of ClearQueryStore.

func (*Database) ClrTypeByName added in v0.0.13

func (d *Database) ClrTypeByName(schema, name string) (*ClrType, error)

ClrTypeByName returns one CLR type, or a not-found error (errors.Is ErrNotFound) when the database has none by that name.

func (*Database) ClrTypeByNameContext added in v0.0.13

func (d *Database) ClrTypeByNameContext(ctx context.Context, schema, name string) (*ClrType, error)

ClrTypeByNameContext is the context-aware variant of ClrTypeByName.

func (*Database) ClrTypeSeq added in v0.0.13

func (d *Database) ClrTypeSeq(ctx context.Context) iter.Seq2[*ClrType, error]

ClrTypeSeq returns an iterator over all CLR user-defined types in the database.

func (*Database) ClrTypes added in v0.0.13

func (d *Database) ClrTypes() ([]*ClrType, error)

ClrTypes returns the CLR user-defined types in the database.

func (*Database) ClrTypesContext added in v0.0.13

func (d *Database) ClrTypesContext(ctx context.Context) ([]*ClrType, error)

ClrTypesContext is the context-aware variant of ClrTypes.

func (*Database) Collation

func (d *Database) Collation() string

Collation returns the database collation name.

func (*Database) ColumnEncryptionKeyByName added in v0.0.10

func (d *Database) ColumnEncryptionKeyByName(name string) (*ColumnEncryptionKey, error)

ColumnEncryptionKeyByName returns one column encryption key by name.

func (*Database) ColumnEncryptionKeyByNameContext added in v0.0.10

func (d *Database) ColumnEncryptionKeyByNameContext(ctx context.Context, name string) (*ColumnEncryptionKey, error)

ColumnEncryptionKeyByNameContext is the context-aware variant of ColumnEncryptionKeyByName.

func (*Database) ColumnEncryptionKeySeq added in v0.0.5

func (d *Database) ColumnEncryptionKeySeq(ctx context.Context) iter.Seq2[*ColumnEncryptionKey, error]

ColumnEncryptionKeySeq returns an iterator over all column encryption keys in the database.

func (*Database) ColumnEncryptionKeys

func (d *Database) ColumnEncryptionKeys() ([]*ColumnEncryptionKey, error)

ColumnEncryptionKeys returns all column encryption keys in the database.

func (*Database) ColumnEncryptionKeysContext added in v0.0.5

func (d *Database) ColumnEncryptionKeysContext(ctx context.Context) ([]*ColumnEncryptionKey, error)

ColumnEncryptionKeysContext is the context-aware variant of ColumnEncryptionKeys.

func (*Database) ColumnMasterKeyByName added in v0.0.10

func (d *Database) ColumnMasterKeyByName(name string) (*ColumnMasterKey, error)

ColumnMasterKeyByName returns one column master key by name.

func (*Database) ColumnMasterKeyByNameContext added in v0.0.10

func (d *Database) ColumnMasterKeyByNameContext(ctx context.Context, name string) (*ColumnMasterKey, error)

ColumnMasterKeyByNameContext is the context-aware variant of ColumnMasterKeyByName.

func (*Database) ColumnMasterKeySeq added in v0.0.5

func (d *Database) ColumnMasterKeySeq(ctx context.Context) iter.Seq2[*ColumnMasterKey, error]

ColumnMasterKeySeq returns an iterator over all column master keys in the database.

func (*Database) ColumnMasterKeys

func (d *Database) ColumnMasterKeys() ([]*ColumnMasterKey, error)

ColumnMasterKeys returns all column master keys in the database.

func (*Database) ColumnMasterKeysContext added in v0.0.5

func (d *Database) ColumnMasterKeysContext(ctx context.Context) ([]*ColumnMasterKey, error)

ColumnMasterKeysContext is the context-aware variant of ColumnMasterKeys.

func (*Database) ColumnPermissionSeq added in v0.0.8

func (d *Database) ColumnPermissionSeq(ctx context.Context, schema, name string) iter.Seq2[*ColumnPermissionEntry, error]

ColumnPermissionSeq returns an iterator over every column-level GRANT/DENY entry recorded on schema.name.

func (*Database) ColumnPermissions added in v0.0.8

func (d *Database) ColumnPermissions(schema, name string) ([]*ColumnPermissionEntry, error)

ColumnPermissions returns every column-level GRANT/DENY entry recorded on schema.name, for all principals and all columns.

func (*Database) ColumnPermissionsContext added in v0.0.8

func (d *Database) ColumnPermissionsContext(ctx context.Context, schema, name string) ([]*ColumnPermissionEntry, error)

ColumnPermissionsContext is the context-aware variant of ColumnPermissions.

func (*Database) ColumnPermissionsForPrincipal added in v0.0.8

func (d *Database) ColumnPermissionsForPrincipal(principal string) ([]*ColumnPermissionEntry, error)

ColumnPermissionsForPrincipal returns every column-level GRANT/DENY entry principal holds anywhere in the database — the column-level counterpart of PermissionsForPrincipal, which reports object-, schema- and database-scoped entries and deliberately leaves column entries out (a Securables page lists securables, and a column is not one of them; SSMS puts them behind a per-securable "Column Permissions..." button).

func (*Database) ColumnPermissionsForPrincipalContext added in v0.0.8

func (d *Database) ColumnPermissionsForPrincipalContext(ctx context.Context, principal string) ([]*ColumnPermissionEntry, error)

ColumnPermissionsForPrincipalContext is the context-aware variant of ColumnPermissionsForPrincipal.

func (*Database) ColumnPermissionsForPrincipalSeq added in v0.0.8

func (d *Database) ColumnPermissionsForPrincipalSeq(ctx context.Context, principal string) iter.Seq2[*ColumnPermissionEntry, error]

ColumnPermissionsForPrincipalSeq returns an iterator over every column-level GRANT/DENY entry principal holds anywhere in the database.

func (*Database) CompatibilityLevel

func (d *Database) CompatibilityLevel() CompatibilityLevel

CompatibilityLevel returns the database compatibility level.

func (*Database) CreateCertificate added in v0.0.9

func (d *Database) CreateCertificate(spec CertificateSpec) error

CreateCertificate creates a certificate in the database.

func (*Database) CreateCertificateContext added in v0.0.9

func (d *Database) CreateCertificateContext(ctx context.Context, spec CertificateSpec) error

CreateCertificateContext is the context-aware variant of CreateCertificate.

func (*Database) CreateColumnEncryptionKey added in v0.0.10

func (d *Database) CreateColumnEncryptionKey(name string, values []ColumnEncryptionKeyValue) error

CreateColumnEncryptionKey creates a column encryption key from one or more already-encrypted values.

Each value's key material is the CEK encrypted under a column master key, which is done client-side by whatever can reach that master key's private key (SSMS and the SqlColumnEncryptionKey PowerShell cmdlets both do) — nothing here can generate or verify it, and the server rejects a value it cannot decrypt on first use. Pass two values only to reproduce a key mid-rotation; one is the ordinary case.

func (*Database) CreateColumnEncryptionKeyContext added in v0.0.10

func (d *Database) CreateColumnEncryptionKeyContext(ctx context.Context, name string, values []ColumnEncryptionKeyValue) error

CreateColumnEncryptionKeyContext is the context-aware variant of CreateColumnEncryptionKey. The statement is written the way the scripter writes it (buildColumnEncryptionKeyScript), so a key created here and one scripted from the server read back the same.

func (*Database) CreateColumnMasterKey

func (d *Database) CreateColumnMasterKey(name, keyStoreProvider, keyPath string, enclaveComputations bool) error

CreateColumnMasterKey creates a column master key metadata entry. Note: the actual key must already exist in the key store.

enclaveComputations can only be false here. The ENCLAVE_COMPUTATIONS clause takes a signature over the key's metadata — CREATE COLUMN MASTER KEY spells it ENCLAVE_COMPUTATIONS (SIGNATURE = 0x...) and has no boolean form — and that signature is computed by the client from the master key's private key, so nothing here can supply it. Passing true returns an error naming CreateColumnMasterKeyWithSignature rather than emitting a statement the server will reject.

func (*Database) CreateColumnMasterKeyContext added in v0.0.5

func (d *Database) CreateColumnMasterKeyContext(ctx context.Context, name, keyStoreProvider, keyPath string, enclaveComputations bool) error

CreateColumnMasterKeyContext is the context-aware variant of CreateColumnMasterKey.

func (*Database) CreateColumnMasterKeyWithSignature added in v0.0.10

func (d *Database) CreateColumnMasterKeyWithSignature(name, keyStoreProvider, keyPath string, signature []byte) error

CreateColumnMasterKeyWithSignature creates a column master key that allows enclave computations. signature is the digital signature over the key's metadata, the same value ColumnMasterKey.Signature reads back and the scripter writes out verbatim; it is produced client-side by whatever holds the master key's private key (SSMS and the SqlColumnMasterKey PowerShell cmdlets both do), and the server verifies it against the rest of the metadata, so an empty or wrong one is rejected. Use CreateColumnMasterKey for a key that does not allow enclave computations.

The ENCLAVE_COMPUTATIONS clause is SQL Server 2019 syntax; below that this refuses rather than sending a statement the parser rejects. Ask EnclaveComputationsSupported first.

func (*Database) CreateColumnMasterKeyWithSignatureContext added in v0.0.10

func (d *Database) CreateColumnMasterKeyWithSignatureContext(ctx context.Context, name, keyStoreProvider, keyPath string, signature []byte) error

CreateColumnMasterKeyWithSignatureContext is the context-aware variant of CreateColumnMasterKeyWithSignature.

func (*Database) CreateDatabaseAuditSpecification added in v0.0.12

func (d *Database) CreateDatabaseAuditSpecification(spec DatabaseAuditSpecificationSpec) (*DatabaseAuditSpecification, error)

CreateDatabaseAuditSpecification creates a database audit specification.

func (*Database) CreateDatabaseAuditSpecificationContext added in v0.0.12

func (d *Database) CreateDatabaseAuditSpecificationContext(ctx context.Context, spec DatabaseAuditSpecificationSpec) (*DatabaseAuditSpecification, error)

CreateDatabaseAuditSpecificationContext is the context-aware variant of CreateDatabaseAuditSpecification.

func (*Database) CreateDatabaseScopedCredential added in v0.0.12

func (d *Database) CreateDatabaseScopedCredential(spec DatabaseScopedCredentialSpec) (*DatabaseScopedCredential, error)

CreateDatabaseScopedCredential creates a database-scoped credential.

func (*Database) CreateDatabaseScopedCredentialContext added in v0.0.12

func (d *Database) CreateDatabaseScopedCredentialContext(ctx context.Context, spec DatabaseScopedCredentialSpec) (*DatabaseScopedCredential, error)

CreateDatabaseScopedCredentialContext is the context-aware variant of CreateDatabaseScopedCredential.

func (*Database) CreateDate

func (d *Database) CreateDate() time.Time

CreateDate returns the date the database was created.

func (*Database) CreateMasterKey added in v0.0.9

func (d *Database) CreateMasterKey(password string) error

CreateMasterKey creates the database master key, protected by password.

The key is also encrypted by the service master key automatically, which is what lets SQL Server open it without the password at startup. Losing that — a restore onto another instance, or a service master key that no longer decrypts — leaves the password as the only way in, so it is worth keeping.

func (*Database) CreateMasterKeyContext added in v0.0.9

func (d *Database) CreateMasterKeyContext(ctx context.Context, password string) error

CreateMasterKeyContext is the context-aware variant of CreateMasterKey.

func (*Database) CreatePartitionFunction

func (d *Database) CreatePartitionFunction(req CreatePartitionFunctionRequest) error

CreatePartitionFunction creates a partition function.

func (*Database) CreatePartitionFunctionContext added in v0.0.5

func (d *Database) CreatePartitionFunctionContext(ctx context.Context, req CreatePartitionFunctionRequest) error

CreatePartitionFunctionContext is the context-aware variant of CreatePartitionFunction.

func (*Database) CreatePartitionScheme

func (d *Database) CreatePartitionScheme(name, functionName string, fileGroups []string) error

CreatePartitionScheme creates a partition scheme backed by a partition function.

func (*Database) CreatePartitionSchemeContext added in v0.0.5

func (d *Database) CreatePartitionSchemeContext(ctx context.Context, name, functionName string, fileGroups []string) error

CreatePartitionSchemeContext is the context-aware variant of CreatePartitionScheme.

func (*Database) CreateSchema

func (d *Database) CreateSchema(name, owner string) error

CreateSchema creates a new schema in the database.

func (*Database) CreateSchemaContext

func (d *Database) CreateSchemaContext(ctx context.Context, name, owner string) error

CreateSchemaContext is the context-aware variant of CreateSchema.

func (*Database) CreateSequence

func (d *Database) CreateSequence(req CreateSequenceRequest) error

CreateSequence creates a new sequence in the database.

func (*Database) CreateSequenceContext added in v0.0.5

func (d *Database) CreateSequenceContext(ctx context.Context, req CreateSequenceRequest) error

CreateSequenceContext is the context-aware variant of CreateSequence.

func (*Database) CreateStoredProcedure

func (d *Database) CreateStoredProcedure(schema, name, body string) error

CreateStoredProcedure creates (or replaces) a stored procedure. schema may be empty (defaults to dbo). body is the raw T-SQL after AS.

func (*Database) CreateStoredProcedureContext

func (d *Database) CreateStoredProcedureContext(ctx context.Context, schema, name, body string) error

CreateStoredProcedureContext is the context-aware variant.

func (*Database) CreateSynonym

func (d *Database) CreateSynonym(schema, name, baseObject string) error

CreateSynonym creates a synonym for a base object. baseObject should be the fully qualified name, e.g. "[OtherDB].[dbo].[MyTable]".

func (*Database) CreateSynonymContext added in v0.0.5

func (d *Database) CreateSynonymContext(ctx context.Context, schema, name, baseObject string) error

CreateSynonymContext is the context-aware variant of CreateSynonym.

func (*Database) CreateTable

func (d *Database) CreateTable(req CreateTableRequest) error

CreateTable creates a table from a CreateTableRequest.

func (*Database) CreateTableContext

func (d *Database) CreateTableContext(ctx context.Context, req CreateTableRequest) error

CreateTableContext is the context-aware variant of CreateTable.

func (*Database) CreateUser

func (d *Database) CreateUser(userName, loginName, defaultSchema string) error

CreateUser creates a database user mapped to a login.

func (*Database) CreateUserContext

func (d *Database) CreateUserContext(ctx context.Context, userName, loginName, defaultSchema string) error

CreateUserContext is the context-aware variant of CreateUser.

func (*Database) DatabaseAuditSpecification added in v0.0.12

func (d *Database) DatabaseAuditSpecification(name string) *DatabaseAuditSpecification

DatabaseAuditSpecification returns a lightweight handle by name, without querying the catalog — the counterpart of Server.Database. Every cached field stays at its zero value; DatabaseAuditSpecificationByName populates them. This is the only form usable under a WithScript-derived context.

func (*Database) DatabaseAuditSpecificationByName added in v0.0.12

func (d *Database) DatabaseAuditSpecificationByName(name string) (*DatabaseAuditSpecification, error)

DatabaseAuditSpecificationByName returns one specification with every field populated, or a not-found error (errors.Is ErrNotFound).

func (*Database) DatabaseAuditSpecificationByNameContext added in v0.0.12

func (d *Database) DatabaseAuditSpecificationByNameContext(ctx context.Context, name string) (*DatabaseAuditSpecification, error)

DatabaseAuditSpecificationByNameContext is the context-aware variant of DatabaseAuditSpecificationByName.

func (*Database) DatabaseAuditSpecifications added in v0.0.12

func (d *Database) DatabaseAuditSpecifications() ([]*DatabaseAuditSpecification, error)

DatabaseAuditSpecifications returns every audit specification in the database, with its action groups and actions.

func (*Database) DatabaseAuditSpecificationsContext added in v0.0.12

func (d *Database) DatabaseAuditSpecificationsContext(ctx context.Context) ([]*DatabaseAuditSpecification, error)

DatabaseAuditSpecificationsContext is the context-aware variant of DatabaseAuditSpecifications.

func (*Database) DatabaseExtendedProperties

func (d *Database) DatabaseExtendedProperties() ([]*ExtendedProperty, error)

DatabaseExtendedProperties returns all extended properties at database level.

func (*Database) DatabaseExtendedPropertiesContext added in v0.0.5

func (d *Database) DatabaseExtendedPropertiesContext(ctx context.Context) ([]*ExtendedProperty, error)

DatabaseExtendedPropertiesContext is the context-aware variant of DatabaseExtendedProperties.

func (*Database) DatabaseExtendedPropertySeq added in v0.0.5

func (d *Database) DatabaseExtendedPropertySeq(ctx context.Context) iter.Seq2[*ExtendedProperty, error]

DatabaseExtendedPropertySeq returns an iterator over all extended properties at database level.

func (*Database) DatabasePermissionSeq added in v0.0.4

func (d *Database) DatabasePermissionSeq(ctx context.Context) iter.Seq2[*DatabasePermissionEntry, error]

DatabasePermissionSeq returns an iterator over all database-scoped GRANT/DENY entries.

func (*Database) DatabasePermissions added in v0.0.4

func (d *Database) DatabasePermissions() ([]*DatabasePermissionEntry, error)

DatabasePermissions returns every database-scoped GRANT/DENY entry — permissions granted on the database itself, not on a specific object within it (see Permissions for that).

func (*Database) DatabasePermissionsContext added in v0.0.4

func (d *Database) DatabasePermissionsContext(ctx context.Context) ([]*DatabasePermissionEntry, error)

DatabasePermissionsContext is the context-aware variant of DatabasePermissions.

func (*Database) DatabaseRoleSeq added in v0.0.6

func (d *Database) DatabaseRoleSeq(ctx context.Context) iter.Seq2[*DatabaseRole, error]

DatabaseRoleSeq returns an iterator over all database-level roles.

func (*Database) DatabaseRoles

func (d *Database) DatabaseRoles() ([]*DatabaseRole, error)

DatabaseRoles returns all roles defined in the database.

func (*Database) DatabaseRolesContext

func (d *Database) DatabaseRolesContext(ctx context.Context) ([]*DatabaseRole, error)

DatabaseRolesContext is the context-aware variant of DatabaseRoles.

func (*Database) DatabaseScopedConfigSeq added in v0.0.6

func (d *Database) DatabaseScopedConfigSeq(ctx context.Context) iter.Seq2[*DatabaseScopedConfig, error]

DatabaseScopedConfigSeq returns an iterator over all database-scoped configuration options.

func (*Database) DatabaseScopedConfigs added in v0.0.5

func (d *Database) DatabaseScopedConfigs() ([]*DatabaseScopedConfig, error)

DatabaseScopedConfigs returns every database scoped configuration option.

func (*Database) DatabaseScopedConfigsContext added in v0.0.5

func (d *Database) DatabaseScopedConfigsContext(ctx context.Context) ([]*DatabaseScopedConfig, error)

DatabaseScopedConfigsContext is the context-aware variant of DatabaseScopedConfigs.

func (*Database) DatabaseScopedCredential added in v0.0.12

func (d *Database) DatabaseScopedCredential(name string) *DatabaseScopedCredential

DatabaseScopedCredential returns a lightweight handle for a credential by name, without querying the catalog — the counterpart of Server.Database. Identity, CredentialID and every other cached field stay at their zero value; DatabaseScopedCredentialByName is what populates them.

Every write method on *DatabaseScopedCredential addresses the credential by name, so this handle is enough to go on operating on one the caller already knows exists — and is the only usable form under a WithScript-derived context, where DatabaseScopedCredentialByNameContext's lookup is a real read and a credential whose CREATE was merely collected is not there to find.

func (*Database) DatabaseScopedCredentialByName added in v0.0.12

func (d *Database) DatabaseScopedCredentialByName(name string) (*DatabaseScopedCredential, error)

DatabaseScopedCredentialByName returns one credential with every field populated, or a not-found error (errors.Is ErrNotFound) when the database has none by that name.

func (*Database) DatabaseScopedCredentialByNameContext added in v0.0.12

func (d *Database) DatabaseScopedCredentialByNameContext(ctx context.Context, name string) (*DatabaseScopedCredential, error)

DatabaseScopedCredentialByNameContext is the context-aware variant of DatabaseScopedCredentialByName.

func (*Database) DatabaseScopedCredentialSeq added in v0.0.12

func (d *Database) DatabaseScopedCredentialSeq(ctx context.Context) iter.Seq2[*DatabaseScopedCredential, error]

DatabaseScopedCredentialSeq returns an iterator over all database-scoped credentials in the database (as opposed to Server.CredentialSeq's server-level scope).

func (*Database) DatabaseScopedCredentials added in v0.0.12

func (d *Database) DatabaseScopedCredentials() ([]*DatabaseScopedCredential, error)

DatabaseScopedCredentials returns every database-scoped credential in the database.

func (*Database) DatabaseScopedCredentialsContext added in v0.0.12

func (d *Database) DatabaseScopedCredentialsContext(ctx context.Context) ([]*DatabaseScopedCredential, error)

DatabaseScopedCredentialsContext is the context-aware variant of DatabaseScopedCredentials.

func (*Database) DatabaseTrigger added in v0.0.12

func (d *Database) DatabaseTrigger(name string) *DatabaseTrigger

DatabaseTrigger returns a lightweight handle for a database-scope DDL trigger by name, without querying sys.triggers — the counterpart of Server.Database and Server.ServerTrigger.

Every other field stays at its zero value; DatabaseTriggerByName is what populates them. EnableContext, DisableContext and DropContext address the trigger by name, so this handle is enough to act on one the caller already knows exists, and is the only usable form under a WithScript context, where DatabaseTriggerByNameContext's lookup is a real read.

func (*Database) DatabaseTriggerByName added in v0.0.12

func (d *Database) DatabaseTriggerByName(name string) (*DatabaseTrigger, error)

DatabaseTriggerByName returns one database-scope DDL trigger with every field populated, or a not-found error (errors.Is ErrNotFound) when the database has none by that name.

func (*Database) DatabaseTriggerByNameContext added in v0.0.12

func (d *Database) DatabaseTriggerByNameContext(ctx context.Context, name string) (*DatabaseTrigger, error)

DatabaseTriggerByNameContext is the context-aware variant of DatabaseTriggerByName.

func (*Database) DatabaseTriggerSeq added in v0.0.12

func (d *Database) DatabaseTriggerSeq(ctx context.Context) iter.Seq2[*DatabaseTrigger, error]

DatabaseTriggerSeq returns an iterator over every database-scope DDL trigger — the parent_class = 0 family, which TriggerSeq does not list.

func (*Database) DatabaseTriggers added in v0.0.12

func (d *Database) DatabaseTriggers() ([]*DatabaseTrigger, error)

DatabaseTriggers returns every database-scope DDL trigger.

func (*Database) DatabaseTriggersContext added in v0.0.12

func (d *Database) DatabaseTriggersContext(ctx context.Context) ([]*DatabaseTrigger, error)

DatabaseTriggersContext is the context-aware variant of DatabaseTriggers.

func (*Database) DefaultByName added in v0.0.13

func (d *Database) DefaultByName(schema, name string) (*Default, error)

DefaultByName returns one standalone default, or a not-found error (errors.Is ErrNotFound) when the database has none by that name.

func (*Database) DefaultByNameContext added in v0.0.13

func (d *Database) DefaultByNameContext(ctx context.Context, schema, name string) (*Default, error)

DefaultByNameContext is the context-aware variant of DefaultByName.

func (*Database) DefaultSeq added in v0.0.13

func (d *Database) DefaultSeq(ctx context.Context) iter.Seq2[*Default, error]

DefaultSeq returns an iterator over all standalone defaults in the database.

func (*Database) Defaults added in v0.0.13

func (d *Database) Defaults() ([]*Default, error)

Defaults returns the standalone defaults defined in the database — the CREATE DEFAULT objects, not table default constraints.

func (*Database) DefaultsContext added in v0.0.13

func (d *Database) DefaultsContext(ctx context.Context) ([]*Default, error)

DefaultsContext is the context-aware variant of Defaults.

func (*Database) DenyColumnPermission added in v0.0.8

func (d *Database) DenyColumnPermission(schema, name string, permission ObjectPermission, columns []string, principal string) error

DenyColumnPermission denies permission on the named columns of schema.name to principal.

func (*Database) DenyColumnPermissionContext added in v0.0.8

func (d *Database) DenyColumnPermissionContext(ctx context.Context, schema, name string, permission ObjectPermission, columns []string, principal string) error

DenyColumnPermissionContext is the context-aware variant of DenyColumnPermission.

func (*Database) DenyColumnPermissionWithOptions added in v0.0.8

func (d *Database) DenyColumnPermissionWithOptions(schema, name string, permission ObjectPermission, columns []string, principal string, opts PermissionOptions) error

DenyColumnPermissionWithOptions denies a column-level permission honouring opts — the CASCADE form of DenyColumnPermission.

func (*Database) DenyColumnPermissionWithOptionsContext added in v0.0.8

func (d *Database) DenyColumnPermissionWithOptionsContext(ctx context.Context, schema, name string, permission ObjectPermission, columns []string, principal string, opts PermissionOptions) error

DenyColumnPermissionWithOptionsContext is the context-aware variant of DenyColumnPermissionWithOptions.

func (*Database) DenyDatabasePermission added in v0.0.4

func (d *Database) DenyDatabasePermission(permission, principal string) error

DenyDatabasePermission denies a database-level permission to principal.

func (*Database) DenyDatabasePermissionContext added in v0.0.4

func (d *Database) DenyDatabasePermissionContext(ctx context.Context, permission, principal string) error

DenyDatabasePermissionContext is the context-aware variant of DenyDatabasePermission.

func (*Database) DenyDatabasePermissionWithOptions added in v0.0.8

func (d *Database) DenyDatabasePermissionWithOptions(permission, principal string, opts PermissionOptions) error

DenyDatabasePermissionWithOptions denies a database-level permission to principal, honouring opts.

func (*Database) DenyDatabasePermissionWithOptionsContext added in v0.0.8

func (d *Database) DenyDatabasePermissionWithOptionsContext(ctx context.Context, permission, principal string, opts PermissionOptions) error

DenyDatabasePermissionWithOptionsContext is the context-aware variant of DenyDatabasePermissionWithOptions.

func (*Database) DenyPermission added in v0.0.4

func (d *Database) DenyPermission(schema, name string, permission ObjectPermission, principal string) error

DenyPermission denies permission on schema.name to principal.

func (*Database) DenyPermissionContext added in v0.0.4

func (d *Database) DenyPermissionContext(ctx context.Context, schema, name string, permission ObjectPermission, principal string) error

DenyPermissionContext is the context-aware variant of DenyPermission.

func (*Database) DenyPermissionWithOptions added in v0.0.8

func (d *Database) DenyPermissionWithOptions(schema, name string, permission ObjectPermission, principal string, opts PermissionOptions) error

DenyPermissionWithOptions denies permission on schema.name to principal, honouring opts — the CASCADE form of DenyPermission.

func (*Database) DenyPermissionWithOptionsContext added in v0.0.8

func (d *Database) DenyPermissionWithOptionsContext(ctx context.Context, schema, name string, permission ObjectPermission, principal string, opts PermissionOptions) error

DenyPermissionWithOptionsContext is the context-aware variant of DenyPermissionWithOptions.

func (*Database) DenySchemaPermission added in v0.0.5

func (d *Database) DenySchemaPermission(schemaName string, permission ObjectPermission, principal string) error

DenySchemaPermission denies permission on a schema to principal.

func (*Database) DenySchemaPermissionContext added in v0.0.5

func (d *Database) DenySchemaPermissionContext(ctx context.Context, schemaName string, permission ObjectPermission, principal string) error

DenySchemaPermissionContext is the context-aware variant of DenySchemaPermission.

func (*Database) DenySchemaPermissionWithOptions added in v0.0.8

func (d *Database) DenySchemaPermissionWithOptions(schemaName string, permission ObjectPermission, principal string, opts PermissionOptions) error

DenySchemaPermissionWithOptions denies permission on a schema to principal, honouring opts.

func (*Database) DenySchemaPermissionWithOptionsContext added in v0.0.8

func (d *Database) DenySchemaPermissionWithOptionsContext(ctx context.Context, schemaName string, permission ObjectPermission, principal string, opts PermissionOptions) error

DenySchemaPermissionWithOptionsContext is the context-aware variant of DenySchemaPermissionWithOptions.

func (*Database) Dependencies added in v0.0.4

func (d *Database) Dependencies(schema, name string) ([]*Dependency, error)

Dependencies returns the objects that schema.name's own definition references — SSMS's "Object Dependencies > Objects on which ... depends".

func (*Database) DependenciesContext added in v0.0.4

func (d *Database) DependenciesContext(ctx context.Context, schema, name string) ([]*Dependency, error)

DependenciesContext is the context-aware variant of Dependencies.

func (*Database) DependencySeq added in v0.0.6

func (d *Database) DependencySeq(ctx context.Context, schema, name string) iter.Seq2[*Dependency, error]

DependencySeq returns an iterator over the objects schema.name's own definition references.

func (*Database) DependentSeq added in v0.0.6

func (d *Database) DependentSeq(ctx context.Context, schema, name string) iter.Seq2[*Dependency, error]

DependentSeq returns an iterator over the objects whose own definition references schema.name.

func (*Database) Dependents added in v0.0.4

func (d *Database) Dependents(schema, name string) ([]*Dependency, error)

Dependents returns the objects whose own definition references schema.name — SSMS's "Object Dependencies > Objects that depend on ...".

func (*Database) DependentsContext added in v0.0.4

func (d *Database) DependentsContext(ctx context.Context, schema, name string) ([]*Dependency, error)

DependentsContext is the context-aware variant of Dependents.

func (*Database) DiskUsage added in v0.0.13

func (d *Database) DiskUsage() (DiskUsage, error)

DiskUsage returns the database's disk-usage breakdown.

func (*Database) DiskUsageContext added in v0.0.13

func (d *Database) DiskUsageContext(ctx context.Context) (DiskUsage, error)

DiskUsageContext is the context-aware variant of DiskUsage.

It is one round trip: the file figures and the allocation figures are unrelated aggregates over unrelated tables, so they are cross-joined rather than queried one after the other.

func (*Database) DropAssembly added in v0.0.13

func (d *Database) DropAssembly(name string) error

DropAssembly drops an assembly by name — the form for a caller that has the name but not the object. An assembly still referenced by a routine or type is refused by the server, as is one another assembly depends on.

func (*Database) DropAssemblyContext added in v0.0.13

func (d *Database) DropAssemblyContext(ctx context.Context, name string) error

DropAssemblyContext is the context-aware variant of DropAssembly.

func (*Database) DropDatabaseRole added in v0.0.9

func (d *Database) DropDatabaseRole(name string) error

DropDatabaseRole drops a database role. A role that still owns a schema or has members is refused by the server, not here.

func (*Database) DropDatabaseRoleContext added in v0.0.9

func (d *Database) DropDatabaseRoleContext(ctx context.Context, name string) error

DropDatabaseRoleContext is the context-aware variant of DropDatabaseRole.

func (*Database) DropDefault added in v0.0.13

func (d *Database) DropDefault(schema, name string) error

DropDefault drops a standalone default by name. A default still bound to a column or type is refused by the server until sp_unbindefault releases it.

func (*Database) DropDefaultContext added in v0.0.13

func (d *Database) DropDefaultContext(ctx context.Context, schema, name string) error

DropDefaultContext is the context-aware variant of DropDefault.

func (*Database) DropExtendedProperty

func (d *Database) DropExtendedProperty(name string, level ExtendedPropertyLevel) error

DropExtendedProperty drops an extended property from an object.

func (*Database) DropExtendedPropertyContext added in v0.0.4

func (d *Database) DropExtendedPropertyContext(ctx context.Context, name string, level ExtendedPropertyLevel) error

DropExtendedPropertyContext is the context-aware variant of DropExtendedProperty.

func (*Database) DropExternalDataSource added in v0.0.13

func (d *Database) DropExternalDataSource(name string) error

DropExternalDataSource drops an external data source by name. One still referenced by an external table is refused by the server.

func (*Database) DropExternalDataSourceContext added in v0.0.13

func (d *Database) DropExternalDataSourceContext(ctx context.Context, name string) error

DropExternalDataSourceContext is the context-aware variant of DropExternalDataSource.

func (*Database) DropExternalFileFormat added in v0.0.13

func (d *Database) DropExternalFileFormat(name string) error

DropExternalFileFormat drops an external file format by name. One still referenced by an external table is refused by the server.

func (*Database) DropExternalFileFormatContext added in v0.0.13

func (d *Database) DropExternalFileFormatContext(ctx context.Context, name string) error

DropExternalFileFormatContext is the context-aware variant of DropExternalFileFormat.

func (*Database) DropExternalLibrary added in v0.0.13

func (d *Database) DropExternalLibrary(name string) error

DropExternalLibrary drops an external library by name.

func (*Database) DropExternalLibraryContext added in v0.0.13

func (d *Database) DropExternalLibraryContext(ctx context.Context, name string) error

DropExternalLibraryContext is the context-aware variant of DropExternalLibrary.

func (*Database) DropFunction added in v0.0.9

func (d *Database) DropFunction(schema, name string) error

DropFunction drops a user-defined function — scalar, inline table-valued, or multi-statement table-valued alike, all of which DROP FUNCTION removes. A function that isn't there is the server's error, not a silent success — see the note on Database.DropTable.

func (*Database) DropFunctionContext added in v0.0.9

func (d *Database) DropFunctionContext(ctx context.Context, schema, name string) error

DropFunctionContext is the context-aware variant of DropFunction.

func (*Database) DropPlanGuide added in v0.0.13

func (d *Database) DropPlanGuide(name string) error

DropPlanGuide drops a plan guide by name — the form for a caller that has the name but not the object.

func (*Database) DropPlanGuideContext added in v0.0.13

func (d *Database) DropPlanGuideContext(ctx context.Context, name string) error

DropPlanGuideContext is the context-aware variant of DropPlanGuide.

func (*Database) DropRule added in v0.0.13

func (d *Database) DropRule(schema, name string) error

DropRule drops a rule by name. A rule still bound to a column or type is refused by the server until sp_unbindrule releases it.

func (*Database) DropRuleContext added in v0.0.13

func (d *Database) DropRuleContext(ctx context.Context, schema, name string) error

DropRuleContext is the context-aware variant of DropRule.

func (*Database) DropSchema

func (d *Database) DropSchema(name string) error

DropSchema drops a schema from the database.

func (*Database) DropSchemaContext

func (d *Database) DropSchemaContext(ctx context.Context, name string) error

DropSchemaContext is the context-aware variant of DropSchema.

func (*Database) DropSequence added in v0.0.9

func (d *Database) DropSequence(schema, name string) error

DropSequence drops a sequence by name — the form for a caller that has the name but not the object, as Sequences() would have to be listed first to get one.

func (*Database) DropSequenceContext added in v0.0.9

func (d *Database) DropSequenceContext(ctx context.Context, schema, name string) error

DropSequenceContext is the context-aware variant of DropSequence.

func (*Database) DropStoredProcedure

func (d *Database) DropStoredProcedure(schema, name string) error

DropStoredProcedure drops a stored procedure. A procedure that isn't there is the server's error, not a silent success — see the note on Database.DropTable.

func (*Database) DropStoredProcedureContext

func (d *Database) DropStoredProcedureContext(ctx context.Context, schema, name string) error

DropStoredProcedureContext is the context-aware variant.

func (*Database) DropSynonym added in v0.0.9

func (d *Database) DropSynonym(schema, name string) error

DropSynonym drops a synonym by name — the form for a caller that has the name but not the object, as Synonyms() would have to be listed first to get one. A synonym that isn't there is the server's error, not a silent success — see the note on Database.DropTable.

func (*Database) DropSynonymContext added in v0.0.9

func (d *Database) DropSynonymContext(ctx context.Context, schema, name string) error

DropSynonymContext is the context-aware variant of DropSynonym.

func (*Database) DropTable

func (d *Database) DropTable(schema, name string, cascade bool) error

DropTable drops a table. When cascade=true it first drops all incoming foreign-key constraints.

Dropping something that isn't there is an error

This and every other Drop* write method issue a bare DROP, so a name that matches nothing comes back as the server's "Cannot drop ... because it does not exist" rather than as success. Half of them used to carry IF EXISTS and half did not, which made the same gesture in a caller's UI report two different things about the same situation: a deleted view that was already gone said "deleted", a deleted sequence said the server refused. Callers that want the idempotent form should ignore the error, which is a decision they can make and this package cannot make for them.

The generated *scripts* keep IF EXISTS — Scripter's DROP-and-CREATE output exists to be re-run, which is the opposite requirement.

func (*Database) DropTableContext

func (d *Database) DropTableContext(ctx context.Context, schema, name string, cascade bool) error

DropTableContext is the context-aware variant of DropTable.

func (*Database) DropTrigger added in v0.0.9

func (d *Database) DropTrigger(schema, name string) error

DropTrigger drops a DML trigger. schema is the trigger's own schema — the schema of the table it is defined on. A trigger that isn't there is the server's error, not a silent success — see the note on Database.DropTable.

func (*Database) DropTriggerContext added in v0.0.9

func (d *Database) DropTriggerContext(ctx context.Context, schema, name string) error

DropTriggerContext is the context-aware variant of DropTrigger.

func (*Database) DropType added in v0.0.13

func (d *Database) DropType(schema, name string) error

DropType drops an alias, table or CLR type — all three are DROP TYPE, and nothing in the statement distinguishes them, so one method serves all three families. A type still referenced by a column, parameter or function is refused by the server; that error is the caller's to report.

func (*Database) DropTypeContext added in v0.0.13

func (d *Database) DropTypeContext(ctx context.Context, schema, name string) error

DropTypeContext is the context-aware variant of DropType.

func (*Database) DropUser

func (d *Database) DropUser(name string) error

DropUser drops a database user.

func (*Database) DropUserContext

func (d *Database) DropUserContext(ctx context.Context, name string) error

DropUserContext is the context-aware variant of DropUser.

func (*Database) DropView added in v0.0.9

func (d *Database) DropView(schema, name string) error

DropView drops a view. A view that isn't there is the server's error, not a silent success — see the note on Database.DropTable.

func (*Database) DropViewContext added in v0.0.9

func (d *Database) DropViewContext(ctx context.Context, schema, name string) error

DropViewContext is the context-aware variant of DropView.

func (*Database) DropXmlSchemaCollection added in v0.0.13

func (d *Database) DropXmlSchemaCollection(schema, name string) error

DropXmlSchemaCollection drops an XML schema collection.

func (*Database) DropXmlSchemaCollectionContext added in v0.0.13

func (d *Database) DropXmlSchemaCollectionContext(ctx context.Context, schema, name string) error

DropXmlSchemaCollectionContext is the context-aware variant of DropXmlSchemaCollection.

func (*Database) EffectiveObjectPermissionSeq added in v0.0.8

func (d *Database) EffectiveObjectPermissionSeq(ctx context.Context, schema, name, principal string) iter.Seq2[*EffectivePermission, error]

EffectiveObjectPermissionSeq returns an iterator over every permission principal effectively holds on the table or view schema.name.

func (*Database) EffectiveObjectPermissions added in v0.0.8

func (d *Database) EffectiveObjectPermissions(schema, name, principal string) ([]*EffectivePermission, error)

EffectiveObjectPermissions returns every permission principal effectively holds on the table or view schema.name, column-level entries included (see EffectivePermission.Subentity). principal must be a database user — see EffectivePermissions for why a role cannot be one.

func (*Database) EffectiveObjectPermissionsContext added in v0.0.8

func (d *Database) EffectiveObjectPermissionsContext(ctx context.Context, schema, name, principal string) ([]*EffectivePermission, error)

EffectiveObjectPermissionsContext is the context-aware variant of EffectiveObjectPermissions.

func (*Database) EffectivePermissionSeq added in v0.0.8

func (d *Database) EffectivePermissionSeq(ctx context.Context, principal string) iter.Seq2[*EffectivePermission, error]

EffectivePermissionSeq returns an iterator over every permission principal effectively holds on the database itself.

func (*Database) EffectivePermissions added in v0.0.8

func (d *Database) EffectivePermissions(principal string) ([]*EffectivePermission, error)

EffectivePermissions returns every permission principal effectively holds on the database itself — SSMS's Effective tab on a database user's Securables page, with the database row selected.

principal must be a database *user* that exists in this database. A database role is not accepted and cannot be made to work: every function here resolves permissions by impersonating the principal, and SQL Server refuses to impersonate a role — "Cannot execute as the database principal because the principal %q does not exist, this type of principal cannot be impersonated, or you do not have permission" (Msg 15517), verified live 2026-08-05 against a role that plainly did exist. There is no principal argument to fn_my_permissions to use instead; it always answers for the current execution context.

func (*Database) EffectivePermissionsContext added in v0.0.8

func (d *Database) EffectivePermissionsContext(ctx context.Context, principal string) ([]*EffectivePermission, error)

EffectivePermissionsContext is the context-aware variant of EffectivePermissions.

func (*Database) EffectiveSchemaPermissionSeq added in v0.0.8

func (d *Database) EffectiveSchemaPermissionSeq(ctx context.Context, schemaName, principal string) iter.Seq2[*EffectivePermission, error]

EffectiveSchemaPermissionSeq returns an iterator over every permission principal effectively holds on a schema.

func (*Database) EffectiveSchemaPermissions added in v0.0.8

func (d *Database) EffectiveSchemaPermissions(schemaName, principal string) ([]*EffectivePermission, error)

EffectiveSchemaPermissions returns every permission principal effectively holds on a schema. principal must be a database user — see EffectivePermissions for why a role cannot be one.

func (*Database) EffectiveSchemaPermissionsContext added in v0.0.8

func (d *Database) EffectiveSchemaPermissionsContext(ctx context.Context, schemaName, principal string) ([]*EffectivePermission, error)

EffectiveSchemaPermissionsContext is the context-aware variant of EffectiveSchemaPermissions.

func (*Database) EnclaveComputationsSupported added in v0.0.11

func (d *Database) EnclaveComputationsSupported() bool

EnclaveComputationsSupported reports whether this instance understands CREATE COLUMN MASTER KEY's ENCLAVE_COMPUTATIONS clause, which SQL Server 2019 added. Below it the clause is not "ignored" — the parser rejects the whole statement with "Incorrect syntax near ','", so a caller offering an enclave option should hide it rather than let it fail on submit.

An unread version (0) is treated as supported, the convention every version gate here follows.

func (*Database) EstimatedPlan added in v0.0.4

func (d *Database) EstimatedPlan(sql string) (*ExecutionPlan, error)

EstimatedPlan captures sql's estimated execution plan without running it (SET SHOWPLAN_XML ON) — SSMS's "Display Estimated Execution Plan".

func (*Database) EstimatedPlanContext added in v0.0.4

func (d *Database) EstimatedPlanContext(ctx context.Context, sqlText string) (*ExecutionPlan, error)

EstimatedPlanContext is the context-aware variant of EstimatedPlan.

func (*Database) ExecProc added in v0.0.4

func (d *Database) ExecProc(schema, name string, params ...ProcParam) (ProcResult, error)

ExecProc executes a stored procedure by schema and name, binding the given parameters and capturing its return status. Output parameter values are written to the pointers passed to Out / InOut. Any result sets the procedure emits are discarded; use the query methods when you need the rows.

func (*Database) ExecProcContext added in v0.0.4

func (d *Database) ExecProcContext(ctx context.Context, schema, name string, params ...ProcParam) (ProcResult, error)

ExecProcContext is the context-aware variant of ExecProc.

func (*Database) ExtendedProperties

func (d *Database) ExtendedProperties(level ExtendedPropertyLevel) ([]*ExtendedProperty, error)

ExtendedProperties returns the extended properties for a specific object.

func (*Database) ExtendedPropertiesContext added in v0.0.5

func (d *Database) ExtendedPropertiesContext(ctx context.Context, level ExtendedPropertyLevel) ([]*ExtendedProperty, error)

ExtendedPropertiesContext is the context-aware variant of ExtendedProperties.

Every level goes through nullableStr, level 0 included. Hard-coded quotes there instead send an empty N-literal for a level the caller left empty, and fn_listextendedproperty reads that as a level named by the empty string rather than as an absent one — so a zero ExtendedPropertyLevel, which AddExtendedProperty and its siblings write as @level0type = NULL, came back from this read as no rows at all. The read and the three writes have to name the same object.

func (*Database) ExtendedPropertySeq added in v0.0.6

func (d *Database) ExtendedPropertySeq(ctx context.Context, level ExtendedPropertyLevel) iter.Seq2[*ExtendedProperty, error]

ExtendedPropertySeq returns an iterator over the extended properties at the given level (as opposed to DatabaseExtendedPropertySeq's database-level-only shortcut).

func (*Database) ExternalDataSourceByName added in v0.0.13

func (d *Database) ExternalDataSourceByName(name string) (*ExternalDataSource, error)

ExternalDataSourceByName returns one external data source, or a not-found error (errors.Is ErrNotFound) when the database has none by that name.

func (*Database) ExternalDataSourceByNameContext added in v0.0.13

func (d *Database) ExternalDataSourceByNameContext(ctx context.Context, name string) (*ExternalDataSource, error)

ExternalDataSourceByNameContext is the context-aware variant of ExternalDataSourceByName.

func (*Database) ExternalDataSourceSeq added in v0.0.13

func (d *Database) ExternalDataSourceSeq(ctx context.Context) iter.Seq2[*ExternalDataSource, error]

ExternalDataSourceSeq returns an iterator over all external data sources in the database.

func (*Database) ExternalDataSources added in v0.0.13

func (d *Database) ExternalDataSources() ([]*ExternalDataSource, error)

ExternalDataSources returns the external data sources defined in the database.

func (*Database) ExternalDataSourcesContext added in v0.0.13

func (d *Database) ExternalDataSourcesContext(ctx context.Context) ([]*ExternalDataSource, error)

ExternalDataSourcesContext is the context-aware variant of ExternalDataSources.

func (*Database) ExternalFileFormatByName added in v0.0.13

func (d *Database) ExternalFileFormatByName(name string) (*ExternalFileFormat, error)

ExternalFileFormatByName returns one external file format, or a not-found error (errors.Is ErrNotFound) when the database has none by that name.

func (*Database) ExternalFileFormatByNameContext added in v0.0.13

func (d *Database) ExternalFileFormatByNameContext(ctx context.Context, name string) (*ExternalFileFormat, error)

ExternalFileFormatByNameContext is the context-aware variant of ExternalFileFormatByName.

func (*Database) ExternalFileFormatSeq added in v0.0.13

func (d *Database) ExternalFileFormatSeq(ctx context.Context) iter.Seq2[*ExternalFileFormat, error]

ExternalFileFormatSeq returns an iterator over all external file formats in the database.

func (*Database) ExternalFileFormats added in v0.0.13

func (d *Database) ExternalFileFormats() ([]*ExternalFileFormat, error)

ExternalFileFormats returns the external file formats defined in the database.

func (*Database) ExternalFileFormatsContext added in v0.0.13

func (d *Database) ExternalFileFormatsContext(ctx context.Context) ([]*ExternalFileFormat, error)

ExternalFileFormatsContext is the context-aware variant of ExternalFileFormats.

func (*Database) ExternalLibraries added in v0.0.13

func (d *Database) ExternalLibraries() ([]*ExternalLibrary, error)

ExternalLibraries returns the external libraries registered in the database. It returns an ErrUnsupportedVersion error before SQL Server 2017.

func (*Database) ExternalLibrariesContext added in v0.0.13

func (d *Database) ExternalLibrariesContext(ctx context.Context) ([]*ExternalLibrary, error)

ExternalLibrariesContext is the context-aware variant of ExternalLibraries.

func (*Database) ExternalLibraryByName added in v0.0.13

func (d *Database) ExternalLibraryByName(name string) (*ExternalLibrary, error)

ExternalLibraryByName returns one external library, or a not-found error (errors.Is ErrNotFound) when the database has none by that name. It returns an ErrUnsupportedVersion error before SQL Server 2017.

func (*Database) ExternalLibraryByNameContext added in v0.0.13

func (d *Database) ExternalLibraryByNameContext(ctx context.Context, name string) (*ExternalLibrary, error)

ExternalLibraryByNameContext is the context-aware variant of ExternalLibraryByName.

func (*Database) ExternalLibrarySeq added in v0.0.13

func (d *Database) ExternalLibrarySeq(ctx context.Context) iter.Seq2[*ExternalLibrary, error]

ExternalLibrarySeq returns an iterator over all external libraries in the database. It yields a single (nil, ErrUnsupportedVersion) before SQL Server 2017, where the catalog view does not exist.

func (*Database) FileGroupSeq added in v0.0.6

func (d *Database) FileGroupSeq(ctx context.Context) iter.Seq2[*FileGroup, error]

FileGroupSeq returns an iterator over all filegroups in the database.

func (*Database) FileGroups

func (d *Database) FileGroups() ([]*FileGroup, error)

FileGroups returns all filegroups and their files.

func (*Database) FileGroupsContext

func (d *Database) FileGroupsContext(ctx context.Context) ([]*FileGroup, error)

FileGroupsContext is the context-aware variant of FileGroups.

func (*Database) FileSeq added in v0.0.4

func (d *Database) FileSeq(ctx context.Context) iter.Seq2[*DatabaseFileInfo, error]

FileSeq returns an iterator over every file in the database.

func (*Database) Files added in v0.0.4

func (d *Database) Files() ([]*DatabaseFileInfo, error)

Files returns every file in the database, data and log alike.

func (*Database) FilesContext added in v0.0.4

func (d *Database) FilesContext(ctx context.Context) ([]*DatabaseFileInfo, error)

FilesContext is the context-aware variant of Files.

func (*Database) FindSecurables added in v0.0.8

func (d *Database) FindSecurables(search SecurableSearch) ([]SecurableRef, error)

FindSecurables returns the schemas, tables and views matching search.

func (*Database) FindSecurablesContext added in v0.0.8

func (d *Database) FindSecurablesContext(ctx context.Context, search SecurableSearch) ([]SecurableRef, error)

FindSecurablesContext is the context-aware variant of FindSecurables.

One query over sys.schemas, sys.tables and sys.views, for a caller that needs candidates matching what the user typed rather than the whole catalog — a database with thousands of tables makes "list everything and filter in the client" both slow to open and useless as a picker.

func (*Database) FlushQueryStore added in v0.0.5

func (d *Database) FlushQueryStore() error

FlushQueryStore forces Query Store to persist its in-memory data to disk immediately (SSMS's "Flush Data" action), via sys.sp_query_store_flush_db.

func (*Database) FlushQueryStoreContext added in v0.0.5

func (d *Database) FlushQueryStoreContext(ctx context.Context) error

FlushQueryStoreContext is the context-aware variant of FlushQueryStore.

func (*Database) GrantColumnPermission added in v0.0.8

func (d *Database) GrantColumnPermission(schema, name string, permission ObjectPermission, columns []string, principal string) error

GrantColumnPermission grants permission on the named columns of schema.name to principal. Passing several columns renders the one statement SQL Server accepts for them — GRANT SELECT (a, b) ON ... — not one statement per column.

func (*Database) GrantColumnPermissionContext added in v0.0.8

func (d *Database) GrantColumnPermissionContext(ctx context.Context, schema, name string, permission ObjectPermission, columns []string, principal string) error

GrantColumnPermissionContext is the context-aware variant of GrantColumnPermission.

func (*Database) GrantColumnPermissionWithOptions added in v0.0.8

func (d *Database) GrantColumnPermissionWithOptions(schema, name string, permission ObjectPermission, columns []string, principal string, opts PermissionOptions) error

GrantColumnPermissionWithOptions grants a column-level permission honouring opts — the WITH GRANT OPTION form of GrantColumnPermission.

func (*Database) GrantColumnPermissionWithOptionsContext added in v0.0.8

func (d *Database) GrantColumnPermissionWithOptionsContext(ctx context.Context, schema, name string, permission ObjectPermission, columns []string, principal string, opts PermissionOptions) error

GrantColumnPermissionWithOptionsContext is the context-aware variant of GrantColumnPermissionWithOptions.

func (*Database) GrantDatabasePermission added in v0.0.4

func (d *Database) GrantDatabasePermission(permission, principal string) error

GrantDatabasePermission grants a database-level permission to principal.

func (*Database) GrantDatabasePermissionContext added in v0.0.4

func (d *Database) GrantDatabasePermissionContext(ctx context.Context, permission, principal string) error

GrantDatabasePermissionContext is the context-aware variant of GrantDatabasePermission.

func (*Database) GrantDatabasePermissionWithOptions added in v0.0.8

func (d *Database) GrantDatabasePermissionWithOptions(permission, principal string, opts PermissionOptions) error

GrantDatabasePermissionWithOptions grants a database-level permission to principal, honouring opts.

func (*Database) GrantDatabasePermissionWithOptionsContext added in v0.0.8

func (d *Database) GrantDatabasePermissionWithOptionsContext(ctx context.Context, permission, principal string, opts PermissionOptions) error

GrantDatabasePermissionWithOptionsContext is the context-aware variant of GrantDatabasePermissionWithOptions.

func (*Database) GrantPermission added in v0.0.4

func (d *Database) GrantPermission(schema, name string, permission ObjectPermission, principal string) error

GrantPermission grants permission on schema.name to principal.

func (*Database) GrantPermissionContext added in v0.0.4

func (d *Database) GrantPermissionContext(ctx context.Context, schema, name string, permission ObjectPermission, principal string) error

GrantPermissionContext is the context-aware variant of GrantPermission.

func (*Database) GrantPermissionWithOptions added in v0.0.8

func (d *Database) GrantPermissionWithOptions(schema, name string, permission ObjectPermission, principal string, opts PermissionOptions) error

GrantPermissionWithOptions grants permission on schema.name to principal, honouring opts — the WITH GRANT OPTION form of GrantPermission.

func (*Database) GrantPermissionWithOptionsContext added in v0.0.8

func (d *Database) GrantPermissionWithOptionsContext(ctx context.Context, schema, name string, permission ObjectPermission, principal string, opts PermissionOptions) error

GrantPermissionWithOptionsContext is the context-aware variant of GrantPermissionWithOptions.

func (*Database) GrantSchemaPermission added in v0.0.5

func (d *Database) GrantSchemaPermission(schemaName string, permission ObjectPermission, principal string) error

GrantSchemaPermission grants permission on a schema to principal.

func (*Database) GrantSchemaPermissionContext added in v0.0.5

func (d *Database) GrantSchemaPermissionContext(ctx context.Context, schemaName string, permission ObjectPermission, principal string) error

GrantSchemaPermissionContext is the context-aware variant of GrantSchemaPermission.

func (*Database) GrantSchemaPermissionWithOptions added in v0.0.8

func (d *Database) GrantSchemaPermissionWithOptions(schemaName string, permission ObjectPermission, principal string, opts PermissionOptions) error

GrantSchemaPermissionWithOptions grants permission on a schema to principal, honouring opts.

func (*Database) GrantSchemaPermissionWithOptionsContext added in v0.0.8

func (d *Database) GrantSchemaPermissionWithOptionsContext(ctx context.Context, schemaName string, permission ObjectPermission, principal string, opts PermissionOptions) error

GrantSchemaPermissionWithOptionsContext is the context-aware variant of GrantSchemaPermissionWithOptions.

func (*Database) HasMasterKey added in v0.0.9

func (d *Database) HasMasterKey() (bool, error)

HasMasterKey reports whether the database has a master key. A certificate whose private key is to open without a password needs one.

func (*Database) HasMasterKeyContext added in v0.0.9

func (d *Database) HasMasterKeyContext(ctx context.Context) (bool, error)

HasMasterKeyContext is the context-aware variant of HasMasterKey.

func (*Database) ID

func (d *Database) ID() int

ID returns the database_id from sys.databases.

func (*Database) IsReadOnly

func (d *Database) IsReadOnly() bool

IsReadOnly reports whether the database is set to read-only.

func (*Database) IsSnapshot added in v0.0.13

func (d *Database) IsSnapshot() bool

IsSnapshot reports whether this database is a database snapshot.

func (*Database) IsSystem added in v0.0.4

func (d *Database) IsSystem() bool

IsSystem reports whether this is one of SQL Server's four built-in system databases (master, tempdb, model, msdb), identified by their permanently reserved database_id (1-4) rather than by name.

func (*Database) LatestResourceStats added in v0.0.13

func (d *Database) LatestResourceStats() (*DatabaseResourceStat, error)

LatestResourceStats returns the newest sys.dm_db_resource_stats row for this database.

func (*Database) LatestResourceStatsContext added in v0.0.13

func (d *Database) LatestResourceStatsContext(ctx context.Context) (*DatabaseResourceStat, error)

LatestResourceStatsContext is the context-aware variant of LatestResourceStats, for a caller that wants the database's current consumption rather than its history.

It returns ErrNotFound when the view is empty, which a database that has been idle since the instance last restarted is.

func (*Database) Name

func (d *Database) Name() string

Name returns the database name.

func (*Database) ObjectColumnSeq added in v0.0.8

func (d *Database) ObjectColumnSeq(ctx context.Context, schema, name string) iter.Seq2[*Column, error]

ObjectColumnSeq returns an iterator over the columns of the table or view schema.name — the Database-scoped counterpart of Table.ColumnSeq, and the only one of the two that reaches a view.

func (*Database) ObjectColumns added in v0.0.8

func (d *Database) ObjectColumns(schema, name string) ([]*Column, error)

ObjectColumns returns the columns of the table or view schema.name, in ordinal order. Table.Columns covers tables only, and a view has no handle type of its own that carries an object_id, so this is the way to reach a view's columns — which do carry permissions, and so do turn up on a Securables page.

func (*Database) ObjectColumnsContext added in v0.0.8

func (d *Database) ObjectColumnsContext(ctx context.Context, schema, name string) ([]*Column, error)

ObjectColumnsContext is the context-aware variant of ObjectColumns.

The columns a view does not have — identity, computed text, defaults, primary key — come back at their zero values, because the joins that supply them simply do not match for a view. Name, ordinal, type, length/precision/scale, nullability and collation are all real.

func (*Database) ObjectTriggers added in v0.0.12

func (d *Database) ObjectTriggers(schema, name string) ([]*Trigger, error)

ObjectTriggers returns the DML triggers defined on one table or view — AFTER and INSTEAD OF triggers, the parent_class = 1 family, for a single parent named rather than handed over as a *Table.

It is Table.Triggers' by-name counterpart, and it exists because View is a plain row struct with no back-pointer to its database, so a view's INSTEAD OF triggers had no reader at all. The parent is resolved by OBJECT_ID, which does not care which of the two it is.

func (*Database) ObjectTriggersContext added in v0.0.12

func (d *Database) ObjectTriggersContext(ctx context.Context, schema, name string) ([]*Trigger, error)

ObjectTriggersContext is the context-aware variant of ObjectTriggers.

func (*Database) Options added in v0.0.4

func (d *Database) Options() (*DatabaseOptions, error)

Options returns the database's ALTER DATABASE SET options.

func (*Database) OptionsContext added in v0.0.4

func (d *Database) OptionsContext(ctx context.Context) (*DatabaseOptions, error)

OptionsContext is the context-aware variant of Options. Queried against sys.databases at server scope (like Server.DatabaseByNameContext), not through d.query — these are catalog-view columns, not per-database data.

func (*Database) ParameterSeq added in v0.0.10

func (d *Database) ParameterSeq(ctx context.Context, schema, name string) iter.Seq2[*Parameter, error]

ParameterSeq returns an iterator over the parameters of one stored procedure or function.

func (*Database) Parameters added in v0.0.10

func (d *Database) Parameters(schema, name string) ([]*Parameter, error)

Parameters returns the parameters of one stored procedure or function, in declaration order.

func (*Database) ParametersContext added in v0.0.10

func (d *Database) ParametersContext(ctx context.Context, schema, name string) ([]*Parameter, error)

ParametersContext is the context-aware variant of Parameters.

func (*Database) PartitionFunctionByName added in v0.0.10

func (d *Database) PartitionFunctionByName(name string) (*PartitionFunction, error)

PartitionFunctionByName returns one partition function by name.

func (*Database) PartitionFunctionByNameContext added in v0.0.10

func (d *Database) PartitionFunctionByNameContext(ctx context.Context, name string) (*PartitionFunction, error)

PartitionFunctionByNameContext is the context-aware variant of PartitionFunctionByName.

func (*Database) PartitionFunctionSeq added in v0.0.5

func (d *Database) PartitionFunctionSeq(ctx context.Context) iter.Seq2[*PartitionFunction, error]

PartitionFunctionSeq returns an iterator over all partition functions in the database.

func (*Database) PartitionFunctions

func (d *Database) PartitionFunctions() ([]*PartitionFunction, error)

PartitionFunctions returns all partition functions in the database.

func (*Database) PartitionFunctionsContext added in v0.0.5

func (d *Database) PartitionFunctionsContext(ctx context.Context) ([]*PartitionFunction, error)

PartitionFunctionsContext is the context-aware variant of PartitionFunctions.

func (*Database) PartitionSchemeByName added in v0.0.10

func (d *Database) PartitionSchemeByName(name string) (*PartitionScheme, error)

PartitionSchemeByName returns one partition scheme by name.

func (*Database) PartitionSchemeByNameContext added in v0.0.10

func (d *Database) PartitionSchemeByNameContext(ctx context.Context, name string) (*PartitionScheme, error)

PartitionSchemeByNameContext is the context-aware variant of PartitionSchemeByName.

func (*Database) PartitionSchemeSeq added in v0.0.5

func (d *Database) PartitionSchemeSeq(ctx context.Context) iter.Seq2[*PartitionScheme, error]

PartitionSchemeSeq returns an iterator over all partition schemes in the database.

func (*Database) PartitionSchemes

func (d *Database) PartitionSchemes() ([]*PartitionScheme, error)

PartitionSchemes returns all partition schemes in the database.

func (*Database) PartitionSchemesContext added in v0.0.5

func (d *Database) PartitionSchemesContext(ctx context.Context) ([]*PartitionScheme, error)

PartitionSchemesContext is the context-aware variant of PartitionSchemes.

func (*Database) PermissionSeq added in v0.0.6

func (d *Database) PermissionSeq(ctx context.Context, schema, name string) iter.Seq2[*PermissionEntry, error]

PermissionSeq returns an iterator over the GRANT/DENY entries recorded for schema.name.

func (*Database) Permissions added in v0.0.4

func (d *Database) Permissions(schema, name string) ([]*PermissionEntry, error)

Permissions returns the GRANT/DENY entries recorded for schema.name — SSMS's object Properties > Permissions page.

func (*Database) PermissionsContext added in v0.0.4

func (d *Database) PermissionsContext(ctx context.Context, schema, name string) ([]*PermissionEntry, error)

PermissionsContext is the context-aware variant of Permissions.

func (*Database) PermissionsForPrincipal added in v0.0.5

func (d *Database) PermissionsForPrincipal(principal string) ([]*PrincipalSecurable, error)

PermissionsForPrincipal returns every explicit GRANT/DENY entry recorded for principal across database-, schema-, and table/view-scoped securables. Stored procedure and function securables are deliberately excluded — they need their own permission catalog (EXECUTE-centric, distinct from the table/view one) not built yet; see SchemaPermissionNames/ ObjectPermissionNames for the catalogs this DOES cover.

func (*Database) PermissionsForPrincipalContext added in v0.0.5

func (d *Database) PermissionsForPrincipalContext(ctx context.Context, principal string) ([]*PrincipalSecurable, error)

PermissionsForPrincipalContext is the context-aware variant of PermissionsForPrincipal.

func (*Database) PermissionsForPrincipalSeq added in v0.0.6

func (d *Database) PermissionsForPrincipalSeq(ctx context.Context, principal string) iter.Seq2[*PrincipalSecurable, error]

PermissionsForPrincipalSeq returns an iterator over every explicit GRANT/DENY entry recorded for principal across database-, schema-, and table/view-scoped securables.

func (*Database) PlanGuide added in v0.0.13

func (d *Database) PlanGuide(name string) *PlanGuide

PlanGuide returns a lightweight handle for a plan guide by name, without querying sys.plan_guides — the counterpart of Server.Database and Database.DatabaseTrigger.

Every other field stays at its zero value; PlanGuideByName is what populates them. Enable, Disable and Drop address the guide by name, so this handle is enough to act on one the caller already knows exists, and is the only usable form under a WithScript context, where PlanGuideByNameContext's lookup is a real read.

func (*Database) PlanGuideByName added in v0.0.13

func (d *Database) PlanGuideByName(name string) (*PlanGuide, error)

PlanGuideByName returns one plan guide with every field populated, or a not-found error (errors.Is ErrNotFound) when the database has none by that name.

func (*Database) PlanGuideByNameContext added in v0.0.13

func (d *Database) PlanGuideByNameContext(ctx context.Context, name string) (*PlanGuide, error)

PlanGuideByNameContext is the context-aware variant of PlanGuideByName.

func (*Database) PlanGuideSeq added in v0.0.13

func (d *Database) PlanGuideSeq(ctx context.Context) iter.Seq2[*PlanGuide, error]

PlanGuideSeq returns an iterator over all plan guides in the database.

func (*Database) PlanGuides added in v0.0.13

func (d *Database) PlanGuides() ([]*PlanGuide, error)

PlanGuides returns the plan guides defined in the database.

func (*Database) PlanGuidesContext added in v0.0.13

func (d *Database) PlanGuidesContext(ctx context.Context) ([]*PlanGuide, error)

PlanGuidesContext is the context-aware variant of PlanGuides.

func (*Database) QueryStore added in v0.0.5

func (d *Database) QueryStore() (*QueryStoreInfo, error)

QueryStore returns the database's Query Store configuration and state.

func (*Database) QueryStoreContext added in v0.0.5

func (d *Database) QueryStoreContext(ctx context.Context) (*QueryStoreInfo, error)

QueryStoreContext is the context-aware variant of QueryStore.

func (*Database) QueryStoreForcePlan added in v0.0.11

func (d *Database) QueryStoreForcePlan(queryID, planID int64) error

QueryStoreForcePlan pins one plan as the only plan the optimizer may use for a query — SSMS's Force Plan.

func (*Database) QueryStoreForcePlanContext added in v0.0.11

func (d *Database) QueryStoreForcePlanContext(ctx context.Context, queryID, planID int64) error

QueryStoreForcePlanContext is the context-aware variant of QueryStoreForcePlan. It needs ALTER on the database.

Forcing does not guarantee the plan is used: the engine records a failure on sys.query_store_plan.last_force_failure_reason_desc and silently recompiles when the plan can no longer be produced (a dropped index, say). Read the plan back with QueryStorePlansContext to see whether it took.

func (*Database) QueryStoreForcedPlanQueries added in v0.0.11

func (d *Database) QueryStoreForcedPlanQueries(opts QueryStoreReportOptions) ([]*QSQueryStat, error)

QueryStoreForcedPlanQueries lists the queries that have a forced plan — SSMS's Queries With Forced Plans view.

func (*Database) QueryStoreForcedPlanQueriesContext added in v0.0.11

func (d *Database) QueryStoreForcedPlanQueriesContext(ctx context.Context, opts QueryStoreReportOptions) ([]*QSQueryStat, error)

QueryStoreForcedPlanQueriesContext is the context-aware variant of QueryStoreForcedPlanQueries.

The forced-plan predicate is applied as a HAVING over the whole query rather than a WHERE on the plan: a query's *other* plans still have runtime stats in the window, and filtering them out at the row level would report the forced plan's cost as the query's total.

func (*Database) QueryStoreHighVariationQueries added in v0.0.11

func (d *Database) QueryStoreHighVariationQueries(opts QueryStoreReportOptions) ([]*QSQueryStat, error)

QueryStoreHighVariationQueries ranks queries by how unstable one metric is — SSMS's Queries With High Variation view.

func (*Database) QueryStoreHighVariationQueriesContext added in v0.0.11

func (d *Database) QueryStoreHighVariationQueriesContext(ctx context.Context, opts QueryStoreReportOptions) ([]*QSQueryStat, error)

QueryStoreHighVariationQueriesContext is the context-aware variant of QueryStoreHighVariationQueries.

Ranking is by coefficient of variation (stdev/avg), not by stdev: the most expensive query in the database otherwise tops a variation report merely for being expensive. Value still carries the statistic the caller asked for, so the report can show the cost beside the instability.

func (*Database) QueryStoreMetrics added in v0.0.11

func (d *Database) QueryStoreMetrics() []QSMetric

QueryStoreMetrics returns every metric a Query Store report can rank by, in SSMS's display order. Metrics the instance is too old to have are left out, so a caller building a selector from this never offers one that cannot be read.

func (*Database) QueryStoreOverallConsumption added in v0.0.11

func (d *Database) QueryStoreOverallConsumption(opts QueryStoreReportOptions) ([]*QSIntervalStat, error)

QueryStoreOverallConsumption totals one metric per runtime-stats interval across the whole database — SSMS's Overall Resource Consumption view.

func (*Database) QueryStoreOverallConsumptionContext added in v0.0.11

func (d *Database) QueryStoreOverallConsumptionContext(ctx context.Context, opts QueryStoreReportOptions) ([]*QSIntervalStat, error)

QueryStoreOverallConsumptionContext is the context-aware variant of QueryStoreOverallConsumption. Rows come back oldest first, ready to plot, and Options.Top does not apply — the caller asked for a time range, and dropping intervals out of the middle of it would misdraw the chart.

func (*Database) QueryStorePlans added in v0.0.11

func (d *Database) QueryStorePlans(queryID int64, opts QueryStoreReportOptions) ([]*QSPlan, error)

QueryStorePlans returns every plan Query Store holds for one query, with its cost over the report's window — the plan list under SSMS's Query Store views, and what Force Plan picks from.

func (*Database) QueryStorePlansContext added in v0.0.11

func (d *Database) QueryStorePlansContext(ctx context.Context, queryID int64, opts QueryStoreReportOptions) ([]*QSPlan, error)

QueryStorePlansContext is the context-aware variant of QueryStorePlans.

The runtime-stats join is a LEFT one: a plan that did not run inside the window still exists, is still forceable, and still has plan XML worth showing — dropping it would hide the very plan a user opened the report to force back.

func (*Database) QueryStoreQueryText added in v0.0.11

func (d *Database) QueryStoreQueryText(queryID int64) (text, objectName string, err error)

QueryStoreQueryText returns one query's SQL text and the schema-qualified module it belongs to, empty if it is ad hoc.

func (*Database) QueryStoreQueryTextContext added in v0.0.11

func (d *Database) QueryStoreQueryTextContext(ctx context.Context, queryID int64) (text, objectName string, err error)

QueryStoreQueryTextContext is the context-aware variant of QueryStoreQueryText. A query id Query Store no longer holds — cleanup removes them — comes back as an error wrapping ErrNotFound.

func (*Database) QueryStoreRegressedQueries added in v0.0.11

func (d *Database) QueryStoreRegressedQueries(opts QueryStoreReportOptions) ([]*QSQueryStat, error)

QueryStoreRegressedQueries ranks queries by how much one metric has grown between two windows — SSMS's Regressed Queries view.

func (*Database) QueryStoreRegressedQueriesContext added in v0.0.11

func (d *Database) QueryStoreRegressedQueriesContext(ctx context.Context, opts QueryStoreReportOptions) ([]*QSQueryStat, error)

QueryStoreRegressedQueriesContext is the context-aware variant of QueryStoreRegressedQueries. It compares [From, To) against [BaselineFrom, BaselineTo), which default to the equally long window immediately before From.

The join between the two windows is an inner one on purpose: a query with no executions in the baseline window has not regressed, it is new, and ranking it by "growth from zero" would fill the report with first-time queries and hide the actual regressions.

func (*Database) QueryStoreTopResourceQueries added in v0.0.11

func (d *Database) QueryStoreTopResourceQueries(opts QueryStoreReportOptions) ([]*QSQueryStat, error)

QueryStoreTopResourceQueries ranks the database's queries by one metric — SSMS's Top Resource Consuming Queries view.

func (*Database) QueryStoreTopResourceQueriesContext added in v0.0.11

func (d *Database) QueryStoreTopResourceQueriesContext(ctx context.Context, opts QueryStoreReportOptions) ([]*QSQueryStat, error)

QueryStoreTopResourceQueriesContext is the context-aware variant of QueryStoreTopResourceQueries.

func (*Database) QueryStoreTrackedQuery added in v0.0.11

func (d *Database) QueryStoreTrackedQuery(queryID int64, opts QueryStoreReportOptions) ([]*QSPlanIntervalStat, error)

QueryStoreTrackedQuery returns one query's per-plan time series — SSMS's Tracked Queries view.

func (*Database) QueryStoreTrackedQueryContext added in v0.0.11

func (d *Database) QueryStoreTrackedQueryContext(ctx context.Context, queryID int64, opts QueryStoreReportOptions) ([]*QSPlanIntervalStat, error)

QueryStoreTrackedQueryContext is the context-aware variant of QueryStoreTrackedQuery. Rows come back plan by plan, oldest interval first, which is the order a per-plan series is plotted in.

func (*Database) QueryStoreUnforcePlan added in v0.0.11

func (d *Database) QueryStoreUnforcePlan(queryID, planID int64) error

QueryStoreUnforcePlan releases a plan forced by QueryStoreForcePlan, returning the query to normal optimization — SSMS's Unforce Plan.

func (*Database) QueryStoreUnforcePlanContext added in v0.0.11

func (d *Database) QueryStoreUnforcePlanContext(ctx context.Context, queryID, planID int64) error

QueryStoreUnforcePlanContext is the context-aware variant of QueryStoreUnforcePlan. It needs ALTER on the database.

func (*Database) QueryStoreWaitCategories added in v0.0.11

func (d *Database) QueryStoreWaitCategories(opts QueryStoreReportOptions) ([]*QSWaitStat, error)

QueryStoreWaitCategories totals wait time by category — the top half of SSMS's Query Wait Statistics view.

func (*Database) QueryStoreWaitCategoriesContext added in v0.0.11

func (d *Database) QueryStoreWaitCategoriesContext(ctx context.Context, opts QueryStoreReportOptions) ([]*QSWaitStat, error)

QueryStoreWaitCategoriesContext is the context-aware variant of QueryStoreWaitCategories. Values are milliseconds whatever Options.Metric says — Query Store records wait time and nothing else per category — but Options.Statistic still applies.

func (*Database) QueryStoreWaitStatsSupported added in v0.0.11

func (d *Database) QueryStoreWaitStatsSupported() bool

QueryStoreWaitStatsSupported reports whether this instance has sys.query_store_wait_stats, which SQL Server 2017 added. Below it the two wait reports return an error rather than an empty result, so a caller building a report list should leave them out.

func (*Database) QueryStoreWaitingQueries added in v0.0.11

func (d *Database) QueryStoreWaitingQueries(category string, opts QueryStoreReportOptions) ([]*QSQueryStat, error)

QueryStoreWaitingQueries ranks the queries waiting in one category — the drill-down half of SSMS's Query Wait Statistics view.

func (*Database) QueryStoreWaitingQueriesContext added in v0.0.11

func (d *Database) QueryStoreWaitingQueriesContext(ctx context.Context, category string, opts QueryStoreReportOptions) ([]*QSQueryStat, error)

QueryStoreWaitingQueriesContext is the context-aware variant of QueryStoreWaitingQueries. category is a sys.query_store_wait_stats wait_category_desc value — one of the Category strings QueryStoreWaitCategoriesContext returned. An empty category covers every one of them. Values are milliseconds.

func (*Database) RecoveryModel

func (d *Database) RecoveryModel() RecoveryModel

RecoveryModel returns the database recovery model.

func (*Database) RecoveryStatus added in v0.0.10

func (d *Database) RecoveryStatus() (*DatabaseRecoveryStatus, error)

RecoveryStatus returns this database's place in its log backup chain.

func (*Database) RecoveryStatusContext added in v0.0.10

func (d *Database) RecoveryStatusContext(ctx context.Context) (*DatabaseRecoveryStatus, error)

RecoveryStatusContext is the context-aware variant of RecoveryStatus.

func (*Database) RemoveFile added in v0.0.4

func (d *Database) RemoveFile(name string) error

RemoveFile drops a file from the database. The file must be empty (0 bytes of used space) — SQL Server itself enforces this, not gosmo.

func (*Database) RemoveFileContext added in v0.0.4

func (d *Database) RemoveFileContext(ctx context.Context, name string) error

RemoveFileContext is the context-aware variant of RemoveFile.

func (*Database) RemoveFileGroup added in v0.0.4

func (d *Database) RemoveFileGroup(name string) error

RemoveFileGroup drops a filegroup. It must be empty (no files) — SQL Server itself enforces this, not gosmo.

func (*Database) RemoveFileGroupContext added in v0.0.4

func (d *Database) RemoveFileGroupContext(ctx context.Context, name string) error

RemoveFileGroupContext is the context-aware variant of RemoveFileGroup.

func (*Database) RemoveRoleMember

func (d *Database) RemoveRoleMember(roleName, memberName string) error

RemoveRoleMember removes a user from a database role.

func (*Database) RemoveRoleMemberContext

func (d *Database) RemoveRoleMemberContext(ctx context.Context, roleName, memberName string) error

RemoveRoleMemberContext is the context-aware variant.

func (*Database) RenameObject added in v0.0.9

func (d *Database) RenameObject(schema, oldName, newName string) error

RenameObject renames any schema-scoped object sp_rename's default 'OBJECT' type covers — a view, procedure, function, sequence, synonym, or trigger. A table is the same statement with its own wording; see RenameTable. An index, statistic, or column each needs its own @objtype and has its own method.

newName is a bare name: sp_rename refuses a qualified one, and renaming does not move the object between schemas (ALTER SCHEMA ... TRANSFER does).

func (*Database) RenameObjectContext added in v0.0.9

func (d *Database) RenameObjectContext(ctx context.Context, schema, oldName, newName string) error

RenameObjectContext is the context-aware variant of RenameObject.

func (*Database) RenameTable

func (d *Database) RenameTable(schema, oldName, newName string) error

RenameTable renames a table using sp_rename.

func (*Database) RenameTableContext

func (d *Database) RenameTableContext(ctx context.Context, schema, oldName, newName string) error

RenameTableContext is the context-aware variant of RenameTable.

func (*Database) RenameUserDefinedDataType added in v0.0.13

func (d *Database) RenameUserDefinedDataType(schema, oldName, newName string) error

RenameUserDefinedDataType renames an alias type (sp_rename's 'USERDATATYPE' class).

Alias types only. The class is documented as covering "an alias data type added by sp_addtype or CREATE TYPE", and it is the whole of what sp_rename can rename in sys.types: a table type or a CLR type has no @objtype at all, and passing one of those here renames nothing while reporting success — so callers must not route them through this method.

newName is a bare name, as everywhere sp_rename is used.

func (*Database) RenameUserDefinedDataTypeContext added in v0.0.13

func (d *Database) RenameUserDefinedDataTypeContext(ctx context.Context, schema, oldName, newName string) error

RenameUserDefinedDataTypeContext is the context-aware variant of RenameUserDefinedDataType.

func (*Database) ResourceGovernance added in v0.0.13

func (d *Database) ResourceGovernance() (*UserDBResourceGovernance, error)

ResourceGovernance returns this database's row of sys.dm_user_db_resource_governance.

func (*Database) ResourceGovernanceContext added in v0.0.13

func (d *Database) ResourceGovernanceContext(ctx context.Context) (*UserDBResourceGovernance, error)

ResourceGovernanceContext is the context-aware variant of ResourceGovernance: the limits governing this database, the scale its ResourceStats percentages are of.

It returns ErrNotFound when the instance governs no row for the database, and an ErrUnsupportedVersion error off an Azure engine edition.

func (*Database) ResourceStats added in v0.0.13

func (d *Database) ResourceStats(max int) ([]*DatabaseResourceStat, error)

ResourceStats returns the most recent max rows of sys.dm_db_resource_stats for this database, oldest first.

func (*Database) ResourceStatsContext added in v0.0.13

func (d *Database) ResourceStatsContext(ctx context.Context, max int) ([]*DatabaseResourceStat, error)

ResourceStatsContext is the context-aware variant of ResourceStats. max caps how far back the read reaches; a max of 0 or less means the whole retained history, which is about an hour.

The view exists only on an Azure engine edition, so this refuses anywhere else with an ErrUnsupportedVersion error rather than letting the server answer with an "invalid object name".

func (*Database) RevokeColumnPermission added in v0.0.8

func (d *Database) RevokeColumnPermission(schema, name string, permission ObjectPermission, columns []string, principal string) error

RevokeColumnPermission revokes permission on the named columns of schema.name from principal.

func (*Database) RevokeColumnPermissionContext added in v0.0.8

func (d *Database) RevokeColumnPermissionContext(ctx context.Context, schema, name string, permission ObjectPermission, columns []string, principal string) error

RevokeColumnPermissionContext is the context-aware variant of RevokeColumnPermission.

func (*Database) RevokeColumnPermissionWithOptions added in v0.0.8

func (d *Database) RevokeColumnPermissionWithOptions(schema, name string, permission ObjectPermission, columns []string, principal string, opts PermissionOptions) error

RevokeColumnPermissionWithOptions revokes a column-level permission honouring opts — the CASCADE and GRANT OPTION FOR forms of RevokeColumnPermission.

func (*Database) RevokeColumnPermissionWithOptionsContext added in v0.0.8

func (d *Database) RevokeColumnPermissionWithOptionsContext(ctx context.Context, schema, name string, permission ObjectPermission, columns []string, principal string, opts PermissionOptions) error

RevokeColumnPermissionWithOptionsContext is the context-aware variant of RevokeColumnPermissionWithOptions.

func (*Database) RevokeDatabasePermission added in v0.0.4

func (d *Database) RevokeDatabasePermission(permission, principal string) error

RevokeDatabasePermission revokes a database-level permission from principal.

func (*Database) RevokeDatabasePermissionContext added in v0.0.4

func (d *Database) RevokeDatabasePermissionContext(ctx context.Context, permission, principal string) error

RevokeDatabasePermissionContext is the context-aware variant of RevokeDatabasePermission.

func (*Database) RevokeDatabasePermissionWithOptions added in v0.0.8

func (d *Database) RevokeDatabasePermissionWithOptions(permission, principal string, opts PermissionOptions) error

RevokeDatabasePermissionWithOptions revokes a database-level permission from principal, honouring opts.

func (*Database) RevokeDatabasePermissionWithOptionsContext added in v0.0.8

func (d *Database) RevokeDatabasePermissionWithOptionsContext(ctx context.Context, permission, principal string, opts PermissionOptions) error

RevokeDatabasePermissionWithOptionsContext is the context-aware variant of RevokeDatabasePermissionWithOptions.

func (*Database) RevokePermission added in v0.0.4

func (d *Database) RevokePermission(schema, name string, permission ObjectPermission, principal string) error

RevokePermission revokes permission on schema.name from principal.

func (*Database) RevokePermissionContext added in v0.0.4

func (d *Database) RevokePermissionContext(ctx context.Context, schema, name string, permission ObjectPermission, principal string) error

RevokePermissionContext is the context-aware variant of RevokePermission.

func (*Database) RevokePermissionWithOptions added in v0.0.8

func (d *Database) RevokePermissionWithOptions(schema, name string, permission ObjectPermission, principal string, opts PermissionOptions) error

RevokePermissionWithOptions revokes permission on schema.name from principal, honouring opts — the CASCADE and GRANT OPTION FOR forms of RevokePermission.

func (*Database) RevokePermissionWithOptionsContext added in v0.0.8

func (d *Database) RevokePermissionWithOptionsContext(ctx context.Context, schema, name string, permission ObjectPermission, principal string, opts PermissionOptions) error

RevokePermissionWithOptionsContext is the context-aware variant of RevokePermissionWithOptions.

func (*Database) RevokeSchemaPermission added in v0.0.5

func (d *Database) RevokeSchemaPermission(schemaName string, permission ObjectPermission, principal string) error

RevokeSchemaPermission revokes permission on a schema from principal.

func (*Database) RevokeSchemaPermissionContext added in v0.0.5

func (d *Database) RevokeSchemaPermissionContext(ctx context.Context, schemaName string, permission ObjectPermission, principal string) error

RevokeSchemaPermissionContext is the context-aware variant of RevokeSchemaPermission.

func (*Database) RevokeSchemaPermissionWithOptions added in v0.0.8

func (d *Database) RevokeSchemaPermissionWithOptions(schemaName string, permission ObjectPermission, principal string, opts PermissionOptions) error

RevokeSchemaPermissionWithOptions revokes permission on a schema from principal, honouring opts.

func (*Database) RevokeSchemaPermissionWithOptionsContext added in v0.0.8

func (d *Database) RevokeSchemaPermissionWithOptionsContext(ctx context.Context, schemaName string, permission ObjectPermission, principal string, opts PermissionOptions) error

RevokeSchemaPermissionWithOptionsContext is the context-aware variant of RevokeSchemaPermissionWithOptions.

func (*Database) RoleByName added in v0.0.5

func (d *Database) RoleByName(name string) (*DatabaseRole, error)

RoleByName returns a single database role by name, with its principal detail (SID, create/modify dates) filled in — DatabaseRolesContext leaves these out since Object Explorer's tree listing never needs them.

func (*Database) RoleByNameContext added in v0.0.5

func (d *Database) RoleByNameContext(ctx context.Context, name string) (*DatabaseRole, error)

RoleByNameContext is the context-aware variant of RoleByName.

func (*Database) RoleMemberSeq added in v0.0.6

func (d *Database) RoleMemberSeq(ctx context.Context, roleName string) iter.Seq2[*RoleMember, error]

RoleMemberSeq returns an iterator over a database role's members.

func (*Database) RoleMembers added in v0.0.5

func (d *Database) RoleMembers(roleName string) ([]*RoleMember, error)

RoleMembers returns the direct members of a database role, with each member's principal type — DatabaseRolesContext/RoleByNameContext only return member names, concatenated, with no type.

func (*Database) RoleMembersContext added in v0.0.5

func (d *Database) RoleMembersContext(ctx context.Context, roleName string) ([]*RoleMember, error)

RoleMembersContext is the context-aware variant of RoleMembers.

func (*Database) RuleByName added in v0.0.13

func (d *Database) RuleByName(schema, name string) (*Rule, error)

RuleByName returns one rule, or a not-found error (errors.Is ErrNotFound) when the database has none by that name.

func (*Database) RuleByNameContext added in v0.0.13

func (d *Database) RuleByNameContext(ctx context.Context, schema, name string) (*Rule, error)

RuleByNameContext is the context-aware variant of RuleByName.

func (*Database) RuleSeq added in v0.0.13

func (d *Database) RuleSeq(ctx context.Context) iter.Seq2[*Rule, error]

RuleSeq returns an iterator over all standalone rules in the database.

func (*Database) Rules added in v0.0.13

func (d *Database) Rules() ([]*Rule, error)

Rules returns the standalone rules defined in the database.

func (*Database) RulesContext added in v0.0.13

func (d *Database) RulesContext(ctx context.Context) ([]*Rule, error)

RulesContext is the context-aware variant of Rules.

func (*Database) SchemaByName added in v0.0.10

func (d *Database) SchemaByName(name string) (*Schema, error)

SchemaByName returns one schema by name.

func (*Database) SchemaByNameContext added in v0.0.10

func (d *Database) SchemaByNameContext(ctx context.Context, name string) (*Schema, error)

SchemaByNameContext is the context-aware variant of SchemaByName. It returns an error satisfying errors.Is(err, ErrNotFound) when the database has no such schema.

func (*Database) SchemaPermissionSeq added in v0.0.6

func (d *Database) SchemaPermissionSeq(ctx context.Context, schemaName string) iter.Seq2[*PermissionEntry, error]

SchemaPermissionSeq returns an iterator over a schema's explicit GRANT/DENY entries.

func (*Database) SchemaPermissions added in v0.0.5

func (d *Database) SchemaPermissions(schemaName string) ([]*PermissionEntry, error)

SchemaPermissions returns the GRANT/DENY entries recorded on SCHEMA::schemaName — SSMS's Schema Properties > Permissions page. This is the schema-scoped analog of Permissions: that one resolves its securable via OBJECT_ID(schema.name), which only works for table/view securables — a schema has no OBJECT_ID, so it needs its own query keyed on SCHEMA_ID instead.

func (*Database) SchemaPermissionsContext added in v0.0.5

func (d *Database) SchemaPermissionsContext(ctx context.Context, schemaName string) ([]*PermissionEntry, error)

SchemaPermissionsContext is the context-aware variant of SchemaPermissions.

func (*Database) SchemaSeq

func (d *Database) SchemaSeq(ctx context.Context) iter.Seq2[*Schema, error]

SchemaSeq returns an iterator over all schemas in the database.

func (*Database) Schemas

func (d *Database) Schemas() ([]*Schema, error)

Schemas returns all schemas in the database.

func (*Database) SchemasContext

func (d *Database) SchemasContext(ctx context.Context) ([]*Schema, error)

SchemasContext is the context-aware variant of Schemas.

func (*Database) Search added in v0.0.4

func (d *Database) Search(pattern string) ([]*SearchResult, error)

Search finds tables, views, stored procedures, functions, and triggers whose name contains pattern, matching SSMS's Object Explorer Details search box. The match is case-insensitive whatever the database's collation is.

func (*Database) SearchContext added in v0.0.4

func (d *Database) SearchContext(ctx context.Context, pattern string) ([]*SearchResult, error)

SearchContext is the context-aware variant of Search.

Both sides of the LIKE are wrapped in LOWER, the rule ObjectFilter.clause documents: a bare LIKE follows the database's collation, so on a case-sensitive one a search for "customer" never finds Customer. Lowering only the column is worse still — a pattern with any upper-case letter then matches nothing at all.

func (*Database) SearchSeq added in v0.0.6

func (d *Database) SearchSeq(ctx context.Context, pattern string) iter.Seq2[*SearchResult, error]

SearchSeq returns an iterator over every table, view, stored procedure, function, and trigger whose name contains pattern.

func (*Database) SecurityPolicies

func (d *Database) SecurityPolicies() ([]*SecurityPolicy, error)

SecurityPolicies returns all security policies in the database.

func (*Database) SecurityPoliciesContext added in v0.0.5

func (d *Database) SecurityPoliciesContext(ctx context.Context) ([]*SecurityPolicy, error)

SecurityPoliciesContext is the context-aware variant of SecurityPolicies.

func (*Database) SecurityPolicyByName added in v0.0.10

func (d *Database) SecurityPolicyByName(schema, name string) (*SecurityPolicy, error)

SecurityPolicyByName returns one security policy by schema-qualified name.

func (*Database) SecurityPolicyByNameContext added in v0.0.10

func (d *Database) SecurityPolicyByNameContext(ctx context.Context, schema, name string) (*SecurityPolicy, error)

SecurityPolicyByNameContext is the context-aware variant of SecurityPolicyByName.

func (*Database) SecurityPolicySeq added in v0.0.5

func (d *Database) SecurityPolicySeq(ctx context.Context) iter.Seq2[*SecurityPolicy, error]

SecurityPolicySeq returns an iterator over all security policies in the database.

func (*Database) SequenceSeq

func (d *Database) SequenceSeq(ctx context.Context) iter.Seq2[*Sequence, error]

SequenceSeq returns an iterator over all sequences in the database.

func (*Database) Sequences

func (d *Database) Sequences() ([]*Sequence, error)

Sequences returns all sequences in the database.

func (*Database) SequencesContext added in v0.0.4

func (d *Database) SequencesContext(ctx context.Context) ([]*Sequence, error)

SequencesContext is the context-aware variant of Sequences.

func (*Database) Server

func (d *Database) Server() *Server

Server returns the parent Server.

func (*Database) SetChangeTracking added in v0.0.4

func (d *Database) SetChangeTracking(info ChangeTrackingInfo) error

SetChangeTracking enables, reconfigures, or disables change tracking for the database. info.RetentionUnit defaults to "DAYS" when empty.

func (*Database) SetChangeTrackingContext added in v0.0.4

func (d *Database) SetChangeTrackingContext(ctx context.Context, info ChangeTrackingInfo) error

SetChangeTrackingContext is the context-aware variant of SetChangeTracking.

func (*Database) SetCompatibilityLevel

func (d *Database) SetCompatibilityLevel(level CompatibilityLevel) error

SetCompatibilityLevel changes the database compatibility level.

func (*Database) SetCompatibilityLevelContext

func (d *Database) SetCompatibilityLevelContext(ctx context.Context, level CompatibilityLevel) error

SetCompatibilityLevelContext is the context-aware variant.

func (*Database) SetDatabaseOption added in v0.0.4

func (d *Database) SetDatabaseOption(opt DatabaseOption, value string) error

SetDatabaseOption changes one ALTER DATABASE ... SET option. value is the keyword or clause that follows the option name verbatim, e.g. "ON", "OFF", "CHECKSUM", "PARTIAL", "SNAPSHOT_ISOLATION" — see SQL Server's ALTER DATABASE SET reference for each option's accepted values.

func (*Database) SetDatabaseOptionContext added in v0.0.4

func (d *Database) SetDatabaseOptionContext(ctx context.Context, opt DatabaseOption, value string) error

SetDatabaseOptionContext is the context-aware variant of SetDatabaseOption.

func (*Database) SetDatabaseScopedConfig added in v0.0.5

func (d *Database) SetDatabaseScopedConfig(name, value string, forSecondary bool) error

SetDatabaseScopedConfig changes one database scoped configuration option. value is the keyword or literal that follows the option name verbatim, e.g. "ON", "OFF", "4" — see ALTER DATABASE SCOPED CONFIGURATION's reference for each option's accepted values. forSecondary applies the change to readable secondary replicas (FOR SECONDARY) instead of the primary.

func (*Database) SetDatabaseScopedConfigContext added in v0.0.5

func (d *Database) SetDatabaseScopedConfigContext(ctx context.Context, name, value string, forSecondary bool) error

SetDatabaseScopedConfigContext is the context-aware variant of SetDatabaseScopedConfig. Unlike ALTER DATABASE SET options (SetDatabaseOptionContext), ALTER DATABASE SCOPED CONFIGURATION is scoped to whichever database is current, so this runs through d.exec (USE first), not d.server.execContext.

func (*Database) SetDefaultFileGroup added in v0.0.4

func (d *Database) SetDefaultFileGroup(name string) error

SetDefaultFileGroup marks a filegroup as the database's default.

func (*Database) SetDefaultFileGroupContext added in v0.0.4

func (d *Database) SetDefaultFileGroupContext(ctx context.Context, name string) error

SetDefaultFileGroupContext is the context-aware variant of SetDefaultFileGroup.

func (*Database) SetExtendedProperty added in v0.0.4

func (d *Database) SetExtendedProperty(name, value string, level ExtendedPropertyLevel) error

SetExtendedProperty updates the value of an existing extended property. Fails if no property with this name exists at this level — see AddExtendedProperty to create one.

func (*Database) SetExtendedPropertyContext added in v0.0.4

func (d *Database) SetExtendedPropertyContext(ctx context.Context, name, value string, level ExtendedPropertyLevel) error

SetExtendedPropertyContext is the context-aware variant of SetExtendedProperty.

func (*Database) SetFileGroupReadOnly added in v0.0.4

func (d *Database) SetFileGroupReadOnly(name string, readOnly bool) error

SetFileGroupReadOnly sets or clears a filegroup's read-only flag.

func (*Database) SetFileGroupReadOnlyContext added in v0.0.4

func (d *Database) SetFileGroupReadOnlyContext(ctx context.Context, name string, readOnly bool) error

SetFileGroupReadOnlyContext is the context-aware variant of SetFileGroupReadOnly.

The keywords are the underscored spellings on purpose. ALTER DATABASE also accepts READONLY/READWRITE, but only for backward compatibility — SQL Server documents that pair as deprecated and slated for removal, and it is the spelling this used to emit.

func (*Database) SetOffline added in v0.0.5

func (d *Database) SetOffline() error

SetOffline takes the database offline.

func (*Database) SetOfflineContext added in v0.0.5

func (d *Database) SetOfflineContext(ctx context.Context) error

SetOfflineContext is the context-aware variant of SetOffline. Existing connections are rolled back immediately, matching SSMS's Object Explorer "Take Database Offline" behavior.

func (*Database) SetOnline added in v0.0.5

func (d *Database) SetOnline() error

SetOnline brings an offline database back online.

func (*Database) SetOnlineContext added in v0.0.5

func (d *Database) SetOnlineContext(ctx context.Context) error

SetOnlineContext is the context-aware variant of SetOnline.

func (*Database) SetOwner added in v0.0.4

func (d *Database) SetOwner(principal string) error

SetOwner transfers database ownership to a new principal.

func (*Database) SetOwnerContext added in v0.0.4

func (d *Database) SetOwnerContext(ctx context.Context, principal string) error

SetOwnerContext is the context-aware variant of SetOwner.

func (*Database) SetQueryStoreOptions added in v0.0.5

func (d *Database) SetQueryStoreOptions(opts QueryStoreOptions) error

SetQueryStoreOptions turns Query Store on (reconfiguring it) or off.

func (*Database) SetQueryStoreOptionsContext added in v0.0.5

func (d *Database) SetQueryStoreOptionsContext(ctx context.Context, opts QueryStoreOptions) error

SetQueryStoreOptionsContext is the context-aware variant of SetQueryStoreOptions. Like SetRecoveryModelContext, this is an ALTER DATABASE statement naming the database explicitly, so it runs through d.server.execContext rather than d.exec.

func (*Database) SetReadOnly

func (d *Database) SetReadOnly(readOnly bool) error

SetReadOnly sets the database to read-only or read-write.

func (*Database) SetReadOnlyContext

func (d *Database) SetReadOnlyContext(ctx context.Context, readOnly bool) error

SetReadOnlyContext is the context-aware variant.

func (*Database) SetRecoveryModel

func (d *Database) SetRecoveryModel(model RecoveryModel) error

SetRecoveryModel changes the database recovery model.

func (*Database) SetRecoveryModelContext

func (d *Database) SetRecoveryModelContext(ctx context.Context, model RecoveryModel) error

SetRecoveryModelContext is the context-aware variant.

func (*Database) SetTableChangeTracking added in v0.0.4

func (d *Database) SetTableChangeTracking(schema, name string, enable, trackColumns bool) error

SetTableChangeTracking enables or disables change tracking on one table. trackColumns is ignored when enable is false.

func (*Database) SetTableChangeTrackingContext added in v0.0.4

func (d *Database) SetTableChangeTrackingContext(ctx context.Context, schema, name string, enable, trackColumns bool) error

SetTableChangeTrackingContext is the context-aware variant of SetTableChangeTracking.

func (*Database) SetUserAccess added in v0.0.5

func (d *Database) SetUserAccess(mode string) error

SetUserAccess changes the database's user-access mode (MULTI_USER, SINGLE_USER, or RESTRICTED_USER — SSMS's Database Properties > Options "Restrict access" setting). Existing connections that would violate the new mode are rolled back immediately, matching SSMS's own behavior.

func (*Database) SetUserAccessContext added in v0.0.5

func (d *Database) SetUserAccessContext(ctx context.Context, mode string) error

SetUserAccessContext is the context-aware variant of SetUserAccess.

func (*Database) SourceDatabaseID added in v0.0.13

func (d *Database) SourceDatabaseID() int

SourceDatabaseID returns the database_id of the database a snapshot was taken of, and 0 on a database that is not a snapshot.

func (*Database) SpaceUsed

func (d *Database) SpaceUsed() (SpaceInfo, error)

SpaceUsed returns space usage for the database.

func (*Database) SpaceUsedContext

func (d *Database) SpaceUsedContext(ctx context.Context) (SpaceInfo, error)

SpaceUsedContext is the context-aware variant of SpaceUsed.

func (*Database) State

func (d *Database) State() string

State returns the state_desc (ONLINE, OFFLINE, RESTORING ...).

func (*Database) StoredProcedureSeq

func (d *Database) StoredProcedureSeq(ctx context.Context) iter.Seq2[*StoredProcedure, error]

StoredProcedureSeq returns an iterator over all stored procedures.

func (*Database) StoredProcedures

func (d *Database) StoredProcedures() ([]*StoredProcedure, error)

StoredProcedures returns all stored procedures in the database.

func (*Database) StoredProceduresContext

func (d *Database) StoredProceduresContext(ctx context.Context) ([]*StoredProcedure, error)

StoredProceduresContext is the context-aware variant of StoredProcedures.

func (*Database) StoredProceduresFiltered added in v0.0.10

func (d *Database) StoredProceduresFiltered(filter ObjectFilter) ([]*StoredProcedure, error)

StoredProceduresFiltered returns the stored procedures an ObjectFilter matches, narrowed by the server. An empty filter is StoredProceduresContext.

func (*Database) StoredProceduresFilteredContext added in v0.0.10

func (d *Database) StoredProceduresFilteredContext(ctx context.Context, filter ObjectFilter) ([]*StoredProcedure, error)

StoredProceduresFilteredContext is the context-aware variant of StoredProceduresFiltered.

func (*Database) SynonymSeq added in v0.0.5

func (d *Database) SynonymSeq(ctx context.Context) iter.Seq2[*Synonym, error]

SynonymSeq returns an iterator over all synonyms in the database.

func (*Database) Synonyms

func (d *Database) Synonyms() ([]*Synonym, error)

Synonyms returns all synonyms in the database.

func (*Database) SynonymsContext added in v0.0.4

func (d *Database) SynonymsContext(ctx context.Context) ([]*Synonym, error)

SynonymsContext is the context-aware variant of Synonyms.

func (*Database) SystemCatalog added in v0.0.5

func (d *Database) SystemCatalog() (*Catalog, error)

SystemCatalog returns a bulk snapshot of every catalog view in the "sys" schema (sys.tables, sys.columns, sys.objects, ...) — see SystemCatalogContext.

func (*Database) SystemCatalogContext added in v0.0.5

func (d *Database) SystemCatalogContext(ctx context.Context) (*Catalog, error)

SystemCatalogContext is the context-aware variant of SystemCatalog. The "sys" schema's catalog views are defined identically in every database on a server, so a caller only needs to load this once per connection — any database works equally well as the query target, not just master.

Unlike CatalogContext, this queries sys.all_objects/sys.all_columns rather than sys.objects/sys.columns: the latter two, despite the generic names, only ever surface user-created objects (is_ms_shipped=1 rows are invisible through them) — sys.tables, sys.columns, sys.objects itself, and every other built-in catalog view only show up through the "all_" variants.

func (*Database) SystemDataTypeSeq added in v0.0.13

func (d *Database) SystemDataTypeSeq(ctx context.Context) iter.Seq2[*SystemDataType, error]

SystemDataTypeSeq returns an iterator over the built-in data types the instance ships.

func (*Database) SystemDataTypes added in v0.0.13

func (d *Database) SystemDataTypes() ([]*SystemDataType, error)

SystemDataTypes returns the built-in data types the instance ships.

func (*Database) SystemDataTypesContext added in v0.0.13

func (d *Database) SystemDataTypesContext(ctx context.Context) ([]*SystemDataType, error)

SystemDataTypesContext is the context-aware variant of SystemDataTypes.

func (*Database) SystemFunctionSeq added in v0.0.5

func (d *Database) SystemFunctionSeq(ctx context.Context) iter.Seq2[*UserDefinedFunction, error]

SystemFunctionSeq returns an iterator over every system function in the "sys" schema.

func (*Database) SystemFunctions added in v0.0.5

func (d *Database) SystemFunctions() ([]*UserDefinedFunction, error)

SystemFunctions returns every system function SQL Server ships in the "sys" schema (sys.fn_listextendedproperty, ...) — see SystemFunctionsContext.

func (*Database) SystemFunctionsContext added in v0.0.5

func (d *Database) SystemFunctionsContext(ctx context.Context) ([]*UserDefinedFunction, error)

SystemFunctionsContext is the context-aware variant of SystemFunctions. Reads sys.all_objects rather than sys.objects for the same reason SystemViewsContext reads sys.all_objects instead of sys.views: shipped objects are invisible through the non-"all_" catalog views. Restricted to the same type set as UserDefinedFunctionsContext ('FN'/'TF'/'IF') — aggregate ('AF') and CLR scalar ('FS') functions are excluded, matching that same scope. The "sys" schema is identical in every database on a server, so this only needs loading once per connection.

func (*Database) SystemFunctionsFiltered added in v0.0.10

func (d *Database) SystemFunctionsFiltered(filter ObjectFilter) ([]*UserDefinedFunction, error)

SystemFunctionsFiltered returns the system functions an ObjectFilter matches, narrowed by the server. An empty filter is SystemFunctionsContext.

func (*Database) SystemFunctionsFilteredContext added in v0.0.10

func (d *Database) SystemFunctionsFilteredContext(ctx context.Context, filter ObjectFilter) ([]*UserDefinedFunction, error)

SystemFunctionsFilteredContext is the context-aware variant of SystemFunctionsFiltered.

func (*Database) SystemStoredProcedureSeq added in v0.0.5

func (d *Database) SystemStoredProcedureSeq(ctx context.Context) iter.Seq2[*StoredProcedure, error]

SystemStoredProcedureSeq returns an iterator over every system stored procedure in the "sys" schema.

func (*Database) SystemStoredProcedures added in v0.0.5

func (d *Database) SystemStoredProcedures() ([]*StoredProcedure, error)

SystemStoredProcedures returns every system stored procedure SQL Server ships in the "sys" schema (sp_help, sp_who, ...) — see SystemStoredProceduresContext.

func (*Database) SystemStoredProceduresContext added in v0.0.5

func (d *Database) SystemStoredProceduresContext(ctx context.Context) ([]*StoredProcedure, error)

SystemStoredProceduresContext is the context-aware variant of SystemStoredProcedures. Reads sys.all_objects rather than sys.procedures for the same reason SystemViewsContext reads sys.all_objects instead of sys.views: shipped objects are invisible through the non-"all_" catalog views. Restricted to types 'P'/'PC' (SQL/CLR stored procedure), matching what sys.procedures itself documents — extended stored procedures ('X', e.g. xp_cmdshell) are a distinct object kind and excluded. The "sys" schema is identical in every database on a server, so this only needs loading once per connection.

func (*Database) SystemStoredProceduresFiltered added in v0.0.10

func (d *Database) SystemStoredProceduresFiltered(filter ObjectFilter) ([]*StoredProcedure, error)

SystemStoredProceduresFiltered returns the system stored procedures an ObjectFilter matches, narrowed by the server. An empty filter is SystemStoredProceduresContext.

func (*Database) SystemStoredProceduresFilteredContext added in v0.0.10

func (d *Database) SystemStoredProceduresFilteredContext(ctx context.Context, filter ObjectFilter) ([]*StoredProcedure, error)

SystemStoredProceduresFilteredContext is the context-aware variant of SystemStoredProceduresFiltered.

func (*Database) SystemViewSeq added in v0.0.5

func (d *Database) SystemViewSeq(ctx context.Context) iter.Seq2[*View, error]

SystemViewSeq returns an iterator over every system catalog view in the "sys" schema.

func (*Database) SystemViews added in v0.0.5

func (d *Database) SystemViews() ([]*View, error)

SystemViews returns every catalog view SQL Server ships in the "sys" schema (sys.tables, sys.columns, sys.objects, ...) — see SystemViewsContext.

func (*Database) SystemViewsContext added in v0.0.5

func (d *Database) SystemViewsContext(ctx context.Context) ([]*View, error)

SystemViewsContext is the context-aware variant of SystemViews. Unlike Views, this reads sys.all_objects/sys.all_sql_modules rather than sys.views/sys.sql_modules: the "sys." schema's own views are shipped objects (is_ms_shipped=1), invisible through the non-"all_" catalog views — same reasoning as SystemCatalogContext. The "sys" schema's catalog views are defined identically in every database on a server, so a caller only needs to load this once per connection.

func (*Database) SystemViewsFiltered added in v0.0.10

func (d *Database) SystemViewsFiltered(filter ObjectFilter) ([]*View, error)

SystemViewsFiltered returns the system views an ObjectFilter matches, narrowed by the server. An empty filter is SystemViewsContext.

func (*Database) SystemViewsFilteredContext added in v0.0.10

func (d *Database) SystemViewsFilteredContext(ctx context.Context, filter ObjectFilter) ([]*View, error)

SystemViewsFilteredContext is the context-aware variant of SystemViewsFiltered.

func (*Database) Table added in v0.0.9

func (d *Database) Table(schema, name string) *Table

Table returns a lightweight handle to a table by name, without a query. Nothing verifies that the table exists, and every field but Schema and Name stays at its zero value — ObjectID included.

That is the limit of what this handle is for: the methods it serves are the name-only ones, which name the table in the statement text (DropConstraint, Rename, the ALTER-style writes). Every method that queries by ObjectID — Columns, Indexes, Statistics, Triggers, Partitions, the size and detail reads — would find object 0 and return nothing, so those need a Table from Tables/TableByName instead.

Like Server.Database, this is also the only form that works under a WithScript-derived context, where no lookup can run at all.

func (*Database) TableByName

func (d *Database) TableByName(schema, name string) (*Table, error)

TableByName returns a single table by schema and name using a direct query.

It finds a system table (is_ms_shipped = 1) as readily as a user one: the caller asked for a table by name, and msdb's own tables — which is most of what msdb has — are the ones a by-name lookup would otherwise never reach. Tables() still lists only the user tables; the predicate belongs to the listing, not to the lookup.

func (*Database) TableByNameContext

func (d *Database) TableByNameContext(ctx context.Context, schema, name string) (*Table, error)

TableByNameContext is the context-aware variant of TableByName.

func (*Database) TableChangeTracking added in v0.0.4

func (d *Database) TableChangeTracking() ([]*TableChangeTracking, error)

TableChangeTracking returns change tracking state for every user table in the database, whether or not tracking is actually enabled on it.

func (*Database) TableChangeTrackingContext added in v0.0.4

func (d *Database) TableChangeTrackingContext(ctx context.Context) ([]*TableChangeTracking, error)

TableChangeTrackingContext is the context-aware variant of TableChangeTracking.

func (*Database) TableChangeTrackingFor added in v0.0.10

func (d *Database) TableChangeTrackingFor(schema, name string) (*TableChangeTracking, error)

TableChangeTrackingFor returns change tracking state for one user table.

func (*Database) TableChangeTrackingForContext added in v0.0.10

func (d *Database) TableChangeTrackingForContext(ctx context.Context, schema, name string) (*TableChangeTracking, error)

TableChangeTrackingForContext is the context-aware variant of TableChangeTrackingFor. A table that exists but has tracking switched off is not an error — it comes back with Enabled false. The error satisfies errors.Is(err, ErrNotFound) only when the database has no such user table.

func (*Database) TableChangeTrackingSeq added in v0.0.4

func (d *Database) TableChangeTrackingSeq(ctx context.Context) iter.Seq2[*TableChangeTracking, error]

TableChangeTrackingSeq returns an iterator over every user table's change tracking state.

func (*Database) TableKindsPresent added in v0.0.13

func (d *Database) TableKindsPresent() (TableKindPresence, error)

TableKindsPresent reports which table families the database has.

func (*Database) TableKindsPresentContext added in v0.0.13

func (d *Database) TableKindsPresentContext(ctx context.Context) (TableKindPresence, error)

TableKindsPresentContext is the context-aware variant of TableKindsPresent.

func (*Database) TableRowCounts added in v0.0.7

func (d *Database) TableRowCounts() (map[int]int64, error)

TableRowCounts returns the row count of every user table in the database, keyed by object_id — Table.RowCount for all tables in a single round trip.

Use this over a loop of Table.RowCount whenever the caller wants more than a couple of tables: the per-table form costs one query (and one pooled connection) each. The filter and aggregate are the same, so the counts are identical either way — metadata counts from sys.partitions, which is what SSMS's object grids show, not a COUNT(*).

A table with no row in sys.partitions is absent from the map rather than present as 0; callers should treat a missing key as zero rows.

func (*Database) TableRowCountsContext added in v0.0.7

func (d *Database) TableRowCountsContext(ctx context.Context) (map[int]int64, error)

TableRowCountsContext is the context-aware variant of TableRowCounts.

func (*Database) TableSeq

func (d *Database) TableSeq(ctx context.Context) iter.Seq2[*Table, error]

TableSeq returns an iterator over all user tables in the database.

func (*Database) TableSpaceUsedAll added in v0.0.7

func (d *Database) TableSpaceUsedAll() (map[int]*TableSpaceInfo, error)

TableSpaceUsedAll returns space usage for every user table in the database, keyed by object_id — the same breakdown Table.SpaceUsed gives for one table, for all of them in a single round trip.

Use this over a loop of Table.SpaceUsed whenever the caller wants more than a couple of tables: the per-table form costs one query (and one pooled connection) each, so a grid listing a few hundred tables is a few hundred round trips. The aggregate expressions and joins are the same, so the numbers are identical either way.

A table with no allocated pages at all has no row in sys.partitions to aggregate and is therefore absent from the map, not present with zeroes — callers should treat a missing key as "no space used".

func (*Database) TableSpaceUsedAllContext added in v0.0.7

func (d *Database) TableSpaceUsedAllContext(ctx context.Context) (map[int]*TableSpaceInfo, error)

TableSpaceUsedAllContext is the context-aware variant of TableSpaceUsedAll.

func (*Database) Tables

func (d *Database) Tables() ([]*Table, error)

Tables returns all user tables in the database.

func (*Database) TablesBySchema

func (d *Database) TablesBySchema(schema string) ([]*Table, error)

TablesBySchema returns all tables in a specific schema.

func (*Database) TablesBySchemaContext

func (d *Database) TablesBySchemaContext(ctx context.Context, schema string) ([]*Table, error)

TablesBySchemaContext is the context-aware variant of TablesBySchema.

func (*Database) TablesBySchemaSeq added in v0.0.6

func (d *Database) TablesBySchemaSeq(ctx context.Context, schema string) iter.Seq2[*Table, error]

TablesBySchemaSeq returns an iterator over every user table in the given schema.

func (*Database) TablesContext

func (d *Database) TablesContext(ctx context.Context) ([]*Table, error)

TablesContext is the context-aware variant of Tables.

func (*Database) TablesFiltered added in v0.0.10

func (d *Database) TablesFiltered(filter ObjectFilter) ([]*Table, error)

TablesFiltered returns the user tables an ObjectFilter matches, narrowed by the server rather than by the caller. An empty filter is TablesContext.

func (*Database) TablesFilteredContext added in v0.0.10

func (d *Database) TablesFilteredContext(ctx context.Context, filter ObjectFilter) ([]*Table, error)

TablesFilteredContext is the context-aware variant of TablesFiltered.

func (*Database) TablesOfKind added in v0.0.13

func (d *Database) TablesOfKind(kind TableKind) ([]*Table, error)

TablesOfKind returns the tables of one kind.

func (*Database) TablesOfKindContext added in v0.0.13

func (d *Database) TablesOfKindContext(ctx context.Context, kind TableKind) ([]*Table, error)

TablesOfKindContext is the context-aware variant of TablesOfKind.

func (*Database) TablesOfKindFiltered added in v0.0.13

func (d *Database) TablesOfKindFiltered(kind TableKind, filter ObjectFilter) ([]*Table, error)

TablesOfKindFiltered returns the tables of one kind an ObjectFilter matches, narrowed by the server. An empty filter is TablesOfKind.

func (*Database) TablesOfKindFilteredContext added in v0.0.13

func (d *Database) TablesOfKindFilteredContext(ctx context.Context, kind TableKind, filter ObjectFilter) ([]*Table, error)

TablesOfKindFilteredContext is the context-aware variant of TablesOfKindFiltered.

TableKindGraph is refused below SQL Server 2017 (errors.Is ErrUnsupportedVersion) rather than answered with an empty list.

func (*Database) TransferObject added in v0.0.10

func (d *Database) TransferObject(targetSchema, schema, name string) error

TransferObject moves a schema-scoped object into another schema (ALTER SCHEMA ... TRANSFER), which is the operation sp_rename cannot do — a rename takes a bare name and never crosses schemas.

The object keeps its name and its object_id; permissions granted on it directly are dropped by the server, which is the documented behaviour of ALTER SCHEMA TRANSFER and the reason it is not a cosmetic change. An empty schema means dbo, as everywhere else here.

This is sp_rename's default 'OBJECT' class: tables, views, procedures, functions, sequences and synonyms. A type or an XML schema collection needs TRANSFER's own class prefix and is not covered.

func (*Database) TransferObjectContext added in v0.0.10

func (d *Database) TransferObjectContext(ctx context.Context, targetSchema, schema, name string) error

TransferObjectContext is the context-aware variant of TransferObject.

func (*Database) TransferType added in v0.0.13

func (d *Database) TransferType(targetSchema, schema, name string) error

TransferType moves an alias, table or CLR type into another schema.

ALTER SCHEMA ... TRANSFER's default class covers only the objects in sys.objects; a type lives in sys.types and needs the TYPE:: prefix, which is why Database.TransferObject does not serve here. Everything else about the operation is that method's: the type keeps its name, and permissions granted on it directly are dropped by the server.

func (*Database) TransferTypeContext added in v0.0.13

func (d *Database) TransferTypeContext(ctx context.Context, targetSchema, schema, name string) error

TransferTypeContext is the context-aware variant of TransferType.

func (*Database) TransferXmlSchemaCollection added in v0.0.13

func (d *Database) TransferXmlSchemaCollection(targetSchema, schema, name string) error

TransferXmlSchemaCollection moves an XML schema collection into another schema. Its class prefix is the whole three-word noun, not an abbreviation of it.

func (*Database) TransferXmlSchemaCollectionContext added in v0.0.13

func (d *Database) TransferXmlSchemaCollectionContext(ctx context.Context, targetSchema, schema, name string) error

TransferXmlSchemaCollectionContext is the context-aware variant of TransferXmlSchemaCollection.

func (*Database) TriggerSeq added in v0.0.6

func (d *Database) TriggerSeq(ctx context.Context) iter.Seq2[*Trigger, error]

TriggerSeq returns an iterator over every DML trigger in the database (as opposed to Table.TriggerSeq's single-table scope).

func (*Database) Triggers

func (d *Database) Triggers() ([]*Trigger, error)

Triggers returns all DML triggers in the database.

func (*Database) TriggersContext

func (d *Database) TriggersContext(ctx context.Context) ([]*Trigger, error)

TriggersContext is the context-aware variant of Triggers.

func (*Database) UserByName added in v0.0.5

func (d *Database) UserByName(name string) (*User, error)

UserByName returns a single database user by name, with its SID and matching server login (if any) filled in — UsersContext leaves these out since Object Explorer's tree listing never needs them.

func (*Database) UserByNameContext added in v0.0.5

func (d *Database) UserByNameContext(ctx context.Context, name string) (*User, error)

UserByNameContext is the context-aware variant of UserByName.

func (*Database) UserDefinedDataTypeByName added in v0.0.13

func (d *Database) UserDefinedDataTypeByName(schema, name string) (*UserDefinedDataType, error)

UserDefinedDataTypeByName returns one alias type, or a not-found error (errors.Is ErrNotFound) when the database has none by that name.

func (*Database) UserDefinedDataTypeByNameContext added in v0.0.13

func (d *Database) UserDefinedDataTypeByNameContext(ctx context.Context, schema, name string) (*UserDefinedDataType, error)

UserDefinedDataTypeByNameContext is the context-aware variant of UserDefinedDataTypeByName.

func (*Database) UserDefinedDataTypeSeq added in v0.0.13

func (d *Database) UserDefinedDataTypeSeq(ctx context.Context) iter.Seq2[*UserDefinedDataType, error]

UserDefinedDataTypeSeq returns an iterator over all alias types in the database.

func (*Database) UserDefinedDataTypes added in v0.0.13

func (d *Database) UserDefinedDataTypes() ([]*UserDefinedDataType, error)

UserDefinedDataTypes returns the alias types defined in the database.

func (*Database) UserDefinedDataTypesContext added in v0.0.13

func (d *Database) UserDefinedDataTypesContext(ctx context.Context) ([]*UserDefinedDataType, error)

UserDefinedDataTypesContext is the context-aware variant of UserDefinedDataTypes.

func (*Database) UserDefinedFunctionSeq added in v0.0.6

func (d *Database) UserDefinedFunctionSeq(ctx context.Context) iter.Seq2[*UserDefinedFunction, error]

UserDefinedFunctionSeq returns an iterator over all user-created functions (as opposed to SystemFunctionSeq's "sys" schema functions).

func (*Database) UserDefinedFunctions

func (d *Database) UserDefinedFunctions() ([]*UserDefinedFunction, error)

UserDefinedFunctions returns all UDFs in the database.

func (*Database) UserDefinedFunctionsContext

func (d *Database) UserDefinedFunctionsContext(ctx context.Context) ([]*UserDefinedFunction, error)

UserDefinedFunctionsContext is the context-aware variant.

func (*Database) UserDefinedFunctionsFiltered added in v0.0.10

func (d *Database) UserDefinedFunctionsFiltered(filter ObjectFilter) ([]*UserDefinedFunction, error)

UserDefinedFunctionsFiltered returns the UDFs an ObjectFilter matches, narrowed by the server. An empty filter is UserDefinedFunctionsContext.

func (*Database) UserDefinedFunctionsFilteredContext added in v0.0.10

func (d *Database) UserDefinedFunctionsFilteredContext(ctx context.Context, filter ObjectFilter) ([]*UserDefinedFunction, error)

UserDefinedFunctionsFilteredContext is the context-aware variant of UserDefinedFunctionsFiltered.

func (*Database) UserDefinedTableTypeByName added in v0.0.13

func (d *Database) UserDefinedTableTypeByName(schema, name string) (*UserDefinedTableType, error)

UserDefinedTableTypeByName returns one table type, or a not-found error (errors.Is ErrNotFound) when the database has none by that name.

func (*Database) UserDefinedTableTypeByNameContext added in v0.0.13

func (d *Database) UserDefinedTableTypeByNameContext(ctx context.Context, schema, name string) (*UserDefinedTableType, error)

UserDefinedTableTypeByNameContext is the context-aware variant of UserDefinedTableTypeByName.

func (*Database) UserDefinedTableTypeSeq added in v0.0.13

func (d *Database) UserDefinedTableTypeSeq(ctx context.Context) iter.Seq2[*UserDefinedTableType, error]

UserDefinedTableTypeSeq returns an iterator over all table types in the database.

func (*Database) UserDefinedTableTypes added in v0.0.13

func (d *Database) UserDefinedTableTypes() ([]*UserDefinedTableType, error)

UserDefinedTableTypes returns the table types defined in the database.

func (*Database) UserDefinedTableTypesContext added in v0.0.13

func (d *Database) UserDefinedTableTypesContext(ctx context.Context) ([]*UserDefinedTableType, error)

UserDefinedTableTypesContext is the context-aware variant of UserDefinedTableTypes.

func (*Database) UserSeq

func (d *Database) UserSeq(ctx context.Context) iter.Seq2[*User, error]

UserSeq returns an iterator over all database users.

func (*Database) Users

func (d *Database) Users() ([]*User, error)

Users returns all database users.

func (*Database) UsersContext

func (d *Database) UsersContext(ctx context.Context) ([]*User, error)

UsersContext is the context-aware variant of Users.

func (*Database) ViewSeq

func (d *Database) ViewSeq(ctx context.Context) iter.Seq2[*View, error]

ViewSeq returns an iterator over all views in the database.

func (*Database) Views

func (d *Database) Views() ([]*View, error)

Views returns all views in the database.

func (*Database) ViewsContext

func (d *Database) ViewsContext(ctx context.Context) ([]*View, error)

ViewsContext is the context-aware variant of Views.

func (*Database) ViewsFiltered added in v0.0.10

func (d *Database) ViewsFiltered(filter ObjectFilter) ([]*View, error)

ViewsFiltered returns the views an ObjectFilter matches, narrowed by the server rather than by the caller. An empty filter is ViewsContext.

func (*Database) ViewsFilteredContext added in v0.0.10

func (d *Database) ViewsFilteredContext(ctx context.Context, filter ObjectFilter) ([]*View, error)

ViewsFilteredContext is the context-aware variant of ViewsFiltered.

func (*Database) XmlSchemaCollectionByName added in v0.0.13

func (d *Database) XmlSchemaCollectionByName(schema, name string) (*XmlSchemaCollection, error)

XmlSchemaCollectionByName returns one XML schema collection, or a not-found error (errors.Is ErrNotFound) when the database has none by that name.

func (*Database) XmlSchemaCollectionByNameContext added in v0.0.13

func (d *Database) XmlSchemaCollectionByNameContext(ctx context.Context, schema, name string) (*XmlSchemaCollection, error)

XmlSchemaCollectionByNameContext is the context-aware variant of XmlSchemaCollectionByName.

func (*Database) XmlSchemaCollectionSeq added in v0.0.13

func (d *Database) XmlSchemaCollectionSeq(ctx context.Context) iter.Seq2[*XmlSchemaCollection, error]

XmlSchemaCollectionSeq returns an iterator over all XML schema collections in the database.

func (*Database) XmlSchemaCollections added in v0.0.13

func (d *Database) XmlSchemaCollections() ([]*XmlSchemaCollection, error)

XmlSchemaCollections returns the XML schema collections in the database.

func (*Database) XmlSchemaCollectionsContext added in v0.0.13

func (d *Database) XmlSchemaCollectionsContext(ctx context.Context) ([]*XmlSchemaCollection, error)

XmlSchemaCollectionsContext is the context-aware variant of XmlSchemaCollections.

type DatabaseAuditAction added in v0.0.12

type DatabaseAuditAction struct {
	// ActionName is the action keyword — SELECT, INSERT, EXECUTE, …
	ActionName string

	// ClassDesc is the securable class: OBJECT, SCHEMA or DATABASE. An empty
	// value writes OBJECT, which is what SSMS defaults to.
	ClassDesc string

	// SchemaName is the securable's schema, for an OBJECT. Empty for the
	// SCHEMA and DATABASE classes, whose securable is a single name.
	SchemaName string

	// ObjectName is the securable's name — the object, schema or database.
	ObjectName string

	// Principal is the database principal whose access is audited. An empty
	// value writes public.
	Principal string

	// AuditedResult is what the server records for the action (SUCCESS AND
	// FAILURE, SUCCESS, FAILURE). It is a property of the row, not part of
	// the ADD clause, and is read-only.
	AuditedResult string
}

DatabaseAuditAction is one audited action on one securable: the `SELECT ON OBJECT::dbo.T BY public` form of a detail row.

func (DatabaseAuditAction) FullName added in v0.0.12

func (a DatabaseAuditAction) FullName() string

FullName returns the securable as it appears in the ADD clause — [dbo].[T] for an object, [dbo] for a schema.

type DatabaseAuditSpecification added in v0.0.12

type DatabaseAuditSpecification struct {
	SpecificationID int
	Name            string
	AuditGUID       string

	// AuditName is the server audit this specification writes to, resolved
	// through sys.server_audits. It is empty for an orphaned specification:
	// dropping an audit a specification still references succeeds and leaves
	// the audit_guid pointing at nothing, which is why the read below joins
	// with a LEFT JOIN.
	AuditName string

	IsEnabled  bool
	CreateDate time.Time
	ModifyDate time.Time

	// ActionGroups are the audit action groups the specification records, in
	// name order — the detail rows with is_group = 1.
	ActionGroups []string

	// Actions are the individual actions on securables the specification
	// records — the detail rows with is_group = 0.
	Actions []DatabaseAuditAction
	// contains filtered or unexported fields
}

DatabaseAuditSpecification mirrors a row of sys.database_audit_specifications.

func (*DatabaseAuditSpecification) AddActions added in v0.0.12

func (spec *DatabaseAuditSpecification) AddActions(groups []string, actions []DatabaseAuditAction) error

AddActions adds audit action groups and per-securable actions to the specification. Either list may be empty; both being empty writes nothing.

func (*DatabaseAuditSpecification) AddActionsContext added in v0.0.12

func (spec *DatabaseAuditSpecification) AddActionsContext(ctx context.Context, groups []string, actions []DatabaseAuditAction) error

AddActionsContext is the context-aware variant of AddActions. The specification is disabled for the duration and restored afterwards.

func (*DatabaseAuditSpecification) Database added in v0.0.12

func (spec *DatabaseAuditSpecification) Database() *Database

Database returns the database the specification lives in.

func (*DatabaseAuditSpecification) Drop added in v0.0.12

func (spec *DatabaseAuditSpecification) Drop() error

Drop deletes the specification.

func (*DatabaseAuditSpecification) DropActions added in v0.0.12

func (spec *DatabaseAuditSpecification) DropActions(groups []string, actions []DatabaseAuditAction) error

DropActions removes audit action groups and per-securable actions from the specification.

func (*DatabaseAuditSpecification) DropActionsContext added in v0.0.12

func (spec *DatabaseAuditSpecification) DropActionsContext(ctx context.Context, groups []string, actions []DatabaseAuditAction) error

DropActionsContext is the context-aware variant of DropActions.

func (*DatabaseAuditSpecification) DropContext added in v0.0.12

func (spec *DatabaseAuditSpecification) DropContext(ctx context.Context) error

DropContext is the context-aware variant of Drop. An enabled specification is disabled first; there is nothing to restore afterwards.

func (*DatabaseAuditSpecification) SetAudit added in v0.0.12

func (spec *DatabaseAuditSpecification) SetAudit(auditName string) error

SetAudit rebinds the specification to a different server audit.

func (*DatabaseAuditSpecification) SetAuditContext added in v0.0.12

func (spec *DatabaseAuditSpecification) SetAuditContext(ctx context.Context, auditName string) error

SetAuditContext is the context-aware variant of SetAudit. The specification is disabled for the duration and restored afterwards.

func (*DatabaseAuditSpecification) SetState added in v0.0.12

func (spec *DatabaseAuditSpecification) SetState(on bool) error

SetState enables or disables the specification.

func (*DatabaseAuditSpecification) SetStateContext added in v0.0.12

func (spec *DatabaseAuditSpecification) SetStateContext(ctx context.Context, on bool) error

SetStateContext is the context-aware variant of SetState. This is the one ALTER form the server accepts on an enabled specification.

func (*DatabaseAuditSpecification) WithDisabled added in v0.0.12

func (spec *DatabaseAuditSpecification) WithDisabled(ctx context.Context, fn func(context.Context) error) error

WithDisabled runs fn with the specification disabled, restoring the state afterwards. Every write method already does this for itself, so a caller needs WithDisabled only to make several of them share one window: recording then stops once for the whole batch instead of once per statement, and a failure part-way through cannot leave the specification off.

fn must use the context it is handed — that is what the nested writes read to know the window is already open.

type DatabaseAuditSpecificationSpec added in v0.0.12

type DatabaseAuditSpecificationSpec struct {
	Name string

	// AuditName is the server audit the specification writes to. Required.
	AuditName string

	// ActionGroups are the database-scope action groups to record.
	ActionGroups []string

	// Actions are the individual actions on securables to record. A
	// specification with neither groups nor actions is legal and records
	// nothing.
	Actions []DatabaseAuditAction

	// Enabled creates the specification with STATE = ON.
	Enabled bool
}

DatabaseAuditSpecificationSpec describes a specification to create.

type DatabaseCapabilities added in v0.0.10

type DatabaseCapabilities struct {
	// Accessible reports HAS_DBACCESS: whether the login can open the
	// database at all. When it is false the two maps are empty, because
	// nothing inside the database could be asked — a USE into it fails.
	//
	// This is the one field to check before expanding a database in a tree or
	// opening its properties: every folder under an inaccessible database
	// fails separately and identically.
	Accessible bool

	// Roles maps each name in ProbedDatabaseRoles to membership.
	Roles map[string]bool

	// Permissions maps each name in ProbedDatabasePermissions to its state.
	Permissions map[string]CapabilityState

	// SchemaPermissions maps each schema in the database to the state of each
	// name in ProbedSchemaPermissions on it. Read it through
	// SchemaPermission/PermitsOnSchema rather than directly.
	//
	// It exists because the database-scope map cannot answer for a schema: a
	// principal granted ALTER on one schema and nothing else holds no
	// database-wide permission at all, and a caller gating a rename or a drop
	// on the database-scope answer withholds it from exactly the principal
	// SQL Server would let through.
	SchemaPermissions map[string]map[string]CapabilityState

	// ExplicitSchemaPermissions maps a schema name to the state each name in
	// ProbedSchemaPermissions is *explicitly* recorded in for the login, read
	// out of sys.database_permissions rather than asked with
	// HAS_PERMS_BY_NAME. Read it through DeniedOnSchema.
	//
	// It exists because SchemaPermissions cannot answer "is this denied?":
	// HAS_PERMS_BY_NAME returns 0 both for a permission explicitly denied on
	// the schema and for one simply never granted, so its CapabilityDenied
	// means "the server said no to this question", not "a DENY row exists".
	// The difference decides whether a wider grant may answer for the schema —
	// it may for the second, and must not for the first, because SQL Server
	// resolves a schema-scope DENY over a database-wide GRANT.
	//
	// Sparse in ObjectPermissions' sense: a schema nobody granted or denied
	// anything on has no row. Ownership is deliberately not folded in — an
	// owner never carries a DENY, so it cannot change the one answer this map
	// is read for.
	ExplicitSchemaPermissions map[string]map[string]CapabilityState

	// ExplicitDatabasePermissions maps each name in ProbedDatabasePermissions
	// to the state it is *explicitly* recorded in for the login at DATABASE
	// scope (class 0), read out of sys.database_permissions rather than asked
	// with HAS_PERMS_BY_NAME. Read it through DeniedOnDatabase.
	//
	// It is ExplicitSchemaPermissions' database-scope twin and exists for the
	// same reason: Permissions cannot answer "is this denied?", because
	// HAS_PERMS_BY_NAME returns 0 both for a permission explicitly denied and
	// for one simply never granted. The difference decides whether a
	// *narrower* grant may answer for the database — it may for the second,
	// and must not for the first, because SQL Server resolves a database-scope
	// DENY over an object- or schema-scope GRANT.
	//
	// Sparse in ObjectPermissions' sense: a permission with no explicit row
	// has no entry.
	//
	// Only DENY rows are read. The grant direction is already answered, and
	// answered better, by HAS_PERMS_BY_NAME in Permissions, which folds in
	// role membership and covering permissions. CONTROL is deliberately not
	// matched alongside the permission asked about the way the schema block
	// matches it: DENY CONTROL at database scope denies CONNECT with it, so
	// the login cannot open the database at all and Accessible false is what
	// reports that — verified live 2026-09-04, Msg 916.
	ExplicitDatabasePermissions map[string]CapabilityState

	// ExplicitPrincipalPermissions maps a database principal's name — a user
	// or a database role — to the state each name in
	// ProbedPrincipalPermissions is *explicitly* recorded in for the login at
	// DATABASE_PRINCIPAL scope (class 4), read out of sys.database_permissions.
	// Read it through DeniedOnPrincipal.
	//
	// It is ExplicitSchemaPermissions' class-4 twin and exists for the same
	// reason: a class-4 DENY overrides the database-wide ALTER ANY USER a gate
	// would otherwise read as permission, and HAS_PERMS_BY_NAME cannot tell
	// that DENY from a permission never granted.
	//
	// Sparse in ObjectPermissions' sense: a principal nobody denied anything
	// on has no row.
	//
	// Only DENY rows are read, for ExplicitDatabasePermissions' reason and one
	// of its own: at this class there is no grant direction to miss at all.
	// GRANT ALTER ON USER::x permits neither the rename nor the drop — see
	// ProbedPrincipalPermissions, where the live result is recorded.
	//
	// **Roles are recorded but answer differently, and a caller must not treat
	// the two alike.** Verified live on majors 13, 14 and 17: a class-4 DENY on
	// a *role* withholds nothing — DROP ROLE and ALTER ROLE ... WITH NAME check
	// ALTER ANY ROLE at database scope and are permitted with the DENY in
	// place, even though HAS_PERMS_BY_NAME reports 0 for ALTER on the role.
	// The rows are kept because they are what the catalog says and a caller may
	// have a use for them, but a gate over role rename or drop that reads this
	// map withholds an action the server allows.
	ExplicitPrincipalPermissions map[string]map[string]CapabilityState

	// ObjectPermissions maps "schema.object" to the state of each name in
	// ProbedObjectPermissions on it. Read it through HasOnObject.
	//
	// Unlike the other three maps this one is *sparse*: it holds a row only
	// for an object the login was granted a permission on, was denied one on,
	// or owns. A missing entry means "no explicit grant", never "not probed",
	// so an Allows/Permits-style reading of it would report every object in
	// the database as permitted. HasOnObject is the only safe test.
	ObjectPermissions map[string]map[string]CapabilityState

	// ColumnPermissions maps "schema.object.column" to the state of each name
	// in ProbedObjectPermissions that was granted or denied on that column.
	// Read it through HasOnColumn/DeniedOnColumn/DeniedOnAnyColumn.
	//
	// It is separate from ObjectPermissions rather than folded into it because
	// a column-scope row answers for the column alone: recorded on the table
	// it would report a DENY on one column as a DENY on the whole table, and a
	// GRANT on one column as a grant on all of them. Sparse for
	// ObjectPermissions' reason, and read the same way.
	ColumnPermissions map[string]map[string]CapabilityState

	// SecurablePermissions maps each assembly, user-defined type and XML
	// schema collection in the database — keyed by DatabaseSecurableKey — to
	// the state of each name in ProbedSecurablePermissions on it. Read it
	// through HasOnSecurable or PermitsOnSecurable.
	//
	// It exists because none of the maps above can answer for these three
	// classes: ObjectPermissions is class 1 only, and a principal granted
	// CONTROL on one assembly, or owning it, holds no database- or
	// schema-scope permission at all. A caller gating the drop on those alone
	// withholds it from exactly the principal SQL Server lets through.
	//
	// Like AvailabilityGroupPermissions this is a HAS_PERMS_BY_NAME answer, so
	// it is *not* sparse: every securable the login can see has a row, and a
	// missing one means it was created after the probe or was never asked.
	// Which statements its answer decides is recorded, with the live result,
	// on ProbedSecurablePermissions — a transfer entirely, a drop only in the
	// permitting direction.
	SecurablePermissions map[string]map[string]CapabilityState
}

DatabaseCapabilities is what the connected login may do inside one database.

Obtain one with Database.Capabilities. Every method is nil-safe.

func (*DatabaseCapabilities) Allows added in v0.0.10

func (c *DatabaseCapabilities) Allows(name string) bool

Allows reports that the permission is not known to be denied. See Capabilities.Allows, which explains why it and Has are not opposites.

At database scope this is *not* the whole test for withholding something — use Permits. Allows answers only the question it is asked, and an inaccessible database was never asked anything.

func (*DatabaseCapabilities) AllowsOnSchema added in v0.0.11

func (c *DatabaseCapabilities) AllowsOnSchema(schema, name string) bool

AllowsOnSchema reports that the permission is not known to be denied on the schema. See Capabilities.Allows.

func (*DatabaseCapabilities) ColumnPermission added in v0.0.11

func (c *DatabaseCapabilities) ColumnPermission(schema, object, column, name string) CapabilityState

ColumnPermission returns the state of one OBJECT-scope permission recorded on a single column. A column with no explicit grant or deny is CapabilityUnknown, which here means "nothing was recorded for it".

func (*DatabaseCapabilities) DeniedOnAnyColumn added in v0.0.11

func (c *DatabaseCapabilities) DeniedOnAnyColumn(schema, object, name string) (string, bool)

DeniedOnAnyColumn reports that the permission is denied on at least one column of the object, and names one such column.

This is what a caller gating a *table-wide* action asks. SQL Server resolves a column-scope DENY over every wider grant exactly as it does an object-scope one, so a statement touching all the columns fails Msg 230 for a principal that holds the permission on the table itself — and asking DeniedOnObject alone lets the wider grant answer for a column it does not cover. An action scoped to named columns should ask DeniedOnColumn per column instead.

func (*DatabaseCapabilities) DeniedOnColumn added in v0.0.11

func (c *DatabaseCapabilities) DeniedOnColumn(schema, object, column, name string) bool

DeniedOnColumn reports that the permission is explicitly denied on the column. DeniedOnObject's counterpart and sound for its reason — it asks for a recorded state rather than for the absence of one — with the same two exceptions belonging to the caller: sysadmin bypasses the check, and a database that was never probed records nothing.

func (*DatabaseCapabilities) DeniedOnDatabase added in v0.0.12

func (c *DatabaseCapabilities) DeniedOnDatabase(name string) bool

DeniedOnDatabase reports that the permission is explicitly denied at DATABASE scope — Permissions' withholding counterpart, and the only sound read of ExplicitDatabasePermissions.

It is DeniedOnSchema one scope wider, and sound for the same reason: it asks for a state that was recorded rather than for the absence of one, so a permission nobody denied reads unknown, which is not a denial. Permits cannot stand in for it — HAS_PERMS_BY_NAME answers 0 for a permission never granted, which is the ordinary case for a principal working through an object- or schema-scope grant, and withholding on that would take the write away from exactly the principal it was granted to.

A caller may withhold on it because SQL Server resolves DENY over GRANT across scopes in *both* directions: a principal granted ALTER on one table, in a database that denies it ALTER, reads HAS_PERMS_BY_NAME('dbo.t1','OBJECT','ALTER') = 0 and its ALTER TABLE fails — verified live 2026-09-04. The narrower grant does not survive the wider DENY; only a *column* grant overrides an object DENY, which is the one documented exception and runs the other way. The same two exceptions belong to the caller as for DeniedOnSchema: a member of sysadmin bypasses the check and must be asked about first, and a database that was never probed records nothing.

func (*DatabaseCapabilities) DeniedOnObject added in v0.0.11

func (c *DatabaseCapabilities) DeniedOnObject(schema, object, name string) bool

DeniedOnObject reports that the permission is explicitly denied on the object — the one thing this map may be read for in order to *withhold* something, and the counterpart to HasOnObject.

It is sound where an AllowsOnObject would not be, because it asks for the state that was actually recorded rather than for the absence of one: an object nobody mentioned has no row and reads CapabilityUnknown, which is not a denial. Only a DENY reaching the login — directly, through a role, or through public — puts CapabilityDenied here.

A caller may withhold on it because SQL Server resolves an object-scope DENY over every wider grant: a principal holding database-wide ALTER, or db_owner, reads HAS_PERMS_BY_NAME 0 on a table denied ALTER and its rename fails Msg 297 (verified live 2026-09-01). Two exceptions belong to the caller, not here: a member of sysadmin bypasses the check entirely and must be asked about first, and a database that was never probed records nothing, which reads as no denial and so withholds nothing.

Ownership needs no such care. A DENY cannot be made to the owner of the securable — SQL Server refuses it — and transferring ownership to a denied principal *deletes* the DENY row, so an owner never carries one (both verified live 2026-09-01). An owner denied through public is genuinely refused by the server, which is what this then reports.

func (*DatabaseCapabilities) DeniedOnPrincipal added in v0.0.12

func (c *DatabaseCapabilities) DeniedOnPrincipal(principal, name string) bool

DeniedOnPrincipal reports that the permission is explicitly denied on the database principal — the only sound read of ExplicitPrincipalPermissions, for DeniedOnSchema's reason: it asks for a state that was recorded rather than for the absence of one, so a principal nobody denied reads unknown, which is not a denial.

A caller may withhold on it because SQL Server resolves a class-4 DENY over the database-wide ALTER ANY USER that would otherwise permit the write: verified live on majors 13, 14 and 17, DENY ALTER ON USER::x (or DENY CONTROL) refuses both ALTER USER ... WITH NAME and DROP USER for a principal holding ALTER ANY USER. The same two exceptions belong to the caller as for DeniedOnSchema — a member of sysadmin bypasses the check and must be asked about first, and a database that was never probed records nothing.

**For a database role, the answer is actionable per action, not per role.** The map records users and roles alike, because both are class 4 and the catalog does not distinguish them here, but a class-4 DENY on a *role* does not withhold everything a DENY on a user does. Verified live on majors 13, 14 and 17, with HAS_PERMS_BY_NAME reporting 0 for ALTER on the role throughout:

  • DROP ROLE and ALTER ROLE ... WITH NAME check ALTER ANY ROLE at database scope and go through with the DENY in place. A gate that withholds a role rename or drop on this answer withholds an action the server allows.
  • ALTER ROLE ... ADD MEMBER / DROP MEMBER is refused (Msg 15151). A gate that offers a membership edit on this answer offers one the server refuses (probed 2026-09-04 on majors 13 and 17).

Membership also checks ALTER on the *member*: adding a user carrying a class-4 DENY to a role nobody denied is refused too, so a membership gate has to ask about both principals.

func (*DatabaseCapabilities) DeniedOnSchema added in v0.0.11

func (c *DatabaseCapabilities) DeniedOnSchema(schema, name string) bool

DeniedOnSchema reports that the permission is explicitly denied on the schema — SchemaPermissions' withholding counterpart, and the only sound read of ExplicitSchemaPermissions.

It is sound where an AllowsOnSchema-style read of the sparse map would not be, for DeniedOnObject's reason: it asks for a state that was recorded rather than for the absence of one, so a schema nobody mentioned reads unknown, which is not a denial.

A caller may withhold on it because SQL Server resolves DENY over GRANT across scopes: a principal holding database-wide ALTER whose schema carries DENY ALTER cannot rename, move or drop anything in it, and the write fails Msg 297. The same two exceptions belong to the caller as for DeniedOnObject: a member of sysadmin bypasses the check and must be asked about first, and a database that was never probed records nothing.

func (*DatabaseCapabilities) Has added in v0.0.10

func (c *DatabaseCapabilities) Has(name string) bool

Has reports that the permission is known to be held — the test for offering something extra. See Capabilities.Has.

func (*DatabaseCapabilities) HasOnColumn added in v0.0.11

func (c *DatabaseCapabilities) HasOnColumn(schema, object, column, name string) bool

HasOnColumn reports that the permission is known to be held on the column. HasOnObject's counterpart, and additive for the same reason: a column carrying no row of its own is covered by whatever the table and the wider scopes grant.

func (*DatabaseCapabilities) HasOnObject added in v0.0.11

func (c *DatabaseCapabilities) HasOnObject(schema, object, name string) bool

HasOnObject reports that the permission is known to be held on the object.

This is the only sound test against ObjectPermissions, and the reason is the map's sparseness rather than the usual offer-versus-withhold distinction: an object nobody granted anything on has no row, so "not denied" is true of every object in the database and an AllowsOnObject would gate nothing.

Use it as an *additional* reason to permit something, alongside the database- and schema-scope answers — never as the reason to withhold it. A principal granted ALTER on one table holds no permission at either wider scope, so those answer 0 and a caller reading only them withholds a write SQL Server would have allowed.

func (*DatabaseCapabilities) HasOnSchema added in v0.0.11

func (c *DatabaseCapabilities) HasOnSchema(schema, name string) bool

HasOnSchema reports that the permission is known to be held on the schema — the test for offering something extra. See Capabilities.Has.

func (*DatabaseCapabilities) HasOnSecurable added in v0.0.13

func (c *DatabaseCapabilities) HasOnSecurable(kind DatabaseSecurableKind, schema, name, perm string) bool

HasOnSecurable reports that the permission is known to be held on the securable — the test for offering something extra, such as a drop the wider rights beside it do not permit. See Capabilities.Has.

func (*DatabaseCapabilities) InRole added in v0.0.10

func (c *DatabaseCapabilities) InRole(name string) bool

InRole reports whether the login's user in this database is a member of the named fixed database role. As with Capabilities.InServerRole, membership in db_owner (or in sysadmin) is not folded in.

func (*DatabaseCapabilities) ObjectPermission added in v0.0.11

func (c *DatabaseCapabilities) ObjectPermission(schema, object, name string) CapabilityState

ObjectPermission returns the state of one OBJECT-scope permission on the named object. An object with no explicit grant, deny or distinct owner is CapabilityUnknown — which here means "nothing was recorded for it", not "the probe did not run".

func (*DatabaseCapabilities) Permission added in v0.0.10

func (c *DatabaseCapabilities) Permission(name string) CapabilityState

Permission returns the state of one database-scope permission. A name that was never probed is CapabilityUnknown.

func (*DatabaseCapabilities) Permits added in v0.0.10

func (c *DatabaseCapabilities) Permits(name string) bool

Permits is the test for withholding something at database scope: Allows, plus the accessibility the permission answer takes for granted.

A database the login cannot open answers CapabilityUnknown to every permission, because there was nothing inside it to ask — Accessible false is the only thing the server said. Unknown fails open, so Allows alone reports "not known to be denied" for a database the login cannot so much as connect to, and a caller following Capabilities.Allows's advice would offer Back Up and Delete on exactly the databases it has no business writing to.

The fail-open direction is kept where it belongs: a probe that could not run at all leaves Accessible true (see Database.CapabilitiesContext), so Permits still says yes there. Only a measured "cannot open this" withholds.

Capabilities has no counterpart because there is no server-scope equivalent of an inaccessible database: a login that cannot reach the instance has no Capabilities to ask.

One shape to know: a nil *DatabaseCapabilities is "nothing known" and fails open, but the *zero value* is not — its Accessible is false, which reads as a measured "cannot open this" and withholds. Anything hand-building one to stand in for a probe that could not run must set Accessible true, the way CapabilitiesContext does for every database it reached.

func (*DatabaseCapabilities) PermitsOnSchema added in v0.0.11

func (c *DatabaseCapabilities) PermitsOnSchema(schema, name string) bool

PermitsOnSchema is the test for withholding something scoped to one schema: AllowsOnSchema, plus the accessibility every answer inside the database takes for granted. Permits's counterpart — see it for why accessibility belongs in the withholding test.

func (*DatabaseCapabilities) PermitsOnSecurable added in v0.0.13

func (c *DatabaseCapabilities) PermitsOnSecurable(kind DatabaseSecurableKind, schema, name, perm string) bool

PermitsOnSecurable is the test for withholding something the securable's own permission decides alone — ALTER SCHEMA ... TRANSFER of a type or a collection, which nothing narrower or wider than CONTROL permits. It is PermitsOnSchema one scope down: not known to be denied, plus the accessibility every answer inside the database takes for granted.

It is sound in the withholding direction because the map is not sparse, for Capabilities.PermitsOnAvailabilityGroup's reason: a 0 here is the server's answer about this securable, not a silence.

func (*DatabaseCapabilities) Probed added in v0.0.11

func (c *DatabaseCapabilities) Probed() bool

Probed reports whether these capabilities came from a database that answered. Capabilities.Probed's counterpart, and needed for the same reason: InRole answers false for a role that was never asked about exactly as it does for one the login is not in, so a caller that would withhold something on "not a member" must check this first.

It reads Roles rather than Accessible because an inaccessible database is a real answer — the probe ran and reported that nothing inside could be asked.

func (*DatabaseCapabilities) SchemaPermission added in v0.0.11

func (c *DatabaseCapabilities) SchemaPermission(schema, name string) CapabilityState

SchemaPermission returns the state of one SCHEMA-scope permission on the named schema. A schema that does not exist, or a name that was never probed, is CapabilityUnknown — as is every schema of a database that was not probed at all.

func (*DatabaseCapabilities) SecurablePermission added in v0.0.13

func (c *DatabaseCapabilities) SecurablePermission(kind DatabaseSecurableKind, schema, name, perm string) CapabilityState

SecurablePermission returns the state of one permission on an assembly, a user-defined type or an XML schema collection; schema is "" for an assembly. A securable the probe did not reach, a name that was never probed, and every securable of a database that was not probed at all are CapabilityUnknown.

type DatabaseFile

type DatabaseFile struct {
	Name          string
	PhysicalName  string
	Size          int64  // in KB
	MaxSize       int64  // in KB; -1 = unlimited
	GrowthType    string // "KB" | "PERCENT"
	Growth        int64
	IsPrimaryFile bool
	FileGroupName string
}

DatabaseFile represents a single data or log file.

type DatabaseFileInfo added in v0.0.4

type DatabaseFileInfo struct {
	FileID          int
	Name            string
	PhysicalName    string
	Type            string // "ROWS", "LOG", or "FILESTREAM" (sys.database_files.type_desc)
	FileGroup       string // "" for log files, which don't belong to one
	State           string // e.g. "ONLINE"
	SizeKB          int64
	MaxSizeKB       int64 // -1 = unlimited
	GrowthKB        int64 // 0 when IsPercentGrowth is true
	GrowthPercent   int   // 0 when IsPercentGrowth is false
	IsPercentGrowth bool
}

DatabaseFileInfo describes a single database file, including log files — unlike FileGroups/FileGroupsContext (database.go), which only sees files that belong to a filegroup and so omits the log. Sizes are normalized to KB (FileGroupsContext's MaxSize/Growth fields are not, for backward compatibility with existing callers).

type DatabaseFileSpec added in v0.0.4

type DatabaseFileSpec struct {
	Name      string
	FileGroup string // ignored when Type is "LOG"
	Type      string // "LOG" adds a log file; anything else (including "") adds a data file
	Path      string
	SizeKB    int64
	// GrowthKB and GrowthPercent are mutually exclusive; GrowthPercent
	// wins if both are set. Leaving both zero omits FILEGROWTH (server
	// default).
	GrowthKB      int64
	GrowthPercent int
	// DisableGrowth creates the file with autogrowth off (FILEGROWTH = 0),
	// and takes precedence over GrowthKB/GrowthPercent. It exists because
	// zero cannot say it: leaving both growth fields at zero means "omit
	// FILEGROWTH, take the server default", which is the opposite of
	// switching growth off.
	DisableGrowth bool
	// MaxSizeKB: 0 omits MAXSIZE (server default), -1 means UNLIMITED,
	// >0 is the cap in KB.
	MaxSizeKB int64
}

DatabaseFileSpec describes a file to add via AddFile.

type DatabaseMirroringEndpoint added in v0.0.9

type DatabaseMirroringEndpoint struct {
	Name string
	Port int

	// State is STARTED, STOPPED or DISABLED. Only a STARTED endpoint accepts
	// connections, and an endpoint left STOPPED is the usual reason a replica
	// that looks correctly configured never synchronizes.
	State string

	// Role is ALL, PARTNER or WITNESS. Availability groups need ALL.
	Role string

	IsEncryptionEnabled bool

	// EncryptionAlgorithm is AES, RC4, or one of the mixed forms. RC4 is
	// deprecated and refused outright on recent versions.
	EncryptionAlgorithm string

	// ConnectionAuth is how the far end proves who it is — NTLM, KERBEROS,
	// NEGOTIATE, CERTIFICATE, or one of the combined forms. A Linux
	// availability group is normally CERTIFICATE, since the instances share no
	// domain; a Windows one is normally NEGOTIATE.
	ConnectionAuth string

	// Owner is the login that owns the endpoint.
	Owner string
	// contains filtered or unexported fields
}

DatabaseMirroringEndpoint is an instance's database mirroring endpoint.

func (*DatabaseMirroringEndpoint) Drop added in v0.0.9

func (e *DatabaseMirroringEndpoint) Drop() error

Drop deletes the endpoint.

func (*DatabaseMirroringEndpoint) DropContext added in v0.0.9

func (e *DatabaseMirroringEndpoint) DropContext(ctx context.Context) error

DropContext is the context-aware variant of Drop.

func (*DatabaseMirroringEndpoint) GrantConnect added in v0.0.9

func (e *DatabaseMirroringEndpoint) GrantConnect(login string) error

GrantConnect grants a login CONNECT on the endpoint — what lets the other replicas' service accounts open a connection to it.

func (*DatabaseMirroringEndpoint) GrantConnectContext added in v0.0.9

func (e *DatabaseMirroringEndpoint) GrantConnectContext(ctx context.Context, login string) error

GrantConnectContext is the context-aware variant of GrantConnect.

func (*DatabaseMirroringEndpoint) Server added in v0.0.9

func (e *DatabaseMirroringEndpoint) Server() *Server

Server returns the connection this endpoint was read from.

func (*DatabaseMirroringEndpoint) Start added in v0.0.9

func (e *DatabaseMirroringEndpoint) Start() error

Start starts a stopped endpoint. An endpoint that is not STARTED accepts no connections, so a replica behind one never synchronizes.

func (*DatabaseMirroringEndpoint) StartContext added in v0.0.9

func (e *DatabaseMirroringEndpoint) StartContext(ctx context.Context) error

StartContext is the context-aware variant of Start.

func (*DatabaseMirroringEndpoint) Stop added in v0.0.9

func (e *DatabaseMirroringEndpoint) Stop() error

Stop stops the endpoint, breaking every replica connection through it.

func (*DatabaseMirroringEndpoint) StopContext added in v0.0.9

func (e *DatabaseMirroringEndpoint) StopContext(ctx context.Context) error

StopContext is the context-aware variant of Stop.

func (*DatabaseMirroringEndpoint) URL added in v0.0.9

URL is the endpoint's address as an availability replica's ENDPOINT_URL — "tcp://<server>:<port>", built from the instance's own name.

The host is the server's name rather than whatever address the client connected through, because this string is consumed by the *other* replicas: they resolve it themselves, and the address that reached this instance from here may be meaningless there.

type DatabaseOption added in v0.0.4

type DatabaseOption string

DatabaseOption identifies one ALTER DATABASE ... SET option.

const (
	DBOptAutoClose                 DatabaseOption = "AUTO_CLOSE"
	DBOptAutoShrink                DatabaseOption = "AUTO_SHRINK"
	DBOptAutoCreateStatistics      DatabaseOption = "AUTO_CREATE_STATISTICS"
	DBOptAutoUpdateStatistics      DatabaseOption = "AUTO_UPDATE_STATISTICS"
	DBOptAutoUpdateStatisticsAsync DatabaseOption = "AUTO_UPDATE_STATISTICS_ASYNC"
	DBOptANSINullDefault           DatabaseOption = "ANSI_NULL_DEFAULT"
	DBOptANSINulls                 DatabaseOption = "ANSI_NULLS"
	DBOptANSIPadding               DatabaseOption = "ANSI_PADDING"
	DBOptANSIWarnings              DatabaseOption = "ANSI_WARNINGS"
	DBOptArithAbort                DatabaseOption = "ARITHABORT"
	DBOptConcatNullYieldsNull      DatabaseOption = "CONCAT_NULL_YIELDS_NULL"
	DBOptNumericRoundAbort         DatabaseOption = "NUMERIC_ROUNDABORT"
	DBOptQuotedIdentifier          DatabaseOption = "QUOTED_IDENTIFIER"
	DBOptRecursiveTriggers         DatabaseOption = "RECURSIVE_TRIGGERS"
	DBOptCursorCloseOnCommit       DatabaseOption = "CURSOR_CLOSE_ON_COMMIT"
	DBOptCursorDefault             DatabaseOption = "CURSOR_DEFAULT"
	DBOptTrustworthy               DatabaseOption = "TRUSTWORTHY"
	DBOptPageVerify                DatabaseOption = "PAGE_VERIFY"
	DBOptContainment               DatabaseOption = "CONTAINMENT"
	DBOptSnapshotIsolation         DatabaseOption = "ALLOW_SNAPSHOT_ISOLATION"
	DBOptReadCommittedSnapshot     DatabaseOption = "READ_COMMITTED_SNAPSHOT"
)

type DatabaseOptions added in v0.0.4

type DatabaseOptions struct {
	Owner             string
	PageVerify        string // e.g. "CHECKSUM", "TORN_PAGE_DETECTION", "NONE"
	UserAccess        string // "MULTI_USER", "SINGLE_USER", "RESTRICTED_USER"
	Containment       string // "NONE", "PARTIAL"
	DefaultCursor     string // "LOCAL" or "GLOBAL"
	SnapshotIsolation string // e.g. "OFF", "ON"

	AutoClose             bool
	AutoShrink            bool
	AutoCreateStats       bool
	AutoUpdateStats       bool
	AutoUpdateStatsAsync  bool
	ANSINullDefault       bool
	ANSINulls             bool
	ANSIPadding           bool
	ANSIWarnings          bool
	ArithAbort            bool
	ConcatNullYieldsNull  bool
	NumericRoundAbort     bool
	QuotedIdentifier      bool
	RecursiveTriggers     bool
	CursorCloseOnCommit   bool
	ReadCommittedSnapshot bool
	IsTrustworthy         bool
	IsBrokerEnabled       bool
	IsEncrypted           bool
}

DatabaseOptions holds the ALTER DATABASE SET options and related flags from sys.databases that aren't already covered by Database's own cached fields (RecoveryModel, CompatibilityLevel, Collation, IsReadOnly).

type DatabasePermissionEntry added in v0.0.4

type DatabasePermissionEntry struct {
	Principal     string
	PrincipalType string // e.g. "DATABASE_ROLE", "SQL_USER"
	Grantor       string
	Permission    string // e.g. "CONNECT", "CREATE TABLE", "ALTER"
	State         string // "GRANT", "GRANT_WITH_GRANT_OPTION", "DENY"
}

DatabasePermissionEntry is one GRANT/DENY entry recorded at database scope, as reported by sys.database_permissions — SSMS's Database Properties > Permissions page.

type DatabaseRecoveryStatus added in v0.0.10

type DatabaseRecoveryStatus struct {
	// DatabaseName is the database this row describes.
	DatabaseName string

	// LastLogBackupLSN is the log sequence number of the last log backup, in
	// the decimal form SQL Server stores it (numeric(25,0)), or "" when the
	// column is NULL — which is the pseudo-simple state above.
	LastLogBackupLSN string

	// LogBackupChainStarted is LastLogBackupLSN != "", named for the question
	// callers actually ask.
	LogBackupChainStarted bool
}

DatabaseRecoveryStatus reports a database's place in its log backup chain, from sys.database_recovery_status.

The distinction it carries is not "has a backup" — it is whether the log backup chain has been started at all, which is what SQL Server tests before it will let a database join an availability group or a mirroring session. A database in the FULL recovery model that has never had a full backup is running in the so-called pseudo-simple model: no log chain exists, and ALTER AVAILABILITY GROUP ... ADD DATABASE fails with Msg 1475 ("might contain bulk logged changes that have not been backed up"). Switching a database to SIMPLE and back to FULL breaks the chain again.

type DatabaseResourceStat added in v0.0.13

type DatabaseResourceStat struct {
	EndTime time.Time
	// AvgCPUPercent, AvgDataIOPercent, AvgLogWritePercent and
	// AvgMemoryUsagePercent are averages over the window, as a percentage of
	// the database's limit.
	AvgCPUPercent         float64
	AvgDataIOPercent      float64
	AvgLogWritePercent    float64
	AvgMemoryUsagePercent float64
	// XTPStoragePercent is In-Memory OLTP storage used, as a percentage.
	XTPStoragePercent float64
	// MaxWorkerPercent and MaxSessionPercent are the window's peaks, not
	// averages: the highest concurrent workers and sessions reached, against
	// the database's limits.
	MaxWorkerPercent  float64
	MaxSessionPercent float64
	// DTULimit is the database's DTU allocation. It is NULL on a Managed
	// Instance, which is vCore-based, and so reads as zero there.
	DTULimit int
	// AvgLoginRatePercent is logins against the limit, as a percentage.
	AvgLoginRatePercent float64
	// AvgInstanceCPUPercent and AvgInstanceMemoryPercent are the *instance's*
	// consumption over the same window, which lets a caller tell "this
	// database is busy" from "this instance is busy".
	AvgInstanceCPUPercent    float64
	AvgInstanceMemoryPercent float64
	// CPULimit is the database's vCore allocation.
	CPULimit float64
	// UsedStorageMB and AllocatedStorageMB are the database's data size and
	// the space allocated to hold it.
	UsedStorageMB      int64
	AllocatedStorageMB int64
	// ReplicaRole is the role the replica answering held during the window:
	// 0 primary, 1 secondary, 2 named secondary, 3 geo-replication forwarder.
	ReplicaRole int
}

DatabaseResourceStat is one row of sys.dm_db_resource_stats: a single database's resource consumption over a fixed 15-second window, retained about an hour.

It is the database-scoped counterpart of ServerResourceStat and has the same contract — every value is already an average or a maximum over the window, so a caller plots it directly rather than differencing it. The view is scoped to the database the connection is in, which is why this hangs off Database rather than Server.

The row carries no start_time: the window is the 15 seconds ending at EndTime. Percentages are of the database's own governed limit, not of the instance — AvgInstanceCPUPercent and AvgInstanceMemoryPercent are the two that are instance-wide, and are what says whether a quiet database is sharing a busy instance.

type DatabaseRole

type DatabaseRole struct {
	Name        string
	ID          int
	IsFixedRole bool
	Owner       string
	Members     []string
	SID         []byte
	CreateDate  time.Time
	ModifyDate  time.Time
	// contains filtered or unexported fields
}

DatabaseRole represents a database-level role.

func (*DatabaseRole) ChangeOwner added in v0.0.5

func (r *DatabaseRole) ChangeOwner(newOwner string) error

ChangeOwner transfers ownership of the database role to a new principal.

func (*DatabaseRole) ChangeOwnerContext added in v0.0.5

func (r *DatabaseRole) ChangeOwnerContext(ctx context.Context, newOwner string) error

ChangeOwnerContext is the context-aware variant of ChangeOwner.

func (*DatabaseRole) Drop added in v0.0.9

func (r *DatabaseRole) Drop() error

Drop drops this database role.

func (*DatabaseRole) DropContext added in v0.0.9

func (r *DatabaseRole) DropContext(ctx context.Context) error

DropContext is the context-aware variant of Drop.

func (*DatabaseRole) Rename added in v0.0.5

func (r *DatabaseRole) Rename(newName string) error

Rename changes the database role's name.

func (*DatabaseRole) RenameContext added in v0.0.5

func (r *DatabaseRole) RenameContext(ctx context.Context, newName string) error

RenameContext is the context-aware variant of Rename.

type DatabaseScopedConfig added in v0.0.5

type DatabaseScopedConfig struct {
	ID                int
	Name              string
	Value             string
	ValueForSecondary string
	// IsValueDefault is false on SQL Server 2016, whose
	// sys.database_scoped_configurations has no is_value_default column —
	// see scopedConfigSelect.
	IsValueDefault bool
}

DatabaseScopedConfig mirrors one row of sys.database_scoped_configurations. Value and ValueForSecondary are the raw CAST(... AS NVARCHAR) text SQL Server reports for that option's sql_variant column — boolean-style options render as "0"/"1" this way, not "OFF"/"ON", while enum-style options like ELEVATE_ONLINE render their keyword directly (e.g. "OFF"). Callers that know an option is boolean should compare against "1", not "ON".

type DatabaseScopedCredential added in v0.0.12

type DatabaseScopedCredential struct {
	CredentialID int
	Name         string
	Identity     string
	CreateDate   time.Time
	ModifyDate   time.Time
	// contains filtered or unexported fields
}

DatabaseScopedCredential mirrors a row from sys.database_scoped_credentials.

Get one from Database.DatabaseScopedCredential(name) or one of the reads below. A DatabaseScopedCredential built as a struct literal has no database behind it and will panic on Alter or Drop.

func (*DatabaseScopedCredential) Alter added in v0.0.12

func (c *DatabaseScopedCredential) Alter(identity string, secret *string) error

Alter changes the credential's identity, and its secret.

func (*DatabaseScopedCredential) AlterContext added in v0.0.12

func (c *DatabaseScopedCredential) AlterContext(ctx context.Context, identity string, secret *string) error

AlterContext is the context-aware variant of Alter.

A nil secret does not leave the stored secret alone — it clears it, for the same reason Credential.AlterContext's does. ALTER DATABASE SCOPED CREDENTIAL resets both halves every time and an omitted SECRET sets the stored secret to NULL; there is no T-SQL form that changes the identity while keeping the secret. Since the secret can never be read back, a caller that wants to keep one has to ask the user for it again and pass it here. Both branches are deliberate: pass a pointer to the new secret to set it, and nil only when clearing it is the intent.

func (*DatabaseScopedCredential) Database added in v0.0.12

func (c *DatabaseScopedCredential) Database() *Database

Database returns the database the credential lives in.

func (*DatabaseScopedCredential) Drop added in v0.0.12

func (c *DatabaseScopedCredential) Drop() error

Drop deletes the credential.

func (*DatabaseScopedCredential) DropContext added in v0.0.12

func (c *DatabaseScopedCredential) DropContext(ctx context.Context) error

DropContext is the context-aware variant of Drop. No IF EXISTS: dropping one that isn't there reaches the caller as the server's error, the way every other Drop* in this package does.

type DatabaseScopedCredentialSpec added in v0.0.12

type DatabaseScopedCredentialSpec struct {
	Name string

	// Identity is the account the credential presents when the database
	// reaches outside itself. CREATE DATABASE SCOPED CREDENTIAL requires it.
	Identity string

	// Secret is the password half — a shared access signature, a storage key
	// or a password, depending on what the identity means. Empty omits the
	// SECRET clause, creating a credential with a NULL secret, which is
	// legitimate for an identity that needs no password (Managed Identity is
	// the usual case).
	Secret string
}

DatabaseScopedCredentialSpec describes a database-scoped credential to create.

type DatabaseSecurableKind added in v0.0.13

type DatabaseSecurableKind string

DatabaseSecurableKind is the kind of database securable DatabaseCapabilities.SecurablePermissions is keyed by — ServerSecurableKind's database-scope twin. Its values are the class words SQL Server itself uses, in HAS_PERMS_BY_NAME and in GRANT ... ON <kind>::<name>.

const (
	// DatabaseSecurableAssembly is an assembly — class 5, schemaless.
	DatabaseSecurableAssembly DatabaseSecurableKind = "ASSEMBLY"

	// DatabaseSecurableType is a user-defined type — class 6, covering alias,
	// table and CLR types alike.
	DatabaseSecurableType DatabaseSecurableKind = "TYPE"

	// DatabaseSecurableXmlSchemaCollection is an XML schema collection —
	// class 10.
	DatabaseSecurableXmlSchemaCollection DatabaseSecurableKind = "XML SCHEMA COLLECTION"
)

type DatabaseSnapshot added in v0.0.13

type DatabaseSnapshot struct {
	Name       string
	DatabaseID int

	// SourceDatabase is the name of the database the snapshot was taken of,
	// empty in the rare case where the source has since been dropped — which
	// also makes the snapshot unusable, but it stays in the catalog until it
	// is dropped itself.
	SourceDatabase   string
	SourceDatabaseID int

	// State is the snapshot's own state_desc. A snapshot whose sparse files
	// have run out of disk goes SUSPECT and stays there; there is no repair
	// but dropping it.
	State string

	CreateDate time.Time
	// contains filtered or unexported fields
}

DatabaseSnapshot describes one database snapshot and the database it was taken of.

func (*DatabaseSnapshot) Database added in v0.0.13

func (s *DatabaseSnapshot) Database() *Database

Database returns a lightweight handle for the snapshot database itself, for reading its (read-only) contents.

func (*DatabaseSnapshot) Drop added in v0.0.13

func (s *DatabaseSnapshot) Drop() error

Drop drops the snapshot. Dropping a snapshot deletes its sparse files and leaves the source database untouched.

func (*DatabaseSnapshot) DropContext added in v0.0.13

func (s *DatabaseSnapshot) DropContext(ctx context.Context) error

DropContext is the context-aware variant of Drop.

func (*DatabaseSnapshot) Restore added in v0.0.13

func (s *DatabaseSnapshot) Restore() error

Restore reverts the snapshot's source database to it.

func (*DatabaseSnapshot) RestoreContext added in v0.0.13

func (s *DatabaseSnapshot) RestoreContext(ctx context.Context) error

RestoreContext is the context-aware variant of Restore.

func (*DatabaseSnapshot) Server added in v0.0.13

func (s *DatabaseSnapshot) Server() *Server

Server returns the server the snapshot is on.

type DatabaseTrigger added in v0.0.12

type DatabaseTrigger struct {
	Name string

	// IsEnabled is the inverse of the catalog's is_disabled.
	IsEnabled bool

	CreateDate time.Time
	ModifyDate time.Time

	// Events are the type_desc values from sys.trigger_events —
	// "CREATE_TABLE", "ALTER_PROCEDURE", and so on. A trigger declared FOR a
	// whole event group lists the group's individual events, which is what
	// the catalog records.
	Events []string

	// Definition is the trigger body from sys.sql_modules. It is empty for an
	// encrypted trigger (the catalog reports NULL) and for a CLR trigger,
	// which has no row there at all.
	Definition string
	// contains filtered or unexported fields
}

database_trigger.go covers database-scope DDL triggers — sys.triggers with parent_class = 0, SSMS's <database> > Programmability > Database Triggers folder.

This is the third trigger family, and the one neither of the other two can be widened to cover. Database.Triggers reads parent_class = 1 (a DML trigger on a table or a view) and its Trigger carries TableName and Schema, which a DDL trigger has nothing to put in: it has no parent object, so no schema either. ServerTriggers reads sys.server_triggers, a different view altogether. Everything here addresses the trigger by bare name, ON DATABASE.

func (*DatabaseTrigger) Database added in v0.0.12

func (t *DatabaseTrigger) Database() *Database

Database returns the database the trigger is defined on.

func (*DatabaseTrigger) Disable added in v0.0.12

func (t *DatabaseTrigger) Disable() error

Disable disables the trigger, leaving its definition in place.

func (*DatabaseTrigger) DisableContext added in v0.0.12

func (t *DatabaseTrigger) DisableContext(ctx context.Context) error

DisableContext is the context-aware variant of Disable.

func (*DatabaseTrigger) Drop added in v0.0.12

func (t *DatabaseTrigger) Drop() error

Drop removes the trigger. A trigger that isn't there is the server's error, not a silent success — see the note on Database.DropTable.

This is not Database.DropTrigger: that one schema-qualifies the name, which a DDL trigger has no schema for, and omits the ON DATABASE clause the server requires here.

func (*DatabaseTrigger) DropContext added in v0.0.12

func (t *DatabaseTrigger) DropContext(ctx context.Context) error

DropContext is the context-aware variant of Drop.

func (*DatabaseTrigger) Enable added in v0.0.12

func (t *DatabaseTrigger) Enable() error

Enable enables the trigger.

func (*DatabaseTrigger) EnableContext added in v0.0.12

func (t *DatabaseTrigger) EnableContext(ctx context.Context) error

EnableContext is the context-aware variant of Enable.

type DateCriterion added in v0.0.10

type DateCriterion struct {
	Op  DateOp
	Day time.Time
}

DateCriterion is one comparison against a creation date. Day's time of day is ignored.

type DateOp added in v0.0.10

type DateOp int

DateOp is one comparison a date criterion makes. All three work on whole calendar days: a creation date is a timestamp, and "created on the 20th" means the day, not midnight exactly.

const (
	DateOn DateOp = iota
	DateBefore
	DateAfter
)

type Default added in v0.0.13

type Default struct {
	Name       string
	Schema     string
	ObjectID   int
	Definition string
	CreateDate time.Time
	ModifyDate time.Time
	// contains filtered or unexported fields
}

Default mirrors a sys.objects row of type 'D' with parent_object_id = 0 — a CREATE DEFAULT object, not a default constraint. Table default constraints reach a caller through Column.DefaultValue.

func (*Default) Database added in v0.0.13

func (df *Default) Database() *Database

Database returns the database the default belongs to.

func (*Default) Drop added in v0.0.13

func (df *Default) Drop() error

Drop drops the default.

func (*Default) DropContext added in v0.0.13

func (df *Default) DropContext(ctx context.Context) error

DropContext is the context-aware variant of Drop.

func (*Default) FullName added in v0.0.13

func (df *Default) FullName() string

FullName returns the schema-qualified, bracket-quoted name.

type Dependency added in v0.0.4

type Dependency struct {
	Schema        string
	Name          string
	TypeDesc      string // e.g. "USER_TABLE", "VIEW", "SQL_STORED_PROCEDURE"
	IsSchemaBound bool
}

Dependency is one edge in an object dependency graph, as reported by sys.sql_expression_dependencies — e.g. a view referencing a table, or a stored procedure referencing a function.

type DetachOptions added in v0.0.11

type DetachOptions struct {
	// DropConnections rolls back and disconnects everything using the
	// database first (SET SINGLE_USER WITH ROLLBACK IMMEDIATE). Without it a
	// database with any other connection open refuses to detach. A detach
	// that then fails is put back to MULTI_USER, so a refusal never leaves
	// the database single-user — same contract as RenameDatabaseContext.
	DropConnections bool

	// UpdateStatistics runs UPDATE STATISTICS across the database before
	// detaching, so the statistics survive into whatever attaches it next.
	//
	// The zero value skips it — sp_detach_db's @skipchecks = 'true' — which
	// is both what SSMS's Detach dialog offers unchecked and what a large
	// database wants: the update scans every statistics object in it. Note
	// this is the opposite of what the procedure does when left to its own
	// defaults.
	UpdateStatistics bool

	// DropFullTextIndexFile deletes the full-text index files rather than
	// leaving them beside the data files. Named for what it *does*, not for
	// what it keeps, so that the zero value is sp_detach_db's own default
	// (@keepfulltextindexfile = 'true') and no caller loses a catalog by
	// leaving a field unset.
	DropFullTextIndexFile bool
}

DetachOptions are sp_detach_db's three choices, named for what they do rather than for the procedure's parameters, whose senses are inverted.

type DetachedDatabase added in v0.0.11

type DetachedDatabase struct {
	// Name is the name the database was detached under. An attach may use a
	// different one; nothing in the files ties them together.
	Name      string
	Version   string
	Collation string
	Files     []*DetachedFile
}

DetachedDatabase is what a detached primary data file says about the database it belongs to.

func (*DetachedDatabase) DataFiles added in v0.0.11

func (d *DetachedDatabase) DataFiles() []*DetachedFile

func (*DetachedDatabase) LogFiles added in v0.0.11

func (d *DetachedDatabase) LogFiles() []*DetachedFile

LogFiles returns the log files of the detached database, and DataFiles the rest. Attach's two interesting subsets, so a caller building a file list does not re-derive the status bit.

func (*DetachedDatabase) PrimaryFile added in v0.0.11

func (d *DetachedDatabase) PrimaryFile() *DetachedFile

PrimaryFile returns the database's primary data file — the one whose path DetachedDatabaseInfo was given, and the only one an attach can relocate without the caller naming it.

file_id 1 is the primary data file, always; DBCC CHECKPRIMARYFILE's row order is not documented to match it, and the primary is not documented to come back first. The fallback to the first data file is for a fileid column that came back NULL — better the wrong data file than nil, which reads as "this database has no primary".

type DetachedFile added in v0.0.11

type DetachedFile struct {
	FileID int
	// Name is the file's logical name, PhysicalName the path it was detached
	// from — which is where the file is only until someone moves it.
	Name         string
	PhysicalName string
	IsLog        bool
}

DetachedFile is one file of a detached database, as its primary data file records it.

type DeviceCodeMessage added in v0.0.13

type DeviceCodeMessage struct {
	// UserCode is the code the user types in.
	UserCode string
	// VerificationURL is the page the user types it into.
	VerificationURL string
	// Message is Microsoft's own one-line instruction carrying both, suitable
	// for display as it is.
	Message string
}

DeviceCodeMessage is what AuthEntraDeviceCode needs the user to see: a code to enter at a verification URL, on any device.

type DiskUsage added in v0.0.13

type DiskUsage struct {
	// DataFilesMB and LogFilesMB are the on-disk sizes of the ROWS and LOG
	// files respectively — DataFilesMB + LogFilesMB is the database's
	// footprint.
	DataFilesMB float64
	LogFilesMB  float64

	// DataMB is row data in heaps and clustered indexes, IndexMB is row
	// data in every other index, and both include the LOB and row-overflow
	// pages belonging to them, so no used page is counted twice or missed.
	DataMB  float64
	IndexMB float64
	// UnusedMB is reserved-but-unused space inside extents already
	// allocated to an object.
	UnusedMB float64
	// UnallocatedMB is data-file space not yet allocated to anything.
	UnallocatedMB float64

	// LogUsedMB and LogUnusedMB split the log files the same way — the
	// active portion against what a shrink could give back.
	LogUsedMB   float64
	LogUnusedMB float64
}

DiskUsage is a database's disk-usage breakdown — the numbers behind SSMS's "Disk Usage" report, in MB.

The two halves are read separately, one per file kind, and each is a composition of the space its files hold:

data files: DataMB + IndexMB + UnusedMB + UnallocatedMB
log files:  LogUsedMB + LogUnusedMB

UnallocatedMB and LogUnusedMB are file space not yet handed to any object, the same free-space measure SpaceInfo reports; UnusedMB is space already allocated to an object in extents whose pages it has not filled yet, so shrinking a file reclaims the former and rebuilding an index the latter.

The data-file parts are counted from allocated pages and the file totals from the files themselves, so the four data parts sum to slightly less than DataFilesMB: the difference is the database's own internal pages (IAM, boot page, allocation bitmaps), which belong to no allocation unit. Read the parts against each other, not against DataFilesMB — that is how the SSMS report presents them too.

type DiskVolumeInfo added in v0.0.5

type DiskVolumeInfo struct {
	// MountPoint is the drive letter (Windows) or mount path (Linux). Some
	// hosts — e.g. a containerized Linux instance without a distinct OS
	// volume — report this as empty.
	MountPoint string
	// VolumeName is the OS volume label, also sometimes empty.
	VolumeName string
	// SamplePath is one database file's path stored on this volume, for
	// display when MountPoint and VolumeName are both empty.
	SamplePath  string
	TotalMB     float64
	AvailableMB float64
}

DiskVolumeInfo describes free/total space for one storage volume backing at least one of the server's database files, as reported by sys.dm_os_volume_stats — a DMV SQL Server exposes identically on Windows and Linux, so this is usable regardless of the host OS.

type EffectivePermission added in v0.0.8

type EffectivePermission struct {
	// Entity is the securable the permission applies to, as
	// fn_my_permissions names it — "database", "server", or the
	// schema-qualified object name.
	Entity string

	// Subentity is the column name for a column-level permission, empty
	// otherwise. Asking about an object reports both: the object-level rows
	// with an empty Subentity, then one row per column that carries a
	// column-level permission of its own.
	Subentity string

	// Permission is the permission name, e.g. "SELECT", "VIEW DEFINITION".
	Permission string
}

EffectivePermission is one permission a principal effectively holds on a securable, as reported by fn_my_permissions. Unlike a PermissionEntry it is not an explicit GRANT/DENY row: role membership, ownership, and permissions inherited from a wider scope (a schema grant covering a table, CONTROL implying everything below it) are all already resolved into it, and anything DENY takes away is simply absent.

type Endpoint added in v0.0.11

type Endpoint struct {
	EndpointID int
	Name       string

	// Owner is the login that owns the endpoint, empty when this login cannot
	// resolve the principal.
	Owner string

	// Protocol is TCP, HTTP, SHARED_MEMORY, NAMED_PIPES or VIA.
	Protocol string

	// Type is the payload: TSQL, SERVICE_BROKER, DATABASE_MIRRORING or SOAP.
	Type string

	// State is STARTED, STOPPED or DISABLED. Only a STARTED endpoint accepts
	// connections.
	State string

	// IsAdmin marks the Dedicated Admin Connection.
	IsAdmin bool

	// Port is the TCP port, 0 for an endpoint on another protocol and for the
	// built-in TCP ones, which report 0 rather than the instance's real port.
	Port int

	// IsSystem marks one of the built-in endpoints, which cannot be altered or
	// dropped — see ErrSystemEndpoint.
	IsSystem bool
	// contains filtered or unexported fields
}

Endpoint mirrors a row of sys.endpoints — one server endpoint of any protocol and payload.

Type-specific detail is not on this struct: MirroringDetail and ServiceBrokerDetail read it when it is wanted, so listing every endpoint costs one query rather than three.

func (*Endpoint) Drop added in v0.0.11

func (e *Endpoint) Drop() error

Drop removes the endpoint.

func (*Endpoint) DropContext added in v0.0.11

func (e *Endpoint) DropContext(ctx context.Context) error

DropContext is the context-aware variant of Drop. A built-in endpoint is refused with ErrSystemEndpoint before any statement is built.

func (*Endpoint) MirroringDetail added in v0.0.11

func (e *Endpoint) MirroringDetail() (*DatabaseMirroringEndpoint, error)

MirroringDetail reads the database mirroring settings of a DATABASE_MIRRORING endpoint — role, encryption and connection auth.

func (*Endpoint) MirroringDetailContext added in v0.0.11

func (e *Endpoint) MirroringDetailContext(ctx context.Context) (*DatabaseMirroringEndpoint, error)

MirroringDetailContext is the context-aware variant of MirroringDetail.

It returns (nil, nil) for an endpoint that is not a mirroring one, matching DatabaseMirroringEndpointContext's convention: a caller asking every endpoint for its mirroring detail branches on absence as the ordinary case. An instance has at most one mirroring endpoint, so the read needs no name.

func (*Endpoint) ServiceBrokerDetail added in v0.0.11

func (e *Endpoint) ServiceBrokerDetail() (*ServiceBrokerEndpointDetail, error)

ServiceBrokerDetail reads the Service Broker settings of a SERVICE_BROKER endpoint.

func (*Endpoint) ServiceBrokerDetailContext added in v0.0.11

func (e *Endpoint) ServiceBrokerDetailContext(ctx context.Context) (*ServiceBrokerEndpointDetail, error)

ServiceBrokerDetailContext is the context-aware variant of ServiceBrokerDetail. It returns (nil, nil) for an endpoint that is not a Service Broker one, the same convention MirroringDetailContext follows.

func (*Endpoint) SetState added in v0.0.11

func (e *Endpoint) SetState(state EndpointState) error

SetState starts, stops or disables the endpoint.

func (*Endpoint) SetStateContext added in v0.0.11

func (e *Endpoint) SetStateContext(ctx context.Context, state EndpointState) error

SetStateContext is the context-aware variant of SetState. A built-in endpoint is refused with ErrSystemEndpoint before any statement is built.

type EndpointSpec added in v0.0.9

type EndpointSpec struct {
	// Name is the endpoint's name. Required; it is arbitrary and purely local
	// — replicas address each other by URL, never by endpoint name.
	Name string

	// Port is the TCP port to listen on. Zero means 5022, the conventional
	// database mirroring port.
	Port int

	// Role is ALL, PARTNER or WITNESS. Empty means ALL, which is what an
	// availability group replica needs.
	Role string

	// Authentication is the AUTHENTICATION clause — WINDOWS NEGOTIATE,
	// WINDOWS KERBEROS, CERTIFICATE <name>, and so on. Empty means WINDOWS
	// NEGOTIATE.
	//
	// Passed through as written, because the clause is a small grammar rather
	// than one keyword ("CERTIFICATE x", "WINDOWS NEGOTIATE CERTIFICATE x").
	// Instances with no domain in common — the usual Linux case — need a
	// certificate here, and the certificate has to already exist and have been
	// exchanged with every other replica.
	Authentication string

	// Encryption is the ENCRYPTION clause's state: REQUIRED, SUPPORTED or
	// DISABLED. Empty means REQUIRED.
	Encryption string

	// EncryptionAlgorithm is the ALGORITHM sub-clause. Empty omits it, leaving
	// the server's default; AES is the only sensible value on any supported
	// version.
	EncryptionAlgorithm string
}

EndpointSpec describes a database mirroring endpoint to create.

type EndpointState added in v0.0.11

type EndpointState string

EndpointState is the state an endpoint can be put into.

const (
	// EndpointStarted accepts connections.
	EndpointStarted EndpointState = "STARTED"
	// EndpointStopped refuses connections but still listens, answering with
	// an error rather than nothing.
	EndpointStopped EndpointState = "STOPPED"
	// EndpointDisabled does not listen at all.
	EndpointDisabled EndpointState = "DISABLED"
)

type EngineEdition added in v0.0.12

type EngineEdition int

EngineEdition values as returned by SERVERPROPERTY('EngineEdition') and carried in ServerInfo.EngineEdition. 7 is unassigned and 10 was never shipped publicly, so the list is deliberately not contiguous.

const (
	EnginePersonal          EngineEdition = 1
	EngineStandard          EngineEdition = 2
	EngineEnterprise        EngineEdition = 3
	EngineExpress           EngineEdition = 4
	EngineAzureSQLDatabase  EngineEdition = 5
	EngineAzureSynapse      EngineEdition = 6
	EngineAzureManagedInst  EngineEdition = 8
	EngineAzureSQLEdge      EngineEdition = 9
	EngineAzureSynapseSrvls EngineEdition = 11
)

func (EngineEdition) IsAzure added in v0.0.12

func (e EngineEdition) IsAzure() bool

IsAzure reports whether e is one of the Azure-hosted engine editions, whose ProductVersion is a fixed compatibility fiction rather than a feature level: a Managed Instance answers 12.0.2000.8 (SQL Server 2014) while running an 18.x engine with every catalog column 2016 through 2022 added. Every version gate here has to ask this before it believes VersionMajor — see serverMajorVersion in version_gate.go.

type EntraCache added in v0.0.13

type EntraCache struct {
	// contains filtered or unexported fields
}

EntraCache holds Microsoft Entra credentials and the access tokens they have issued, so that every connection authenticating as the same identity signs in once rather than once per physical connection. Share one across every ConnectContext call that should share a sign-in — typically one per process. It holds tokens and, for the methods that take one, secrets, in memory only; nothing is written to disk, so a new process signs in again.

An identity is the auth method with the fields that decide who signs in — tenant, client and application IDs, user or login hint, certificate path, sign-in authority, and a digest of the secrets — never the server, so one sign-in covers every server in the tenant, as it does in SSMS. A cached token is reused until five minutes before it expires (or the refresh time the issuer suggests), then renewed through the same credential, which for the interactive flows is normally silent.

The zero value is not usable; call NewEntraCache. An EntraCache is safe for concurrent use.

func NewEntraCache added in v0.0.13

func NewEntraCache() *EntraCache

NewEntraCache returns an empty EntraCache.

func (*EntraCache) Clear added in v0.0.13

func (c *EntraCache) Clear()

Clear forgets every credential and token c holds. The next connection through c signs in again — the way to switch accounts. Pools already open keep the connections they have; only new physical connections are affected.

func (*EntraCache) Warm added in v0.0.13

func (c *EntraCache) Warm(ctx context.Context, opts ConnectionOptions) error

Warm signs in for opts ahead of any connection, filling c with the token the connection will need, so that a human sign-in (AuthEntraInteractive, AuthEntraDeviceCode) runs under ctx — which may be long and cancellable — rather than under a connect timeout, inside the TDS login handshake. Pass the same options, with EntraCache set to c, to ConnectContext afterwards. opts.EntraCache itself is ignored here.

The token's scope, sign-in authority and — when TenantID is empty — tenant are the server's to announce, and it announces them only part-way through a login. So Warm first opens a login to Server and abandons it as soon as the server has said them, before any token is sent; c remembers the answer per Server, so later Warms for the same server skip it. That probe runs under ctx and at most opts.ConnectTimeout, and its failure — an unreachable server, one that does not accept Entra logins — is Warm's error.

Warm does nothing and returns nil when there is no sign-in to do: a non-Entra method, AccessTokenProvider, or AuthEntraServicePrincipalAccessToken.

type ErrorLogEntry

type ErrorLogEntry struct {
	// LogDate is Date rendered as RFC 3339, kept for compatibility with
	// callers written before Date existed.
	LogDate string
	// Process is the SQL Server log's ProcessInfo column, empty on an Agent
	// log entry.
	Process string
	Text    string
	// Date is the entry's timestamp. The log stores no time zone, so this
	// is the server's local wall clock carried in UTC.
	Date time.Time
	// ErrorLevel is the Agent log's severity column, 0 on a SQL Server log
	// entry.
	ErrorLevel int
}

ErrorLogEntry represents one row returned by xp_readerrorlog.

The middle column differs by log family, so only one of Process and ErrorLevel is meaningful for a given entry: the SQL Server log reports a ProcessInfo string ("Server", "spid9s"), the Agent log an integer severity. See Source for the one that applies.

func (*ErrorLogEntry) Source added in v0.0.9

func (e *ErrorLogEntry) Source() string

Source returns whichever of Process and ErrorLevel the entry's log family populated — the value to show in a "Source" column that spans both.

type ErrorLogFile added in v0.0.9

type ErrorLogFile struct {
	// Number is the archive number — 0 for the current log, 1 for the most
	// recently archived one, and so on. It is what ReadLog takes.
	Number int
	// Date is the last-written timestamp exactly as the server formatted it,
	// kept because that formatting follows the server's locale and is the
	// only thing to display when LastWritten couldn't be parsed.
	Date string
	// LastWritten is Date parsed, or the zero time if the server's format
	// wasn't one of the known ones.
	LastWritten time.Time
	// SizeBytes is the log file's size on disk.
	SizeBytes int64
}

ErrorLogFile is one log file reported by sp_enumerrorlogs: the current log plus however many archives the instance is configured to keep.

type ErrorLogType added in v0.0.9

type ErrorLogType int

ErrorLogType selects which of the two log families a read or an enumeration addresses. The values are the log-type argument xp_readerrorlog and sp_enumerrorlogs themselves take, so they can be passed straight through.

const (
	// ErrorLogSQLServer is the SQL Server error log (ERRORLOG, ERRORLOG.1, …).
	ErrorLogSQLServer ErrorLogType = 1
	// ErrorLogAgent is the SQL Server Agent error log (SQLAGENT.OUT,
	// SQLAGENT.1, …).
	ErrorLogAgent ErrorLogType = 2
)

func (ErrorLogType) String added in v0.0.9

func (t ErrorLogType) String() string

String names the log family for display.

type ExecutionPlan added in v0.0.4

type ExecutionPlan struct {
	// XML is the last plan in All, in SQL Server's "Showplan XML" format —
	// the same document SSMS parses to draw its graphical plan.
	XML string

	// All holds every captured plan document, one per statement, in the
	// order the server returned them. Never empty on a successful capture.
	All []string
}

ExecutionPlan holds the execution plans captured for one batch.

A batch of several statements yields several plan documents, not one: under SET SHOWPLAN_XML the server returns one row per statement, and under SET STATISTICS XML one extra result set per statement. All holds every one of them, in the order the server produced them; XML is the *last*, which is what this type returned when it held a single string and is kept for callers written against that. A caller that means "the plan for the batch" wants All.

type ExtendedProperty

type ExtendedProperty struct {
	Name  string
	Value string
}

ExtendedProperty mirrors a row from sys.extended_properties.

type ExtendedPropertyLevel

type ExtendedPropertyLevel struct {
	Level0Type string // e.g. "SCHEMA"
	Level0Name string
	Level1Type string // e.g. "TABLE"
	Level1Name string
	Level2Type string // e.g. "COLUMN"
	Level2Name string
}

ExtendedPropertyLevel identifies the object level for an extended property.

type ExternalDataSource added in v0.0.13

type ExternalDataSource struct {
	Name         string
	DataSourceID int

	// Location is the connection string of the remote source — an
	// hdfs://, sqlserver://, abfss:// or similar URL depending on Type.
	Location string

	// Type is the source kind, as type_desc reports it: HADOOP,
	// RDBMS, SHARD_MAP_MANAGER, BLOB_STORAGE, EXTERNAL_GENERICS.
	Type string

	// ResourceManagerLocation is the Hadoop resource manager endpoint for a
	// HADOOP source, empty otherwise.
	ResourceManagerLocation string

	// Credential is the database-scoped credential the source authenticates
	// with, empty when it uses none.
	Credential string

	// DatabaseName and ShardMapName are the remote database and shard map
	// for an elastic-query source, empty for the others.
	DatabaseName string
	ShardMapName string

	// ConnectionOptions and PushdownEnabled are SQL Server 2019 and later;
	// on an older instance ConnectionOptions is empty and PushdownEnabled
	// reads as false, rather than the read failing.
	ConnectionOptions string
	PushdownEnabled   bool
	// contains filtered or unexported fields
}

ExternalDataSource mirrors a sys.external_data_sources row.

func (*ExternalDataSource) Database added in v0.0.13

func (s *ExternalDataSource) Database() *Database

Database returns the database the data source belongs to.

func (*ExternalDataSource) Drop added in v0.0.13

func (s *ExternalDataSource) Drop() error

Drop drops the external data source.

func (*ExternalDataSource) DropContext added in v0.0.13

func (s *ExternalDataSource) DropContext(ctx context.Context) error

DropContext is the context-aware variant of Drop.

type ExternalFileFormat added in v0.0.13

type ExternalFileFormat struct {
	Name         string
	FileFormatID int

	// FormatType is DELIMITEDTEXT, RCFILE, ORC, PARQUET, JSON or DELTA.
	FormatType string

	FieldTerminator string
	StringDelimiter string
	DateFormat      string
	UseTypeDefault  bool
	SerDeMethod     string
	RowTerminator   string
	Encoding        string
	DataCompression string

	// FirstRow and ParserVersion are SQL Server 2019 and later; on an older
	// instance FirstRow is 0 and ParserVersion empty rather than the read
	// failing.
	FirstRow      int
	ParserVersion string
	// contains filtered or unexported fields
}

ExternalFileFormat mirrors a sys.external_file_formats row.

Most fields apply to one format type only — the delimited-text fields are empty on a PARQUET format, and SerDeMethod is set only on a HIVE RCFILE — so read FormatType first.

func (*ExternalFileFormat) Database added in v0.0.13

func (f *ExternalFileFormat) Database() *Database

Database returns the database the file format belongs to.

func (*ExternalFileFormat) Drop added in v0.0.13

func (f *ExternalFileFormat) Drop() error

Drop drops the external file format.

func (*ExternalFileFormat) DropContext added in v0.0.13

func (f *ExternalFileFormat) DropContext(ctx context.Context) error

DropContext is the context-aware variant of Drop.

type ExternalLibrary added in v0.0.13

type ExternalLibrary struct {
	Name      string
	LibraryID int

	// Owner is the database principal that owns the library, empty when
	// principal_id names one that no longer exists.
	Owner string

	// Language is the runtime the package belongs to — "R" or "Python".
	Language string

	// Scope is PUBLIC for a library every user can load and PRIVATE for one
	// scoped to its owner.
	Scope string
	// contains filtered or unexported fields
}

ExternalLibrary mirrors a sys.external_libraries row — an R or Python package uploaded for Machine Learning Services.

The catalog view carries no platform column on any instance gosmo supports: the documented platform/platform_desc pair is absent from majors 14 and 17 alike, so there is no field for it here.

func (*ExternalLibrary) Database added in v0.0.13

func (l *ExternalLibrary) Database() *Database

Database returns the database the library belongs to.

func (*ExternalLibrary) Drop added in v0.0.13

func (l *ExternalLibrary) Drop() error

Drop drops the external library.

func (*ExternalLibrary) DropContext added in v0.0.13

func (l *ExternalLibrary) DropContext(ctx context.Context) error

DropContext is the context-aware variant of Drop.

type ExtraParamError added in v0.0.13

type ExtraParamError struct {
	Key string
	// Reserved reports that a ConnectionOptions field controls Key — the
	// caller should set that field instead. When false the entry itself is
	// malformed: an empty name, more than one value, or the same key twice in
	// different case.
	Reserved bool
	// contains filtered or unexported fields
}

ExtraParamError is the error Connect and ConnectionString return for a ConnectionOptions.ExtraParams entry they refuse. Key is the name as the caller gave it.

func (*ExtraParamError) Error added in v0.0.13

func (e *ExtraParamError) Error() string

type FileGroup

type FileGroup struct {
	Name string

	// Type is sys.filegroups.type_desc: "ROWS_FILEGROUP",
	// "FILESTREAM_DATA_FILEGROUP" or "MEMORY_OPTIMIZED_DATA_FILEGROUP". It
	// decides what a file added to the group becomes — ALTER DATABASE ADD FILE
	// has no file-type keyword, so the same clause makes a FILESTREAM file in a
	// FILESTREAM filegroup and an ordinary data file in a ROWS one.
	Type string

	// IsDefault is per filegroup *type*, not per database: a database with a
	// FILESTREAM filegroup reports one default ROWS filegroup and one default
	// FILESTREAM filegroup, both true.
	IsDefault  bool
	IsReadOnly bool
	Files      []DatabaseFile
}

FileGroup represents a SQL Server filegroup.

func (*FileGroup) IsFileStream added in v0.0.12

func (fg *FileGroup) IsFileStream() bool

IsFileStream reports whether files added to this filegroup are FILESTREAM data files, which take neither SIZE nor FILEGROWTH (SQL Server error 5509) and whose FILENAME is a directory rather than a file.

type FileModify added in v0.0.4

type FileModify struct {
	NewName       string
	SizeKB        int64
	GrowthKB      int64
	GrowthPercent int
	// DisableGrowth turns autogrowth off (FILEGROWTH = 0), and takes
	// precedence over GrowthKB/GrowthPercent.
	//
	// It is a separate field because this struct's zero value means "leave
	// this property alone", so GrowthKB = 0 cannot ask for FILEGROWTH = 0 —
	// the one that omits the clause and the one that disables growth are
	// the same value. Without it a UI whose growth control bottoms out at
	// zero produces an ALTER with no FILEGROWTH clause, and if nothing else
	// on the file changed, buildAlterFileStatement returns "" and
	// AlterFileContext returns nil: an Apply that reports success and did
	// nothing.
	DisableGrowth bool
	MaxSizeKB     int64 // -1 = UNLIMITED
}

FileModify holds the fields to change on an existing file via AlterFile. Zero-valued fields are left unchanged; NewName renames the file.

type FileSystemEntry added in v0.0.9

type FileSystemEntry struct {
	Name         string
	FullPath     string
	IsDirectory  bool
	Size         int64
	LastModified time.Time
}

FileSystemEntry is one file or directory in a server-side directory listing. Size and LastModified are zero for entries the server reports without them (the xp_dirtree fallback on pre-2017 instances).

type FixedDrive added in v0.0.9

type FixedDrive struct {
	Name           string // "C:\" on Windows, "/" on Linux
	Type           string // e.g. "DRIVE_FIXED"
	FreeSpaceBytes int64
}

FixedDrive is one fixed drive (a volume, on Windows) visible to the SQL Server host. On Linux the server reports the single root filesystem.

type ForeignKey

type ForeignKey struct {
	Name                string
	Columns             []string
	ReferencedTable     string
	ReferencedSchema    string
	ReferencedColumns   []string
	DeleteAction        string // NO_ACTION, CASCADE, SET_NULL, SET_DEFAULT
	UpdateAction        string
	IsDisabled          bool
	IsNotForReplication bool
}

ForeignKey mirrors Microsoft.SqlServer.Management.Smo.ForeignKey.

type Index

type Index struct {
	Name               string
	IndexID            int
	Type               IndexType
	IsClustered        bool
	IsUnique           bool
	IsPrimaryKey       bool
	IsUniqueConstraint bool
	IsDisabled         bool
	FillFactor         int
	IsPadded           bool
	IgnoreDupKey       bool
	AllowRowLocks      bool
	AllowPageLocks     bool
	DataCompression    string
	KeyColumns         []IndexColumn
	IncludedColumns    []IndexColumn
	FilterDefinition   string
	DataSpace          DataSpace
}

Index mirrors Microsoft.SqlServer.Management.Smo.Index.

func (*Index) Disable

func (idx *Index) Disable(t *Table) error

Disable disables the index (ALTER INDEX ... DISABLE).

func (*Index) DisableContext

func (idx *Index) DisableContext(ctx context.Context, t *Table) error

DisableContext is the context-aware variant of Disable.

func (*Index) Drop

func (idx *Index) Drop(t *Table) error

Drop drops the index.

func (*Index) DropContext

func (idx *Index) DropContext(ctx context.Context, t *Table) error

DropContext is the context-aware variant of Drop.

func (*Index) Enable

func (idx *Index) Enable(t *Table) error

Enable re-enables a disabled index by rebuilding it.

func (*Index) EnableContext added in v0.0.6

func (idx *Index) EnableContext(ctx context.Context, t *Table) error

EnableContext is the context-aware variant of Enable.

func (*Index) Fragmentation added in v0.0.6

func (idx *Index) Fragmentation(t *Table, mode string) (*IndexFragmentation, error)

Fragmentation returns fragmentation and page-density statistics for this index alone — the single-index analog of Table.FragmentationStats, used by Index Properties' Fragmentation page. mode follows Table.FragmentationStats's (LIMITED, SAMPLED, or DETAILED); page density is only populated by SAMPLED or DETAILED (LIMITED always reports 0, same as the underlying DMV).

func (*Index) FragmentationContext added in v0.0.6

func (idx *Index) FragmentationContext(ctx context.Context, t *Table, mode string) (*IndexFragmentation, error)

FragmentationContext is the context-aware variant of Fragmentation.

func (*Index) Rebuild

func (idx *Index) Rebuild(t *Table, fillFactor int) error

Rebuild rebuilds the index (ALTER INDEX ... REBUILD). Pass fillFactor=0 to keep the existing fill factor.

func (*Index) RebuildContext

func (idx *Index) RebuildContext(ctx context.Context, t *Table, fillFactor int) error

RebuildContext is the context-aware variant of Rebuild.

func (*Index) RebuildWithOptions added in v0.0.6

func (idx *Index) RebuildWithOptions(t *Table, fillFactor int, padIndex bool, dataCompression string) error

RebuildWithOptions rebuilds the index with an explicit fill factor, pad index setting, and data compression (ALTER INDEX ... REBUILD WITH) — the only way to change these three, since none is a plain ALTER INDEX SET option. Pass dataCompression="" to leave compression unspecified (keeps the index's current setting).

func (*Index) RebuildWithOptionsContext added in v0.0.6

func (idx *Index) RebuildWithOptionsContext(ctx context.Context, t *Table, fillFactor int, padIndex bool, dataCompression string) error

RebuildWithOptionsContext is the context-aware variant of RebuildWithOptions.

func (*Index) Rename added in v0.0.6

func (idx *Index) Rename(t *Table, newName string) error

Rename renames the index using sp_rename — also the mechanism for renaming a PRIMARY KEY or UNIQUE constraint, since its name is the backing index's name in sys.indexes.

func (*Index) RenameContext added in v0.0.6

func (idx *Index) RenameContext(ctx context.Context, t *Table, newName string) error

RenameContext is the context-aware variant of Rename.

func (*Index) Reorganize

func (idx *Index) Reorganize(t *Table) error

Reorganize reorganizes the index (ALTER INDEX ... REORGANIZE).

func (*Index) ReorganizeContext

func (idx *Index) ReorganizeContext(ctx context.Context, t *Table) error

ReorganizeContext is the context-aware variant of Reorganize.

func (*Index) SetIncludedColumns added in v0.0.6

func (idx *Index) SetIncludedColumns(t *Table, columns []string) error

SetIncludedColumns replaces the index's included (non-key) columns. Changing included columns isn't a plain ALTER — it requires recreating the index, so this reissues a full CREATE INDEX ... WITH (DROP_EXISTING = ON) from idx's own key columns, uniqueness, type, and filter, with columns as the new INCLUDE list.

func (*Index) SetIncludedColumnsContext added in v0.0.6

func (idx *Index) SetIncludedColumnsContext(ctx context.Context, t *Table, columns []string) error

SetIncludedColumnsContext is the context-aware variant of SetIncludedColumns.

func (*Index) SetLockOptions added in v0.0.6

func (idx *Index) SetLockOptions(t *Table, allowRowLocks, allowPageLocks bool) error

SetLockOptions applies just the lock-granularity SET options (ALTER INDEX ... SET (ALLOW_ROW_LOCKS = .., ALLOW_PAGE_LOCKS = ..)) — unlike SetOptions, this never touches IGNORE_DUP_KEY, which SQL Server rejects outright on an index backing a PRIMARY KEY or UNIQUE constraint ("Cannot use index option ignore_dup_key to alter index '...' as it enforces a primary or unique constraint").

func (*Index) SetLockOptionsContext added in v0.0.6

func (idx *Index) SetLockOptionsContext(ctx context.Context, t *Table, allowRowLocks, allowPageLocks bool) error

SetLockOptionsContext is the context-aware variant of SetLockOptions.

func (*Index) SetOptions added in v0.0.6

func (idx *Index) SetOptions(t *Table, ignoreDupKey, allowRowLocks, allowPageLocks bool) error

SetOptions applies the index's SET-able runtime options (ALTER INDEX ... SET). Fill factor, pad index, and data compression only take effect on a rebuild — see RebuildWithOptions for those.

func (*Index) SetOptionsContext added in v0.0.6

func (idx *Index) SetOptionsContext(ctx context.Context, t *Table, ignoreDupKey, allowRowLocks, allowPageLocks bool) error

SetOptionsContext is the context-aware variant of SetOptions.

func (*Index) StorageInfo added in v0.0.6

func (idx *Index) StorageInfo(t *Table) (*IndexStorageInfo, error)

StorageInfo returns filegroup/partitioning and space usage for this index.

func (*Index) StorageInfoContext added in v0.0.6

func (idx *Index) StorageInfoContext(ctx context.Context, t *Table) (*IndexStorageInfo, error)

StorageInfoContext is the context-aware variant of StorageInfo.

func (*Index) UpdateStatistics added in v0.0.6

func (idx *Index) UpdateStatistics(t *Table) error

UpdateStatistics updates the statistics object tied to this index (UPDATE STATISTICS table (index) — every index has an implicit statistics object with the same name).

func (*Index) UpdateStatisticsContext added in v0.0.6

func (idx *Index) UpdateStatisticsContext(ctx context.Context, t *Table) error

UpdateStatisticsContext is the context-aware variant of UpdateStatistics.

type IndexAllocationUnit added in v0.0.6

type IndexAllocationUnit struct {
	Type   string
	Pages  int64
	UsedKB int64
}

IndexAllocationUnit is one row of an index's allocation-unit space breakdown (IN_ROW_DATA, LOB_DATA, ROW_OVERFLOW_DATA).

type IndexColumn

type IndexColumn struct {
	Name       string
	Descending bool
	IsIncluded bool
}

IndexColumn represents one column in an index.

type IndexColumnDef

type IndexColumnDef struct {
	Name       string
	Descending bool
}

IndexColumnDef describes one key column for a new index.

type IndexFragmentation

type IndexFragmentation struct {
	IndexName           string
	IndexID             int
	AvgFragmentationPct float64
	PageCount           int64
	FragmentCount       int64
	AvgPageSpaceUsedPct float64
}

IndexFragmentation holds fragmentation statistics for one index. AvgPageSpaceUsedPct is only populated when the DMV ran in SAMPLED or DETAILED mode (see Index.Fragmentation's mode parameter); Table.FragmentationStats's own LIMITED-mode query leaves it zero, matching the underlying DMV.

type IndexStorageInfo added in v0.0.6

type IndexStorageInfo struct {
	FileGroup       string
	PartitionScheme string
	PartitionColumn string
	RowCount        int64
	UsedKB          int64
	ReservedKB      int64
	AvgRecordSize   float64
	Allocations     []IndexAllocationUnit
}

IndexStorageInfo holds an index's filegroup/partitioning and space usage — SSMS's Index Properties > Storage page.

type IndexType

type IndexType string

IndexType represents the type of an index.

const (
	IndexTypeClustered            IndexType = "CLUSTERED"
	IndexTypeNonClustered         IndexType = "NONCLUSTERED"
	IndexTypeXML                  IndexType = "XML"
	IndexTypeSpatial              IndexType = "SPATIAL"
	IndexTypeColumnStore          IndexType = "COLUMNSTORE"
	IndexTypeClusteredColumnStore IndexType = "CLUSTERED COLUMNSTORE"
)

The values match sys.indexes.type_desc, except IndexTypeColumnStore, which predates IndexTypeClusteredColumnStore and keeps its original spelling. A type_desc with no constant here is carried through verbatim (see Table.IndexesContext), so Type is never empty for an index that exists.

func (IndexType) IsColumnStore added in v0.0.7

func (t IndexType) IsColumnStore() bool

IsColumnStore reports whether t is either columnstore index type.

type InstanceResourceGovernance added in v0.0.12

type InstanceResourceGovernance struct {
	// ServerName is the instance's name as the governor knows it.
	ServerName string

	// CapCPU is instance_cap_cpu, the percentage of a vCore's throughput the
	// instance may use — 100 on a General Purpose instance that is not
	// throttled below its purchased cores.
	CapCPU int
	// MaxLogRate is instance_max_log_rate in bytes per second, the transaction
	// log throughput ceiling. It is the limit a bulk load hits first on
	// General Purpose.
	MaxLogRate int64
	// MaxWorkerThreads is instance_max_worker_threads.
	MaxWorkerThreads int

	// LocalIOPS, ManagedXStoreIOPS and ExternalXStoreIOPS are
	// volume_local_iops / volume_managed_xstore_iops /
	// volume_external_xstore_iops: the IOPS ceiling of each storage class the
	// instance can place a file on.
	LocalIOPS          int
	ManagedXStoreIOPS  int
	ExternalXStoreIOPS int

	// LocalMaxOutstandingIO, ManagedXStoreMaxOutstandingIO and
	// ExternalXStoreMaxOutstandingIO are the queue depth allowed against each
	// of those. The view spells the columns `..._max_oustanding_io`, missing
	// the first `t` — Microsoft's typo, kept in the query because the column
	// is named that on the server.
	LocalMaxOutstandingIO          int
	ManagedXStoreMaxOutstandingIO  int
	ExternalXStoreMaxOutstandingIO int

	// TempDBLogFileNumber is tempdb_log_file_number.
	TempDBLogFileNumber int
	// DataDirectoryQuotaMB and DataDirectoryUsageMB are
	// user_data_directory_space_quota_mb / _usage_mb — the *file directory's*
	// limit, which on General Purpose is far larger than the storage the
	// instance is billed for. ServerResourceStat's ReservedStorageMB /
	// StorageSpaceUsedMB is the pair that actually governs; these two say how
	// much room the directory itself has.
	DataDirectoryQuotaMB int
	DataDirectoryUsageMB int
	// BufferPoolExtensionSizeGB is bufferpool_extension_size_gb, 0 when the
	// extension is off.
	BufferPoolExtensionSizeGB int
}

InstanceResourceGovernance is the single row of sys.dm_instance_resource_governance: the fixed limits the Azure SQL Managed Instance's resource governor enforces on the whole instance.

These are ceilings, not readings — they change only when the instance is resized, which is what makes them the scale a ServerResourceStat history is read against. Every field is nullable in the view; an unset one reads as zero, and the empty string for ServerName.

type Job

type Job struct {
	JobID            string
	Name             string
	Description      string
	IsEnabled        bool
	Category         string
	OwnerLoginName   string
	DateCreated      time.Time
	DateModified     time.Time
	StartStepID      int
	DeleteLevel      NotifyLevel
	NotifyLevelEmail NotifyLevel
	// NotifyEmailOperatorName is "" if no operator is configured to be
	// emailed on job completion.
	NotifyEmailOperatorName string
	LastRunDate             time.Time
	LastRunOutcome          JobOutcome
	LastRunDuration         time.Duration
	NextRunDate             time.Time
	CurrentState            JobState
	// contains filtered or unexported fields
}

Job mirrors a row in msdb.dbo.sysjobs together with its latest activity.

func (*Job) AddSchedule

func (j *Job) AddSchedule(req JobScheduleRequest) error

AddSchedule attaches a schedule to the job.

func (*Job) AddScheduleContext

func (j *Job) AddScheduleContext(ctx context.Context, req JobScheduleRequest) error

AddScheduleContext is the context-aware variant of AddSchedule.

func (*Job) AddStep

func (j *Job) AddStep(req JobStepRequest) error

AddStep adds a T-SQL or other subsystem step to the job.

func (*Job) AddStepContext

func (j *Job) AddStepContext(ctx context.Context, req JobStepRequest) error

AddStepContext is the context-aware variant of AddStep.

func (*Job) AttachSchedule added in v0.0.6

func (j *Job) AttachSchedule(scheduleName string) error

AttachSchedule attaches an existing shared schedule to the job — as opposed to AddSchedule, which creates a brand-new schedule and attaches it in one step.

func (*Job) AttachScheduleContext added in v0.0.6

func (j *Job) AttachScheduleContext(ctx context.Context, scheduleName string) error

AttachScheduleContext is the context-aware variant of AttachSchedule.

func (*Job) DetachSchedule added in v0.0.6

func (j *Job) DetachSchedule(scheduleName string) error

DetachSchedule detaches a schedule from the job without deleting the schedule itself (it may still be shared by other jobs).

func (*Job) DetachScheduleContext added in v0.0.6

func (j *Job) DetachScheduleContext(ctx context.Context, scheduleName string) error

DetachScheduleContext is the context-aware variant of DetachSchedule.

func (*Job) Disable

func (j *Job) Disable() error

Disable disables the job.

func (*Job) DisableContext added in v0.0.6

func (j *Job) DisableContext(ctx context.Context) error

DisableContext is the context-aware variant of Disable.

func (*Job) Drop

func (j *Job) Drop() error

Drop drops the agent job.

func (*Job) DropContext

func (j *Job) DropContext(ctx context.Context) error

DropContext is the context-aware variant of Drop.

func (*Job) Enable

func (j *Job) Enable() error

Enable enables the job.

func (*Job) EnableContext added in v0.0.6

func (j *Job) EnableContext(ctx context.Context) error

EnableContext is the context-aware variant of Enable.

func (*Job) History

func (j *Job) History(limit int) ([]*JobHistoryEntry, error)

History returns the execution history (most recent first). Pass limit=0 to use the default of 100 rows.

func (*Job) HistoryContext

func (j *Job) HistoryContext(ctx context.Context, limit int) ([]*JobHistoryEntry, error)

HistoryContext is the context-aware variant of History.

func (*Job) HistorySeq added in v0.0.6

func (j *Job) HistorySeq(ctx context.Context, limit int) iter.Seq2[*JobHistoryEntry, error]

HistorySeq returns an iterator over this job's most recent history entries, up to limit.

func (*Job) InsertStep added in v0.0.10

func (j *Job) InsertStep(req JobStepRequest, stepID int) error

InsertStep adds a step at position stepID, renumbering the steps at and after it, rather than appending.

The renumbering is msdb's, and it carries every other step's "go to step N" reference with it — verified against SQL Server 2025. sp_delete_jobstep is not symmetrical about this: it clears a reference to a step at or after the one deleted instead of following it, which is why ReorderSteps repairs references itself.

func (*Job) InsertStepContext added in v0.0.10

func (j *Job) InsertStepContext(ctx context.Context, req JobStepRequest, stepID int) error

InsertStepContext is the context-aware variant of InsertStep.

func (*Job) MoveStep added in v0.0.10

func (j *Job) MoveStep(stepID, newStepID int) error

MoveStep moves the step at position stepID to position newStepID, renumbering the steps in between. See MoveStepContext.

func (*Job) MoveStepContext added in v0.0.10

func (j *Job) MoveStepContext(ctx context.Context, stepID, newStepID int) error

MoveStepContext moves one step to another position, which is what "move up" and "move down" in a job's step list amount to.

msdb has no procedure that renumbers a step in place, so the move is a delete followed by an insert at the target position — which is why the step's whole definition has to survive the round trip, and why JobStep and JobStepRequest model every sysjobsteps column that sp_add_jobstep can set rather than the handful a step form edits.

The delete and the insert are one transactional batch, because a failure between them would leave the step deleted and its definition nowhere but in gosmo's memory. See atomicBatch.

"Go to step N" references follow the steps they name. sp_add_jobstep remaps them on insert, but sp_delete_jobstep does not — it resets a reference to a step at or after the deleted one to "quit with success", silently (verified against SQL Server 2025). So every reference is written back afterwards from the pre-move reading, mapped through the move. A reference that pointed at the moved step still points at it; one that pointed at a step the move shifted follows that step.

func (*Job) Rename added in v0.0.6

func (j *Job) Rename(newName string) error

Rename changes the job's name.

func (*Job) RenameContext added in v0.0.6

func (j *Job) RenameContext(ctx context.Context, newName string) error

RenameContext is the context-aware variant of Rename.

func (*Job) ReorderSteps added in v0.0.10

func (j *Job) ReorderSteps(order func(n int) []int) error

ReorderSteps puts the job's steps into the given order. See ReorderStepsContext.

func (*Job) ReorderStepsContext added in v0.0.10

func (j *Job) ReorderStepsContext(ctx context.Context, order func(n int) []int) error

ReorderStepsContext rewrites the job's step order. order is given the current number of steps and returns the current step ids in the sequence they should end up in — every id exactly once.

The reorder is realised as delete-and-insert per step that has to move, fewest first, and every "go to step N" reference is rewritten afterwards through the composed mapping. See MoveStepContext for why both halves are necessary.

All of it goes to the server as a single transactional batch, so the job is either in the requested order or in the order it started in, and never in the state between a step's delete and its re-insert — where the step exists nowhere but in this function. See atomicBatch.

The step listing that decides all this is read outside the transaction, so a concurrent edit of the same job is still last-writer-wins; the batch makes the reorder atomic, not serializable.

The job must have been read with JobByName: the step listing is by job_id, which a bare Server.Job handle does not carry.

func (*Job) ScheduleSeq added in v0.0.6

func (j *Job) ScheduleSeq(ctx context.Context) iter.Seq2[*Schedule, error]

ScheduleSeq returns an iterator over the schedules attached to this job.

func (*Job) Schedules added in v0.0.6

func (j *Job) Schedules() ([]*Schedule, error)

Schedules returns every schedule attached to the job.

func (*Job) SchedulesContext added in v0.0.6

func (j *Job) SchedulesContext(ctx context.Context) ([]*Schedule, error)

SchedulesContext is the context-aware variant of Schedules.

func (*Job) SetCategory added in v0.0.6

func (j *Job) SetCategory(category string) error

SetCategory reassigns the job's category.

func (*Job) SetCategoryContext added in v0.0.6

func (j *Job) SetCategoryContext(ctx context.Context, category string) error

SetCategoryContext is the context-aware variant of SetCategory.

func (*Job) SetDeleteLevel added in v0.0.6

func (j *Job) SetDeleteLevel(level NotifyLevel) error

SetDeleteLevel sets the job's automatic-delete condition.

func (*Job) SetDeleteLevelContext added in v0.0.6

func (j *Job) SetDeleteLevelContext(ctx context.Context, level NotifyLevel) error

SetDeleteLevelContext is the context-aware variant of SetDeleteLevel.

func (*Job) SetDescription added in v0.0.6

func (j *Job) SetDescription(desc string) error

SetDescription changes the job's description.

func (*Job) SetDescriptionContext added in v0.0.6

func (j *Job) SetDescriptionContext(ctx context.Context, desc string) error

SetDescriptionContext is the context-aware variant of SetDescription.

func (*Job) SetEmailNotify added in v0.0.6

func (j *Job) SetEmailNotify(operatorName string, level NotifyLevel) error

SetEmailNotify sets which operator is emailed on job completion, and under what condition. operatorName == "" leaves the currently configured operator unchanged (SQL Server has no documented "clear to none" value for sp_update_job's @notify_email_operator_name; pair with NotifyNever to stop emailing without needing to clear it).

func (*Job) SetEmailNotifyContext added in v0.0.6

func (j *Job) SetEmailNotifyContext(ctx context.Context, operatorName string, level NotifyLevel) error

SetEmailNotifyContext is the context-aware variant of SetEmailNotify.

func (*Job) SetOwner added in v0.0.6

func (j *Job) SetOwner(loginName string) error

SetOwner reassigns the job's owner login.

func (*Job) SetOwnerContext added in v0.0.6

func (j *Job) SetOwnerContext(ctx context.Context, loginName string) error

SetOwnerContext is the context-aware variant of SetOwner.

func (*Job) SetStartStep added in v0.0.6

func (j *Job) SetStartStep(stepID int) error

SetStartStep changes which step the job begins execution from.

func (*Job) SetStartStepContext added in v0.0.6

func (j *Job) SetStartStepContext(ctx context.Context, stepID int) error

SetStartStepContext is the context-aware variant of SetStartStep.

func (*Job) Start

func (j *Job) Start(stepName string) error

Start starts the job, optionally from a specific step name.

func (*Job) StartContext

func (j *Job) StartContext(ctx context.Context, stepName string) error

StartContext is the context-aware variant of Start.

func (*Job) StepSeq added in v0.0.6

func (j *Job) StepSeq(ctx context.Context) iter.Seq2[*JobStep, error]

StepSeq returns an iterator over a job's steps, in step_id order.

func (*Job) Steps

func (j *Job) Steps() ([]*JobStep, error)

Steps returns all steps defined for the job, ordered by step_id.

func (*Job) StepsContext

func (j *Job) StepsContext(ctx context.Context) ([]*JobStep, error)

StepsContext is the context-aware variant of Steps.

func (*Job) Stop

func (j *Job) Stop() error

Stop stops a running job.

func (*Job) StopContext

func (j *Job) StopContext(ctx context.Context) error

StopContext is the context-aware variant of Stop.

type JobHistoryEntry

type JobHistoryEntry struct {
	// JobName is only populated by Server.JobHistory (the cross-job
	// history query); it's left "" by Job.History, whose caller already
	// knows which job it asked about.
	JobName  string
	RunDate  time.Time
	Duration time.Duration
	Outcome  JobOutcome
	Message  string
	StepID   int
	StepName string
}

JobHistoryEntry represents one row from msdb.dbo.sysjobhistory.

type JobNotificationRef added in v0.0.6

type JobNotificationRef struct {
	JobName string
	Level   NotifyLevel
}

JobNotificationRef describes one job configured to email an operator on completion.

type JobOutcome

type JobOutcome int

JobOutcome represents the last run outcome for a job or step.

const (
	JobOutcomeFailed    JobOutcome = 0
	JobOutcomeSucceeded JobOutcome = 1
	JobOutcomeRetried   JobOutcome = 2
	JobOutcomeCancelled JobOutcome = 3
	JobOutcomeUnknown   JobOutcome = 5
)

type JobScheduleRequest

type JobScheduleRequest struct {
	Name    string
	Enabled bool
	// FreqType: 1=once, 4=daily, 8=weekly, 16=monthly, 64=when agent starts.
	FreqType     int
	FreqInterval int
	// FreqSubdayType: 1=once, 2=seconds, 4=minutes, 8=hours.
	FreqSubdayType     int
	FreqSubdayInterval int
	// ActiveStartTime and ActiveEndTime are HHMMSS integers, e.g. 23000 = 02:30:00.
	ActiveStartTime int
	ActiveEndTime   int
}

JobScheduleRequest describes a schedule to attach to a job.

type JobState

type JobState int

JobState is SQL Server Agent's job_state encoding for a job — the value xp_sqlagent_enum_jobs reports, which sp_help_job passes through as current_execution_status and SSMS's Job Activity Monitor displays.

Agent keeps this in memory for the jobs it runs itself; msdb has no column for it. Jobs and JobByName read it through jobStates and fall back to a start/stop_execution_date derivation over msdb.dbo.sysjobactivity for every job that read does not cover — Agent stopped, or a login with neither sysadmin nor SQLAgentReaderRole — in which case only JobStateExecuting and JobStateIdle can be told apart. JobStateUnknown is what a multi-server job Agent does not run itself reports.

const (
	JobStateUnknown                     JobState = 0
	JobStateExecuting                   JobState = 1
	JobStateWaitingForWorker            JobState = 2
	JobStateBetweenRetries              JobState = 3
	JobStateIdle                        JobState = 4
	JobStateSuspended                   JobState = 5
	JobStateWaitingForStepToFinish      JobState = 6
	JobStatePerformingCompletionActions JobState = 7
)

type JobStep

type JobStep struct {
	StepID    int
	Name      string
	Subsystem string // "TSQL", "CmdExec", "SSIS", etc.
	Command   string
	// Database is only meaningful for TSQL steps.
	Database        string
	OnSuccessAction int
	// OnSuccessStepID is the target step_id when OnSuccessAction is
	// "go to step N" (4); otherwise unused.
	OnSuccessStepID int
	OnFailAction    int
	// OnFailStepID is the target step_id when OnFailAction is "go to
	// step N" (4); otherwise unused.
	OnFailStepID   int
	LastRunOutcome JobOutcome
	// LastRunDate is when the step last ran, from sysjobsteps'
	// last_run_date/last_run_time integer pair. Zero when the step has never
	// run — test it with IsZero(), not against a sentinel date.
	LastRunDate time.Time
	// LastRunDuration is sysjobsteps.last_run_duration verbatim: an HHMMSS
	// integer, not a count of seconds (10230 is 1h 02m 30s). LastRunElapsed
	// is the same value decoded, and is what display code should use.
	LastRunDuration int
	LastRunElapsed  time.Duration
	RetryAttempts   int
	RetryInterval   int
	OutputFileName  string
	// Flags is the raw sysjobsteps.flags bitmask (append-to-output-file,
	// log-to-table, include-step-output-in-history, ...). See Microsoft's
	// sp_add_jobstep documentation for bit meanings; gosmo round-trips it
	// as-is rather than decoding it into named booleans.
	Flags int
	// ProxyName is the proxy account the step runs under, or "" for none
	// (the Agent service account). Resolved from sysjobsteps.proxy_id.
	ProxyName string
	// AdditionalParameters is sysjobsteps.additional_parameters, used by
	// some subsystems and left empty by TSQL steps.
	AdditionalParameters string
	// CmdExecSuccessCode is the process exit code a CmdExec step treats as
	// success. Zero for every other subsystem, and also the CmdExec default.
	CmdExecSuccessCode int
	// Server is sysjobsteps.server, the target server for a replication or
	// analysis-services step; "" for the common case.
	Server string
	// DatabaseUserName is the user a TSQL step impersonates, or "" to run as
	// the job owner's mapping.
	DatabaseUserName string
	// OSRunPriority is the process priority for a CmdExec step.
	OSRunPriority int
	// contains filtered or unexported fields
}

JobStep represents one step of an agent job.

func (*JobStep) Delete added in v0.0.6

func (s *JobStep) Delete() error

Delete removes the job step via sp_delete_jobstep.

func (*JobStep) DeleteContext added in v0.0.6

func (s *JobStep) DeleteContext(ctx context.Context) error

DeleteContext is the context-aware variant of Delete.

The step is addressed by its number, which is what sp_delete_jobstep takes: a *JobStep is a snapshot, and its StepID is only current until something renumbers the job.

func (*JobStep) SetFlow added in v0.0.10

func (s *JobStep) SetFlow(onSuccessAction, onSuccessStepID, onFailAction, onFailStepID int) error

SetFlow changes only the step's control flow — what happens after it succeeds or fails — leaving its command, proxy, flags and everything else untouched.

Every other parameter is omitted, which sp_update_jobstep reads as "leave alone". That is what makes this usable for repairing references after a reorder, where rewriting the whole definition would be both wasteful and a chance to lose a column the request does not model.

func (*JobStep) SetFlowContext added in v0.0.10

func (s *JobStep) SetFlowContext(ctx context.Context, onSuccessAction, onSuccessStepID, onFailAction, onFailStepID int) error

SetFlowContext is the context-aware variant of SetFlow.

func (*JobStep) Update added in v0.0.6

func (s *JobStep) Update(req JobStepRequest) error

Update replaces the step's definition via sp_update_jobstep.

func (*JobStep) UpdateContext added in v0.0.6

func (s *JobStep) UpdateContext(ctx context.Context, req JobStepRequest) error

UpdateContext is the context-aware variant of Update.

type JobStepRequest

type JobStepRequest struct {
	Name      string
	Subsystem string // "TSQL" is the most common value
	Command   string
	// Database is only used for TSQL steps.
	//
	// Empty means "leave the step's own database alone" on an update, not
	// "clear it": sp_update_jobstep accepts N” without error and changes
	// nothing, so JobStep.UpdateContext omits @database_name entirely rather
	// than sending a value that would be silently ignored. On AddStep an
	// empty value likewise sends no @database_name, and the server applies
	// its default. There is no way to null the column through this type,
	// because msdb offers none.
	Database string
	// OnSuccessAction: 1=quit success, 2=quit fail, 3=go to next step, 4=go to step N.
	OnSuccessAction int
	// OnSuccessStepID is the target step_id when OnSuccessAction is 4.
	OnSuccessStepID int
	OnFailAction    int
	// OnFailStepID is the target step_id when OnFailAction is 4.
	OnFailStepID  int
	RetryAttempts int
	// RetryInterval is in minutes.
	RetryInterval int
	// OutputFileName is sent on every update, empty or not — unlike
	// Database, whose empty value means "keep". @output_file_name does
	// honour N”: it nulls the column, so blanking this field is how a
	// caller's form clears a step's output file. Two string fields of this
	// struct therefore read an empty value differently, because msdb does.
	OutputFileName string
	// Flags is the raw sysjobsteps.flags bitmask.
	//
	// This field and the six below it are sent by AddStep and InsertStep,
	// which create a row and so decide every column of it. UpdateContext
	// deliberately does not send them: an omitted sp_update_jobstep
	// parameter means "leave alone", which is what an edit of the fields a
	// step form owns should do to a step's proxy, flags and run-as user.
	Flags int
	// ProxyName, AdditionalParameters, Server and DatabaseUserName are sent
	// only when non-empty: msdb reads an omitted parameter as "leave alone"
	// on an update and "use the default" on an add, while N” for a proxy or
	// a user name is an error rather than a clear.
	ProxyName            string
	AdditionalParameters string
	Server               string
	DatabaseUserName     string
	// CmdExecSuccessCode and OSRunPriority are sent verbatim, zero included:
	// zero is msdb's own default for both, so it cannot be told from unset
	// and there is nothing to lose by sending it.
	CmdExecSuccessCode int
	OSRunPriority      int
}

JobStepRequest describes a step to add to, or replace the definition of (see JobStep.Update), a job.

type KerberosOptions added in v0.0.4

type KerberosOptions struct {
	// ConfigFile is the path to krb5.conf. Defaults to $KRB5_CONFIG then
	// /etc/krb5.conf. The file must exist for any Kerberos login.
	ConfigFile string

	// CredCacheFile is the path to a credential cache produced by "kinit".
	// Defaults to $KRB5CCNAME. Use this for single sign-on.
	CredCacheFile string

	// KeytabFile is the path to a keytab holding the client's long-term key,
	// for unattended logins. Requires User and Realm. Defaults to
	// $KRB5_KTNAME or the configured default client keytab.
	KeytabFile string

	// Realm is the Kerberos realm, e.g. "CONTOSO.COM". When empty it is
	// taken from a "user@REALM" User, then from the krb5.conf default realm.
	Realm string

	// DNSLookupKDC, when non-nil, overrides whether KDCs are located via DNS
	// SRV records. The driver defaults to true.
	DNSLookupKDC *bool

	// UDPPreferenceLimit caps the message size sent over UDP before TCP is
	// used. Zero leaves the driver default (1, i.e. effectively always TCP).
	UDPPreferenceLimit int
}

KerberosOptions configures Kerberos authentication for AuthWindows on non-Windows hosts (and on Windows when set explicitly, in preference to native SSPI). Every field is optional: with all left zero the driver uses the ambient Kerberos setup — /etc/krb5.conf (or $KRB5_CONFIG) and the credential cache from a prior "kinit" ($KRB5CCNAME or the default cache) — which is the usual single-sign-on flow on a domain-joined Linux host.

The three credential sources are mutually exclusive and tried in this order of precedence by the driver: an explicit KeytabFile (with User and Realm), then a CredCacheFile, then User + Password (with Realm). When none is set, the credential cache is discovered from the environment.

type Language added in v0.0.4

type Language struct {
	LangID int
	Name   string
	Alias  string
}

Language mirrors a row from sys.syslanguages — used to populate the server's "Default language" and a Login's "Default language" dropdowns.

type LinkedServer

type LinkedServer struct {
	Name       string
	Product    string
	Provider   string
	DataSource string
	IsRemote   bool
}

LinkedServer represents a linked server definition.

type LogSearch added in v0.0.10

type LogSearch struct {
	Text1, Text2 string
	From, To     time.Time
}

LogSearch narrows a log read at the server. Every field is optional, and a zero LogSearch reads the whole file — what ReadLog does.

These are xp_readerrorlog's own arguments 3-6, with its semantics: Text1 and Text2 are case-insensitive substrings AND-ed together (not two alternatives), and From/To bound the entry timestamp. Filtering here rather than in the caller matters for the current log on a busy instance, which runs to tens of thousands of entries.

type Login

type Login struct {
	Name string
	SID  []byte
	// LoginType is the login's type_desc: "SQL_LOGIN", "WINDOWS_LOGIN",
	// "WINDOWS_GROUP", "EXTERNAL_LOGIN", "EXTERNAL_GROUP",
	// "CERTIFICATE_MAPPED_LOGIN" or "ASYMMETRIC_KEY_MAPPED_LOGIN".
	LoginType       string
	IsDisabled      bool
	DefaultDatabase string
	CreateDate      time.Time
	ModifyDate      time.Time

	// MappedObject is the master certificate or asymmetric key a
	// CERTIFICATE_MAPPED_LOGIN / ASYMMETRIC_KEY_MAPPED_LOGIN maps to. It is
	// not read with the login — the name lives in master, not in
	// sys.server_principals — so it is empty until ResolveMapping fills it.
	MappedObject string
	// contains filtered or unexported fields
}

Login represents a SQL Server server-level login.

func (*Login) AddServerRoleMember

func (l *Login) AddServerRoleMember(roleName string) error

AddServerRoleMember adds this login to a server role.

func (*Login) AddServerRoleMemberContext

func (l *Login) AddServerRoleMemberContext(ctx context.Context, roleName string) error

AddServerRoleMemberContext is the context-aware variant of AddServerRoleMember.

func (*Login) ChangePassword

func (l *Login) ChangePassword(newPassword string) error

ChangePassword changes the login's password.

func (*Login) ChangePasswordContext

func (l *Login) ChangePasswordContext(ctx context.Context, newPassword string) error

ChangePasswordContext changes the login's password.

Security: the password is quoted via nStringLiteral (N'...', doubling any embedded quote) rather than interpolated raw. HASHED is deliberately not used — it tells SQL Server the value is already one of its own password-hash formats, not cleartext, so passing a hex encoding of the cleartext under HASHED either fails outright or creates a login nothing can ever authenticate as.

func (*Login) ChangePasswordWithOptions added in v0.0.4

func (l *Login) ChangePasswordWithOptions(newPassword string, mustChange, unlock bool) error

ChangePasswordWithOptions changes the login's password with the same quoted-literal encoding ChangePassword uses, plus MUST_CHANGE (force a password change at next login) and UNLOCK (clear a lockout).

func (*Login) ChangePasswordWithOptionsContext added in v0.0.4

func (l *Login) ChangePasswordWithOptionsContext(ctx context.Context, newPassword string, mustChange, unlock bool) error

ChangePasswordWithOptionsContext is the context-aware variant of ChangePasswordWithOptions.

func (*Login) Details added in v0.0.4

func (l *Login) Details() (*LoginDetails, error)

Details returns the login's password-policy and status information.

func (*Login) DetailsContext added in v0.0.4

func (l *Login) DetailsContext(ctx context.Context) (*LoginDetails, error)

DetailsContext is the context-aware variant of Details.

func (*Login) Disable

func (l *Login) Disable() error

Disable disables the login.

func (*Login) DisableContext

func (l *Login) DisableContext(ctx context.Context) error

DisableContext is the context-aware variant of Disable.

func (*Login) Drop

func (l *Login) Drop() error

Drop drops the login from the server.

func (*Login) DropContext added in v0.0.6

func (l *Login) DropContext(ctx context.Context) error

DropContext is the context-aware variant of Drop.

func (*Login) Enable

func (l *Login) Enable() error

Enable enables the login.

func (*Login) EnableContext

func (l *Login) EnableContext(ctx context.Context) error

EnableContext is the context-aware variant of Enable.

func (*Login) MapCredential added in v0.0.4

func (l *Login) MapCredential(credential string) error

MapCredential maps a server credential to the login.

func (*Login) MapCredentialContext added in v0.0.4

func (l *Login) MapCredentialContext(ctx context.Context, credential string) error

MapCredentialContext is the context-aware variant of MapCredential.

func (*Login) MapToDatabase added in v0.0.4

func (l *Login) MapToDatabase(dbName, userName, defaultSchema string) error

MapToDatabase creates a user for this login in the named database (CREATE USER ... FOR LOGIN).

func (*Login) MapToDatabaseContext added in v0.0.4

func (l *Login) MapToDatabaseContext(ctx context.Context, dbName, userName, defaultSchema string) error

MapToDatabaseContext is the context-aware variant of MapToDatabase.

func (*Login) RemoveServerRoleMember

func (l *Login) RemoveServerRoleMember(roleName string) error

RemoveServerRoleMember removes this login from a server role.

func (*Login) RemoveServerRoleMemberContext

func (l *Login) RemoveServerRoleMemberContext(ctx context.Context, roleName string) error

RemoveServerRoleMemberContext is the context-aware variant of RemoveServerRoleMember.

func (*Login) Rename added in v0.0.4

func (l *Login) Rename(newName string) error

Rename changes the login's name.

func (*Login) RenameContext added in v0.0.4

func (l *Login) RenameContext(ctx context.Context, newName string) error

RenameContext is the context-aware variant of Rename.

func (*Login) ResolveMapping added in v0.0.10

func (l *Login) ResolveMapping() error

ResolveMapping looks up the certificate or asymmetric key this login maps to and stores its name in MappedObject.

func (*Login) ResolveMappingContext added in v0.0.10

func (l *Login) ResolveMappingContext(ctx context.Context) error

ResolveMappingContext is the context-aware variant of ResolveMapping.

It is a no-op for every login type but CERTIFICATE_MAPPED_LOGIN and ASYMMETRIC_KEY_MAPPED_LOGIN. The lookup is by SID against master, where a login-mapped certificate or asymmetric key must live, and names master explicitly because the connection may be in any database. MappedObject is left empty, without an error, when nothing matches — the mapped object can have been dropped out from under the login.

func (*Login) SetDefaultDatabase added in v0.0.4

func (l *Login) SetDefaultDatabase(name string) error

SetDefaultDatabase changes the login's default database.

func (*Login) SetDefaultDatabaseContext added in v0.0.4

func (l *Login) SetDefaultDatabaseContext(ctx context.Context, name string) error

SetDefaultDatabaseContext is the context-aware variant of SetDefaultDatabase.

func (*Login) SetDefaultLanguage added in v0.0.4

func (l *Login) SetDefaultLanguage(lang string) error

SetDefaultLanguage changes the login's default language.

func (*Login) SetDefaultLanguageContext added in v0.0.4

func (l *Login) SetDefaultLanguageContext(ctx context.Context, lang string) error

SetDefaultLanguageContext is the context-aware variant of SetDefaultLanguage.

func (*Login) SetPasswordPolicy added in v0.0.4

func (l *Login) SetPasswordPolicy(checkPolicy, checkExpiration bool) error

SetPasswordPolicy sets the login's CHECK_POLICY and CHECK_EXPIRATION flags. SQL Server rejects checkExpiration=true with checkPolicy=false — surfaced as the returned error, not pre-validated here.

func (*Login) SetPasswordPolicyContext added in v0.0.4

func (l *Login) SetPasswordPolicyContext(ctx context.Context, checkPolicy, checkExpiration bool) error

SetPasswordPolicyContext is the context-aware variant of SetPasswordPolicy.

func (*Login) UnmapCredential added in v0.0.4

func (l *Login) UnmapCredential(credential string) error

UnmapCredential removes a credential mapping from the login.

func (*Login) UnmapCredentialContext added in v0.0.4

func (l *Login) UnmapCredentialContext(ctx context.Context, credential string) error

UnmapCredentialContext is the context-aware variant of UnmapCredential.

func (*Login) UnmapFromDatabase added in v0.0.4

func (l *Login) UnmapFromDatabase(dbName string) error

UnmapFromDatabase drops this login's mapped user in the named database.

func (*Login) UnmapFromDatabaseContext added in v0.0.4

func (l *Login) UnmapFromDatabaseContext(ctx context.Context, dbName string) error

UnmapFromDatabaseContext is the context-aware variant of UnmapFromDatabase.

func (*Login) UserMappingSeq added in v0.0.4

func (l *Login) UserMappingSeq(ctx context.Context) iter.Seq2[*LoginUserMapping, error]

UserMappingSeq returns an iterator over every database this login is mapped into.

func (*Login) UserMappings added in v0.0.4

func (l *Login) UserMappings() ([]*LoginUserMapping, error)

UserMappings returns every database this login has a mapped user in. Only mapped databases are included — combine with Server.Databases to build a full "all databases, mapped or not" view. Databases that are offline, or that the login can't currently reach, are skipped rather than failing the whole scan (SSMS's own User Mapping page behaves the same way). A cancelled context is not skipped — it ends the scan and is returned.

The skip covers a database whose query never opened. Once its rows are being read, a failure ends the scan with an error instead: those rows are already in the result, so skipping would return a short list and call it success.

func (*Login) UserMappingsContext added in v0.0.4

func (l *Login) UserMappingsContext(ctx context.Context) ([]*LoginUserMapping, error)

UserMappingsContext is the context-aware variant of UserMappings.

type LoginDetails added in v0.0.4

type LoginDetails struct {
	IsLocked            bool
	IsExpired           bool
	MustChangePassword  bool
	IsPolicyChecked     bool
	IsExpirationChecked bool
	PasswordLastSet     time.Time
	// LastLogin is best-effort: it reflects the most recent session found
	// in sys.dm_exec_sessions, which only holds currently-connected (or
	// very recently disconnected) sessions, not full login history. It is
	// the zero Time if no matching session is currently visible.
	LastLogin        time.Time
	BadPasswordCount int
	// BadPasswordTime is the last failed-login attempt time, or the zero
	// Time if none is recorded.
	BadPasswordTime time.Time
	DefaultLanguage string
	CredentialName  string
	// ConnectSQLState is "GRANT", "DENY", or "" (default/unset) for the
	// login's explicit CONNECT SQL server permission.
	ConnectSQLState string
}

LoginDetails holds the login's password-policy and status fields — SSMS's Login Properties > Status page (plus the policy checkboxes and credential mapping shown on the General page). Windows logins have no password policy; those fields read as their zero value rather than erroring, since LOGINPROPERTY simply returns NULL for them.

type LoginSource added in v0.0.10

type LoginSource int

LoginSource names what a new login authenticates from — the FROM clause of CREATE LOGIN, or WITH PASSWORD for a SQL login.

const (
	// LoginSourceAuto resolves from the password CreateLogin is given: empty
	// means a Windows login, non-empty a SQL login. It is the zero value, so
	// a CreateLoginOptions written before LoginSource existed behaves exactly
	// as it did.
	LoginSourceAuto LoginSource = iota
	// LoginSourceSQL is a SQL Server login (WITH PASSWORD).
	LoginSourceSQL
	// LoginSourceWindows is a Windows user or group login (FROM WINDOWS).
	LoginSourceWindows
	// LoginSourceExternalProvider is a Microsoft Entra ID (Azure AD) login
	// (FROM EXTERNAL PROVIDER) — SQL Server 2022 and later, Azure SQL
	// Managed Instance, and Azure SQL Database.
	LoginSourceExternalProvider
	// LoginSourceCertificate maps the login to a certificate in master
	// (FROM CERTIFICATE). Nothing authenticates as such a login; it exists
	// to hold permissions for code signed by the certificate.
	LoginSourceCertificate
	// LoginSourceAsymmetricKey maps the login to an asymmetric key in master
	// (FROM ASYMMETRIC KEY), the asymmetric-key counterpart of
	// LoginSourceCertificate.
	LoginSourceAsymmetricKey
)

func (LoginSource) String added in v0.0.10

func (src LoginSource) String() string

String renders the source as the words used in error messages.

type LoginUserMapping added in v0.0.4

type LoginUserMapping struct {
	Database      string
	User          string
	DefaultSchema string
	Roles         []string
}

LoginUserMapping describes one database this login is mapped into — SSMS's Login Properties > User Mapping page.

type MailProfile

type MailProfile struct {
	ProfileID   int
	Name        string
	Description string
	IsDefault   bool
}

MailProfile represents an msdb Database Mail profile.

type NotificationMethod added in v0.0.6

type NotificationMethod int

NotificationMethod is msdb's bitmask for how an operator is notified (sysnotifications.notification_method, and reused by sysalerts.include_event_description — see Alert.IncludeEventDescriptionIn).

const (
	NotifyMethodEmail   NotificationMethod = 1
	NotifyMethodPager   NotificationMethod = 2
	NotifyMethodNetSend NotificationMethod = 4
)

func (NotificationMethod) String added in v0.0.6

func (m NotificationMethod) String() string

String renders the method bitmask as e.g. "Email, Pager".

type NotifyLevel added in v0.0.6

type NotifyLevel int

NotifyLevel is the "when" condition for a job's email notification and its automatic-delete behavior — msdb's shared 0-3 encoding used by both sysjobs.notify_level_email and sysjobs.delete_level.

const (
	NotifyNever      NotifyLevel = 0
	NotifyOnSuccess  NotifyLevel = 1
	NotifyOnFailure  NotifyLevel = 2
	NotifyOnComplete NotifyLevel = 3
)

type OSJobObject added in v0.0.12

type OSJobObject struct {
	// CPURate is cpu_rate, the job object's CPU allocation in units of
	// 1/10000 of a single processor's capacity — 400 on a 4 vCore instance.
	CPURate int
	// CPUAffinityMask and CPUAffinityGroup are the processors the job object
	// may run on.
	CPUAffinityMask  int64
	CPUAffinityGroup int

	// MemoryLimitMB, ProcessMemoryLimitMB and WorkingSetLimitMB are the job
	// object's three memory ceilings; LowMemorySignalThresholdMB is where the
	// host starts signalling memory pressure.
	MemoryLimitMB           int64
	ProcessMemoryLimitMB    int64
	WorkingSetLimitMB       int64
	LowMemSignalThresholdMB int64
	NonSOSMemGapMB          int64
	PeakProcessMemoryUsedMB int64
	PeakJobMemoryUsedMB     int64

	// TotalUserTime and TotalKernelTime are cumulative CPU time in
	// 100-nanosecond units, the Windows FILETIME tick — divide by 10,000,000
	// for seconds.
	TotalUserTime   int64
	TotalKernelTime int64

	// ReadOperationCount and WriteOperationCount are cumulative IO operation
	// counts for the whole job object.
	ReadOperationCount  int64
	WriteOperationCount int64
}

OSJobObject is the single row of sys.dm_os_job_object: the Windows job object the SQL Server process runs inside on an Azure SQL Managed Instance, and the memory and CPU limits that job object imposes.

It is the layer *below* the resource governor — the governor's limits are what SQL Server enforces on itself, these are what the host enforces on SQL Server — which is why an instance can be under its governor limits and still be squeezed.

Every field is nullable in the view (WorkingSetLimitMB is NULL on a live General Purpose instance), and an unset one reads as zero.

type ObjectFilter added in v0.0.10

type ObjectFilter struct {
	Name    []TextCriterion
	Schema  []TextCriterion
	Created []DateCriterion
	// MemoryOptimized, when set, requires sys.tables.is_memory_optimized to
	// equal it. Only the table listing has such a column; on any other family
	// it is ignored rather than failing, since a filter is a description of
	// what the caller wants and not every family can express all of it.
	MemoryOptimized *bool
}

ObjectFilter narrows a catalog listing. Every criterion narrows it further — they are AND-ed, never OR-ed — and a zero ObjectFilter narrows nothing, so the unfiltered listing is the same call with an empty one.

Matching is case-insensitive regardless of the database's collation (see the note on clause), which is the behaviour a user typing into a filter box expects and the one a case-sensitive database would otherwise break.

func (ObjectFilter) Empty added in v0.0.10

func (f ObjectFilter) Empty() bool

Empty reports whether f narrows anything at all.

type ObjectPermission

type ObjectPermission string

ObjectPermission represents a single permission on a securable.

const (
	PermSelect             ObjectPermission = "SELECT"
	PermInsert             ObjectPermission = "INSERT"
	PermUpdate             ObjectPermission = "UPDATE"
	PermDelete             ObjectPermission = "DELETE"
	PermExecute            ObjectPermission = "EXECUTE"
	PermControl            ObjectPermission = "CONTROL"
	PermView               ObjectPermission = "VIEW DEFINITION"
	PermAlter              ObjectPermission = "ALTER"
	PermReferences         ObjectPermission = "REFERENCES"
	PermTakeOwnership      ObjectPermission = "TAKE OWNERSHIP"
	PermViewChangeTracking ObjectPermission = "VIEW CHANGE TRACKING"
)

type Operator added in v0.0.6

type Operator struct {
	ID              int
	Name            string
	Enabled         bool
	EmailAddress    string
	PagerAddress    string
	NetSendAddress  string
	Category        string
	LastEmailDate   time.Time
	LastPagerDate   time.Time
	LastNetSendDate time.Time
	// contains filtered or unexported fields
}

Operator represents a SQL Server Agent operator (msdb.dbo.sysoperators) — a notification target for job and alert email.

func (*Operator) Disable added in v0.0.6

func (o *Operator) Disable() error

Disable disables the operator.

func (*Operator) DisableContext added in v0.0.6

func (o *Operator) DisableContext(ctx context.Context) error

DisableContext is the context-aware variant of Disable.

func (*Operator) Drop added in v0.0.6

func (o *Operator) Drop() error

Drop deletes the operator via sp_delete_operator.

func (*Operator) DropContext added in v0.0.6

func (o *Operator) DropContext(ctx context.Context) error

DropContext is the context-aware variant of Drop.

func (*Operator) Enable added in v0.0.6

func (o *Operator) Enable() error

Enable enables the operator.

func (*Operator) EnableContext added in v0.0.6

func (o *Operator) EnableContext(ctx context.Context) error

EnableContext is the context-aware variant of Enable.

func (*Operator) NotifyingAlertSeq added in v0.0.6

func (o *Operator) NotifyingAlertSeq(ctx context.Context) iter.Seq2[*AlertNotificationRef, error]

NotifyingAlertSeq returns an iterator over every alert configured to notify this operator.

func (*Operator) NotifyingAlerts added in v0.0.6

func (o *Operator) NotifyingAlerts() ([]*AlertNotificationRef, error)

NotifyingAlerts returns every alert configured to notify this operator.

func (*Operator) NotifyingAlertsContext added in v0.0.6

func (o *Operator) NotifyingAlertsContext(ctx context.Context) ([]*AlertNotificationRef, error)

NotifyingAlertsContext is the context-aware variant of NotifyingAlerts.

func (*Operator) NotifyingJobSeq added in v0.0.6

func (o *Operator) NotifyingJobSeq(ctx context.Context) iter.Seq2[*JobNotificationRef, error]

NotifyingJobSeq returns an iterator over every job configured to e-mail this operator on completion.

func (*Operator) NotifyingJobs added in v0.0.6

func (o *Operator) NotifyingJobs() ([]*JobNotificationRef, error)

NotifyingJobs returns every job configured to email this operator on completion (sysjobs.notify_email_operator_id) — distinct from NotifyingAlerts, which covers alert-triggered notifications.

func (*Operator) NotifyingJobsContext added in v0.0.6

func (o *Operator) NotifyingJobsContext(ctx context.Context) ([]*JobNotificationRef, error)

NotifyingJobsContext is the context-aware variant of NotifyingJobs.

func (*Operator) Rename added in v0.0.6

func (o *Operator) Rename(newName string) error

Rename changes the operator's name.

func (*Operator) RenameContext added in v0.0.6

func (o *Operator) RenameContext(ctx context.Context, newName string) error

RenameContext is the context-aware variant of Rename.

func (*Operator) SetCategory added in v0.0.6

func (o *Operator) SetCategory(category string) error

SetCategory reassigns the operator's category. category == "" clears it — sent as the real [Uncategorized] category, for the same reason Alert.SetCategory does: sp_update_operator's category check (sp_verify_category, shared with sp_update_alert) rejects an empty name outright.

func (*Operator) SetCategoryContext added in v0.0.6

func (o *Operator) SetCategoryContext(ctx context.Context, category string) error

SetCategoryContext is the context-aware variant of SetCategory.

func (*Operator) SetEmailAddress added in v0.0.6

func (o *Operator) SetEmailAddress(addr string) error

SetEmailAddress changes the operator's email address.

func (*Operator) SetEmailAddressContext added in v0.0.6

func (o *Operator) SetEmailAddressContext(ctx context.Context, addr string) error

SetEmailAddressContext is the context-aware variant of SetEmailAddress.

type Parameter added in v0.0.10

type Parameter struct {
	Name       string // including the leading @
	Ordinal    int
	DataType   DataType
	MaxLength  int // -1 = MAX
	Precision  int
	Scale      int
	IsOutput   bool
	HasDefault bool
}

Parameter mirrors one row of sys.parameters: a parameter of a stored procedure or a function. The return value of a scalar function, which the catalog also stores there as parameter_id 0, is not a parameter and is not returned.

func (*Parameter) TypeString added in v0.0.10

func (p *Parameter) TypeString() string

TypeString returns the T-SQL data-type fragment for the parameter, in the same form ColumnTypeString gives a column.

type PartitionFunction

type PartitionFunction struct {
	Name          string
	FunctionID    int
	InputType     DataType
	BoundaryCount int
	IsRight       bool // RIGHT = boundary is in right partition
	Boundaries    []string
	// contains filtered or unexported fields
}

PartitionFunction mirrors sys.partition_functions.

func (*PartitionFunction) Drop

func (pf *PartitionFunction) Drop() error

Drop drops the partition function.

func (*PartitionFunction) DropContext added in v0.0.5

func (pf *PartitionFunction) DropContext(ctx context.Context) error

DropContext is the context-aware variant of Drop.

func (*PartitionFunction) MergeRange

func (pf *PartitionFunction) MergeRange(value string) error

MergeRange removes a boundary value from the partition function.

func (*PartitionFunction) MergeRangeContext added in v0.0.5

func (pf *PartitionFunction) MergeRangeContext(ctx context.Context, value string) error

MergeRangeContext is the context-aware variant of MergeRange.

func (*PartitionFunction) SplitRange

func (pf *PartitionFunction) SplitRange(value string) error

SplitRange adds a new boundary value to the partition function.

func (*PartitionFunction) SplitRangeContext added in v0.0.5

func (pf *PartitionFunction) SplitRangeContext(ctx context.Context, value string) error

SplitRangeContext is the context-aware variant of SplitRange.

type PartitionInfo

type PartitionInfo struct {
	PartitionNumber int
	Rows            int64
	DataCompression string
}

PartitionInfo holds per-partition row counts for a table.

type PartitionScheme

type PartitionScheme struct {
	Name         string
	SchemeID     int
	FunctionName string
	FileGroups   []string
	// contains filtered or unexported fields
}

PartitionScheme mirrors sys.partition_schemes.

func (*PartitionScheme) Drop

func (ps *PartitionScheme) Drop() error

Drop drops the partition scheme.

func (*PartitionScheme) DropContext added in v0.0.5

func (ps *PartitionScheme) DropContext(ctx context.Context) error

DropContext is the context-aware variant of Drop.

type PermissionEntry added in v0.0.4

type PermissionEntry struct {
	Principal     string
	PrincipalType string // e.g. "DATABASE_ROLE", "SQL_USER"
	Grantor       string
	Permission    ObjectPermission
	State         PermissionState
}

PermissionEntry is one GRANT/DENY entry recorded for a securable, as reported by sys.database_permissions. The permission-name and state enums live in types.go (ObjectPermission, PermissionState).

type PermissionOptions added in v0.0.8

type PermissionOptions struct {
	// WithGrantOption appends WITH GRANT OPTION to a GRANT, letting the
	// grantee grant the same permission on to others. GRANT only.
	WithGrantOption bool

	// Cascade appends CASCADE to a DENY or REVOKE, applying it to every
	// principal the grantee passed the permission on to. Required whenever
	// the permission being taken away was granted WITH GRANT OPTION.
	Cascade bool

	// GrantOptionOnly turns a REVOKE into REVOKE GRANT OPTION FOR: the
	// grantee keeps the permission but loses the right to grant it onward.
	// REVOKE only, and always CASCADE.
	GrantOptionOnly bool
}

PermissionOptions carries the GRANT/DENY/REVOKE modifiers the plain Grant/Deny/Revoke trios do not expose. The zero value renders exactly the statement those trios render, at every scope — true by construction since 2026-08-05: each plain method is a one-line delegation to its WithOptions counterpart passing PermissionOptions{}, so there is one renderer (permissionStmt) and one set of error strings rather than two that have to be kept in step.

The three fields are not independent of each other in practice, because SQL Server refuses some sequences outright:

  • A permission granted WITH GRANT OPTION cannot be revoked or denied without CASCADE — "the permission was granted WITH GRANT OPTION" is a hard error, not a warning. Anything that takes such a grant away therefore needs Cascade set.
  • GrantOptionOnly (REVOKE GRANT OPTION FOR) takes away only the right to re-grant and leaves the underlying GRANT in place. It is the "WITH GRANT OPTION -> plain GRANT" downgrade, and SQL Server requires CASCADE with it as well, so Cascade is implied and need not be set.

CASCADE reaches every principal the grantee granted the permission on to, which is the point of it and also why it is opt-in rather than always sent.

type PermissionState

type PermissionState string

PermissionState represents GRANT / DENY / REVOKE.

const (
	PermissionGrant  PermissionState = "GRANT"
	PermissionDeny   PermissionState = "DENY"
	PermissionRevoke PermissionState = "REVOKE"
)

type PlanGuide added in v0.0.13

type PlanGuide struct {
	Name        string
	PlanGuideID int

	// IsDisabled reports a plan guide the optimizer currently ignores.
	IsDisabled bool

	// QueryText is the statement the guide matches, exactly as
	// sp_create_plan_guide was given it — whitespace included, since the
	// match is textual.
	QueryText string

	// Scope is the scope type; ScopeObject is the schema-qualified routine
	// for an OBJECT-scoped guide and empty for the other two.
	Scope       PlanGuideScope
	ScopeObject string

	// ScopeSchema and ScopeName are ScopeObject's two halves, unquoted — the
	// routine as a securable, for a caller that asks about its permissions
	// rather than scripting it. Empty for the SQL and TEMPLATE scopes.
	ScopeSchema string
	ScopeName   string

	// ScopeBatch is the batch text a SQL-scoped guide is bound to, empty
	// when the guide matches the statement in any batch.
	ScopeBatch string

	// Parameters is the parameter list a SQL- or TEMPLATE-scoped guide
	// declares, empty when it has none.
	Parameters string

	// Hints is the OPTION clause the guide applies, or the XML showplan for
	// a guide created from a plan handle.
	Hints string

	CreateDate time.Time
	ModifyDate time.Time
	// contains filtered or unexported fields
}

PlanGuide mirrors a sys.plan_guides row.

func (*PlanGuide) Database added in v0.0.13

func (g *PlanGuide) Database() *Database

Database returns the database the plan guide belongs to.

func (*PlanGuide) Disable added in v0.0.13

func (g *PlanGuide) Disable() error

Disable disables the plan guide. The optimizer then ignores it; the guide itself stays defined.

func (*PlanGuide) DisableContext added in v0.0.13

func (g *PlanGuide) DisableContext(ctx context.Context) error

DisableContext is the context-aware variant of Disable.

func (*PlanGuide) Drop added in v0.0.13

func (g *PlanGuide) Drop() error

Drop drops the plan guide.

func (*PlanGuide) DropContext added in v0.0.13

func (g *PlanGuide) DropContext(ctx context.Context) error

DropContext is the context-aware variant of Drop.

func (*PlanGuide) Enable added in v0.0.13

func (g *PlanGuide) Enable() error

Enable enables the plan guide.

func (*PlanGuide) EnableContext added in v0.0.13

func (g *PlanGuide) EnableContext(ctx context.Context) error

EnableContext is the context-aware variant of Enable.

type PlanGuideScope added in v0.0.13

type PlanGuideScope string

PlanGuideScope is the scope a plan guide matches on.

const (
	// PlanGuideScopeObject matches statements inside one routine.
	PlanGuideScopeObject PlanGuideScope = "OBJECT"
	// PlanGuideScopeSQL matches a standalone statement or batch.
	PlanGuideScopeSQL PlanGuideScope = "SQL"
	// PlanGuideScopeTemplate matches statements that parameterize to the
	// same template.
	PlanGuideScopeTemplate PlanGuideScope = "TEMPLATE"
)

The three scope types sys.plan_guides.scope_type_desc reports.

type PrincipalSecurable added in v0.0.5

type PrincipalSecurable struct {
	SecurableType string
	Schema        string
	Name          string
	Permission    string
	State         string
}

PrincipalSecurable is one GRANT/DENY entry for a securable that a principal (typically a database role) has an explicit permission on — the inverse of Permissions, which is "one securable, every principal." This is "one principal, every securable" — SSMS's Database Role Properties > Securables page. SecurableType is "TABLE", "VIEW", "SCHEMA", or "DATABASE"; Schema and Name are empty for "DATABASE".

type ProcParam added in v0.0.4

type ProcParam struct {
	// contains filtered or unexported fields
}

ProcParam is one argument to a stored procedure. Build it with In (input), Out (output), or InOut (both). Output and in/out parameters carry a pointer the returned value is written to, exactly as with database/sql's sql.Out.

func In added in v0.0.4

func In(name string, value any) ProcParam

In supplies an input parameter (@name = value).

func InOut added in v0.0.4

func InOut(name string, dest any) ProcParam

InOut supplies an INPUT parameter that the procedure also writes back. dest is both the input (its current pointed-to value is sent) and the output (it is overwritten with the returned value).

func Out added in v0.0.4

func Out(name string, dest any) ProcParam

Out captures an OUTPUT parameter. dest must be a non-nil pointer to a settable value (e.g. *int64, *string); it receives the value the procedure writes to @name.

type ProcResult added in v0.0.4

type ProcResult struct {
	// ReturnStatus is the procedure's RETURN value (0 unless the procedure
	// returns another code). SQL Server uses it by convention to signal
	// success (0) or an error (non-zero).
	ReturnStatus int32
}

ProcResult is what ExecProc reports beyond the values written to any output parameters' pointers.

type ProcessorInfo added in v0.0.5

type ProcessorInfo struct {
	CPUCount         int
	HyperthreadRatio int
	NUMANodeCount    int
	CPUNUMANode      []int
}

ProcessorInfo holds server-wide CPU/NUMA topology: the header counts on Server Properties > Processors (CPU count, NUMA nodes, hyperthread ratio) and the NUMA column in its per-CPU affinity grid. CPUNUMANode[i] is the NUMA node hosting logical CPU i.

type QSIntervalStat added in v0.0.11

type QSIntervalStat struct {
	StartTime, EndTime time.Time
	ExecCount          int64
	Value              float64
}

QSIntervalStat is one runtime-stats interval's line in the Overall Resource Consumption report.

type QSMetric added in v0.0.11

type QSMetric string

QSMetric names one resource dimension a Query Store report can rank by — the "Metric" selector in SSMS's Query Store views.

const (
	QSMetricDuration      QSMetric = "Duration"
	QSMetricCPUTime       QSMetric = "CPU time"
	QSMetricLogicalReads  QSMetric = "Logical reads"
	QSMetricLogicalWrites QSMetric = "Logical writes"
	QSMetricPhysicalReads QSMetric = "Physical reads"
	QSMetricCLRTime       QSMetric = "CLR time"
	QSMetricDOP           QSMetric = "DOP"
	QSMetricMemory        QSMetric = "Memory consumption"
	QSMetricRowCount      QSMetric = "Row count"
	QSMetricLogMemory     QSMetric = "Log memory used"
	QSMetricTempDBMemory  QSMetric = "Tempdb memory used"
)

type QSPlan added in v0.0.11

type QSPlan struct {
	PlanID  int64
	QueryID int64

	IsForced               bool
	ForcingType            string
	ForceFailureCount      int64
	LastForceFailureReason string

	CompatibilityLevel int
	IsTrivialPlan      bool
	IsParallelPlan     bool

	LastCompileStartTime time.Time
	LastExecutionTime    time.Time

	QueryPlanXML string

	// ExecCount and Value cover the report's window, so the caller can rank a
	// query's plans the same way its queries were ranked.
	ExecCount int64
	Value     float64
}

QSPlan is one plan of one query, with the plan XML SSMS renders below its Query Store views.

type QSPlanIntervalStat added in v0.0.11

type QSPlanIntervalStat struct {
	PlanID             int64
	StartTime, EndTime time.Time
	ExecCount          int64
	Value              float64
}

QSPlanIntervalStat is one plan's value in one interval — the per-plan time series behind the Tracked Queries report.

type QSQueryStat added in v0.0.11

type QSQueryStat struct {
	QueryID    int64
	QueryText  string
	ObjectName string // schema-qualified module the query is in, empty if ad hoc

	ExecCount int64
	PlanCount int
	// ForcedPlanID is the plan forced for this query, or 0 if none is.
	ForcedPlanID      int64
	LastExecutionTime time.Time

	// Value is the metric under the report's statistic, in the metric's unit.
	Value float64

	// BaselineValue is Value over the report's baseline window, and Regression
	// the amount Value has grown since — the ranking of the Regressed Queries
	// report.
	BaselineValue     float64
	BaselineExecCount int64
	Regression        float64

	// Variation is the metric's coefficient of variation, stdev/avg — the
	// ranking of the High Variation report. Dimensionless, so it compares
	// across queries of very different absolute cost.
	Variation float64
}

QSQueryStat is one query's line in a Query Store report.

Which fields carry a value depends on the report: BaselineValue and BaselineExecCount are populated only by QueryStoreRegressedQueriesContext, and Variation only by QueryStoreHighVariationQueriesContext. Both are zero elsewhere.

type QSStatistic added in v0.0.11

type QSStatistic string

QSStatistic is how a metric is aggregated across the intervals in a report's time range — the "Statistic" selector in SSMS's Query Store views.

const (
	QSStatAvg    QSStatistic = "Avg"
	QSStatMin    QSStatistic = "Min"
	QSStatMax    QSStatistic = "Max"
	QSStatTotal  QSStatistic = "Total"
	QSStatStdDev QSStatistic = "Std dev"
)

func QSStatistics added in v0.0.11

func QSStatistics() []QSStatistic

QSStatistics returns every statistic a Query Store report can aggregate with, in SSMS's display order.

type QSUnit added in v0.0.11

type QSUnit int

QSUnit is what a metric's values are measured in. Query Store reports raw engine units, not display ones: durations are microseconds, I/O and memory are 8-KB pages. A caller formatting a value needs to know which.

const (
	QSUnitCount        QSUnit = iota // dimensionless (DOP, row count)
	QSUnitMicroseconds               // duration, CPU time, CLR time
	QSUnitPages                      // 8-KB pages
	QSUnitBytes
	QSUnitMilliseconds // wait times, which Query Store reports in ms
)

func QSMetricUnit added in v0.0.11

func QSMetricUnit(m QSMetric) (QSUnit, bool)

QSMetricUnit reports the unit a metric's values carry, and whether the metric is one this library knows at all.

type QSWaitStat added in v0.0.11

type QSWaitStat struct {
	Category  string
	ExecCount int64
	Value     float64 // milliseconds
}

QSWaitStat is one wait category's line in the Query Wait Statistics report.

type QueryStoreInfo added in v0.0.5

type QueryStoreInfo struct {
	DesiredState       string // "OFF", "READ_ONLY", "READ_WRITE"
	ActualState        string
	ReadOnlyReason     int
	CurrentStorageMB   int64
	MaxStorageMB       int64
	FlushIntervalSec   int
	IntervalMinutes    int
	MaxPlansPerQuery   int
	CaptureMode        string // "NONE", "AUTO", "ALL", "CUSTOM"
	SizeCleanupMode    string // "OFF", "AUTO"
	StaleThresholdDays int
	// WaitStatsCaptureMode is "OFF" or "ON", and empty on SQL Server 2016,
	// which has no such setting.
	WaitStatsCaptureMode string
	// The custom capture policy is SQL Server 2019 and later; these four are
	// zero on anything older, as they are on any instance whose capture mode
	// isn't CUSTOM.
	CapturePolicyExecCount    int
	CapturePolicyCompileCPUMs int64
	CapturePolicyExecCPUMs    int64
	CapturePolicyStaleHours   int
}

QueryStoreInfo mirrors the single row of sys.database_query_store_options every database has, whether or not Query Store is actually turned on.

type QueryStoreOptions added in v0.0.5

type QueryStoreOptions struct {
	DesiredState       string // "OFF", "READ_ONLY", "READ_WRITE"
	MaxStorageMB       int64
	CaptureMode        string // "NONE", "AUTO", "ALL", "CUSTOM"
	SizeCleanupMode    string // "OFF", "AUTO"
	StaleThresholdDays int
	FlushIntervalSec   int
	IntervalMinutes    int
	MaxPlansPerQuery   int
	// WaitStatsCaptureMode is "OFF" or "ON". It is ignored on SQL Server 2016,
	// which has no such setting — the clause is left out of the statement
	// rather than sent and rejected.
	WaitStatsCaptureMode string
	// Custom capture policy thresholds, used only when CaptureMode is
	// "CUSTOM".
	CapturePolicyExecCount    int
	CapturePolicyCompileCPUMs int64
	CapturePolicyExecCPUMs    int64
	CapturePolicyStaleHours   int
}

QueryStoreOptions holds the settings SetQueryStoreOptions writes via ALTER DATABASE ... SET QUERY_STORE = ON (...). DesiredState of "OFF" turns Query Store off and ignores every other field.

type QueryStoreReportOptions added in v0.0.11

type QueryStoreReportOptions struct {
	// Metric and Statistic pick the value every row is ranked by. Empty means
	// QSMetricDuration and QSStatAvg.
	Metric    QSMetric
	Statistic QSStatistic

	// From and To bound the report by runtime-stats interval, half-open
	// [From, To). A zero To means now; a zero From means an hour before To.
	From, To time.Time

	// BaselineFrom and BaselineTo bound the comparison window
	// QueryStoreRegressedQueriesContext measures regression against, and are
	// ignored by every other report. Zero means the window of the same length
	// immediately before From.
	BaselineFrom, BaselineTo time.Time

	// Top caps how many rows come back. Zero means QSDefaultTop.
	Top int

	// MinExecCount drops queries that ran fewer than this many times in the
	// window — the noise floor for a regression or variation report, where one
	// execution has no meaningful average. Zero keeps everything.
	MinExecCount int64

	// QueryIDs restricts a per-query report to these queries, in place of
	// ranking the whole database — what the Tracked Queries view reads, where
	// the caller already knows which queries it is following. Empty means
	// every query. Honoured by the four per-query reports; ignored by the
	// reports whose rows are not queries (QueryStoreOverallConsumptionContext,
	// QueryStoreWaitCategoriesContext) and by QueryStorePlansContext, which
	// names the one query it is about.
	//
	// Top still applies: a caller asking for more ids than Top gets the
	// costliest of them, so pass Top alongside a long list.
	QueryIDs []int64

	// MinRegressionPct drops queries whose metric has grown by less than this
	// percentage of its baseline value — the threshold SSMS's Regressed
	// Queries view offers, and ignored by every other report. Zero keeps
	// everything.
	//
	// A percentage rather than an absolute amount, because the same report is
	// read under eleven metrics measured in four different units: a threshold
	// of "100" would mean 100 microseconds under Duration and 100 8-KB pages
	// under Logical reads. A query whose baseline value is zero is dropped
	// when a threshold is set — growth from nothing has no percentage.
	MinRegressionPct float64

	// IncludeInternal keeps queries Query Store flags as internal (statistics
	// updates and the like). They are excluded by default, as SSMS excludes
	// them.
	IncludeInternal bool
}

QueryStoreReportOptions selects what one report covers and how it ranks. The zero value is usable: it reports the last hour by average duration, which is what SSMS's views open on.

type RecoveryModel

type RecoveryModel string

RecoveryModel mirrors SQL Server recovery model options.

const (
	RecoveryModelSimple     RecoveryModel = "SIMPLE"
	RecoveryModelFull       RecoveryModel = "FULL"
	RecoveryModelBulkLogged RecoveryModel = "BULK_LOGGED"
)

type RelocateFile

type RelocateFile struct {
	LogicalName  string
	PhysicalName string
}

RelocateFile maps a logical file name to a new physical path.

type RestoreOptions

type RestoreOptions struct {
	// Database is the target database name (required).
	Database string
	// Action: DATABASE (default), LOG, or FILES.
	Action BackupAction
	// Files and FileGroups name the logical files / filegroups a
	// BackupActionFiles restore covers — see BackupOptions.Files for why
	// these are clauses on a RESTORE DATABASE rather than a verb of their own.
	Files      []string
	FileGroups []string
	// Devices is one or more backup file paths (required).
	Devices []string
	// FileNumber selects which backup set on the device to restore (RESTORE's
	// WITH FILE = n, 1-based, as reported by BackupHeader.Position). Zero
	// leaves the clause off, which SQL Server reads as the first set — so a
	// device holding an appended differential or log needs this set
	// explicitly, or the full backup at position 1 is restored instead.
	FileNumber int
	// RelocateFiles maps logical file names to new physical paths.
	RelocateFiles []RelocateFile
	// NoRecovery keeps the database in RESTORING state (for log shipping / tail-log).
	NoRecovery bool
	// Recovery transitions the database to ONLINE (default when neither flag is set).
	Recovery bool
	// StandBy sets standby mode; provide the undo-file path.
	StandBy string
	// Replace forces restoration over an existing database.
	Replace bool
	// Checksum verifies backup checksums.
	Checksum bool
	// Stats controls progress reporting frequency (e.g. 10 = every 10%).
	// If Progress is set and Stats is left at 0, it defaults to 10 so
	// percent-complete messages actually get emitted.
	Stats int
	// Credential names the SQL Server credential a RESTORE ... FROM URL
	// authenticates to Azure Storage with — see BackupOptions.Credential,
	// including why the shared access signature form leaves it empty.
	Credential string
	// StopAt performs a point-in-time restore, to this moment read as the
	// *server's* local wall-clock time. Its date and time-of-day fields are
	// sent as written, to the millisecond, and its Location is ignored: no
	// zone conversion is made, because RESTORE reads STOPAT in the server's
	// time zone and a caller already passing server-local times must keep
	// getting the point they asked for. A time taken in UTC or the client's
	// zone restores to the wrong point unless the zones agree — convert it
	// with In first. SQL Server rounds the milliseconds to datetime's 1/300 s.
	StopAt *time.Time
	// Progress, if set, is called for every message SQL Server emits while
	// the restore runs, including the "N percent processed" notices STATS
	// produces — pct is -1 for a message that doesn't carry a percentage.
	Progress func(pct int, message string)
}

RestoreOptions configures a RESTORE DATABASE or RESTORE LOG operation.

type RoleMember added in v0.0.5

type RoleMember struct {
	Name string
	Type string // e.g. "SQL_USER", "WINDOWS_USER", "DATABASE_ROLE"
}

RoleMember is one direct member of a database role.

type Rule added in v0.0.13

type Rule struct {
	Name       string
	Schema     string
	ObjectID   int
	Definition string
	CreateDate time.Time
	ModifyDate time.Time
	// contains filtered or unexported fields
}

Rule mirrors a sys.objects row of type 'R' — a CREATE RULE object.

func (*Rule) Database added in v0.0.13

func (r *Rule) Database() *Database

Database returns the database the rule belongs to.

func (*Rule) Drop added in v0.0.13

func (r *Rule) Drop() error

Drop drops the rule.

func (*Rule) DropContext added in v0.0.13

func (r *Rule) DropContext(ctx context.Context) error

DropContext is the context-aware variant of Drop.

func (*Rule) FullName added in v0.0.13

func (r *Rule) FullName() string

FullName returns the schema-qualified, bracket-quoted name.

type SQLError added in v0.0.4

type SQLError struct {
	// Number is the SQL Server error number (the "Msg" value), e.g. 208
	// for "Invalid object name".
	Number int32

	// State is the error state, disambiguating errors that share a Number.
	State uint8

	// Class is the severity level (the "Level" value). 0-10 are
	// informational; 11-16 are user-correctable; 17+ are software or
	// hardware errors.
	Class uint8

	// Message is the human-readable error text.
	Message string

	// ServerName is the instance that raised the error.
	ServerName string

	// ProcName is the stored procedure, function, or trigger that raised
	// the error; empty for an ad-hoc batch.
	ProcName string

	// LineNo is the 1-based line within the batch or procedure.
	LineNo int32

	// All lists every error the batch produced, first to last. The final
	// entry mirrors the fields above. Nil when only a single error is
	// reported.
	All []SQLError
}

SQLError is a structured SQL Server error — the "Msg 208, Level 16, State 1, Line 4" detail SSMS shows in its Messages pane. It is extracted from the driver's own error type so callers can inspect the error number, severity, and line without importing github.com/microsoft/go-mssqldb directly. Use AsSQLError to obtain one from any error.

func AsSQLError added in v0.0.4

func AsSQLError(err error) (*SQLError, bool)

AsSQLError reports whether err, or any error it wraps, is a SQL Server error and, if so, returns its structured form.

func (*SQLError) Error added in v0.0.4

func (e *SQLError) Error() string

Error renders the error in the multi-line form SSMS uses: the Header line followed by the message text.

func (*SQLError) Header added in v0.0.4

func (e *SQLError) Header() string

Header renders the SSMS status line for the error: its number, level, state, optional procedure, and line — everything but the message text. SSMS shows this on its own line above the message.

func (*SQLError) IsError added in v0.0.4

func (e *SQLError) IsError() bool

IsError reports whether the severity level is high enough to be treated as a failure (11 and above) rather than an informational message.

type Schedule added in v0.0.6

type Schedule struct {
	ID                   int
	Name                 string
	Enabled              bool
	FreqType             ScheduleFreqType
	FreqInterval         int
	FreqSubdayType       ScheduleSubdayType
	FreqSubdayInterval   int
	FreqRelativeInterval int
	FreqRecurrenceFactor int
	ActiveStartDate      time.Time
	// ActiveEndDate is the zero Time when the schedule has no end date.
	ActiveEndDate time.Time
	// ActiveStartTime and ActiveEndTime are HHMMSS integers, e.g. 10000 = 01:00:00.
	ActiveStartTime int
	ActiveEndTime   int
	OwnerLoginName  string
	CreateDate      time.Time
	ModifyDate      time.Time
	// contains filtered or unexported fields
}

Schedule represents a shared SQL Server Agent schedule (msdb.dbo.sysschedules), which may be attached to more than one job.

func (*Schedule) Description added in v0.0.6

func (sch *Schedule) Description() string

Description renders the schedule's frequency and active-date range as a human-readable summary, the same shape SSMS shows at the bottom of its own Schedule Properties dialog, e.g. "Occurs every day at 01:00:00. Schedule is active from 2026-01-01."

func (*Schedule) Disable added in v0.0.6

func (sch *Schedule) Disable() error

Disable disables the schedule.

func (*Schedule) DisableContext added in v0.0.6

func (sch *Schedule) DisableContext(ctx context.Context) error

DisableContext is the context-aware variant of Disable.

func (*Schedule) Drop added in v0.0.6

func (sch *Schedule) Drop() error

Drop deletes the schedule via sp_delete_schedule. SQL Server refuses the call (returning a wrapped SQLError) if the schedule is still attached to one or more jobs — detach it first via Job.DetachSchedule.

func (*Schedule) DropContext added in v0.0.6

func (sch *Schedule) DropContext(ctx context.Context) error

DropContext is the context-aware variant of Drop.

func (*Schedule) Enable added in v0.0.6

func (sch *Schedule) Enable() error

Enable enables the schedule.

func (*Schedule) EnableContext added in v0.0.6

func (sch *Schedule) EnableContext(ctx context.Context) error

EnableContext is the context-aware variant of Enable.

func (*Schedule) JobSeq added in v0.0.6

func (sch *Schedule) JobSeq(ctx context.Context) iter.Seq2[*Job, error]

JobSeq returns an iterator over the jobs this schedule is attached to.

func (*Schedule) Jobs added in v0.0.6

func (sch *Schedule) Jobs() ([]*Job, error)

Jobs returns every job this schedule is attached to — a "referenced by" list. Only JobID/Name/IsEnabled are populated on each returned Job (not its activity/history joins), enough for a reference list without the extra round trips Server.Jobs pays for.

func (*Schedule) JobsContext added in v0.0.6

func (sch *Schedule) JobsContext(ctx context.Context) ([]*Job, error)

JobsContext is the context-aware variant of Jobs.

func (*Schedule) Rename added in v0.0.6

func (sch *Schedule) Rename(newName string) error

Rename changes the schedule's name.

func (*Schedule) RenameContext added in v0.0.6

func (sch *Schedule) RenameContext(ctx context.Context, newName string) error

RenameContext is the context-aware variant of Rename.

func (*Schedule) SetActiveRange added in v0.0.6

func (sch *Schedule) SetActiveRange(startDate, endDate time.Time, startTime, endTime int) error

SetActiveRange changes the schedule's Duration section: the date range it's active over, plus the daily time-of-day window (HHMMSS) it can fire within. A zero endDate means "no end date".

func (*Schedule) SetActiveRangeContext added in v0.0.6

func (sch *Schedule) SetActiveRangeContext(ctx context.Context, startDate, endDate time.Time, startTime, endTime int) error

SetActiveRangeContext is the context-aware variant of SetActiveRange.

func (*Schedule) SetFrequency added in v0.0.6

func (sch *Schedule) SetFrequency(f ScheduleFrequency) error

SetFrequency replaces the schedule's frequency definition.

func (*Schedule) SetFrequencyContext added in v0.0.6

func (sch *Schedule) SetFrequencyContext(ctx context.Context, f ScheduleFrequency) error

SetFrequencyContext is the context-aware variant of SetFrequency.

func (*Schedule) SetOwner added in v0.0.6

func (sch *Schedule) SetOwner(loginName string) error

SetOwner reassigns the schedule's owner login.

func (*Schedule) SetOwnerContext added in v0.0.6

func (sch *Schedule) SetOwnerContext(ctx context.Context, loginName string) error

SetOwnerContext is the context-aware variant of SetOwner.

type ScheduleFreqType added in v0.0.6

type ScheduleFreqType int

ScheduleFreqType mirrors sysschedules.freq_type.

const (
	FreqOnce            ScheduleFreqType = 1
	FreqDaily           ScheduleFreqType = 4
	FreqWeekly          ScheduleFreqType = 8
	FreqMonthly         ScheduleFreqType = 16
	FreqMonthlyRelative ScheduleFreqType = 32
	FreqAutoStart       ScheduleFreqType = 64
	FreqOnIdle          ScheduleFreqType = 128
)

type ScheduleFrequency added in v0.0.6

type ScheduleFrequency struct {
	FreqType             ScheduleFreqType
	FreqInterval         int
	FreqSubdayType       ScheduleSubdayType
	FreqSubdayInterval   int
	FreqRelativeInterval int
	FreqRecurrenceFactor int
}

ScheduleFrequency bundles the freq_type cluster of sp_update_schedule's parameters — freq_interval's meaning depends on freq_type, so these are only meaningful set together, matching how SSMS's own Schedule Properties dialog submits its whole Frequency section as one unit.

type ScheduleSubdayType added in v0.0.6

type ScheduleSubdayType int

ScheduleSubdayType mirrors sysschedules.freq_subday_type.

const (
	SubdayOnce    ScheduleSubdayType = 1
	SubdaySeconds ScheduleSubdayType = 2
	SubdayMinutes ScheduleSubdayType = 4
	SubdayHours   ScheduleSubdayType = 8
)

type Schema

type Schema struct {
	ID    int
	Name  string
	Owner string
	// contains filtered or unexported fields
}

Schema mirrors Microsoft.SqlServer.Management.Smo.Schema.

func (*Schema) ChangeOwner

func (s *Schema) ChangeOwner(newOwner string) error

ChangeOwner transfers schema ownership to a new principal.

func (*Schema) ChangeOwnerContext

func (s *Schema) ChangeOwnerContext(ctx context.Context, newOwner string) error

ChangeOwnerContext is the context-aware variant of ChangeOwner.

func (*Schema) Drop

func (s *Schema) Drop() error

Drop drops the schema.

func (*Schema) DropContext added in v0.0.6

func (s *Schema) DropContext(ctx context.Context) error

DropContext is the context-aware variant of Drop.

func (*Schema) ObjectCount added in v0.0.5

func (s *Schema) ObjectCount() (int, error)

ObjectCount returns the number of objects (tables, views, procedures, functions, ...) contained in the schema — SSMS's Owned Schemas "Object count" field, fetched lazily only when a schema is selected rather than folded into Schema/SchemasContext (used by every tree-list call).

func (*Schema) ObjectCountContext added in v0.0.5

func (s *Schema) ObjectCountContext(ctx context.Context) (int, error)

ObjectCountContext is the context-aware variant of ObjectCount.

func (*Schema) ObjectCountsByType added in v0.0.10

func (s *Schema) ObjectCountsByType() (SchemaObjectCounts, error)

ObjectCountsByType returns the schema's contents broken down by category — ObjectCount's total, itemized. It is a separate method rather than a widening of ObjectCount because the two do not agree: ObjectCount is one COUNT over sys.objects, while each count here reproduces the predicate of the listing it stands in for, down to the sys.sql_modules join that keeps a CLR or extended procedure out of the stored-procedure count.

func (*Schema) ObjectCountsByTypeContext added in v0.0.10

func (s *Schema) ObjectCountsByTypeContext(ctx context.Context) (SchemaObjectCounts, error)

ObjectCountsByTypeContext is the context-aware variant of ObjectCountsByType.

One round trip of six scalar subqueries rather than a single GROUP BY over sys.objects: the counts have to match what ViewsContext, StoredProceduresContext, UserDefinedFunctionsContext, SynonymsContext, SequencesContext and TablesBySchemaContext would each have returned, and those differ in more than the type code — three join sys.sql_modules, two do not filter is_ms_shipped, and synonyms and sequences have catalog views of their own. A schema that does not exist yields zeros, not an error, because SCHEMA_ID returns NULL for it.

type SchemaObjectCounts added in v0.0.10

type SchemaObjectCounts struct {
	Tables           int
	Views            int
	StoredProcedures int
	Functions        int
	Synonyms         int
	Sequences        int
}

SchemaObjectCounts is a per-category breakdown of what a schema contains, as Schema Properties' Object summary shows it.

type ScriptCollector added in v0.0.4

type ScriptCollector struct {
	Statements []string
	// contains filtered or unexported fields
}

ScriptCollector accumulates the SQL statements a write method would have executed, instead of running them. See WithScript. Statements is guarded by mu since nothing stops a caller from reusing one collector/context across write calls issued from multiple goroutines concurrently.

func WithScript added in v0.0.4

func WithScript(ctx context.Context) (context.Context, *ScriptCollector)

WithScript returns a derived context carrying a *ScriptCollector. Every gosmo write method invoked with the returned context appends its statement to the collector and returns as if it had succeeded, without touching the server — callers use this to preview or hand off the exact SQL a set of pending edits would run (e.g. an "Script Changes" action that opens the statements in a query editor instead of executing them).

Read methods are unaffected: only the exec chokepoints (Server.execContext, Database.exec) consult the collector.

type ScriptOptions

type ScriptOptions struct {
	// Verb selects CREATE (the default), DROP, DROP-and-CREATE, or ALTER.
	Verb ScriptVerb
	// IncludeHeaders adds an informational header comment. Applies to
	// ScriptTable and ScriptDatabase only.
	IncludeHeaders bool
	// IncludeIfNotExists guards each generated statement with its own
	// existence check. Applies to ScriptTable and ScriptDatabase only:
	// ScriptView/StoredProcedure/Function return the module's definition
	// verbatim from sys.sql_modules and don't synthesize DDL to guard.
	//
	// The guard is per statement, never a block spanning several. A BEGIN
	// block containing GO separators is split across batches — GO is a
	// client-side batch break — leaving an unclosed BEGIN in one batch and a
	// bare END in another, which is a script that cannot parse.
	IncludeIfNotExists bool
	// ScriptDrops is the older, narrower spelling of Verb = ScriptDrop, and
	// still honoured: it applies only while Verb is left at its zero value.
	// New code should set Verb.
	ScriptDrops bool
	// SchemaQualify prefixes object names with their schema.
	SchemaQualify bool
	// AnsiPadding emits SET ANSI_PADDING ON before CREATE TABLE.
	AnsiPadding bool
}

ScriptOptions controls how objects are scripted.

func DefaultScriptOptions

func DefaultScriptOptions() ScriptOptions

DefaultScriptOptions returns sensible defaults.

type ScriptVerb added in v0.0.10

type ScriptVerb int

ScriptVerb selects which statement form a Scripter emits.

const (
	// ScriptCreate emits the object's CREATE statement (the zero value).
	ScriptCreate ScriptVerb = iota
	// ScriptDrop emits its DROP statement.
	ScriptDrop
	// ScriptDropAndCreate emits the DROP followed by the CREATE, in that
	// order and in separate batches — the re-runnable form.
	ScriptDropAndCreate
	// ScriptAlter emits ALTER instead of CREATE. Only module objects
	// (views, stored procedures, functions, triggers) have an ALTER form
	// that restates the whole object; everything else falls back to CREATE.
	ScriptAlter
)

type Scripter

type Scripter struct {
	// contains filtered or unexported fields
}

Scripter generates T-SQL DDL scripts for objects in a database.

func NewScripter

func NewScripter(db *Database, opts ScriptOptions) *Scripter

NewScripter creates a Scripter for the given database.

func (*Scripter) ScriptAssembly added in v0.0.13

func (sc *Scripter) ScriptAssembly(name string) (string, error)

ScriptAssembly generates the CREATE (or DROP) script for one CLR assembly.

func (*Scripter) ScriptAssemblyContext added in v0.0.13

func (sc *Scripter) ScriptAssemblyContext(ctx context.Context, name string) (string, error)

ScriptAssemblyContext is the context-aware variant of ScriptAssembly.

func (*Scripter) ScriptCheckConstraint added in v0.0.10

func (sc *Scripter) ScriptCheckConstraint(schema, table, name string) (string, error)

ScriptCheckConstraint generates the script for one CHECK constraint.

func (*Scripter) ScriptCheckConstraintContext added in v0.0.10

func (sc *Scripter) ScriptCheckConstraintContext(ctx context.Context, schema, table, name string) (string, error)

ScriptCheckConstraintContext is the context-aware variant.

func (*Scripter) ScriptClrType added in v0.0.13

func (sc *Scripter) ScriptClrType(schema, name string) (string, error)

ScriptClrType generates the CREATE (or DROP) script for one CLR type.

func (*Scripter) ScriptClrTypeContext added in v0.0.13

func (sc *Scripter) ScriptClrTypeContext(ctx context.Context, schema, name string) (string, error)

ScriptClrTypeContext is the context-aware variant of ScriptClrType.

func (*Scripter) ScriptColumnEncryptionKey added in v0.0.10

func (sc *Scripter) ScriptColumnEncryptionKey(name string) (string, error)

ScriptColumnEncryptionKey generates the CREATE (or DROP) script for one Always Encrypted column encryption key.

func (*Scripter) ScriptColumnEncryptionKeyContext added in v0.0.10

func (sc *Scripter) ScriptColumnEncryptionKeyContext(ctx context.Context, name string) (string, error)

ScriptColumnEncryptionKeyContext is the context-aware variant of ScriptColumnEncryptionKey.

func (*Scripter) ScriptColumnMasterKey added in v0.0.10

func (sc *Scripter) ScriptColumnMasterKey(name string) (string, error)

ScriptColumnMasterKey generates the CREATE (or DROP) script for one Always Encrypted column master key.

func (*Scripter) ScriptColumnMasterKeyContext added in v0.0.10

func (sc *Scripter) ScriptColumnMasterKeyContext(ctx context.Context, name string) (string, error)

ScriptColumnMasterKeyContext is the context-aware variant of ScriptColumnMasterKey.

func (*Scripter) ScriptDatabase

func (sc *Scripter) ScriptDatabase() (string, error)

ScriptDatabase generates a CREATE DATABASE script for the attached database.

func (*Scripter) ScriptDatabaseAuditSpecification added in v0.0.12

func (sc *Scripter) ScriptDatabaseAuditSpecification(name string) (string, error)

ScriptDatabaseAuditSpecification generates the CREATE (or DROP) script for one database audit specification.

func (*Scripter) ScriptDatabaseAuditSpecificationContext added in v0.0.12

func (sc *Scripter) ScriptDatabaseAuditSpecificationContext(ctx context.Context, name string) (string, error)

ScriptDatabaseAuditSpecificationContext is the context-aware variant.

func (*Scripter) ScriptDatabaseContext added in v0.0.10

func (sc *Scripter) ScriptDatabaseContext(ctx context.Context) (string, error)

ScriptDatabaseContext is the context-aware variant of ScriptDatabase.

The context is not decoration. Alone among the Script* methods this one renders from the Database's own cached metadata rather than querying, and a Database from Server.Database(name) carries none — it is a bare handle by design. Rendering that handle emitted "SET RECOVERY ;" and "COMPATIBILITY_LEVEL = 0", neither of which is valid T-SQL, so a handle with no recovery model is refilled from sys.databases first. Each line is still guarded on its own value: a refresh that cannot run leaves the script short a setting, which is recoverable, rather than syntactically broken, which is not.

func (*Scripter) ScriptDatabaseRole added in v0.0.10

func (sc *Scripter) ScriptDatabaseRole(name string) (string, error)

ScriptDatabaseRole generates the CREATE (or DROP) script for one database role, including the ALTER ROLE statements that restore its membership.

func (*Scripter) ScriptDatabaseRoleContext added in v0.0.10

func (sc *Scripter) ScriptDatabaseRoleContext(ctx context.Context, name string) (string, error)

ScriptDatabaseRoleContext is the context-aware variant.

func (*Scripter) ScriptDatabaseScopedCredential added in v0.0.12

func (sc *Scripter) ScriptDatabaseScopedCredential(name string) (string, error)

ScriptDatabaseScopedCredential generates the CREATE (or DROP) script for one database-scoped credential.

func (*Scripter) ScriptDatabaseScopedCredentialContext added in v0.0.12

func (sc *Scripter) ScriptDatabaseScopedCredentialContext(ctx context.Context, name string) (string, error)

ScriptDatabaseScopedCredentialContext is the context-aware variant.

func (*Scripter) ScriptDatabaseTrigger added in v0.0.12

func (sc *Scripter) ScriptDatabaseTrigger(name string) (string, error)

ScriptDatabaseTrigger generates the CREATE (or DROP) script for one database-scope DDL trigger.

func (*Scripter) ScriptDatabaseTriggerContext added in v0.0.12

func (sc *Scripter) ScriptDatabaseTriggerContext(ctx context.Context, name string) (string, error)

ScriptDatabaseTriggerContext is the context-aware variant of ScriptDatabaseTrigger.

scriptModule is not reusable here: it addresses a module by schema and name, and a DDL trigger has no schema.

func (*Scripter) ScriptDefault added in v0.0.13

func (sc *Scripter) ScriptDefault(schema, name string) (string, error)

ScriptDefault generates the CREATE (or DROP) script for one standalone default.

func (*Scripter) ScriptDefaultContext added in v0.0.13

func (sc *Scripter) ScriptDefaultContext(ctx context.Context, schema, name string) (string, error)

ScriptDefaultContext is the context-aware variant of ScriptDefault.

func (*Scripter) ScriptDelete added in v0.0.10

func (sc *Scripter) ScriptDelete(schema, name string) (string, error)

ScriptDelete generates a DELETE template for a table or view.

func (*Scripter) ScriptDeleteContext added in v0.0.10

func (sc *Scripter) ScriptDeleteContext(ctx context.Context, schema, name string) (string, error)

ScriptDeleteContext is the context-aware variant of ScriptDelete.

func (*Scripter) ScriptExecute added in v0.0.10

func (sc *Scripter) ScriptExecute(schema, name string) (string, error)

ScriptExecute generates an EXECUTE template for a stored procedure.

func (*Scripter) ScriptExecuteContext added in v0.0.10

func (sc *Scripter) ScriptExecuteContext(ctx context.Context, schema, name string) (string, error)

ScriptExecuteContext is the context-aware variant of ScriptExecute.

func (*Scripter) ScriptExternalDataSource added in v0.0.13

func (sc *Scripter) ScriptExternalDataSource(name string) (string, error)

ScriptExternalDataSource generates the CREATE (or DROP) script for one external data source.

func (*Scripter) ScriptExternalDataSourceContext added in v0.0.13

func (sc *Scripter) ScriptExternalDataSourceContext(ctx context.Context, name string) (string, error)

ScriptExternalDataSourceContext is the context-aware variant of ScriptExternalDataSource.

func (*Scripter) ScriptExternalFileFormat added in v0.0.13

func (sc *Scripter) ScriptExternalFileFormat(name string) (string, error)

ScriptExternalFileFormat generates the CREATE (or DROP) script for one external file format.

func (*Scripter) ScriptExternalFileFormatContext added in v0.0.13

func (sc *Scripter) ScriptExternalFileFormatContext(ctx context.Context, name string) (string, error)

ScriptExternalFileFormatContext is the context-aware variant of ScriptExternalFileFormat.

func (*Scripter) ScriptExternalLibrary added in v0.0.13

func (sc *Scripter) ScriptExternalLibrary(name string) (string, error)

ScriptExternalLibrary generates the CREATE (or DROP) script for one external library.

func (*Scripter) ScriptExternalLibraryContext added in v0.0.13

func (sc *Scripter) ScriptExternalLibraryContext(ctx context.Context, name string) (string, error)

ScriptExternalLibraryContext is the context-aware variant of ScriptExternalLibrary.

func (*Scripter) ScriptForeignKey added in v0.0.10

func (sc *Scripter) ScriptForeignKey(schema, table, name string) (string, error)

ScriptForeignKey generates the script for one foreign key.

func (*Scripter) ScriptForeignKeyContext added in v0.0.10

func (sc *Scripter) ScriptForeignKeyContext(ctx context.Context, schema, table, name string) (string, error)

ScriptForeignKeyContext is the context-aware variant.

func (*Scripter) ScriptFunction

func (sc *Scripter) ScriptFunction(schema, name string) (string, error)

ScriptFunction returns the CREATE FUNCTION definition.

func (*Scripter) ScriptFunctionCall added in v0.0.10

func (sc *Scripter) ScriptFunctionCall(schema, name, funcType string) (string, error)

ScriptFunctionCall generates a call template for a function: a SELECT of a scalar function's result, or a SELECT from a table-valued one. funcType is the UserDefinedFunction.FuncType — "FN", "IF" or "TF".

func (*Scripter) ScriptFunctionCallContext added in v0.0.10

func (sc *Scripter) ScriptFunctionCallContext(ctx context.Context, schema, name, funcType string) (string, error)

ScriptFunctionCallContext is the context-aware variant of ScriptFunctionCall.

func (*Scripter) ScriptFunctionContext

func (sc *Scripter) ScriptFunctionContext(ctx context.Context, schema, name string) (string, error)

ScriptFunctionContext is the context-aware variant.

func (*Scripter) ScriptIndex added in v0.0.10

func (sc *Scripter) ScriptIndex(schema, table, name string) (string, error)

ScriptIndex generates the CREATE (or DROP) script for one index on a table. An index backing a primary key or unique constraint is scripted as the ALTER TABLE ... ADD CONSTRAINT it really is — CREATE INDEX cannot recreate it.

func (*Scripter) ScriptIndexContext added in v0.0.10

func (sc *Scripter) ScriptIndexContext(ctx context.Context, schema, table, name string) (string, error)

ScriptIndexContext is the context-aware variant of ScriptIndex.

func (*Scripter) ScriptInsert added in v0.0.10

func (sc *Scripter) ScriptInsert(schema, name string) (string, error)

ScriptInsert generates an INSERT template for a table or view.

func (*Scripter) ScriptInsertContext added in v0.0.10

func (sc *Scripter) ScriptInsertContext(ctx context.Context, schema, name string) (string, error)

ScriptInsertContext is the context-aware variant of ScriptInsert.

func (*Scripter) ScriptPartitionFunction added in v0.0.10

func (sc *Scripter) ScriptPartitionFunction(name string) (string, error)

ScriptPartitionFunction generates the CREATE (or DROP) script for one partition function.

func (*Scripter) ScriptPartitionFunctionContext added in v0.0.10

func (sc *Scripter) ScriptPartitionFunctionContext(ctx context.Context, name string) (string, error)

ScriptPartitionFunctionContext is the context-aware variant of ScriptPartitionFunction.

func (*Scripter) ScriptPartitionScheme added in v0.0.10

func (sc *Scripter) ScriptPartitionScheme(name string) (string, error)

ScriptPartitionScheme generates the CREATE (or DROP) script for one partition scheme.

func (*Scripter) ScriptPartitionSchemeContext added in v0.0.10

func (sc *Scripter) ScriptPartitionSchemeContext(ctx context.Context, name string) (string, error)

ScriptPartitionSchemeContext is the context-aware variant of ScriptPartitionScheme.

func (*Scripter) ScriptPlanGuide added in v0.0.13

func (sc *Scripter) ScriptPlanGuide(name string) (string, error)

ScriptPlanGuide generates the CREATE (or DROP) script for one plan guide.

func (*Scripter) ScriptPlanGuideContext added in v0.0.13

func (sc *Scripter) ScriptPlanGuideContext(ctx context.Context, name string) (string, error)

ScriptPlanGuideContext is the context-aware variant of ScriptPlanGuide.

func (*Scripter) ScriptRule added in v0.0.13

func (sc *Scripter) ScriptRule(schema, name string) (string, error)

ScriptRule generates the CREATE (or DROP) script for one rule.

func (*Scripter) ScriptRuleContext added in v0.0.13

func (sc *Scripter) ScriptRuleContext(ctx context.Context, schema, name string) (string, error)

ScriptRuleContext is the context-aware variant of ScriptRule.

func (*Scripter) ScriptSchema added in v0.0.10

func (sc *Scripter) ScriptSchema(name string) (string, error)

ScriptSchema generates the CREATE (or DROP) script for one schema.

func (*Scripter) ScriptSchemaContext added in v0.0.10

func (sc *Scripter) ScriptSchemaContext(ctx context.Context, name string) (string, error)

ScriptSchemaContext is the context-aware variant of ScriptSchema.

func (*Scripter) ScriptSecurityPolicy added in v0.0.10

func (sc *Scripter) ScriptSecurityPolicy(schema, name string) (string, error)

ScriptSecurityPolicy generates the CREATE (or DROP) script for one row-level security policy.

func (*Scripter) ScriptSecurityPolicyContext added in v0.0.10

func (sc *Scripter) ScriptSecurityPolicyContext(ctx context.Context, schema, name string) (string, error)

ScriptSecurityPolicyContext is the context-aware variant of ScriptSecurityPolicy.

func (*Scripter) ScriptSelect added in v0.0.10

func (sc *Scripter) ScriptSelect(schema, name string) (string, error)

ScriptSelect generates a SELECT of every column of a table or view.

func (*Scripter) ScriptSelectContext added in v0.0.10

func (sc *Scripter) ScriptSelectContext(ctx context.Context, schema, name string) (string, error)

ScriptSelectContext is the context-aware variant of ScriptSelect.

func (*Scripter) ScriptSequence added in v0.0.10

func (sc *Scripter) ScriptSequence(schema, name string) (string, error)

ScriptSequence generates the CREATE (or DROP) script for one sequence.

func (*Scripter) ScriptSequenceContext added in v0.0.10

func (sc *Scripter) ScriptSequenceContext(ctx context.Context, schema, name string) (string, error)

ScriptSequenceContext is the context-aware variant of ScriptSequence.

func (*Scripter) ScriptStoredProcedure

func (sc *Scripter) ScriptStoredProcedure(schema, name string) (string, error)

ScriptStoredProcedure returns the CREATE PROCEDURE definition.

func (*Scripter) ScriptStoredProcedureContext

func (sc *Scripter) ScriptStoredProcedureContext(ctx context.Context, schema, name string) (string, error)

ScriptStoredProcedureContext is the context-aware variant.

func (*Scripter) ScriptSynonym added in v0.0.10

func (sc *Scripter) ScriptSynonym(schema, name string) (string, error)

ScriptSynonym generates the CREATE (or DROP) script for one synonym.

func (*Scripter) ScriptSynonymContext added in v0.0.10

func (sc *Scripter) ScriptSynonymContext(ctx context.Context, schema, name string) (string, error)

ScriptSynonymContext is the context-aware variant of ScriptSynonym.

func (*Scripter) ScriptTable

func (sc *Scripter) ScriptTable(schema, name string) (string, error)

ScriptTable generates a CREATE TABLE (or DROP TABLE) script.

func (*Scripter) ScriptTableContext

func (sc *Scripter) ScriptTableContext(ctx context.Context, schema, name string) (string, error)

ScriptTableContext is the context-aware variant of ScriptTable.

func (*Scripter) ScriptTrigger added in v0.0.10

func (sc *Scripter) ScriptTrigger(schema, name string) (string, error)

ScriptTrigger returns the CREATE TRIGGER definition. schema is the trigger's own schema, i.e. its parent table's.

func (*Scripter) ScriptTriggerContext added in v0.0.10

func (sc *Scripter) ScriptTriggerContext(ctx context.Context, schema, name string) (string, error)

ScriptTriggerContext is the context-aware variant of ScriptTrigger.

func (*Scripter) ScriptUpdate added in v0.0.10

func (sc *Scripter) ScriptUpdate(schema, name string) (string, error)

ScriptUpdate generates an UPDATE template for a table or view.

func (*Scripter) ScriptUpdateContext added in v0.0.10

func (sc *Scripter) ScriptUpdateContext(ctx context.Context, schema, name string) (string, error)

ScriptUpdateContext is the context-aware variant of ScriptUpdate.

func (*Scripter) ScriptUser added in v0.0.10

func (sc *Scripter) ScriptUser(name string) (string, error)

ScriptUser generates the CREATE (or DROP) script for one database user.

func (*Scripter) ScriptUserContext added in v0.0.10

func (sc *Scripter) ScriptUserContext(ctx context.Context, name string) (string, error)

ScriptUserContext is the context-aware variant of ScriptUser.

func (*Scripter) ScriptUserDefinedDataType added in v0.0.13

func (sc *Scripter) ScriptUserDefinedDataType(schema, name string) (string, error)

ScriptUserDefinedDataType generates the CREATE (or DROP) script for one alias type.

func (*Scripter) ScriptUserDefinedDataTypeContext added in v0.0.13

func (sc *Scripter) ScriptUserDefinedDataTypeContext(ctx context.Context, schema, name string) (string, error)

ScriptUserDefinedDataTypeContext is the context-aware variant of ScriptUserDefinedDataType.

func (*Scripter) ScriptUserDefinedTableType added in v0.0.13

func (sc *Scripter) ScriptUserDefinedTableType(schema, name string) (string, error)

ScriptUserDefinedTableType generates the CREATE (or DROP) script for one table type.

func (*Scripter) ScriptUserDefinedTableTypeContext added in v0.0.13

func (sc *Scripter) ScriptUserDefinedTableTypeContext(ctx context.Context, schema, name string) (string, error)

ScriptUserDefinedTableTypeContext is the context-aware variant of ScriptUserDefinedTableType.

The columns are read only for a verb that emits a CREATE: a DROP names the type and nothing else, and a caller scripting a drop should not pay for the column read or fail on it.

func (*Scripter) ScriptView

func (sc *Scripter) ScriptView(schema, name string) (string, error)

ScriptView returns the CREATE VIEW definition as stored in sys.sql_modules.

func (*Scripter) ScriptViewContext

func (sc *Scripter) ScriptViewContext(ctx context.Context, schema, name string) (string, error)

ScriptViewContext is the context-aware variant of ScriptView.

func (*Scripter) ScriptXmlSchemaCollection added in v0.0.13

func (sc *Scripter) ScriptXmlSchemaCollection(schema, name string) (string, error)

ScriptXmlSchemaCollection generates the CREATE (or DROP) script for one XML schema collection.

func (*Scripter) ScriptXmlSchemaCollectionContext added in v0.0.13

func (sc *Scripter) ScriptXmlSchemaCollectionContext(ctx context.Context, schema, name string) (string, error)

ScriptXmlSchemaCollectionContext is the context-aware variant of ScriptXmlSchemaCollection.

The schema documents are read only for a verb that emits a CREATE: XML_SCHEMA_NAMESPACE reassembles the whole collection, which a drop does not need.

type SearchResult added in v0.0.4

type SearchResult struct {
	Schema   string
	Name     string
	TypeDesc string // e.g. "USER_TABLE", "VIEW", "SQL_STORED_PROCEDURE"
}

SearchResult is one object matched by Database.Search.

type SecurableRef added in v0.0.8

type SecurableRef struct {
	Type   string
	Schema string
	Name   string
}

SecurableRef names one schema-scoped object a permission can be granted on. Type is "SCHEMA", "TABLE" or "VIEW", matching the SecurableType strings PrincipalSecurable reports; Schema is empty for a "SCHEMA".

This is deliberately just the identity of the securable, not the object: a permissions UI listing candidates to grant on needs the name and the type and nothing else, and loading Table or View values for thousands of candidates to show a picker is work no caller wants.

type SecurableSearch added in v0.0.8

type SecurableSearch struct {
	Name  string
	Limit int
}

SecurableSearch narrows FindSecurables.

Name is matched case-insensitively as a substring of the securable's qualified name — "dbo.Orders" for a table, the bare name for a schema — so both "ord" and "dbo.ord" find dbo.Orders. LIKE wildcards in it are matched literally, not as wildcards. An empty Name matches everything.

Limit caps the rows returned; 0 means no cap. Results are ordered schemas, then tables, then views, each by qualified name, so a capped search returns a stable prefix rather than an arbitrary subset.

type SecurityPolicy

type SecurityPolicy struct {
	Name                string
	Schema              string
	ObjectID            int
	IsEnabled           bool
	IsNotForReplication bool
	// IsSchemaBound reports whether the policy binds the schema of the
	// tables and predicate functions it names, which blocks any change to
	// them while it exists. Part of the CREATE statement, so scripting a
	// policy without it produces one that behaves differently.
	IsSchemaBound bool
	Predicates    []*SecurityPredicate
	// contains filtered or unexported fields
}

SecurityPolicy mirrors sys.security_policies.

func (*SecurityPolicy) Disable

func (p *SecurityPolicy) Disable() error

Disable disables the security policy.

func (*SecurityPolicy) DisableContext added in v0.0.5

func (p *SecurityPolicy) DisableContext(ctx context.Context) error

DisableContext is the context-aware variant of Disable.

func (*SecurityPolicy) Drop

func (p *SecurityPolicy) Drop() error

Drop drops the security policy. A policy that isn't there is the server's error, not a silent success — see the note on Database.DropTable.

func (*SecurityPolicy) DropContext added in v0.0.5

func (p *SecurityPolicy) DropContext(ctx context.Context) error

DropContext is the context-aware variant of Drop.

func (*SecurityPolicy) Enable

func (p *SecurityPolicy) Enable() error

Enable enables the security policy.

func (*SecurityPolicy) EnableContext added in v0.0.5

func (p *SecurityPolicy) EnableContext(ctx context.Context) error

EnableContext is the context-aware variant of Enable.

type SecurityPredicate

type SecurityPredicate struct {
	PredicateType       string // "FILTER" or "BLOCK"
	PredicateDefinition string
	TargetSchema        string
	TargetTable         string
	Operation           string // for BLOCK: AFTER INSERT, AFTER UPDATE, etc.
}

SecurityPredicate represents one predicate in a security policy.

type Sequence

type Sequence struct {
	Name         string
	Schema       string
	ObjectID     int
	DataType     DataType
	StartValue   int64
	Increment    int64
	MinValue     int64
	MaxValue     int64
	IsCycling    bool
	IsCached     bool
	CacheSize    int
	CurrentValue int64
	// contains filtered or unexported fields
}

Sequence mirrors sys.sequences.

func (*Sequence) Drop

func (seq *Sequence) Drop() error

Drop drops the sequence.

func (*Sequence) DropContext added in v0.0.5

func (seq *Sequence) DropContext(ctx context.Context) error

DropContext is the context-aware variant of Drop.

func (*Sequence) NextValue

func (seq *Sequence) NextValue() (int64, error)

NextValue retrieves the next value from the sequence.

func (*Sequence) NextValueContext added in v0.0.5

func (seq *Sequence) NextValueContext(ctx context.Context) (int64, error)

NextValueContext is the context-aware variant of NextValue.

This deliberately uses withConn, not queryRow: "NEXT VALUE FOR" advances the sequence as a side effect of being read, so it isn't safe to retry — unlike every other queryRow caller in this package, re-running it on a fresh connection after a transient failure could silently skip a value. withConn still retries the acquire+USE step (safe, nothing server-side has happened yet), just not the query itself.

func (*Sequence) Restart

func (seq *Sequence) Restart(value int64) error

Restart restarts the sequence at the given value.

func (*Sequence) RestartContext added in v0.0.5

func (seq *Sequence) RestartContext(ctx context.Context, value int64) error

RestartContext is the context-aware variant of Restart.

type Server

type Server struct {
	// contains filtered or unexported fields
}

Server is the top-level object representing a SQL Server instance. Create one with Connect() and use it to enumerate or manage databases, logins, server roles, linked servers, and more.

func Connect

func Connect(opts ConnectionOptions) (*Server, error)

Connect opens a connection to a SQL Server instance and returns a Server. The driver and DSN are chosen automatically based on opts.Auth.

func ConnectContext

func ConnectContext(ctx context.Context, opts ConnectionOptions) (*Server, error)

ConnectContext is the context-aware variant of Connect. The context governs the initial ping and server-info load only; subsequent calls each carry their own context.

func NewServer added in v0.0.10

func NewServer(ctx context.Context, db *sql.DB) (*Server, error)

NewServer wraps an already-open *sql.DB as a Server, loading the same server metadata ConnectContext loads. Use it when the pool is not gosmo's to open: a connection shared with the rest of an application, a driver wrapped for tracing or retries, or a fake driver in a test.

db must be a SQL Server pool — gosmo builds T-SQL and reads system views, and nothing here checks the dialect. Ownership passes to the returned Server: Close closes db, as it does for a pool Connect opened.

This is the inverse of DB(), and the seam that makes gosmo's read and write paths reachable from a caller's tests. Without it a Server can only come from a real network connection, so any code that takes one — an application's whole database layer — is testable only against a live instance.

func (*Server) ActiveSessionSeq added in v0.0.6

func (s *Server) ActiveSessionSeq(ctx context.Context, includeSystem bool) iter.Seq2[*ActiveSession, error]

ActiveSessionSeq returns an iterator over every session currently connected to the server, optionally including system sessions.

func (*Server) ActiveSessions

func (s *Server) ActiveSessions(includeSystem bool) ([]*ActiveSession, error)

ActiveSessions returns running sessions. Set includeSystem=true to include SQL Server internal sessions.

func (*Server) ActiveSessionsContext

func (s *Server) ActiveSessionsContext(ctx context.Context, includeSystem bool) ([]*ActiveSession, error)

ActiveSessionsContext is the context-aware variant of ActiveSessions.

func (*Server) AddServerRoleMember added in v0.0.6

func (s *Server) AddServerRoleMember(roleName, memberName string) error

AddServerRoleMember adds member (a login or another server role, by name) to a server role.

func (*Server) AddServerRoleMemberContext added in v0.0.6

func (s *Server) AddServerRoleMemberContext(ctx context.Context, roleName, memberName string) error

AddServerRoleMemberContext is the context-aware variant of AddServerRoleMember.

func (*Server) AgentInfo added in v0.0.6

func (s *Server) AgentInfo() (*AgentStatus, error)

AgentInfo reports SQL Server Agent's current run state.

func (*Server) AgentInfoContext added in v0.0.6

func (s *Server) AgentInfoContext(ctx context.Context) (*AgentStatus, error)

AgentInfoContext is the context-aware variant of AgentInfo.

func (*Server) Alert added in v0.0.7

func (s *Server) Alert(name string) *Alert

Alert returns a lightweight handle for an alert by name, without querying msdb — the alert-side counterpart of Server.Database. ID, Severity, JobName and every other cached field stay at their zero value; AlertByName is what populates them.

Every write method on *Alert addresses the alert by name (Notify, RemoveNotify, Update, ...), so this handle is enough to keep operating on an alert the caller already knows exists — and is the only usable form under a WithScript context, where AlertByNameContext's lookup is a real read and an alert whose sp_add_alert was merely collected is not there to find.

func (*Server) AlertByName added in v0.0.6

func (s *Server) AlertByName(name string) (*Alert, error)

AlertByName returns a single alert by name.

func (*Server) AlertByNameContext added in v0.0.6

func (s *Server) AlertByNameContext(ctx context.Context, name string) (*Alert, error)

AlertByNameContext is the context-aware variant of AlertByName.

func (*Server) AlertSeq added in v0.0.6

func (s *Server) AlertSeq(ctx context.Context) iter.Seq2[*Alert, error]

AlertSeq returns an iterator over all SQL Server Agent alerts.

func (*Server) Alerts added in v0.0.6

func (s *Server) Alerts() ([]*Alert, error)

Alerts returns every SQL Server Agent alert defined on the server.

func (*Server) AlertsContext added in v0.0.6

func (s *Server) AlertsContext(ctx context.Context) ([]*Alert, error)

AlertsContext is the context-aware variant of Alerts.

func (*Server) AttachDatabase added in v0.0.11

func (s *Server) AttachDatabase(spec AttachSpec) error

AttachDatabase attaches a set of database files to the instance.

func (*Server) AttachDatabaseContext added in v0.0.11

func (s *Server) AttachDatabaseContext(ctx context.Context, spec AttachSpec) error

AttachDatabaseContext is the context-aware variant of AttachDatabase.

func (*Server) AuditActionGroups added in v0.0.11

func (s *Server) AuditActionGroups() ([]string, error)

AuditActionGroups returns every server-scope audit action group the instance knows about.

func (*Server) AuditActionGroupsContext added in v0.0.11

func (s *Server) AuditActionGroupsContext(ctx context.Context) ([]string, error)

AuditActionGroupsContext is the context-aware variant of AuditActionGroups.

The list is read from sys.dm_audit_actions rather than hard-coded so it stays right across versions: each release adds groups, and a fixed table would quietly hide the new ones from anything building a pick list.

func (*Server) AvailabilityGroup added in v0.0.9

func (s *Server) AvailabilityGroup(name string) *AvailabilityGroup

AvailabilityGroup returns a lightweight handle to an availability group by name, with no query and no metadata: every field but Name is zero, so ClusterType, PrimaryReplicaServerName and IsLocalPrimary all read as "unknown" rather than as fact. Use AvailabilityGroupByName to get a group whose fields mean something.

This exists for the one case where the group cannot be read: a secondary of an EXTERNAL- or NONE-cluster group has no row for it until Join succeeds, so the join has to be issued against a handle built from the name alone. It is also what works under a WithScript-derived context, where nothing has been created yet to read back. The same split as Server.Database vs Server.DatabaseByName.

func (*Server) AvailabilityGroupByName added in v0.0.9

func (s *Server) AvailabilityGroupByName(name string) (*AvailabilityGroup, error)

AvailabilityGroupByName returns one availability group by name, or an error wrapping ErrNotFound if this instance knows no group by that name. That error also satisfies errors.Is(err, sql.ErrNoRows), which this method promised before ErrNotFound existed. Note that neither sentinel was ever returned bare — both have always needed errors.Is rather than ==.

func (*Server) AvailabilityGroupByNameContext added in v0.0.9

func (s *Server) AvailabilityGroupByNameContext(ctx context.Context, name string) (*AvailabilityGroup, error)

AvailabilityGroupByNameContext is the context-aware variant of AvailabilityGroupByName.

func (*Server) AvailabilityGroupSeq added in v0.0.9

func (s *Server) AvailabilityGroupSeq(ctx context.Context) iter.Seq2[*AvailabilityGroup, error]

AvailabilityGroupSeq returns an iterator over every availability group this instance participates in.

func (*Server) AvailabilityGroups added in v0.0.9

func (s *Server) AvailabilityGroups() ([]*AvailabilityGroup, error)

AvailabilityGroups returns every availability group this instance participates in. Returns an empty slice — not an error — on an instance where Always On is disabled or no group has been created.

func (*Server) AvailabilityGroupsContext added in v0.0.9

func (s *Server) AvailabilityGroupsContext(ctx context.Context) ([]*AvailabilityGroup, error)

AvailabilityGroupsContext is the context-aware variant of AvailabilityGroups.

func (*Server) Backup

func (s *Server) Backup(opts BackupOptions) error

Backup performs a BACKUP DATABASE (or LOG) operation.

func (*Server) BackupContext

func (s *Server) BackupContext(ctx context.Context, opts BackupOptions) error

BackupContext is the context-aware variant of Backup.

func (*Server) BackupDevice added in v0.0.11

func (s *Server) BackupDevice(name string) *BackupDevice

BackupDevice returns a lightweight handle for a backup device by name, without querying sys.backup_devices — the device-side counterpart of Server.Database. Type and PhysicalName stay at their zero value; BackupDeviceByName is what populates them.

DropContext addresses the device by name, so this handle is enough to drop one the caller already knows exists — and is the only usable form under a WithScript context, where BackupDeviceByNameContext's lookup is a real read and a device whose sp_addumpdevice was merely collected is not there to find.

func (*Server) BackupDeviceByName added in v0.0.11

func (s *Server) BackupDeviceByName(name string) (*BackupDevice, error)

BackupDeviceByName returns one backup device with every field populated, or a not-found error (errors.Is ErrNotFound) when the server has none by that name.

func (*Server) BackupDeviceByNameContext added in v0.0.11

func (s *Server) BackupDeviceByNameContext(ctx context.Context, name string) (*BackupDevice, error)

BackupDeviceByNameContext is the context-aware variant of BackupDeviceByName.

func (*Server) BackupDeviceSeq added in v0.0.11

func (s *Server) BackupDeviceSeq(ctx context.Context) iter.Seq2[*BackupDevice, error]

BackupDeviceSeq returns an iterator over all logical backup devices.

func (*Server) BackupDevices added in v0.0.11

func (s *Server) BackupDevices() ([]*BackupDevice, error)

BackupDevices returns every logical backup device on the server.

func (*Server) BackupDevicesContext added in v0.0.11

func (s *Server) BackupDevicesContext(ctx context.Context) ([]*BackupDevice, error)

BackupDevicesContext is the context-aware variant of BackupDevices.

func (*Server) BackupFileList added in v0.0.5

func (s *Server) BackupFileList(device string) ([]*BackupFile, error)

BackupFileList reads the database files contained in the first backup set on a backup device (RESTORE FILELISTONLY). Use BackupFileListForSet for a device holding more than one set.

func (*Server) BackupFileListContext added in v0.0.5

func (s *Server) BackupFileListContext(ctx context.Context, device string) ([]*BackupFile, error)

BackupFileListContext is the context-aware variant of BackupFileList.

func (*Server) BackupFileListForSet added in v0.0.8

func (s *Server) BackupFileListForSet(device string, fileNumber int) ([]*BackupFile, error)

BackupFileListForSet reads the database files contained in one particular backup set on a device (RESTORE FILELISTONLY WITH FILE = n).

fileNumber is 1-based, as reported by BackupHeader.Position, and matches RestoreOptions.FileNumber — pass the same value to both or the file list describes a different set from the one being restored. Zero leaves the clause off, which SQL Server reads as the first set.

A device that backups were appended to holds one set per backup, and their file lists differ whenever the sets came from different databases or files were added between them. Building RESTORE's MOVE clauses from the wrong set names logical files the restored set does not contain, which SQL Server rejects outright.

func (*Server) BackupFileListForSetContext added in v0.0.8

func (s *Server) BackupFileListForSetContext(ctx context.Context, device string, fileNumber int) ([]*BackupFile, error)

BackupFileListForSetContext is the context-aware variant of BackupFileListForSet.

func (*Server) BackupFileListForSetFrom added in v0.0.11

func (s *Server) BackupFileListForSetFrom(target BackupTarget, fileNumber int) ([]*BackupFile, error)

BackupFileListForSetFrom is BackupFileListForSet for any BackupTarget — a path or a logical backup device.

func (*Server) BackupFileListForSetFromContext added in v0.0.11

func (s *Server) BackupFileListForSetFromContext(ctx context.Context, target BackupTarget, fileNumber int) ([]*BackupFile, error)

BackupFileListForSetFromContext is the context-aware variant of BackupFileListForSetFrom.

func (*Server) BackupFileSeq added in v0.0.5

func (s *Server) BackupFileSeq(ctx context.Context, device string) iter.Seq2[*BackupFile, error]

BackupFileSeq returns an iterator over the database files inside the backup set on a backup device.

func (*Server) BackupHeaderSeq added in v0.0.5

func (s *Server) BackupHeaderSeq(ctx context.Context, device string) iter.Seq2[*BackupHeader, error]

BackupHeaderSeq returns an iterator over the backup sets on a backup device.

func (*Server) BackupHeaders added in v0.0.5

func (s *Server) BackupHeaders(device string) ([]*BackupHeader, error)

BackupHeaders reads the backup sets on a backup device (RESTORE HEADERONLY) — one BackupHeader per set, in position order. device is a path on the server's filesystem; BackupHeadersFrom takes a logical backup device.

func (*Server) BackupHeadersContext added in v0.0.5

func (s *Server) BackupHeadersContext(ctx context.Context, device string) ([]*BackupHeader, error)

BackupHeadersContext is the context-aware variant of BackupHeaders.

func (*Server) BackupHeadersFrom added in v0.0.11

func (s *Server) BackupHeadersFrom(target BackupTarget) ([]*BackupHeader, error)

BackupHeadersFrom is BackupHeaders for any BackupTarget — a path or a logical backup device.

func (*Server) BackupHeadersFromContext added in v0.0.11

func (s *Server) BackupHeadersFromContext(ctx context.Context, target BackupTarget) ([]*BackupHeader, error)

BackupHeadersFromContext is the context-aware variant of BackupHeadersFrom.

func (*Server) BackupHistory

func (s *Server) BackupHistory(databaseName string) ([]*BackupInfo, error)

BackupHistory returns the backup history for a database from msdb.

func (*Server) BackupHistoryContext

func (s *Server) BackupHistoryContext(ctx context.Context, databaseName string) ([]*BackupInfo, error)

BackupHistoryContext is the context-aware variant of BackupHistory.

Every column read here is nullable in msdb, and a NULL in any of them used to kill the whole read — which took Database Properties' General page, the Backup History viewer and Restore's backup-history source down with it. On an on-prem instance the columns happen to be populated by whatever ran the backup, so this never showed; Azure SQL Managed Instance's automated backups leave physical_device_name, user_name and server_name NULL, and

sql: Scan error on column index 7, name "physical_device_name"

was the entire General page. A NULL means "not recorded", so every column is ISNULL'd in the query *and* scanned through a sql.Null* destination: the ISNULL is what the server sends, the Null destination is what survives a column this list forgets to wrap. Do not narrow either half back because a particular server populates the columns.

func (*Server) BackupHistorySeq added in v0.0.6

func (s *Server) BackupHistorySeq(ctx context.Context, databaseName string) iter.Seq2[*BackupInfo, error]

BackupHistorySeq returns an iterator over databaseName's backup/restore history, as recorded in msdb.

func (*Server) Capabilities added in v0.0.10

func (s *Server) Capabilities() (*Capabilities, error)

Capabilities reports what the connected login may do at the server scope.

func (*Server) CapabilitiesContext added in v0.0.10

func (s *Server) CapabilitiesContext(ctx context.Context) (*Capabilities, error)

CapabilitiesContext is the context-aware variant of Capabilities.

One round trip: role membership and permission states come back as one result set of (kind, name, answer) rows, read by name rather than by column position, so adding a name to either list cannot shift the answers after it.

func (*Server) Categories added in v0.0.6

func (s *Server) Categories(class CategoryClass) ([]*Category, error)

Categories returns every category of the given class.

func (*Server) CategoriesContext added in v0.0.6

func (s *Server) CategoriesContext(ctx context.Context, class CategoryClass) ([]*Category, error)

CategoriesContext is the context-aware variant of Categories.

func (*Server) CategorySeq added in v0.0.6

func (s *Server) CategorySeq(ctx context.Context, class CategoryClass) iter.Seq2[*Category, error]

CategorySeq returns an iterator over every category of the given class (job or alert categories).

func (*Server) Close

func (s *Server) Close() error

Close releases all resources held by the server connection pool.

func (*Server) ConfigurationByName

func (s *Server) ConfigurationByName(name string) (*ConfigurationOption, error)

ConfigurationByName returns a single option using a direct parameterised query.

func (*Server) ConfigurationByNameContext

func (s *Server) ConfigurationByNameContext(ctx context.Context, name string) (*ConfigurationOption, error)

ConfigurationByNameContext is the context-aware variant.

func (*Server) ConfigurationSeq added in v0.0.6

func (s *Server) ConfigurationSeq(ctx context.Context) iter.Seq2[*ConfigurationOption, error]

ConfigurationSeq returns an iterator over all sp_configure options.

func (*Server) Configurations

func (s *Server) Configurations() ([]*ConfigurationOption, error)

Configurations returns all server configuration options.

func (*Server) ConfigurationsContext

func (s *Server) ConfigurationsContext(ctx context.Context) ([]*ConfigurationOption, error)

ConfigurationsContext is the context-aware variant of Configurations.

func (*Server) CreateAlert added in v0.0.6

func (s *Server) CreateAlert(req CreateAlertRequest) (*Alert, error)

CreateAlert creates a new SQL Server event alert via sp_add_alert.

func (*Server) CreateAlertContext added in v0.0.6

func (s *Server) CreateAlertContext(ctx context.Context, req CreateAlertRequest) (*Alert, error)

CreateAlertContext is the context-aware variant of CreateAlert.

func (*Server) CreateAvailabilityGroup added in v0.0.9

func (s *Server) CreateAvailabilityGroup(req CreateAvailabilityGroupRequest) (*AvailabilityGroup, error)

CreateAvailabilityGroup creates an availability group with this instance as its primary.

This is step 2 of four; see this section's doc comment for the rest. On its own it leaves a group whose secondaries are all disconnected, because none of them has joined yet.

func (*Server) CreateAvailabilityGroupContext added in v0.0.9

func (s *Server) CreateAvailabilityGroupContext(ctx context.Context, req CreateAvailabilityGroupRequest) (*AvailabilityGroup, error)

CreateAvailabilityGroupContext is the context-aware variant of CreateAvailabilityGroup.

func (*Server) CreateBackupDevice added in v0.0.11

func (s *Server) CreateBackupDevice(name string, devType BackupDeviceType, physicalName string) (*BackupDevice, error)

CreateBackupDevice registers a logical backup device.

func (*Server) CreateBackupDeviceContext added in v0.0.11

func (s *Server) CreateBackupDeviceContext(ctx context.Context, name string, devType BackupDeviceType, physicalName string) (*BackupDevice, error)

CreateBackupDeviceContext is the context-aware variant of CreateBackupDevice.

The statement is built as literals rather than bound parameters because every gosmo write goes through execContext, which under a WithScript context collects the statement text instead of running it — a parameterized EXEC would script as a statement carrying @p1 and nothing to bind it to.

func (*Server) CreateCategory added in v0.0.6

func (s *Server) CreateCategory(class CategoryClass, name string) error

CreateCategory creates a new category via sp_add_category.

func (*Server) CreateCategoryContext added in v0.0.6

func (s *Server) CreateCategoryContext(ctx context.Context, class CategoryClass, name string) error

CreateCategoryContext is the context-aware variant of CreateCategory.

func (*Server) CreateCredential added in v0.0.11

func (s *Server) CreateCredential(spec CredentialSpec) (*Credential, error)

CreateCredential creates a server-level credential.

func (*Server) CreateCredentialContext added in v0.0.11

func (s *Server) CreateCredentialContext(ctx context.Context, spec CredentialSpec) (*Credential, error)

CreateCredentialContext is the context-aware variant of CreateCredential.

func (*Server) CreateDatabase

func (s *Server) CreateDatabase(name string, opts *CreateDatabaseOptions) error

CreateDatabase creates a new database with the given name and optional options.

func (*Server) CreateDatabaseContext

func (s *Server) CreateDatabaseContext(ctx context.Context, name string, opts *CreateDatabaseOptions) error

CreateDatabaseContext is the context-aware variant of CreateDatabase.

func (*Server) CreateDatabaseMirroringEndpoint added in v0.0.9

func (s *Server) CreateDatabaseMirroringEndpoint(spec EndpointSpec) (*DatabaseMirroringEndpoint, error)

CreateDatabaseMirroringEndpoint creates the instance's database mirroring endpoint, started.

Fails if the instance already has one, whatever it is named — see this file's doc comment. Read DatabaseMirroringEndpoint first and reuse what is there rather than treating "no endpoint of my name" as "no endpoint".

func (*Server) CreateDatabaseMirroringEndpointContext added in v0.0.9

func (s *Server) CreateDatabaseMirroringEndpointContext(ctx context.Context, spec EndpointSpec) (*DatabaseMirroringEndpoint, error)

CreateDatabaseMirroringEndpointContext is the context-aware variant of CreateDatabaseMirroringEndpoint.

func (*Server) CreateDatabaseSnapshot added in v0.0.13

func (s *Server) CreateDatabaseSnapshot(req CreateDatabaseSnapshotRequest) (*DatabaseSnapshot, error)

CreateDatabaseSnapshot creates a database snapshot.

func (*Server) CreateDatabaseSnapshotContext added in v0.0.13

func (s *Server) CreateDatabaseSnapshotContext(ctx context.Context, req CreateDatabaseSnapshotRequest) (*DatabaseSnapshot, error)

CreateDatabaseSnapshotContext is the context-aware variant of CreateDatabaseSnapshot.

Under a WithScript context it returns a name-only handle rather than reading the snapshot back: nothing ran, so there is nothing to read, and the by-name lookup would be a real query against a database that does not exist.

func (*Server) CreateJob

func (s *Server) CreateJob(req CreateJobRequest) (*Job, error)

CreateJob creates a new SQL Server Agent job.

func (*Server) CreateJobContext

func (s *Server) CreateJobContext(ctx context.Context, req CreateJobRequest) (*Job, error)

CreateJobContext is the context-aware variant of CreateJob. It also enlists the job to run on the local server via sp_add_jobserver — without that, SQL Server Agent refuses to start the job (sp_start_job: "does not have any job server or servers defined") or let an alert target it (sp_update_alert/sp_add_alert: "cannot be used by an alert"). Multi-server (MSX/TSX) target-server selection is out of scope here, so "(local)" is the only target.

func (*Server) CreateLogin

func (s *Server) CreateLogin(name, password string, opts *CreateLoginOptions) error

CreateLogin creates a login. With no CreateLoginOptions.Source, an empty password means a Windows login (FROM WINDOWS) and a non-empty one a SQL login; set Source to create any of the other kinds.

func (*Server) CreateLoginContext

func (s *Server) CreateLoginContext(ctx context.Context, name, password string, opts *CreateLoginOptions) error

CreateLoginContext is the context-aware variant of CreateLogin.

Security: the password is never string-concatenated raw into the SQL text — it's quoted via nStringLiteral (N'...', doubling any embedded quote), the same escaping every other literal in this package uses. HASHED is deliberately not used here: it tells SQL Server the value is already one of its own password-hash formats, not a cleartext password, so passing an arbitrary hex encoding of the cleartext under HASHED either fails outright or creates a login nothing can ever authenticate as.

DefaultDatabase reaches an external-provider login through a following ALTER LOGIN: OBJECT_ID is the only WITH option FROM EXTERNAL PROVIDER accepts, and DEFAULT_DATABASE alongside it does not parse. A certificate- or asymmetric-key-mapped login cannot have one at all — SQL Server rejects DEFAULT_DATABASE for those in both CREATE and ALTER ("Cannot use the parameter DEFAULT_DATABASE for a certificate or asymmetric key login", verified live) — so asking for one is an error rather than a statement the server will refuse.

func (*Server) CreateOperator added in v0.0.6

func (s *Server) CreateOperator(req CreateOperatorRequest) (*Operator, error)

CreateOperator creates a new operator via sp_add_operator.

func (*Server) CreateOperatorContext added in v0.0.6

func (s *Server) CreateOperatorContext(ctx context.Context, req CreateOperatorRequest) (*Operator, error)

CreateOperatorContext is the context-aware variant of CreateOperator.

func (*Server) CreateSchedule added in v0.0.6

func (s *Server) CreateSchedule(req CreateScheduleRequest) (*Schedule, error)

CreateSchedule creates a new shared schedule via sp_add_schedule. The returned Schedule is not yet attached to any job — see Job.AttachSchedule.

func (*Server) CreateScheduleContext added in v0.0.6

func (s *Server) CreateScheduleContext(ctx context.Context, req CreateScheduleRequest) (*Schedule, error)

CreateScheduleContext is the context-aware variant of CreateSchedule.

func (*Server) CreateServerAudit added in v0.0.11

func (s *Server) CreateServerAudit(spec ServerAuditSpec) (*ServerAudit, error)

CreateServerAudit creates a server audit. It is created disabled, which is what CREATE SERVER AUDIT does; use SetState to turn it on.

func (*Server) CreateServerAuditContext added in v0.0.11

func (s *Server) CreateServerAuditContext(ctx context.Context, spec ServerAuditSpec) (*ServerAudit, error)

CreateServerAuditContext is the context-aware variant of CreateServerAudit.

func (*Server) CreateServerAuditSpecification added in v0.0.11

func (s *Server) CreateServerAuditSpecification(spec ServerAuditSpecificationSpec) (*ServerAuditSpecification, error)

CreateServerAuditSpecification creates a server audit specification.

func (*Server) CreateServerAuditSpecificationContext added in v0.0.11

func (s *Server) CreateServerAuditSpecificationContext(ctx context.Context, spec ServerAuditSpecificationSpec) (*ServerAuditSpecification, error)

CreateServerAuditSpecificationContext is the context-aware variant of CreateServerAuditSpecification.

func (*Server) Credential added in v0.0.11

func (s *Server) Credential(name string) *Credential

Credential returns a lightweight handle for a credential by name, without querying sys.credentials — the credential-side counterpart of Server.Database. Identity, CredentialID and every other cached field stay at their zero value; CredentialByName is what populates them.

Every write method on *Credential addresses the credential by name, so this handle is enough to go on operating on one the caller already knows exists — and is the only usable form under a WithScript context, where CredentialByNameContext's lookup is a real read and a credential whose CREATE CREDENTIAL was merely collected is not there to find.

func (*Server) CredentialByName added in v0.0.11

func (s *Server) CredentialByName(name string) (*Credential, error)

CredentialByName returns one credential with every field populated, or a not-found error (errors.Is ErrNotFound) when the server has none by that name.

func (*Server) CredentialByNameContext added in v0.0.11

func (s *Server) CredentialByNameContext(ctx context.Context, name string) (*Credential, error)

CredentialByNameContext is the context-aware variant of CredentialByName.

func (*Server) CredentialSeq added in v0.0.4

func (s *Server) CredentialSeq(ctx context.Context) iter.Seq2[*Credential, error]

CredentialSeq returns an iterator over all server-level credentials.

func (*Server) Credentials added in v0.0.4

func (s *Server) Credentials() ([]*Credential, error)

Credentials returns every server-level credential.

func (*Server) CredentialsContext added in v0.0.4

func (s *Server) CredentialsContext(ctx context.Context) ([]*Credential, error)

CredentialsContext is the context-aware variant of Credentials.

func (*Server) CryptographicProviders added in v0.0.11

func (s *Server) CryptographicProviders() ([]*CryptographicProvider, error)

CryptographicProviders returns every registered EKM provider.

func (*Server) CryptographicProvidersContext added in v0.0.11

func (s *Server) CryptographicProvidersContext(ctx context.Context) ([]*CryptographicProvider, error)

CryptographicProvidersContext is the context-aware variant of CryptographicProviders. A server with no provider registered — the ordinary case — returns no rows, not an error.

func (*Server) CurrentDatabase added in v0.0.4

func (s *Server) CurrentDatabase() (string, error)

CurrentDatabase returns the name of the database the connection is currently in — the login's default database when ConnectionOptions.Database was left empty at connect time, or whatever a session-level USE has since switched to.

func (*Server) CurrentDatabaseContext added in v0.0.4

func (s *Server) CurrentDatabaseContext(ctx context.Context) (string, error)

CurrentDatabaseContext is the context-aware variant of CurrentDatabase.

func (*Server) CurrentLogin added in v0.0.6

func (s *Server) CurrentLogin() (string, error)

CurrentLogin returns the server login name the connection is authenticated as (SUSER_NAME()) — the real login behind the connection, which for Windows/Entra auth differs from whatever was passed as ConnectionOptions.User (often empty for those methods).

func (*Server) CurrentLoginContext added in v0.0.6

func (s *Server) CurrentLoginContext(ctx context.Context) (string, error)

CurrentLoginContext is the context-aware variant of CurrentLogin.

func (*Server) CycleErrorLog

func (s *Server) CycleErrorLog() error

CycleErrorLog closes the current error log and opens a new one. Equivalent to sp_cycle_errorlog. It is CycleLog fixed to the SQL Server log family.

func (*Server) CycleErrorLogContext

func (s *Server) CycleErrorLogContext(ctx context.Context) error

CycleErrorLogContext is the context-aware variant of CycleErrorLog.

func (*Server) CycleLog added in v0.0.10

func (s *Server) CycleLog(logType ErrorLogType) error

CycleLog closes the current log of the given family and opens a new one, renumbering the archives and deleting the oldest if the instance is already holding as many as it is configured to keep.

func (*Server) CycleLogContext added in v0.0.10

func (s *Server) CycleLogContext(ctx context.Context, logType ErrorLogType) error

CycleLogContext is the context-aware variant of CycleLog. Cycling the Agent log requires SQL Server Agent to be running.

func (*Server) DB

func (s *Server) DB() *sql.DB

DB returns the underlying *sql.DB for ad-hoc queries.

func (*Server) Database added in v0.0.5

func (s *Server) Database(name string) *Database

Database returns a lightweight handle for name without querying the server at all — unlike DatabaseByName/DatabaseByNameContext, it doesn't verify the database exists or populate State/RecoveryModel/Collation/ CompatibilityLevel/etc. (they stay at their zero value). Every write method on *Database (AddFileGroupContext, SetDatabaseOptionContext, SetOwnerContext, ...) only ever needs the database's name, never those cached fields, so this is sufficient for issuing further ALTER-style calls against a database the caller already knows exists — most commonly one it just created in the same operation. It's also the only way to do that under a WithScript-derived context: DatabaseByNameContext's own lookup query is a real read, not a write, so it isn't captured by ScriptCollector and would fail outright (or return stale data) for a database whose CREATE DATABASE was itself only scripted, not actually run.

func (*Server) DatabaseAuditActionGroups added in v0.0.12

func (s *Server) DatabaseAuditActionGroups() ([]string, error)

DatabaseAuditActionGroups returns every database-scope audit action group the instance knows about.

func (*Server) DatabaseAuditActionGroupsContext added in v0.0.12

func (s *Server) DatabaseAuditActionGroupsContext(ctx context.Context) ([]string, error)

DatabaseAuditActionGroupsContext is the context-aware variant of DatabaseAuditActionGroups.

Read from sys.dm_audit_actions for the same reason the server-scope list is (AuditActionGroupsContext): every release adds groups, and a hard-coded table would quietly hide the new ones from a pick list.

func (*Server) DatabaseAuditActions added in v0.0.12

func (s *Server) DatabaseAuditActions() ([]string, error)

DatabaseAuditActions returns every individual database-scope audit action — SELECT, INSERT, EXECUTE and the rest — for the per-securable clause form.

All three securable classes are read, not just DATABASE: the same action name is a separate row per class in sys.dm_audit_actions, and a pick list restricted to the DATABASE class would leave out what can be audited on an object or a schema.

func (*Server) DatabaseAuditActionsContext added in v0.0.12

func (s *Server) DatabaseAuditActionsContext(ctx context.Context) ([]string, error)

DatabaseAuditActionsContext is the context-aware variant of DatabaseAuditActions.

func (*Server) DatabaseByName

func (s *Server) DatabaseByName(name string) (*Database, error)

DatabaseByName returns a single database by name, querying sys.databases so the returned handle is verified to exist and has State/RecoveryModel/ Collation/CompatibilityLevel/etc. populated. Use it when you need to read those or to confirm the database is there; use Database when you only need a handle to issue further ALTER-style calls against a database you already know exists. The two are not interchangeable — see Database.

func (*Server) DatabaseByNameContext

func (s *Server) DatabaseByNameContext(ctx context.Context, name string) (*Database, error)

DatabaseByNameContext is the context-aware variant of DatabaseByName.

func (*Server) DatabaseFiles added in v0.0.11

func (s *Server) DatabaseFiles(database string) ([]*DatabaseFileInfo, error)

DatabaseFiles returns one database's files read from the server-wide catalog, so it answers for a database in any state.

func (*Server) DatabaseFilesContext added in v0.0.11

func (s *Server) DatabaseFilesContext(ctx context.Context, database string) ([]*DatabaseFileInfo, error)

DatabaseFilesContext is the context-aware variant of DatabaseFiles.

It reads sys.master_files rather than sys.database_files, which is the whole point of it: Database.FilesContext runs its read through a USE, and a database that is OFFLINE, RECOVERY_PENDING or SUSPECT refuses the USE — so the paths become unreadable in exactly the states someone needs them in, such as on the way to a detach. FileGroup is always "" here: sys.filegroups is database-scoped and cannot be joined from the server catalog.

A database the login cannot see reads as no rows rather than an error, the way metadata visibility answers everywhere else.

func (*Server) DatabaseMirroringEndpoint added in v0.0.9

func (s *Server) DatabaseMirroringEndpoint() (*DatabaseMirroringEndpoint, error)

DatabaseMirroringEndpoint returns the instance's database mirroring endpoint, or nil when it has none.

func (*Server) DatabaseMirroringEndpointContext added in v0.0.9

func (s *Server) DatabaseMirroringEndpointContext(ctx context.Context) (*DatabaseMirroringEndpoint, error)

DatabaseMirroringEndpointContext is the context-aware variant of DatabaseMirroringEndpoint.

Returns (nil, nil) when the instance has no such endpoint — a normal state on an instance that has never been put in an availability group, and not an error.

func (*Server) DatabaseRecoveryStatuses added in v0.0.10

func (s *Server) DatabaseRecoveryStatuses() ([]*DatabaseRecoveryStatus, error)

DatabaseRecoveryStatuses returns the log backup chain state of every database on the server.

func (*Server) DatabaseRecoveryStatusesContext added in v0.0.10

func (s *Server) DatabaseRecoveryStatusesContext(ctx context.Context) ([]*DatabaseRecoveryStatus, error)

DatabaseRecoveryStatusesContext is the context-aware variant of DatabaseRecoveryStatuses.

One read for the whole server: the state is wanted per database, but a caller deciding which databases qualify for something needs them all, and sys.database_recovery_status is a server-scoped view.

func (*Server) DatabaseSeq

func (s *Server) DatabaseSeq(ctx context.Context) iter.Seq2[*Database, error]

DatabaseSeq returns an iterator over all databases on the server. The second yield value carries any error that stopped the iteration.

func (*Server) DatabaseSnapshot added in v0.0.13

func (s *Server) DatabaseSnapshot(name string) *DatabaseSnapshot

DatabaseSnapshot returns a lightweight handle to a snapshot by name, without a query. Nothing verifies that it exists and every field but Name stays zero — SourceDatabase included, so Restore refuses on it and the caller must go through Server.RestoreFromSnapshot with both names.

Like Server.Database, it is the form the name-only operations take — Drop, which names the snapshot in the statement and reads nothing else — and the only one that works under a WithScript-derived context, where no lookup can run at all.

func (*Server) DatabaseSnapshotByName added in v0.0.13

func (s *Server) DatabaseSnapshotByName(name string) (*DatabaseSnapshot, error)

DatabaseSnapshotByName returns one snapshot, or a not-found error (errors.Is ErrNotFound) when the server has no snapshot by that name. A database that exists but is not a snapshot is not found either — the predicate is part of what is being asked.

func (*Server) DatabaseSnapshotByNameContext added in v0.0.13

func (s *Server) DatabaseSnapshotByNameContext(ctx context.Context, name string) (*DatabaseSnapshot, error)

DatabaseSnapshotByNameContext is the context-aware variant of DatabaseSnapshotByName.

func (*Server) DatabaseSnapshotSeq added in v0.0.13

func (s *Server) DatabaseSnapshotSeq(ctx context.Context) iter.Seq2[*DatabaseSnapshot, error]

DatabaseSnapshotSeq returns an iterator over every database snapshot on the server.

func (*Server) DatabaseSnapshots added in v0.0.13

func (s *Server) DatabaseSnapshots() ([]*DatabaseSnapshot, error)

DatabaseSnapshots returns every database snapshot on the server.

func (*Server) DatabaseSnapshotsContext added in v0.0.13

func (s *Server) DatabaseSnapshotsContext(ctx context.Context) ([]*DatabaseSnapshot, error)

DatabaseSnapshotsContext is the context-aware variant of DatabaseSnapshots.

func (*Server) Databases

func (s *Server) Databases() ([]*Database, error)

Databases returns all user-accessible databases on the server.

func (*Server) DatabasesContext

func (s *Server) DatabasesContext(ctx context.Context) ([]*Database, error)

DatabasesContext returns all databases, honouring the provided context.

func (*Server) DeleteCategory added in v0.0.6

func (s *Server) DeleteCategory(class CategoryClass, name string) error

DeleteCategory deletes a category via sp_delete_category.

func (*Server) DeleteCategoryContext added in v0.0.6

func (s *Server) DeleteCategoryContext(ctx context.Context, class CategoryClass, name string) error

DeleteCategoryContext is the context-aware variant of DeleteCategory.

func (*Server) DenyServerPermission added in v0.0.4

func (s *Server) DenyServerPermission(permission, principal string) error

DenyServerPermission denies a server-level permission to principal.

func (*Server) DenyServerPermissionContext added in v0.0.4

func (s *Server) DenyServerPermissionContext(ctx context.Context, permission, principal string) error

DenyServerPermissionContext is the context-aware variant of DenyServerPermission. See GrantServerPermissionContext's doc comment for the USE master prefix.

func (*Server) DenyServerPermissionWithOptions added in v0.0.8

func (s *Server) DenyServerPermissionWithOptions(permission, principal string, opts PermissionOptions) error

DenyServerPermissionWithOptions denies a server-level permission to principal, honouring opts.

func (*Server) DenyServerPermissionWithOptionsContext added in v0.0.8

func (s *Server) DenyServerPermissionWithOptionsContext(ctx context.Context, permission, principal string, opts PermissionOptions) error

DenyServerPermissionWithOptionsContext is the context-aware variant of DenyServerPermissionWithOptions. See GrantServerPermissionContext for the USE master prefix.

func (*Server) DetachDatabase added in v0.0.11

func (s *Server) DetachDatabase(name string, opts DetachOptions) error

DetachDatabase detaches the named database from the instance, leaving its files on disk.

func (*Server) DetachDatabaseContext added in v0.0.11

func (s *Server) DetachDatabaseContext(ctx context.Context, name string, opts DetachOptions) error

DetachDatabaseContext is the context-aware variant of DetachDatabase.

The database's files are left where they are — this is not a delete, and AttachDatabaseContext brings the same files back, under this name or another one.

func (*Server) DetachedDatabaseInfo added in v0.0.11

func (s *Server) DetachedDatabaseInfo(primaryFilePath string) (*DetachedDatabase, error)

DetachedDatabaseInfo reads a detached database's name and file list out of its primary data file.

func (*Server) DetachedDatabaseInfoContext added in v0.0.11

func (s *Server) DetachedDatabaseInfoContext(ctx context.Context, primaryFilePath string) (*DetachedDatabase, error)

DetachedDatabaseInfoContext is the context-aware variant of DetachedDatabaseInfo. primaryFilePath is a path on the *server's* host, not the caller's.

This is what makes an Attach dialog more than a list of paths typed by hand: a database's secondary and log files are named only inside its primary file, and SQL Server has no documented way to read them back. The undocumented DBCC CHECKPRIMARYFILE is what SMO — and therefore SSMS — uses, and it needs the rights DBCC needs. A caller that cannot run it can still attach: AttachSpec takes the paths directly.

func (*Server) DiskVolumeSeq added in v0.0.5

func (s *Server) DiskVolumeSeq(ctx context.Context) iter.Seq2[DiskVolumeInfo, error]

DiskVolumeSeq returns an iterator over the server's storage volumes.

func (*Server) DiskVolumes added in v0.0.5

func (s *Server) DiskVolumes() ([]DiskVolumeInfo, error)

DiskVolumes returns free/total space for every storage volume backing a database file on the server.

func (*Server) DiskVolumesContext added in v0.0.5

func (s *Server) DiskVolumesContext(ctx context.Context) ([]DiskVolumeInfo, error)

DiskVolumesContext is the context-aware variant of DiskVolumes.

func (*Server) DropDatabase

func (s *Server) DropDatabase(name string, force bool) error

DropDatabase drops the named database. When force is true, active connections are terminated first — by SET SINGLE_USER WITH ROLLBACK IMMEDIATE, or on a Managed Instance, which refuses that statement, by killing the database's sessions (see killDatabaseSessions).

func (*Server) DropDatabaseContext

func (s *Server) DropDatabaseContext(ctx context.Context, name string, force bool) error

DropDatabaseContext is the context-aware variant of DropDatabase.

func (*Server) DropLogin

func (s *Server) DropLogin(name string) error

DropLogin drops a server login.

func (*Server) DropLoginContext

func (s *Server) DropLoginContext(ctx context.Context, name string) error

DropLoginContext is the context-aware variant of DropLogin.

func (*Server) DropServerRole added in v0.0.9

func (s *Server) DropServerRole(name string) error

DropServerRole drops a user-defined server role. A fixed role, or one that still owns another role, is refused by the server, not here.

func (*Server) DropServerRoleContext added in v0.0.9

func (s *Server) DropServerRoleContext(ctx context.Context, name string) error

DropServerRoleContext is the context-aware variant of DropServerRole.

func (*Server) EffectiveServerPermissionSeq added in v0.0.8

func (s *Server) EffectiveServerPermissionSeq(ctx context.Context, login string) iter.Seq2[*EffectivePermission, error]

EffectiveServerPermissionSeq returns an iterator over every server-level permission login effectively holds.

func (*Server) EffectiveServerPermissions added in v0.0.8

func (s *Server) EffectiveServerPermissions(login string) ([]*EffectivePermission, error)

EffectiveServerPermissions returns every server-level permission login effectively holds — SSMS's Effective tab on a Login Properties > Securables page, with the server row selected.

login must be a *login*. A server role is not accepted, for the same reason a database role isn't (see EffectivePermissions): SQL Server refuses to impersonate one, with Msg 15406, the server-principal wording of the same error. The impersonation is EXECUTE AS LOGIN rather than EXECUTE AS USER, and it needs IMPERSONATE on that login (CONTROL SERVER covers it).

func (*Server) EffectiveServerPermissionsContext added in v0.0.8

func (s *Server) EffectiveServerPermissionsContext(ctx context.Context, login string) ([]*EffectivePermission, error)

EffectiveServerPermissionsContext is the context-aware variant of EffectiveServerPermissions.

func (*Server) EndpointByName added in v0.0.11

func (s *Server) EndpointByName(name string) (*Endpoint, error)

EndpointByName returns one endpoint, or a not-found error (errors.Is ErrNotFound) when the server has none by that name.

func (*Server) EndpointByNameContext added in v0.0.11

func (s *Server) EndpointByNameContext(ctx context.Context, name string) (*Endpoint, error)

EndpointByNameContext is the context-aware variant of EndpointByName.

func (*Server) EndpointSeq added in v0.0.11

func (s *Server) EndpointSeq(ctx context.Context) iter.Seq2[*Endpoint, error]

EndpointSeq returns an iterator over every endpoint on the server.

func (*Server) Endpoints added in v0.0.11

func (s *Server) Endpoints() ([]*Endpoint, error)

Endpoints returns every endpoint on the server, built-in ones included.

func (*Server) EndpointsContext added in v0.0.11

func (s *Server) EndpointsContext(ctx context.Context) ([]*Endpoint, error)

EndpointsContext is the context-aware variant of Endpoints.

func (*Server) EnumErrorLogSeq added in v0.0.9

func (s *Server) EnumErrorLogSeq(ctx context.Context, logType ErrorLogType) iter.Seq2[*ErrorLogFile, error]

EnumErrorLogSeq returns an iterator over the available log files of the given family.

func (*Server) EnumErrorLogs added in v0.0.9

func (s *Server) EnumErrorLogs(logType ErrorLogType) ([]*ErrorLogFile, error)

EnumErrorLogs lists the available log files of the given family.

func (*Server) EnumErrorLogsContext added in v0.0.9

func (s *Server) EnumErrorLogsContext(ctx context.Context, logType ErrorLogType) ([]*ErrorLogFile, error)

EnumErrorLogsContext is the context-aware variant of EnumErrorLogs. Results are ordered by Number, current log first — sp_enumerrorlogs returns the Agent family's current log last, not first.

func (*Server) EnumFileSystem added in v0.0.9

func (s *Server) EnumFileSystem(path string) ([]*FileSystemEntry, error)

EnumFileSystem lists the files and directories directly inside path on the server host.

func (*Server) EnumFileSystemContext added in v0.0.9

func (s *Server) EnumFileSystemContext(ctx context.Context, path string) ([]*FileSystemEntry, error)

EnumFileSystemContext is the context-aware variant of EnumFileSystem.

On SQL Server 2017 and later this reads sys.dm_os_enumerate_filesystem, which reports sizes and timestamps; anything else uses xp_dirtree, which reports names and the file/directory flag only.

The version gate is deliberately positive — the DMV is used only when the instance is *known* to be 2017 or later, and an unknown version (no ServerInfo loaded, or a major of 0) takes xp_dirtree. xp_dirtree exists on every version this library talks to and the DMV does not, so guessing toward the DMV turns an unknown pre-2017 instance into a hard failure, while guessing toward xp_dirtree costs a known-modern one only its Size and LastModified fields. A caller browsing for a path needs the names and the directory flag; it can live without the other two. Degrade, don't fail.

func (*Server) EnumFileSystemIsLegacy added in v0.0.10

func (s *Server) EnumFileSystemIsLegacy() bool

EnumFileSystemIsLegacy reports whether EnumFileSystem will take the xp_dirtree path rather than sys.dm_os_enumerate_filesystem — the same positive version gate EnumFileSystemContext applies, exposed so a caller can reason about what it is about to get.

Two things differ on that path and a caller may need to say so: entries carry no Size or LastModified, and xp_dirtree returns *no rows and no error* to a login that is not sysadmin, which is indistinguishable from an empty directory unless the caller knows which path ran.

func (*Server) EventAlertSeq added in v0.0.6

func (s *Server) EventAlertSeq(ctx context.Context) iter.Seq2[*Alert, error]

EventAlertSeq returns an iterator over the SQL-only-implementable subset of alerts (see Server.EventAlerts).

func (*Server) EventAlerts added in v0.0.6

func (s *Server) EventAlerts() ([]*Alert, error)

EventAlerts returns only plain SQL Server event alerts — the SQL-only implementable subset (see Alert.IsEventAlert). WMI alerts and performance-condition alerts are excluded, since they depend on non-SQL subsystems.

func (*Server) EventAlertsContext added in v0.0.6

func (s *Server) EventAlertsContext(ctx context.Context) ([]*Alert, error)

EventAlertsContext is the context-aware variant of EventAlerts.

func (*Server) FileSystemExists added in v0.0.9

func (s *Server) FileSystemExists(path string) (exists, isDirectory bool, err error)

FileSystemExists reports whether path exists on the server host and whether it is a directory. A path that doesn't exist is not an error: exists is false and err is nil.

func (*Server) FileSystemExistsContext added in v0.0.9

func (s *Server) FileSystemExistsContext(ctx context.Context, path string) (exists, isDirectory bool, err error)

FileSystemExistsContext is the context-aware variant of FileSystemExists.

func (*Server) FixedDrives added in v0.0.9

func (s *Server) FixedDrives() ([]*FixedDrive, error)

FixedDrives returns the fixed drives visible to the SQL Server host.

func (*Server) FixedDrivesContext added in v0.0.9

func (s *Server) FixedDrivesContext(ctx context.Context) ([]*FixedDrive, error)

FixedDrivesContext is the context-aware variant of FixedDrives. It reads sys.dm_os_enumerate_fixed_drives on SQL Server 2019 and later, and falls back to xp_fixeddrives — which reports the drive letter and free megabytes only — on older instances.

The fallback is Windows-only: xp_fixeddrives does not exist on SQL Server on Linux, so a pre-2019 Linux instance returns an error here rather than the single root filesystem FixedDrive documents. That is deliberate rather than unnoticed — a Linux host has no drive list to browse, and goSSMS's file dialog only asks for one when a path walks above a root, which "/"-separated paths never do (PosixPathRules.Parent("/") == "/"). Do not "fix" it by synthesizing a "/" entry; there is no caller that would see it.

func (*Server) GrantServerPermission added in v0.0.4

func (s *Server) GrantServerPermission(permission, principal string) error

GrantServerPermission grants a server-level permission to principal.

func (*Server) GrantServerPermissionContext added in v0.0.4

func (s *Server) GrantServerPermissionContext(ctx context.Context, permission, principal string) error

GrantServerPermissionContext is the context-aware variant of GrantServerPermission.

SQL Server rejects GRANT/DENY/REVOKE at server scope outright unless the session's current database is master ("Permissions at the server scope can only be granted when the current database is master") — its own restriction, not one gosmo imposes — so every statement here is prefixed with USE master in the same batch.

That USE does not leak into whatever borrows the connection next, and the reason is the driver, not this package: USE is session state and would otherwise survive the connection's return to the pool. database/sql calls driver.SessionResetter.ResetSession before handing a pooled connection to its next user, and go-mssqldb implements it by flagging the next TDS batch as a connection reset (Conn.ResetSession -> sendSqlBatch72's resetSession), which restores the session's database to the connection string's.

Verified live 2026-08-01, A/B against a connection opened with Database set: eight pooled connections all still reported that database after a GRANT. Recorded because the shape of this code invites the opposite conclusion — a review that session proposed replacing it with a pinned connection that reads DB_NAME(), switches, and switches back, which is three extra round trips per grant to re-solve what the driver already handles.

func (*Server) GrantServerPermissionWithOptions added in v0.0.8

func (s *Server) GrantServerPermissionWithOptions(permission, principal string, opts PermissionOptions) error

GrantServerPermissionWithOptions grants a server-level permission to principal, honouring opts.

func (*Server) GrantServerPermissionWithOptionsContext added in v0.0.8

func (s *Server) GrantServerPermissionWithOptionsContext(ctx context.Context, permission, principal string, opts PermissionOptions) error

GrantServerPermissionWithOptionsContext is the context-aware variant of GrantServerPermissionWithOptions. See GrantServerPermissionContext for the USE master prefix every server-scoped statement carries.

func (*Server) Info

func (s *Server) Info() *ServerInfo

Info returns cached server metadata (version, edition, paths ...).

func (*Server) InstanceResourceGovernance added in v0.0.12

func (s *Server) InstanceResourceGovernance() (*InstanceResourceGovernance, error)

InstanceResourceGovernance returns the instance's resource-governor limits.

func (*Server) InstanceResourceGovernanceContext added in v0.0.12

func (s *Server) InstanceResourceGovernanceContext(ctx context.Context) (*InstanceResourceGovernance, error)

InstanceResourceGovernanceContext is the context-aware variant of InstanceResourceGovernance.

The view exists only on an Azure engine edition, so this refuses anywhere else with an ErrUnsupportedVersion error rather than letting the server answer with an "invalid object name", and returns ErrNotFound in the (unobserved) case of an empty view.

func (*Server) Job added in v0.0.7

func (s *Server) Job(name string) *Job

Job returns a lightweight handle for a job by name, without querying msdb — the job-side counterpart of Server.Database. JobID, Category, LastRunOutcome and every other cached field stay at their zero value; JobByName is what populates them.

Every write method on *Job builds its statement from Name alone (AddStep, AttachSchedule, Start, Rename, ...), so this handle is enough to keep operating on a job the caller already knows exists — and is the only usable form under a WithScript context, where JobByNameContext's lookup is a real read and a job whose sp_add_job was merely collected is not there to find.

func (*Server) JobByName

func (s *Server) JobByName(name string) (*Job, error)

JobByName returns a single job by name using a direct parameterised query.

func (*Server) JobByNameContext

func (s *Server) JobByNameContext(ctx context.Context, name string) (*Job, error)

JobByNameContext is the context-aware variant of JobByName.

func (*Server) JobHistory added in v0.0.6

func (s *Server) JobHistory(limit int) ([]*JobHistoryEntry, error)

JobHistory returns the most recent job-level history entries (step_id = 0, i.e. the overall outcome of each run rather than a single step's) across every job, most recent first. Pass limit=0 for the default of 100 rows.

func (*Server) JobHistoryContext added in v0.0.6

func (s *Server) JobHistoryContext(ctx context.Context, limit int) ([]*JobHistoryEntry, error)

JobHistoryContext is the context-aware variant of JobHistory.

func (*Server) JobHistorySeq added in v0.0.6

func (s *Server) JobHistorySeq(ctx context.Context, limit int) iter.Seq2[*JobHistoryEntry, error]

JobHistorySeq returns an iterator over the most recent job history entries across every SQL Server Agent job, up to limit.

func (*Server) JobSeq

func (s *Server) JobSeq(ctx context.Context) iter.Seq2[*Job, error]

JobSeq returns an iterator over all SQL Server Agent jobs.

func (*Server) Jobs

func (s *Server) Jobs() ([]*Job, error)

Jobs returns all SQL Server Agent jobs from msdb.

func (*Server) JobsContext

func (s *Server) JobsContext(ctx context.Context) ([]*Job, error)

JobsContext is the context-aware variant of Jobs.

func (*Server) KillSession

func (s *Server) KillSession(sessionID int) error

KillSession terminates a session by session ID.

func (*Server) KillSessionContext

func (s *Server) KillSessionContext(ctx context.Context, sessionID int) error

KillSessionContext is the context-aware variant of KillSession.

func (*Server) LanguageSeq added in v0.0.4

func (s *Server) LanguageSeq(ctx context.Context) iter.Seq2[*Language, error]

LanguageSeq returns an iterator over all languages installed on the server.

func (*Server) Languages added in v0.0.4

func (s *Server) Languages() ([]*Language, error)

Languages returns every language installed on the server.

func (*Server) LanguagesContext added in v0.0.4

func (s *Server) LanguagesContext(ctx context.Context) ([]*Language, error)

LanguagesContext is the context-aware variant of Languages.

func (*Server) LatestServerResourceStats added in v0.0.12

func (s *Server) LatestServerResourceStats() (*ServerResourceStat, error)

LatestServerResourceStats returns the newest sys.server_resource_stats row.

func (*Server) LatestServerResourceStatsContext added in v0.0.12

func (s *Server) LatestServerResourceStatsContext(ctx context.Context) (*ServerResourceStat, error)

LatestServerResourceStatsContext is the context-aware variant of LatestServerResourceStats — the instance's current SKU, core count and storage quota in one row, for a caller that wants the shape rather than the history.

It returns ErrNotFound when the view is empty, which a freshly created instance is until its first 15-second window closes.

func (*Server) LinkedServerSeq added in v0.0.6

func (s *Server) LinkedServerSeq(ctx context.Context) iter.Seq2[*LinkedServer, error]

LinkedServerSeq returns an iterator over all linked servers.

func (*Server) LinkedServers

func (s *Server) LinkedServers() ([]*LinkedServer, error)

LinkedServers returns all linked servers defined on this instance.

func (*Server) LinkedServersContext

func (s *Server) LinkedServersContext(ctx context.Context) ([]*LinkedServer, error)

LinkedServersContext is the context-aware variant of LinkedServers.

func (*Server) Login added in v0.0.5

func (s *Server) Login(name string) *Login

Login returns a lightweight handle for name without querying the server at all — unlike LoginByName/LoginByNameContext, it doesn't verify the login exists or populate SID/LoginType/IsDisabled/etc. (they stay at their zero value). Every write method on *Login (AddServerRoleMemberContext, DisableContext, ChangePasswordContext, ...) only ever needs the login's name, never those cached fields, so this is sufficient for issuing further ALTER-style calls against a login the caller already knows exists — most commonly one it just created in the same operation. See Server.Database's doc comment for why this also matters under a WithScript-derived context.

func (*Server) LoginByName added in v0.0.4

func (s *Server) LoginByName(name string) (*Login, error)

LoginByName returns a single server-level login by name.

func (*Server) LoginByNameContext added in v0.0.4

func (s *Server) LoginByNameContext(ctx context.Context, name string) (*Login, error)

LoginByNameContext is the context-aware variant of LoginByName.

func (*Server) LoginSeq

func (s *Server) LoginSeq(ctx context.Context) iter.Seq2[*Login, error]

LoginSeq returns an iterator over all logins on the server.

func (*Server) Logins

func (s *Server) Logins() ([]*Login, error)

Logins returns all server-level logins.

func (*Server) LoginsContext

func (s *Server) LoginsContext(ctx context.Context) ([]*Login, error)

LoginsContext is the context-aware variant of Logins.

Every server-level login is listed, not just the SQL/Windows ones: the type filter also admits Entra ('E','X') and the certificate- and asymmetric-key-mapped logins ('C','K') that hold permissions for signed code, which is what SSMS's Logins folder shows.

func (*Server) MailProfileSeq added in v0.0.6

func (s *Server) MailProfileSeq(ctx context.Context) iter.Seq2[*MailProfile, error]

MailProfileSeq returns an iterator over all Database Mail profiles.

func (*Server) MailProfiles

func (s *Server) MailProfiles() ([]*MailProfile, error)

MailProfiles returns all Database Mail profiles from msdb.

func (*Server) MailProfilesContext

func (s *Server) MailProfilesContext(ctx context.Context) ([]*MailProfile, error)

MailProfilesContext is the context-aware variant of MailProfiles.

func (*Server) MemoryStats added in v0.0.4

func (s *Server) MemoryStats() (*ServerMemoryStats, error)

MemoryStats returns live server memory figures.

func (*Server) MemoryStatsContext added in v0.0.4

func (s *Server) MemoryStatsContext(ctx context.Context) (*ServerMemoryStats, error)

MemoryStatsContext is the context-aware variant of MemoryStats.

func (*Server) Name

func (s *Server) Name() string

Name returns the SQL Server instance name.

func (*Server) OSJobObject added in v0.0.12

func (s *Server) OSJobObject() (*OSJobObject, error)

OSJobObject returns the job object the engine process runs inside.

func (*Server) OSJobObjectContext added in v0.0.12

func (s *Server) OSJobObjectContext(ctx context.Context) (*OSJobObject, error)

OSJobObjectContext is the context-aware variant of OSJobObject.

The view exists only on an Azure engine edition, so this refuses anywhere else with an ErrUnsupportedVersion error, and returns ErrNotFound when the view is empty — which is what a hosted engine that is not inside a job object reports.

func (*Server) Operator added in v0.0.7

func (s *Server) Operator(name string) *Operator

Operator returns a lightweight handle for an operator by name, without querying msdb — the operator-side counterpart of Server.Database. ID, EmailAddress, Category and every other cached field stay at their zero value; OperatorByName is what populates them.

Every write method on *Operator addresses the operator by name, so this handle is enough to keep operating on an operator the caller already knows exists — and is the only usable form under a WithScript context, where OperatorByNameContext's lookup is a real read and an operator whose sp_add_operator was merely collected is not there to find.

func (*Server) OperatorByName added in v0.0.6

func (s *Server) OperatorByName(name string) (*Operator, error)

OperatorByName returns a single operator by name.

func (*Server) OperatorByNameContext added in v0.0.6

func (s *Server) OperatorByNameContext(ctx context.Context, name string) (*Operator, error)

OperatorByNameContext is the context-aware variant of OperatorByName.

func (*Server) OperatorSeq added in v0.0.6

func (s *Server) OperatorSeq(ctx context.Context) iter.Seq2[*Operator, error]

OperatorSeq returns an iterator over all SQL Server Agent operators.

func (*Server) Operators added in v0.0.6

func (s *Server) Operators() ([]*Operator, error)

Operators returns every SQL Server Agent operator defined on the server.

func (*Server) OperatorsContext added in v0.0.6

func (s *Server) OperatorsContext(ctx context.Context) ([]*Operator, error)

OperatorsContext is the context-aware variant of Operators.

func (*Server) ProcessorInfo added in v0.0.5

func (s *Server) ProcessorInfo() (*ProcessorInfo, error)

ProcessorInfo returns server-wide CPU/NUMA topology.

func (*Server) ProcessorInfoContext added in v0.0.5

func (s *Server) ProcessorInfoContext(ctx context.Context) (*ProcessorInfo, error)

ProcessorInfoContext is the context-aware variant of ProcessorInfo.

func (*Server) ReadErrorLog

func (s *Server) ReadErrorLog(logNumber int) ([]*ErrorLogEntry, error)

ReadErrorLog reads a SQL Server error log file. Pass logNumber=0 for the current log, 1 for the first archived log, etc.

func (*Server) ReadErrorLogContext

func (s *Server) ReadErrorLogContext(ctx context.Context, logNumber int) ([]*ErrorLogEntry, error)

ReadErrorLogContext is the context-aware variant of ReadErrorLog. It is ReadLogContext fixed to the SQL Server log family.

func (*Server) ReadErrorLogSeq added in v0.0.6

func (s *Server) ReadErrorLogSeq(ctx context.Context, logNumber int) iter.Seq2[*ErrorLogEntry, error]

ReadErrorLogSeq returns an iterator over the lines of the given SQL Server error log (0 = current, 1 = Errorlog.1, …).

func (*Server) ReadLog added in v0.0.9

func (s *Server) ReadLog(logType ErrorLogType, logNumber int) ([]*ErrorLogEntry, error)

ReadLog reads one log file of the given family. Pass logNumber=0 for the current log, 1 for the first archived log, etc.

func (*Server) ReadLogContext added in v0.0.9

func (s *Server) ReadLogContext(ctx context.Context, logType ErrorLogType, logNumber int) ([]*ErrorLogEntry, error)

ReadLogContext is the context-aware variant of ReadLog. Which of an entry's Process and ErrorLevel is populated follows logType — see ErrorLogEntry.

func (*Server) ReadLogFiltered added in v0.0.10

func (s *Server) ReadLogFiltered(logType ErrorLogType, logNumber int, search LogSearch) ([]*ErrorLogEntry, error)

ReadLogFiltered reads one log file of the given family, keeping only the entries the search matches.

func (*Server) ReadLogFilteredContext added in v0.0.10

func (s *Server) ReadLogFilteredContext(ctx context.Context, logType ErrorLogType, logNumber int, search LogSearch) ([]*ErrorLogEntry, error)

ReadLogFilteredContext is the context-aware variant of ReadLogFiltered, and carries the read every other method here delegates to.

func (*Server) ReadLogSeq added in v0.0.9

func (s *Server) ReadLogSeq(ctx context.Context, logType ErrorLogType, logNumber int) iter.Seq2[*ErrorLogEntry, error]

ReadLogSeq returns an iterator over the lines of the given log file of the given family (0 = current, 1 = the first archive, …).

func (*Server) Reconfigure

func (s *Server) Reconfigure(override bool) error

Reconfigure applies pending sp_configure changes. Pass override=true to use RECONFIGURE WITH OVERRIDE (bypasses range checks).

func (*Server) ReconfigureContext

func (s *Server) ReconfigureContext(ctx context.Context, override bool) error

ReconfigureContext is the context-aware variant of Reconfigure.

func (*Server) RemoveServerRoleMember added in v0.0.6

func (s *Server) RemoveServerRoleMember(roleName, memberName string) error

RemoveServerRoleMember removes member from a server role.

func (*Server) RemoveServerRoleMemberContext added in v0.0.6

func (s *Server) RemoveServerRoleMemberContext(ctx context.Context, roleName, memberName string) error

RemoveServerRoleMemberContext is the context-aware variant of RemoveServerRoleMember.

func (*Server) RenameDatabase added in v0.0.9

func (s *Server) RenameDatabase(oldName, newName string, force bool) error

RenameDatabase renames a database (ALTER DATABASE ... MODIFY NAME). The server needs exclusive access to it, so any other connection to the database fails the statement outright rather than waiting.

When force is true the database is put into SINGLE_USER WITH ROLLBACK IMMEDIATE first — terminating those connections and rolling back their transactions — and back to MULTI_USER afterwards, including when the rename itself fails, so a refused rename never leaves the database single-user. A Managed Instance refuses SET SINGLE_USER, so there force kills the database's sessions instead and changes no access mode.

func (*Server) RenameDatabaseContext added in v0.0.9

func (s *Server) RenameDatabaseContext(ctx context.Context, oldName, newName string, force bool) error

RenameDatabaseContext is the context-aware variant of RenameDatabase.

func (*Server) Restore

func (s *Server) Restore(opts RestoreOptions) error

Restore performs a RESTORE DATABASE (or LOG) operation.

func (*Server) RestoreContext

func (s *Server) RestoreContext(ctx context.Context, opts RestoreOptions) error

RestoreContext is the context-aware variant of Restore.

func (*Server) RestoreFromSnapshot added in v0.0.13

func (s *Server) RestoreFromSnapshot(database, snapshot string) error

RestoreFromSnapshot reverts a database to one of its snapshots.

func (*Server) RestoreFromSnapshotContext added in v0.0.13

func (s *Server) RestoreFromSnapshotContext(ctx context.Context, database, snapshot string) error

RestoreFromSnapshotContext is the context-aware variant of RestoreFromSnapshot.

The server refuses the revert unless the source has exactly one snapshot — every other snapshot of the same database has to be dropped first — and unless nobody else is connected to either database. Both are the server's checks, reported as its error; gosmo does not pre-empt them, because either could change between a check here and the statement.

The snapshot is named as a *string literal*, not an identifier: the FROM DATABASE_SNAPSHOT clause takes a name, not a bracketed reference.

func (*Server) RevokeServerPermission added in v0.0.4

func (s *Server) RevokeServerPermission(permission, principal string) error

RevokeServerPermission revokes a server-level permission from principal.

func (*Server) RevokeServerPermissionContext added in v0.0.4

func (s *Server) RevokeServerPermissionContext(ctx context.Context, permission, principal string) error

RevokeServerPermissionContext is the context-aware variant of RevokeServerPermission. See GrantServerPermissionContext's doc comment for the USE master prefix.

func (*Server) RevokeServerPermissionWithOptions added in v0.0.8

func (s *Server) RevokeServerPermissionWithOptions(permission, principal string, opts PermissionOptions) error

RevokeServerPermissionWithOptions revokes a server-level permission from principal, honouring opts.

func (*Server) RevokeServerPermissionWithOptionsContext added in v0.0.8

func (s *Server) RevokeServerPermissionWithOptionsContext(ctx context.Context, permission, principal string, opts PermissionOptions) error

RevokeServerPermissionWithOptionsContext is the context-aware variant of RevokeServerPermissionWithOptions. See GrantServerPermissionContext for the USE master prefix.

func (*Server) Schedule added in v0.0.7

func (s *Server) Schedule(name string) *Schedule

Schedule returns a lightweight handle for a shared schedule by name, without querying msdb — the schedule-side counterpart of Server.Database. ID, FreqType, ActiveStartDate and every other cached field stay at their zero value; ScheduleByName is what populates them.

Every write method on *Schedule that addresses the schedule by name (Job.AttachSchedule/DetachSchedule take the name directly) works from this handle, which makes it the only usable form under a WithScript context: ScheduleByNameContext's lookup is a real read, so a schedule whose sp_add_schedule was merely collected is not there to find.

func (*Server) ScheduleByName added in v0.0.6

func (s *Server) ScheduleByName(name string) (*Schedule, error)

ScheduleByName returns a single schedule by name.

func (*Server) ScheduleByNameContext added in v0.0.6

func (s *Server) ScheduleByNameContext(ctx context.Context, name string) (*Schedule, error)

ScheduleByNameContext is the context-aware variant of ScheduleByName.

func (*Server) ScheduleSeq added in v0.0.6

func (s *Server) ScheduleSeq(ctx context.Context) iter.Seq2[*Schedule, error]

ScheduleSeq returns an iterator over all SQL Server Agent schedules.

func (*Server) Schedules added in v0.0.6

func (s *Server) Schedules() ([]*Schedule, error)

Schedules returns every SQL Server Agent schedule defined on the server.

func (*Server) SchedulesContext added in v0.0.6

func (s *Server) SchedulesContext(ctx context.Context) ([]*Schedule, error)

SchedulesContext is the context-aware variant of Schedules.

func (*Server) SecurityInfo added in v0.0.4

func (s *Server) SecurityInfo() (*ServerSecurityInfo, error)

SecurityInfo returns server-wide authentication settings.

func (*Server) SecurityInfoContext added in v0.0.4

func (s *Server) SecurityInfoContext(ctx context.Context) (*ServerSecurityInfo, error)

SecurityInfoContext is the context-aware variant of SecurityInfo.

func (*Server) SendMail

func (s *Server) SendMail(profile, recipients, subject, body string) error

SendMail sends an email via Database Mail (sp_send_dbmail).

func (*Server) SendMailContext

func (s *Server) SendMailContext(ctx context.Context, profile, recipients, subject, body string) error

SendMailContext is the context-aware variant of SendMail.

func (*Server) ServerAudit added in v0.0.11

func (s *Server) ServerAudit(name string) *ServerAudit

ServerAudit returns a lightweight handle for a server audit by name, without querying sys.server_audits — the audit-side counterpart of Server.Database. Every cached field stays at its zero value; ServerAuditByName is what populates them.

Every write method addresses the audit by name, so this handle is enough to go on operating on one the caller already knows exists.

func (*Server) ServerAuditByName added in v0.0.11

func (s *Server) ServerAuditByName(name string) (*ServerAudit, error)

ServerAuditByName returns one server audit with every field populated, or a not-found error (errors.Is ErrNotFound) when the server has none by that name.

func (*Server) ServerAuditByNameContext added in v0.0.11

func (s *Server) ServerAuditByNameContext(ctx context.Context, name string) (*ServerAudit, error)

ServerAuditByNameContext is the context-aware variant of ServerAuditByName.

func (*Server) ServerAuditSeq added in v0.0.11

func (s *Server) ServerAuditSeq(ctx context.Context) iter.Seq2[*ServerAudit, error]

ServerAuditSeq returns an iterator over every server audit.

func (*Server) ServerAuditSpecification added in v0.0.11

func (s *Server) ServerAuditSpecification(name string) *ServerAuditSpecification

ServerAuditSpecification returns a lightweight handle by name, without querying the catalog — the counterpart of Server.Database. Every cached field stays at its zero value; ServerAuditSpecificationByName populates them.

func (*Server) ServerAuditSpecificationByName added in v0.0.11

func (s *Server) ServerAuditSpecificationByName(name string) (*ServerAuditSpecification, error)

ServerAuditSpecificationByName returns one specification with every field populated, or a not-found error (errors.Is ErrNotFound).

func (*Server) ServerAuditSpecificationByNameContext added in v0.0.11

func (s *Server) ServerAuditSpecificationByNameContext(ctx context.Context, name string) (*ServerAuditSpecification, error)

ServerAuditSpecificationByNameContext is the context-aware variant of ServerAuditSpecificationByName.

func (*Server) ServerAuditSpecificationSeq added in v0.0.11

func (s *Server) ServerAuditSpecificationSeq(ctx context.Context) iter.Seq2[*ServerAuditSpecification, error]

ServerAuditSpecificationSeq returns an iterator over every server audit specification.

func (*Server) ServerAuditSpecifications added in v0.0.11

func (s *Server) ServerAuditSpecifications() ([]*ServerAuditSpecification, error)

ServerAuditSpecifications returns every server audit specification.

func (*Server) ServerAuditSpecificationsContext added in v0.0.11

func (s *Server) ServerAuditSpecificationsContext(ctx context.Context) ([]*ServerAuditSpecification, error)

ServerAuditSpecificationsContext is the context-aware variant of ServerAuditSpecifications.

func (*Server) ServerAudits added in v0.0.11

func (s *Server) ServerAudits() ([]*ServerAudit, error)

ServerAudits returns every server audit.

func (*Server) ServerAuditsContext added in v0.0.11

func (s *Server) ServerAuditsContext(ctx context.Context) ([]*ServerAudit, error)

ServerAuditsContext is the context-aware variant of ServerAudits.

func (*Server) ServerPermissionSeq added in v0.0.4

func (s *Server) ServerPermissionSeq(ctx context.Context) iter.Seq2[*ServerPermissionEntry, error]

ServerPermissionSeq returns an iterator over all server-level GRANT/DENY entries.

func (*Server) ServerPermissions added in v0.0.4

func (s *Server) ServerPermissions() ([]*ServerPermissionEntry, error)

ServerPermissions returns every server-level GRANT/DENY entry.

func (*Server) ServerPermissionsContext added in v0.0.4

func (s *Server) ServerPermissionsContext(ctx context.Context) ([]*ServerPermissionEntry, error)

ServerPermissionsContext is the context-aware variant of ServerPermissions.

func (*Server) ServerResourceStats added in v0.0.12

func (s *Server) ServerResourceStats(max int) ([]*ServerResourceStat, error)

ServerResourceStats returns the most recent max rows of sys.server_resource_stats, oldest first.

func (*Server) ServerResourceStatsContext added in v0.0.12

func (s *Server) ServerResourceStatsContext(ctx context.Context, max int) ([]*ServerResourceStat, error)

ServerResourceStatsContext is the context-aware variant of ServerResourceStats. max caps how far back the read reaches; a max of 0 or less means the whole retained history.

The view exists only on an Azure engine edition, so this refuses anywhere else with an ErrUnsupportedVersion error rather than letting the server answer with an "invalid object name".

func (*Server) ServerRoleByName added in v0.0.6

func (s *Server) ServerRoleByName(name string) (*ServerRole, error)

ServerRoleByName returns a single server role by name, with its principal detail (SID, create/modify dates) filled in — ServerRolesContext leaves these out since Object Explorer's tree listing never needs them.

func (*Server) ServerRoleByNameContext added in v0.0.6

func (s *Server) ServerRoleByNameContext(ctx context.Context, name string) (*ServerRole, error)

ServerRoleByNameContext is the context-aware variant of ServerRoleByName.

func (*Server) ServerRoleMemberSeq added in v0.0.6

func (s *Server) ServerRoleMemberSeq(ctx context.Context, roleName string) iter.Seq2[*RoleMember, error]

ServerRoleMemberSeq returns an iterator over a server role's members.

func (*Server) ServerRoleMembers added in v0.0.6

func (s *Server) ServerRoleMembers(roleName string) ([]*RoleMember, error)

ServerRoleMembers returns the direct members of a server role (logins or other server roles), with each member's principal type — ServerRolesContext/ServerRoleByNameContext only return member names, concatenated, with no type.

func (*Server) ServerRoleMembersContext added in v0.0.6

func (s *Server) ServerRoleMembersContext(ctx context.Context, roleName string) ([]*RoleMember, error)

ServerRoleMembersContext is the context-aware variant of ServerRoleMembers.

func (*Server) ServerRoleSeq added in v0.0.6

func (s *Server) ServerRoleSeq(ctx context.Context) iter.Seq2[*ServerRole, error]

ServerRoleSeq returns an iterator over all server-level roles.

func (*Server) ServerRoles

func (s *Server) ServerRoles() ([]*ServerRole, error)

ServerRoles returns all fixed and user-defined server roles.

func (*Server) ServerRolesContext

func (s *Server) ServerRolesContext(ctx context.Context) ([]*ServerRole, error)

ServerRolesContext is the context-aware variant of ServerRoles.

func (*Server) ServerTrigger added in v0.0.11

func (s *Server) ServerTrigger(name string) *ServerTrigger

ServerTrigger returns a lightweight handle for a server trigger by name, without querying sys.server_triggers — the counterpart of Server.Database. Every other field stays at its zero value; ServerTriggerByName is what populates them.

EnableContext, DisableContext and DropContext address the trigger by name, so this handle is enough to act on one the caller already knows exists, and is the only usable form under a WithScript context, where ServerTriggerByNameContext's lookup is a real read.

func (*Server) ServerTriggerByName added in v0.0.11

func (s *Server) ServerTriggerByName(name string) (*ServerTrigger, error)

ServerTriggerByName returns one server trigger with every field populated, or a not-found error (errors.Is ErrNotFound) when the server has none by that name.

func (*Server) ServerTriggerByNameContext added in v0.0.11

func (s *Server) ServerTriggerByNameContext(ctx context.Context, name string) (*ServerTrigger, error)

ServerTriggerByNameContext is the context-aware variant of ServerTriggerByName.

func (*Server) ServerTriggerSeq added in v0.0.11

func (s *Server) ServerTriggerSeq(ctx context.Context) iter.Seq2[*ServerTrigger, error]

ServerTriggerSeq returns an iterator over all server-scope DDL and logon triggers.

func (*Server) ServerTriggers added in v0.0.11

func (s *Server) ServerTriggers() ([]*ServerTrigger, error)

ServerTriggers returns every server-scope DDL or logon trigger.

func (*Server) ServerTriggersContext added in v0.0.11

func (s *Server) ServerTriggersContext(ctx context.Context) ([]*ServerTrigger, error)

ServerTriggersContext is the context-aware variant of ServerTriggers.

func (*Server) SnapshotFileDefaults added in v0.0.13

func (s *Server) SnapshotFileDefaults(source, snapshotName string) ([]SnapshotFileSpec, error)

SnapshotFileDefaults returns one SnapshotFileSpec per data file of the source database, with each sparse file placed beside the source file it shadows and suffixed with the snapshot name.

func (*Server) SnapshotFileDefaultsContext added in v0.0.13

func (s *Server) SnapshotFileDefaultsContext(ctx context.Context, source, snapshotName string) ([]SnapshotFileSpec, error)

SnapshotFileDefaultsContext is the context-aware variant of SnapshotFileDefaults.

Only ROWS files are returned. A snapshot has no transaction log and no FILESTREAM container, and naming either in the CREATE DATABASE is an error — "the file … cannot be added to a database snapshot" — which is the usual way a hand-built snapshot statement fails.

func (*Server) SnapshotsOf added in v0.0.13

func (s *Server) SnapshotsOf(database string) ([]*DatabaseSnapshot, error)

SnapshotsOf returns the snapshots taken of one source database.

func (*Server) SnapshotsOfContext added in v0.0.13

func (s *Server) SnapshotsOfContext(ctx context.Context, database string) ([]*DatabaseSnapshot, error)

SnapshotsOfContext is the context-aware variant of SnapshotsOf.

func (*Server) UserDBResourceGovernance added in v0.0.13

func (s *Server) UserDBResourceGovernance() ([]*UserDBResourceGovernance, error)

UserDBResourceGovernance returns one row per database on the instance.

func (*Server) UserDBResourceGovernanceContext added in v0.0.13

func (s *Server) UserDBResourceGovernanceContext(ctx context.Context) ([]*UserDBResourceGovernance, error)

UserDBResourceGovernanceContext is the context-aware variant of UserDBResourceGovernance, ordered by database name.

The view exists only on an Azure engine edition, so this refuses anywhere else with an ErrUnsupportedVersion error rather than letting the server answer with an "invalid object name". It lists the system databases the instance governs (master, model, model_msdb, model_replicatedmaster) alongside the user ones, because the view does.

func (*Server) UserDBResourceGovernanceSeq added in v0.0.13

func (s *Server) UserDBResourceGovernanceSeq(ctx context.Context) iter.Seq2[*UserDBResourceGovernance, error]

UserDBResourceGovernanceSeq returns an iterator over the resource-governor limits for every database on an Azure instance, one row per database.

There is deliberately no iterator for ServerResourceStats or Database.ResourceStats: both take a row cap, which an iterator built from ctx alone has nowhere to carry.

func (*Server) VerifyBackup added in v0.0.5

func (s *Server) VerifyBackup(device string) error

VerifyBackup checks that the backup set on device is complete and readable (RESTORE VERIFYONLY), without restoring it. device is a path on the server's filesystem; VerifyBackupFrom takes a logical backup device.

func (*Server) VerifyBackupContext added in v0.0.5

func (s *Server) VerifyBackupContext(ctx context.Context, device string) error

VerifyBackupContext is the context-aware variant of VerifyBackup.

func (*Server) VerifyBackupFrom added in v0.0.11

func (s *Server) VerifyBackupFrom(target BackupTarget) error

VerifyBackupFrom is VerifyBackup for any BackupTarget — a path or a logical backup device.

func (*Server) VerifyBackupFromContext added in v0.0.11

func (s *Server) VerifyBackupFromContext(ctx context.Context, target BackupTarget) error

VerifyBackupFromContext is the context-aware variant of VerifyBackupFrom.

type ServerAudit added in v0.0.11

type ServerAudit struct {
	AuditID    int
	Name       string
	GUID       string
	Type       string // AuditToFile, AuditToApplicationLog, AuditToSecurityLog
	OnFailure  string // AuditFailureContinue, AuditFailureShutdown, AuditFailureFailOp
	QueueDelay int    // milliseconds; 0 means write synchronously
	Predicate  string // the WHERE filter, empty when the audit has none
	IsEnabled  bool
	CreateDate time.Time
	ModifyDate time.Time

	// The file-target block, all zero for a non-FILE audit — those have no
	// row in sys.server_file_audits at all, which is why the read below
	// joins to it rather than selecting from it.
	LogFilePath      string
	LogFileName      string
	MaxFileSize      int64 // MB; 0 is UNLIMITED
	MaxRolloverFiles int   // AuditUnlimited is UNLIMITED
	MaxFiles         int   // 0 unless MAX_FILES was used instead of rollover
	ReserveDiskSpace bool
	// contains filtered or unexported fields
}

ServerAudit mirrors a row of sys.server_audits, with the file-target block from sys.server_file_audits where there is one.

func (*ServerAudit) Alter added in v0.0.11

func (a *ServerAudit) Alter(spec ServerAuditSpec) error

Alter changes the audit's settings.

func (*ServerAudit) AlterContext added in v0.0.11

func (a *ServerAudit) AlterContext(ctx context.Context, spec ServerAuditSpec) error

AlterContext is the context-aware variant of Alter. The audit is disabled for the duration and restored afterwards — see withAuditDisabled.

Renaming is not part of this: ALTER SERVER AUDIT ... MODIFY NAME is a statement of its own and cannot be combined with any other clause, so it is Rename's job.

func (*ServerAudit) Drop added in v0.0.11

func (a *ServerAudit) Drop() error

Drop deletes the audit.

func (*ServerAudit) DropContext added in v0.0.11

func (a *ServerAudit) DropContext(ctx context.Context) error

DropContext is the context-aware variant of Drop. An enabled audit is disabled first; there is nothing to restore afterwards.

func (*ServerAudit) Rename added in v0.0.11

func (a *ServerAudit) Rename(newName string) error

Rename changes the audit's name.

func (*ServerAudit) RenameContext added in v0.0.11

func (a *ServerAudit) RenameContext(ctx context.Context, newName string) error

RenameContext is the context-aware variant of Rename.

This is the one write that cannot use withAuditDisabled: the wrapper restores the state through the receiver's name, and MODIFY NAME has changed what that name has to be. The restore is therefore spelled out here, addressed to newName on the path where the rename committed and to the old name on the path where it did not.

func (*ServerAudit) SetState added in v0.0.11

func (a *ServerAudit) SetState(on bool) error

SetState enables or disables the audit.

func (*ServerAudit) SetStateContext added in v0.0.11

func (a *ServerAudit) SetStateContext(ctx context.Context, on bool) error

SetStateContext is the context-aware variant of SetState. This is the one ALTER SERVER AUDIT form the server accepts on an enabled audit.

func (*ServerAudit) Status added in v0.0.11

func (a *ServerAudit) Status() (*ServerAuditStatus, error)

Status returns the audit's runtime state.

func (*ServerAudit) StatusContext added in v0.0.11

func (a *ServerAudit) StatusContext(ctx context.Context) (*ServerAuditStatus, error)

StatusContext is the context-aware variant of Status.

This is a separate read rather than more columns on ServerAudits because sys.dm_server_audit_status needs VIEW SERVER STATE: folded into the list query it would fail the whole folder for a login that can see the audits but not the DMV. An audit that has never been started has no row there and returns a not-found error.

func (*ServerAudit) WithDisabled added in v0.0.11

func (a *ServerAudit) WithDisabled(ctx context.Context, fn func(context.Context) error) error

WithDisabled runs fn with the audit disabled, restoring the state afterwards. Every write method already does this for itself, so a caller needs WithDisabled only to make several of them share one window: auditing then stops once for the whole batch instead of once per statement, and a failure part-way through cannot leave the audit off.

fn must use the context it is handed — that is what the nested writes read to know the window is already open.

type ServerAuditSpec added in v0.0.11

type ServerAuditSpec struct {
	Name string

	// Type is the destination: AuditToFile, AuditToApplicationLog or
	// AuditToSecurityLog. Empty on an alter leaves the destination alone.
	Type string

	// QueueDelay is the write delay in milliseconds; 0 means synchronous.
	QueueDelay int

	// OnFailure is one of the AuditFailure* constants. Empty defaults to
	// CONTINUE on a create and leaves it alone on an alter.
	OnFailure string

	// Predicate is the WHERE filter without the keyword. On an alter, empty
	// means REMOVE WHERE — there is no form that leaves an existing
	// predicate alone while changing something else, so the caller must
	// carry the current one forward.
	Predicate string

	// The file-target block, used only when Type is AuditToFile.
	FilePath         string
	MaxFileSize      int64 // MB; 0 is UNLIMITED
	MaxRolloverFiles int   // AuditUnlimited, or 0 when MaxFiles is used
	MaxFiles         int   // mutually exclusive with MaxRolloverFiles
	ReserveDiskSpace bool
}

ServerAuditSpec describes a server audit to create or alter.

type ServerAuditSpecification added in v0.0.11

type ServerAuditSpecification struct {
	SpecificationID int
	Name            string
	AuditGUID       string

	// AuditName is the audit this specification writes to, resolved through
	// sys.server_audits. It is empty for an orphaned specification: dropping
	// an audit a specification still references succeeds and leaves the
	// audit_guid pointing at nothing, which is why the read below joins with
	// a LEFT JOIN.
	AuditName string

	IsEnabled  bool
	CreateDate time.Time
	ModifyDate time.Time

	// ActionGroups are the audit action groups the specification records, in
	// name order.
	ActionGroups []string
	// contains filtered or unexported fields
}

ServerAuditSpecification mirrors a row of sys.server_audit_specifications.

func (*ServerAuditSpecification) AddActionGroups added in v0.0.11

func (spec *ServerAuditSpecification) AddActionGroups(groups ...string) error

AddActionGroups adds audit action groups to the specification.

func (*ServerAuditSpecification) AddActionGroupsContext added in v0.0.11

func (spec *ServerAuditSpecification) AddActionGroupsContext(ctx context.Context, groups ...string) error

AddActionGroupsContext is the context-aware variant of AddActionGroups. The specification is disabled for the duration and restored afterwards.

func (*ServerAuditSpecification) Drop added in v0.0.11

func (spec *ServerAuditSpecification) Drop() error

Drop deletes the specification.

func (*ServerAuditSpecification) DropActionGroups added in v0.0.11

func (spec *ServerAuditSpecification) DropActionGroups(groups ...string) error

DropActionGroups removes audit action groups from the specification.

func (*ServerAuditSpecification) DropActionGroupsContext added in v0.0.11

func (spec *ServerAuditSpecification) DropActionGroupsContext(ctx context.Context, groups ...string) error

DropActionGroupsContext is the context-aware variant of DropActionGroups.

func (*ServerAuditSpecification) DropContext added in v0.0.11

func (spec *ServerAuditSpecification) DropContext(ctx context.Context) error

DropContext is the context-aware variant of Drop. An enabled specification is disabled first; there is nothing to restore afterwards.

func (*ServerAuditSpecification) SetAudit added in v0.0.11

func (spec *ServerAuditSpecification) SetAudit(auditName string) error

SetAudit rebinds the specification to a different server audit.

func (*ServerAuditSpecification) SetAuditContext added in v0.0.11

func (spec *ServerAuditSpecification) SetAuditContext(ctx context.Context, auditName string) error

SetAuditContext is the context-aware variant of SetAudit. The specification is disabled for the duration and restored afterwards.

func (*ServerAuditSpecification) SetState added in v0.0.11

func (spec *ServerAuditSpecification) SetState(on bool) error

SetState enables or disables the specification.

func (*ServerAuditSpecification) SetStateContext added in v0.0.11

func (spec *ServerAuditSpecification) SetStateContext(ctx context.Context, on bool) error

SetStateContext is the context-aware variant of SetState. This is the one ALTER form the server accepts on an enabled specification.

func (*ServerAuditSpecification) WithDisabled added in v0.0.11

func (spec *ServerAuditSpecification) WithDisabled(ctx context.Context, fn func(context.Context) error) error

WithDisabled runs fn with the specification disabled, restoring the state afterwards. Every write method already does this for itself, so a caller needs WithDisabled only to make several of them share one window: recording then stops once for the whole batch instead of once per statement, and a failure part-way through cannot leave the specification off.

fn must use the context it is handed — that is what the nested writes read to know the window is already open.

type ServerAuditSpecificationSpec added in v0.0.11

type ServerAuditSpecificationSpec struct {
	Name string

	// AuditName is the server audit the specification writes to. Required.
	AuditName string

	// ActionGroups are the groups to record. A specification with none is
	// legal and records nothing.
	ActionGroups []string

	// Enabled creates the specification with STATE = ON.
	Enabled bool
}

ServerAuditSpecificationSpec describes a specification to create.

type ServerAuditStatus added in v0.0.11

type ServerAuditStatus struct {
	Status        string // STARTED / STOPPED
	StatusTime    time.Time
	AuditFilePath string // the file currently being written, empty for a log target
	AuditFileSize int64
}

ServerAuditStatus is an audit's runtime state, from sys.dm_server_audit_status.

type ServerInfo

type ServerInfo struct {
	Name           string
	Edition        string
	ProductVersion string
	ProductLevel   string
	VersionMajor   int
	VersionMinor   int
	VersionBuild   int
	Collation      string
	IsClustered    bool
	IsHADREnabled  bool
	IsSingleUser   bool
	// EngineEdition is SERVERPROPERTY('EngineEdition'). Compare it against
	// the Engine* constants; ServerInfo.IsAzure is the test every version
	// gate wants, since an Azure edition's ProductVersion says nothing about
	// what the instance can do.
	EngineEdition int
	// OSVersion is @@VERSION verbatim: the multi-line SQL Server product
	// banner, whose last line names the host OS. Despite the name it is not
	// an OS version string, and it is unfit for a fixed-width label/value row
	// — the first line alone is longer than most. Platform is the parsed OS
	// family. A real OS string would be a new field, never a change of
	// meaning here.
	OSVersion string
	// Platform is the host operating system family — "Windows" or "Linux",
	// or "Azure" for an Azure edition, whose banner names no host OS and
	// whose host is not the caller's to see. Derived from @@VERSION rather
	// than sys.dm_os_host_info so it is populated on pre-2017 instances too.
	// Empty if @@VERSION names none of the three.
	Platform       string
	MaxConnections int

	// PhysicalMemoryMB and LogicalCPUCount come from sys.dm_os_sys_info and
	// are zero when SysInfoUnavailable is set. Read that flag before showing
	// either: zero there means "not readable", not "none".
	PhysicalMemoryMB int64
	LogicalCPUCount  int

	// SysInfoUnavailable reports that sys.dm_os_sys_info could not be read,
	// leaving PhysicalMemoryMB and LogicalCPUCount at zero. The usual cause
	// is a login without VIEW SERVER STATE (VIEW SERVER PERFORMANCE STATE on
	// SQL Server 2022 and later), which every other field here survives — a
	// db_owner with no server-level rights connects fine and gets everything
	// but these two.
	SysInfoUnavailable bool

	DefaultDataPath   string
	DefaultLogPath    string
	DefaultBackupPath string
}

ServerInfo holds basic information about the connected SQL Server instance.

func (*ServerInfo) IsAzure added in v0.0.12

func (i *ServerInfo) IsAzure() bool

IsAzure reports whether the connected instance is one of the Azure-hosted engine editions — SQL Database, Managed Instance, Synapse, SQL Edge. On those, VersionMajor is a fixed number Azure returns for compatibility (12 on a Managed Instance) and is not the feature level; read it for display only.

type ServerMemoryStats added in v0.0.4

type ServerMemoryStats struct {
	PhysicalMemoryMB     int64
	AvailableMemoryMB    int64
	TargetServerMemoryMB int64
	TotalServerMemoryMB  int64
}

ServerMemoryStats holds live memory figures for the Server Properties > Memory page's "Current values" section — unlike the configured min/max server memory (an sp_configure option, see ConfigurationOption), these reflect the server's actual memory state right now.

type ServerPermissionEntry added in v0.0.4

type ServerPermissionEntry struct {
	Principal     string
	PrincipalType string // e.g. "SQL_LOGIN", "SERVER_ROLE"
	Grantor       string
	Permission    string // e.g. "CONNECT SQL", "ALTER ANY LOGIN", "CONTROL SERVER"
	State         string // "GRANT", "GRANT_WITH_GRANT_OPTION", "DENY"
}

ServerPermissionEntry is one GRANT/DENY entry recorded at server scope, as reported by sys.server_permissions — SSMS's Server Properties > Permissions page and a Login's Securables page.

type ServerResourceStat added in v0.0.12

type ServerResourceStat struct {
	StartTime time.Time
	EndTime   time.Time
	// ResourceType is "SQL managed instance"; ResourceName is the instance's
	// short name, e.g. "t-qmi-01".
	ResourceType string
	ResourceName string
	// SKU is the service tier ("GeneralPurpose", "BusinessCritical"), and
	// HardwareGeneration the compute generation ("Gen5").
	SKU                string
	HardwareGeneration string
	VirtualCoreCount   int
	AvgCPUPercent      float64
	// ReservedStorageMB is the storage the instance is provisioned for and
	// StorageSpaceUsedMB what it has used — the pair that actually governs a
	// Managed Instance, and the one to display in place of
	// sys.dm_os_volume_stats, whose total_bytes there is the container's
	// 192 MB system volume rather than the instance's quota.
	ReservedStorageMB  int64
	StorageSpaceUsedMB float64
	IORequests         int64
	IOBytesRead        int64
	IOBytesWritten     int64
}

ServerResourceStat is one row of sys.server_resource_stats: an Azure SQL Managed Instance's own resource accounting for a fixed 15-second window.

Retention is documented as ~14 days but is not what a live instance holds: t-qmi-01 on 2026-09-09 had 927 rows over three days with two multi-hour holes in them. The 15-second cadence is exact *within* a run, so a caller must plot against EndTime and must not assume row n follows row n-1 by 15 seconds.

It is a pre-aggregated history, not a counter to be sampled — every value is already an average or a total over [StartTime, EndTime), so a caller plots it directly and must not run it through a per-second delta.

SKU, HardwareGeneration, VirtualCoreCount, ReservedStorageMB and StorageSpaceUsedMB repeat on every row; the newest row is the instance's current shape, which is what LatestServerResourceStats returns.

type ServerRole

type ServerRole struct {
	Name        string
	ID          int
	IsFixedRole bool
	Owner       string
	Members     []string
	SID         []byte
	CreateDate  time.Time
	ModifyDate  time.Time
	// contains filtered or unexported fields
}

ServerRole represents a server-level role.

func (*ServerRole) ChangeOwner added in v0.0.6

func (r *ServerRole) ChangeOwner(newOwner string) error

ChangeOwner transfers ownership of the server role to a new principal.

func (*ServerRole) ChangeOwnerContext added in v0.0.6

func (r *ServerRole) ChangeOwnerContext(ctx context.Context, newOwner string) error

ChangeOwnerContext is the context-aware variant of ChangeOwner.

func (*ServerRole) Drop added in v0.0.9

func (r *ServerRole) Drop() error

Drop drops this server role.

func (*ServerRole) DropContext added in v0.0.9

func (r *ServerRole) DropContext(ctx context.Context) error

DropContext is the context-aware variant of Drop.

func (*ServerRole) Rename added in v0.0.6

func (r *ServerRole) Rename(newName string) error

Rename changes the server role's name.

func (*ServerRole) RenameContext added in v0.0.6

func (r *ServerRole) RenameContext(ctx context.Context, newName string) error

RenameContext is the context-aware variant of Rename.

type ServerScripter added in v0.0.10

type ServerScripter struct {
	// contains filtered or unexported fields
}

ServerScripter generates T-SQL scripts for server-level objects, the ones that belong to no database: logins and server roles. Scripter's objects all live inside a Database, which is why these are not on it.

func NewServerScripter added in v0.0.10

func NewServerScripter(s *Server, opts ScriptOptions) *ServerScripter

NewServerScripter creates a ServerScripter for the given server.

func (*ServerScripter) ScriptBackupDevice added in v0.0.11

func (sc *ServerScripter) ScriptBackupDevice(name string) (string, error)

ScriptBackupDevice generates the CREATE (or DROP) script for one logical backup device.

func (*ServerScripter) ScriptBackupDeviceContext added in v0.0.11

func (sc *ServerScripter) ScriptBackupDeviceContext(ctx context.Context, name string) (string, error)

ScriptBackupDeviceContext is the context-aware variant of ScriptBackupDevice.

func (*ServerScripter) ScriptCredential added in v0.0.11

func (sc *ServerScripter) ScriptCredential(name string) (string, error)

ScriptCredential generates the CREATE (or DROP) script for one server-level credential.

func (*ServerScripter) ScriptCredentialContext added in v0.0.11

func (sc *ServerScripter) ScriptCredentialContext(ctx context.Context, name string) (string, error)

ScriptCredentialContext is the context-aware variant of ScriptCredential.

func (*ServerScripter) ScriptEndpoint added in v0.0.11

func (sc *ServerScripter) ScriptEndpoint(name string) (string, error)

ScriptEndpoint generates the CREATE (or DROP) script for one endpoint.

func (*ServerScripter) ScriptEndpointContext added in v0.0.11

func (sc *ServerScripter) ScriptEndpointContext(ctx context.Context, name string) (string, error)

ScriptEndpointContext is the context-aware variant of ScriptEndpoint.

A built-in endpoint is refused with ErrSystemEndpoint: neither half of its script would run, since it can be neither dropped nor created.

func (*ServerScripter) ScriptLogin added in v0.0.10

func (sc *ServerScripter) ScriptLogin(name string) (string, error)

ScriptLogin generates the CREATE (or DROP) script for one login.

func (*ServerScripter) ScriptLoginContext added in v0.0.10

func (sc *ServerScripter) ScriptLoginContext(ctx context.Context, name string) (string, error)

ScriptLoginContext is the context-aware variant of ScriptLogin.

A certificate- or asymmetric-key-mapped login needs one more read than the others: the object it maps to is named in master, not in the login's own row. ResolveMappingContext is a no-op for every other type.

func (*ServerScripter) ScriptServerAudit added in v0.0.11

func (sc *ServerScripter) ScriptServerAudit(name string) (string, error)

ScriptServerAudit generates the CREATE (or DROP) script for one server audit.

func (*ServerScripter) ScriptServerAuditContext added in v0.0.11

func (sc *ServerScripter) ScriptServerAuditContext(ctx context.Context, name string) (string, error)

ScriptServerAuditContext is the context-aware variant of ScriptServerAudit.

func (*ServerScripter) ScriptServerAuditSpecification added in v0.0.11

func (sc *ServerScripter) ScriptServerAuditSpecification(name string) (string, error)

ScriptServerAuditSpecification generates the CREATE (or DROP) script for one server audit specification.

func (*ServerScripter) ScriptServerAuditSpecificationContext added in v0.0.11

func (sc *ServerScripter) ScriptServerAuditSpecificationContext(ctx context.Context, name string) (string, error)

ScriptServerAuditSpecificationContext is the context-aware variant of ScriptServerAuditSpecification.

func (*ServerScripter) ScriptServerRole added in v0.0.10

func (sc *ServerScripter) ScriptServerRole(name string) (string, error)

ScriptServerRole generates the CREATE (or DROP) script for one server role, including the ALTER SERVER ROLE statements that restore its membership.

func (*ServerScripter) ScriptServerRoleContext added in v0.0.10

func (sc *ServerScripter) ScriptServerRoleContext(ctx context.Context, name string) (string, error)

ScriptServerRoleContext is the context-aware variant of ScriptServerRole.

func (*ServerScripter) ScriptServerTrigger added in v0.0.11

func (sc *ServerScripter) ScriptServerTrigger(name string) (string, error)

ScriptServerTrigger generates the CREATE (or DROP) script for one server-scope DDL or logon trigger.

func (*ServerScripter) ScriptServerTriggerContext added in v0.0.11

func (sc *ServerScripter) ScriptServerTriggerContext(ctx context.Context, name string) (string, error)

ScriptServerTriggerContext is the context-aware variant of ScriptServerTrigger.

type ServerSecurableKind added in v0.0.12

type ServerSecurableKind string

ServerSecurableKind is the kind of server securable Capabilities.ExplicitServerPermissions is keyed by. Its values are the securable words SQL Server itself uses in DENY ... ON <kind>::<name>.

Logins and server roles are told apart by the *principal's* type_desc rather than by class: both are class 101 SERVER_PRINCIPAL, and there is no class 110. A caller probing a separate class for server roles finds nothing.

const (
	// ServerSecurableLogin is a login — class 101 with a type_desc of
	// SQL_LOGIN, WINDOWS_LOGIN, WINDOWS_GROUP, EXTERNAL_LOGIN,
	// EXTERNAL_GROUP, CERTIFICATE_MAPPED_LOGIN or
	// ASYMMETRIC_KEY_MAPPED_LOGIN.
	ServerSecurableLogin ServerSecurableKind = "LOGIN"

	// ServerSecurableServerRole is a server role — class 101 with a type_desc
	// of SERVER_ROLE.
	ServerSecurableServerRole ServerSecurableKind = "SERVER ROLE"

	// ServerSecurableEndpoint is an endpoint — class 105.
	ServerSecurableEndpoint ServerSecurableKind = "ENDPOINT"
)

type ServerSecurityInfo added in v0.0.4

type ServerSecurityInfo struct {
	// AuthenticationMode is "WINDOWS" (Windows Authentication only) or
	// "MIXED" (SQL Server and Windows Authentication).
	AuthenticationMode string
}

ServerSecurityInfo holds server-wide authentication settings — SSMS's Server Properties > Security page. Login-audit level and the server proxy account live in the registry (xp_instance_regread), which gosmo deliberately does not touch (see README "Features intentionally excluded"); only what SERVERPROPERTY exposes is included here.

type ServerTrigger added in v0.0.11

type ServerTrigger struct {
	Name string

	// IsEnabled is the inverse of the catalog's is_disabled.
	IsEnabled bool

	CreateDate time.Time
	ModifyDate time.Time

	// Events are the type_desc values from sys.server_trigger_events —
	// "CREATE_DATABASE", "LOGON", and so on. A trigger declared FOR a whole
	// event group lists the group's individual events, which is what the
	// catalog records.
	Events []string

	// Definition is the trigger body from sys.server_sql_modules. It is empty
	// for an encrypted trigger (the catalog reports NULL) and for a CLR
	// trigger, which has no row there at all.
	Definition string
	// contains filtered or unexported fields
}

ServerTrigger mirrors a row of sys.server_triggers — a DDL or LOGON trigger defined ON ALL SERVER.

func (*ServerTrigger) Disable added in v0.0.11

func (t *ServerTrigger) Disable() error

Disable disables the trigger, leaving its definition in place.

func (*ServerTrigger) DisableContext added in v0.0.11

func (t *ServerTrigger) DisableContext(ctx context.Context) error

DisableContext is the context-aware variant of Disable.

func (*ServerTrigger) Drop added in v0.0.11

func (t *ServerTrigger) Drop() error

Drop removes the trigger. A trigger that isn't there is the server's error, not a silent success — see the note on Database.DropTable.

func (*ServerTrigger) DropContext added in v0.0.11

func (t *ServerTrigger) DropContext(ctx context.Context) error

DropContext is the context-aware variant of Drop.

func (*ServerTrigger) Enable added in v0.0.11

func (t *ServerTrigger) Enable() error

Enable enables the trigger.

func (*ServerTrigger) EnableContext added in v0.0.11

func (t *ServerTrigger) EnableContext(ctx context.Context) error

EnableContext is the context-aware variant of Enable.

type ServerVersion

type ServerVersion int

ServerVersion represents a SQL Server version.

const (
	SQLServer2012 ServerVersion = 11
	SQLServer2014 ServerVersion = 12
	SQLServer2016 ServerVersion = 13
	SQLServer2017 ServerVersion = 14
	SQLServer2019 ServerVersion = 15
	SQLServer2022 ServerVersion = 16
	SQLServer2025 ServerVersion = 17
)

type ServiceBrokerEndpointDetail added in v0.0.11

type ServiceBrokerEndpointDetail struct {
	// IsMessageForwardingEnabled reports whether the endpoint forwards
	// messages it is not the destination for.
	IsMessageForwardingEnabled bool

	// MessageForwardingSize is the megabytes of storage the endpoint may use
	// for forwarded messages.
	MessageForwardingSize int

	// ConnectionAuth is NTLM, KERBEROS, NEGOTIATE, CERTIFICATE, or one of the
	// combined forms.
	ConnectionAuth string

	// EncryptionAlgorithm is AES, RC4, one of the mixed forms, or NONE.
	EncryptionAlgorithm string

	// CertificateName is the certificate the endpoint authenticates with,
	// empty when it authenticates by Windows credentials alone. The catalog
	// records only the id, and the name is what a script needs.
	CertificateName string
}

ServiceBrokerEndpointDetail is the SERVICE_BROKER-specific half of an endpoint, from sys.service_broker_endpoints.

type SnapshotFileSpec added in v0.0.13

type SnapshotFileSpec struct {
	// LogicalName is the source file's logical name, which the snapshot must
	// reuse verbatim — CREATE DATABASE … AS SNAPSHOT OF matches its file
	// clauses to the source by name, not by position.
	LogicalName string

	// FileName is the path of the sparse file to create. SQL Server writes
	// it with the service account's rights, so the directory must exist and
	// be writable by the instance.
	FileName string
}

SnapshotFileSpec is one sparse file of a new snapshot: the logical name of a data file in the *source* database, and the path the snapshot's sparse file for it goes to.

type SpaceInfo

type SpaceInfo struct {
	TotalMB float64
	DataMB  float64
	LogMB   float64
	// UnallocatedMB is free space within the database's already-allocated
	// data files (SSMS's Database Properties > General "Space available"),
	// not free disk space — it can only shrink the database's on-disk
	// footprint, not grow it, without a file autogrowth event.
	UnallocatedMB float64
	// AvailLogMB is the same free-space measure as UnallocatedMB, but for
	// the log file(s) rather than the data file(s).
	AvailLogMB float64
}

SpaceInfo holds space usage information for a database.

type SpatialBoundingBox added in v0.0.10

type SpatialBoundingBox struct {
	XMin, YMin, XMax, YMax float64
}

SpatialBoundingBox is the rectangle a geometry index tessellates (BOUNDING_BOX). Anything outside it lands in the single top-level cell, so it belongs around the data, not around the coordinate system.

type SpatialGridDensity added in v0.0.10

type SpatialGridDensity string

SpatialGridDensity is one grid level's density in a GRIDS clause.

const (
	SpatialGridLow    SpatialGridDensity = "LOW"
	SpatialGridMedium SpatialGridDensity = "MEDIUM"
	SpatialGridHigh   SpatialGridDensity = "HIGH"
)

type SpatialGridLevels added in v0.0.10

type SpatialGridLevels struct {
	Level1, Level2, Level3, Level4 SpatialGridDensity
}

SpatialGridLevels is a spatial index's per-level grid density (GRIDS). A level left empty is omitted from the clause and takes the server's default, so the zero value means "no GRIDS clause at all".

type SpatialTessellation added in v0.0.10

type SpatialTessellation string

SpatialTessellation is a spatial index's tessellation scheme — the USING clause of CREATE SPATIAL INDEX. The GEOMETRY_ schemes apply to a geometry column and the GEOGRAPHY_ ones to a geography column; the server rejects the mismatch.

const (
	SpatialGeometryGrid      SpatialTessellation = "GEOMETRY_GRID"
	SpatialGeometryAutoGrid  SpatialTessellation = "GEOMETRY_AUTO_GRID"
	SpatialGeographyGrid     SpatialTessellation = "GEOGRAPHY_GRID"
	SpatialGeographyAutoGrid SpatialTessellation = "GEOGRAPHY_AUTO_GRID"
)

func (SpatialTessellation) IsAutoGrid added in v0.0.10

func (s SpatialTessellation) IsAutoGrid() bool

IsAutoGrid reports whether s is one of the automatic schemes, which pick their own grid densities and so take no GRIDS clause.

func (SpatialTessellation) IsGeometry added in v0.0.10

func (s SpatialTessellation) IsGeometry() bool

IsGeometry reports whether s tessellates a geometry column, the two schemes that take a bounding box.

type Statistic

type Statistic struct {
	Name                string
	StatID              int
	IsAutoCreated       bool
	IsUserCreated       bool
	HasFilter           bool
	FilterDef           string
	LastUpdated         time.Time
	RowsSampled         int64
	TotalRows           int64 // renamed from RowCount to avoid shadowing Table.RowCount()
	Steps               int
	UnfilteredRows      int64
	NoRecompute         bool
	IsIncremental       bool
	ModificationCounter int64
	// contains filtered or unexported fields
}

Statistic mirrors sys.stats for a table.

func (*Statistic) ColumnSeq added in v0.0.6

func (st *Statistic) ColumnSeq(ctx context.Context) iter.Seq2[string, error]

ColumnSeq returns an iterator over this statistic's columns, in stat-column order.

func (*Statistic) Columns added in v0.0.6

func (st *Statistic) Columns() ([]string, error)

Columns returns this statistic's columns, in stat-column order. The leading column is what the statistic's histogram is built on; every column contributes to its density vector.

func (*Statistic) ColumnsContext added in v0.0.6

func (st *Statistic) ColumnsContext(ctx context.Context) ([]string, error)

ColumnsContext is the context-aware variant of Columns.

func (*Statistic) DensityVector added in v0.0.6

func (st *Statistic) DensityVector() ([]*StatisticDensity, error)

DensityVector returns this statistic's density vector.

func (*Statistic) DensityVectorContext added in v0.0.6

func (st *Statistic) DensityVectorContext(ctx context.Context) ([]*StatisticDensity, error)

DensityVectorContext is the context-aware variant of DensityVector.

func (*Statistic) DensityVectorSeq added in v0.0.6

func (st *Statistic) DensityVectorSeq(ctx context.Context) iter.Seq2[*StatisticDensity, error]

DensityVectorSeq returns an iterator over this statistic's density vector.

func (*Statistic) Drop

func (st *Statistic) Drop() error

Drop drops this statistic. Correct T-SQL syntax: DROP STATISTICS table_name.stat_name

func (*Statistic) DropContext

func (st *Statistic) DropContext(ctx context.Context) error

DropContext is the context-aware variant of Drop.

func (*Statistic) Header added in v0.0.6

func (st *Statistic) Header() (*StatisticHeader, error)

Header returns this statistic's DBCC SHOW_STATISTICS header row.

func (*Statistic) HeaderContext added in v0.0.6

func (st *Statistic) HeaderContext(ctx context.Context) (*StatisticHeader, error)

HeaderContext is the context-aware variant of Header.

func (*Statistic) Histogram added in v0.0.6

func (st *Statistic) Histogram() ([]*StatisticHistogramStep, error)

Histogram returns this statistic's histogram steps.

func (*Statistic) HistogramContext added in v0.0.6

func (st *Statistic) HistogramContext(ctx context.Context) ([]*StatisticHistogramStep, error)

HistogramContext is the context-aware variant of Histogram.

func (*Statistic) HistogramSeq added in v0.0.6

func (st *Statistic) HistogramSeq(ctx context.Context) iter.Seq2[*StatisticHistogramStep, error]

HistogramSeq returns an iterator over this statistic's histogram steps.

func (*Statistic) Rename added in v0.0.9

func (st *Statistic) Rename(newName string) error

Rename renames the statistic using sp_rename.

func (*Statistic) RenameContext added in v0.0.9

func (st *Statistic) RenameContext(ctx context.Context, newName string) error

RenameContext is the context-aware variant of Rename.

func (*Statistic) Update

func (st *Statistic) Update(samplePct int) error

Update updates this statistic. Pass samplePct=0 for a FULLSCAN; any value 1-100 uses SAMPLE n PERCENT.

func (*Statistic) UpdateContext

func (st *Statistic) UpdateContext(ctx context.Context, samplePct int) error

UpdateContext is the context-aware variant of Update.

type StatisticDensity added in v0.0.6

type StatisticDensity struct {
	AllDensity    float64
	AverageLength float64
	Columns       string
}

StatisticDensity is one row of DBCC SHOW_STATISTICS ... WITH DENSITY_VECTOR — one row per leading-column prefix of the statistic's key columns (e.g. a 2-column statistic yields 2 rows: {col1} and {col1,col2}).

type StatisticHeader added in v0.0.6

type StatisticHeader struct {
	Updated                string
	Rows                   int64
	RowsSampled            int64
	Steps                  int
	Density                float64
	AverageKeyLength       float64
	StringIndex            string
	FilterExpression       string
	UnfilteredRows         int64
	PersistedSamplePercent float64
}

StatisticHeader mirrors the single result row of DBCC SHOW_STATISTICS ... WITH STAT_HEADER. Every field is zero-valued (Updated "") when the statistic exists as metadata but has never actually been populated (e.g. an auto-created statistic on a table nothing has queried yet) — SQL Server itself returns a header row of NULLs in that case.

type StatisticHistogramStep added in v0.0.6

type StatisticHistogramStep struct {
	RangeHighKey      string
	RangeRows         float64
	EqRows            float64
	DistinctRangeRows int64
	AvgRangeRows      float64
}

StatisticHistogramStep is one step of DBCC SHOW_STATISTICS ... WITH HISTOGRAM. RangeHighKey is formatted as text since its underlying SQL type follows the statistic's leading key column (int, varchar, datetime, ...), not one fixed Go type.

type StoredProcedure

type StoredProcedure struct {
	ObjectID   int
	Schema     string
	Name       string
	Definition string
	CreateDate time.Time
	ModifyDate time.Time
}

StoredProcedure represents a stored procedure.

type Synonym

type Synonym struct {
	Name       string
	Schema     string
	ObjectID   int
	BaseObject string // fully qualified base object name
	// contains filtered or unexported fields
}

Synonym mirrors sys.synonyms.

func (*Synonym) Drop

func (syn *Synonym) Drop() error

Drop drops the synonym.

func (*Synonym) DropContext added in v0.0.5

func (syn *Synonym) DropContext(ctx context.Context) error

DropContext is the context-aware variant of Drop.

type SystemDataType added in v0.0.13

type SystemDataType struct {
	Name       string
	SystemType int

	// MaxLength is the storage length in bytes as sys.types reports it, -1
	// for a MAX type. For the parameterized types (varchar, decimal, ...)
	// this is the catalog's declaration of the type itself, not of any
	// column using it.
	MaxLength  int
	Precision  int
	Scale      int
	IsNullable bool
}

SystemDataType is one of the built-in types the instance ships — the fixed list SSMS shows under Types ▸ System Data Types.

It is read from the catalog rather than hard-coded so the list is always the connected instance's own: the set has grown between releases, and a literal list in Go would be a list of some other version's types.

type Table

type Table struct {
	ObjectID             int
	Schema               string
	Name                 string
	CreateDate           time.Time
	ModifyDate           time.Time
	HasReplicationFilter bool
	IsMemoryOptimized    bool

	// The four flags that decide which family a table belongs to — see
	// TableKind, which is how a caller asks for one family at a time.
	// IsSystem is sys.tables.is_ms_shipped: a table SQL Server itself
	// created, msdb's own hundred and forty-odd included.
	IsSystem    bool
	IsFileTable bool
	IsExternal  bool
	IsNode      bool
	IsEdge      bool
	// contains filtered or unexported fields
}

Table mirrors Microsoft.SqlServer.Management.Smo.Table.

func (*Table) AlterColumn added in v0.0.4

func (t *Table) AlterColumn(col ColumnDefinition) error

AlterColumn changes an existing column's data type and/or nullability (ALTER TABLE ... ALTER COLUMN). Identity and default are not settable this way — SQL Server requires dropping and re-adding the column, or its default constraint, for those.

func (*Table) AlterColumnContext added in v0.0.4

func (t *Table) AlterColumnContext(ctx context.Context, col ColumnDefinition) error

AlterColumnContext is the context-aware variant of AlterColumn.

func (*Table) CheckConstraintSeq added in v0.0.6

func (t *Table) CheckConstraintSeq(ctx context.Context) iter.Seq2[*CheckConstraint, error]

CheckConstraintSeq returns an iterator over all CHECK constraints on the table.

func (*Table) CheckConstraints

func (t *Table) CheckConstraints() ([]*CheckConstraint, error)

CheckConstraints returns all CHECK constraints on the table.

func (*Table) CheckConstraintsContext

func (t *Table) CheckConstraintsContext(ctx context.Context) ([]*CheckConstraint, error)

CheckConstraintsContext is the context-aware variant of CheckConstraints.

func (*Table) CheckWhereSyntax added in v0.0.6

func (t *Table) CheckWhereSyntax(predicate string) error

CheckWhereSyntax validates a WHERE predicate against the table without scanning any data (SSMS's "Check Syntax" action for a filtered index or statistic's predicate).

func (*Table) CheckWhereSyntaxContext added in v0.0.6

func (t *Table) CheckWhereSyntaxContext(ctx context.Context, predicate string) error

CheckWhereSyntaxContext is the context-aware variant of CheckWhereSyntax.

func (*Table) ColumnSeq

func (t *Table) ColumnSeq(ctx context.Context) iter.Seq2[*Column, error]

ColumnSeq returns an iterator over all columns in the table, in ordinal order.

func (*Table) Columns

func (t *Table) Columns() ([]*Column, error)

Columns returns all columns for this table in ordinal order.

func (*Table) ColumnsContext

func (t *Table) ColumnsContext(ctx context.Context) ([]*Column, error)

ColumnsContext is the context-aware variant of Columns.

func (*Table) CountWhere added in v0.0.6

func (t *Table) CountWhere(predicate string) (int64, error)

CountWhere returns the number of rows in the table matching a WHERE predicate — used to estimate qualifying rows for a filtered index or filtered statistic's predicate (SSMS's "Estimate Rows" action).

func (*Table) CountWhereContext added in v0.0.6

func (t *Table) CountWhereContext(ctx context.Context, predicate string) (int64, error)

CountWhereContext is the context-aware variant of CountWhere. predicate is interpolated as-is after WHERE; callers pass a filter expression already captured from the server (e.g. an index or statistic's own FilterDefinition), not raw user input.

func (*Table) CreateIndex

func (t *Table) CreateIndex(req CreateIndexRequest) error

CreateIndex creates a new index on the table.

func (*Table) CreateIndexContext

func (t *Table) CreateIndexContext(ctx context.Context, req CreateIndexRequest) error

CreateIndexContext is the context-aware variant of CreateIndex.

func (*Table) CreateStatistic

func (t *Table) CreateStatistic(name string, columns []string, samplePct int) error

CreateStatistic creates a user-defined statistic on one or more columns. Pass samplePct=0 to let the server choose its own sample; see CreateStatisticWithOptions for a filter, FULLSCAN, or NORECOMPUTE.

func (*Table) CreateStatisticContext

func (t *Table) CreateStatisticContext(ctx context.Context, name string, columns []string, samplePct int) error

CreateStatisticContext is the context-aware variant of CreateStatistic.

func (*Table) CreateStatisticWithOptions added in v0.0.10

func (t *Table) CreateStatisticWithOptions(req CreateStatisticRequest) error

CreateStatisticWithOptions creates a user-defined statistic from a full request — the form that reaches the sampling, filter and recompute options CreateStatistic leaves at their defaults.

func (*Table) CreateStatisticWithOptionsContext added in v0.0.10

func (t *Table) CreateStatisticWithOptionsContext(ctx context.Context, req CreateStatisticRequest) error

CreateStatisticWithOptionsContext is the context-aware variant of CreateStatisticWithOptions.

func (*Table) DB

func (t *Table) DB() *Database

DB returns the parent Database.

func (*Table) DataSpace added in v0.0.10

func (t *Table) DataSpace() (DataSpace, error)

DataSpace returns where the table itself stores its rows — the filegroup or partition scheme its heap or clustered index is on, which is CREATE TABLE's ON clause.

func (*Table) DataSpaceContext added in v0.0.10

func (t *Table) DataSpaceContext(ctx context.Context) (DataSpace, error)

DataSpaceContext is the context-aware variant of DataSpace.

Read from index_id 0 or 1, so it answers for a heap as well as a clustered table — which is why it is a query of its own rather than a field of the index list, whose `i.type > 0` filter has no heap in it.

A table with no row there at all — a Database.Table handle, whose ObjectID is zero, or a memory-optimized table — reads as the zero DataSpace and no error: absence means "no filegroup to name", not a failure.

func (*Table) Detail added in v0.0.5

func (t *Table) Detail() (*TableDetail, error)

Detail returns TableDetail for the table.

func (*Table) DetailContext added in v0.0.5

func (t *Table) DetailContext(ctx context.Context) (*TableDetail, error)

DetailContext is the context-aware variant of Detail.

func (*Table) DropColumn added in v0.0.4

func (t *Table) DropColumn(name string) error

DropColumn removes a column from the table (ALTER TABLE ... DROP COLUMN).

Bare, like every other Drop in this package: SQL Server refuses a column a default constraint, index, check constraint or statistic depends on, and that refusal is the answer — dropping the dependencies first is a decision the caller makes, not one a library can make for them. The data in the column goes with it and is not recoverable.

func (*Table) DropColumnContext added in v0.0.4

func (t *Table) DropColumnContext(ctx context.Context, name string) error

DropColumnContext is the context-aware variant of DropColumn.

func (*Table) DropConstraint added in v0.0.9

func (t *Table) DropConstraint(name string) error

DropConstraint drops a named table constraint — a PRIMARY KEY, UNIQUE constraint, FOREIGN KEY, or CHECK constraint. All four share one per-table name space and are all removed by ALTER TABLE ... DROP CONSTRAINT; an index that is not backing a key constraint is not a constraint and needs Index.Drop instead.

func (*Table) DropConstraintContext added in v0.0.9

func (t *Table) DropConstraintContext(ctx context.Context, name string) error

DropConstraintContext is the context-aware variant of DropConstraint.

func (*Table) ForeignKeyByName added in v0.0.10

func (t *Table) ForeignKeyByName(name string) (*ForeignKey, error)

ForeignKeyByName returns one foreign key on the table by name.

func (*Table) ForeignKeyByNameContext added in v0.0.10

func (t *Table) ForeignKeyByNameContext(ctx context.Context, name string) (*ForeignKey, error)

ForeignKeyByNameContext is the context-aware variant of ForeignKeyByName. It returns an error satisfying errors.Is(err, ErrNotFound) when the table has no such foreign key.

func (*Table) ForeignKeySeq

func (t *Table) ForeignKeySeq(ctx context.Context) iter.Seq2[*ForeignKey, error]

ForeignKeySeq returns an iterator over all foreign keys on the table.

func (*Table) ForeignKeys

func (t *Table) ForeignKeys() ([]*ForeignKey, error)

ForeignKeys returns all foreign keys on the table.

func (*Table) ForeignKeysContext

func (t *Table) ForeignKeysContext(ctx context.Context) ([]*ForeignKey, error)

ForeignKeysContext is the context-aware variant of ForeignKeys.

func (*Table) FragmentationStats

func (t *Table) FragmentationStats(mode string) ([]*IndexFragmentation, error)

FragmentationStats returns fragmentation info for all indexes on the table. mode must be one of "LIMITED" (fast, default), "SAMPLED", or "DETAILED".

func (*Table) FragmentationStatsContext

func (t *Table) FragmentationStatsContext(ctx context.Context, mode string) ([]*IndexFragmentation, error)

FragmentationStatsContext is the context-aware variant of FragmentationStats.

func (*Table) FragmentationStatsSeq added in v0.0.6

func (t *Table) FragmentationStatsSeq(ctx context.Context, mode string) iter.Seq2[*IndexFragmentation, error]

FragmentationStatsSeq returns an iterator over fragmentation info for all indexes on the table. mode must be one of "LIMITED" (fast, default), "SAMPLED", or "DETAILED".

func (*Table) FullName

func (t *Table) FullName() string

FullName returns Schema.[Name].

func (*Table) IndexByName added in v0.0.10

func (t *Table) IndexByName(name string) (*Index, error)

IndexByName returns one index on the table by name, with its columns.

func (*Table) IndexByNameContext added in v0.0.10

func (t *Table) IndexByNameContext(ctx context.Context, name string) (*Index, error)

IndexByNameContext is the context-aware variant of IndexByName. It returns an error satisfying errors.Is(err, ErrNotFound) when the table has no such index. Two queries, the same shape as IndexesContext — see its comment for why the columns are not fetched inside the index scan.

func (*Table) IndexSeq

func (t *Table) IndexSeq(ctx context.Context) iter.Seq2[*Index, error]

IndexSeq returns an iterator over all indexes on the table.

func (*Table) Indexes

func (t *Table) Indexes() ([]*Index, error)

Indexes returns all indexes on the table.

func (*Table) IndexesContext

func (t *Table) IndexesContext(ctx context.Context) ([]*Index, error)

IndexesContext is the context-aware variant of Indexes.

Two queries, whatever the index count: one for the indexes, one for every index column on the object at once. Fetching each index's columns inside the loop over the indexes cost a query per index, and Database.query pins its own pooled connection and issues its own USE, so a table with 20 indexes ran 42 round trips across 21 connections — with the outer one held throughout, which is the shape that exhausts a pool rather than merely being slow.

func (*Table) PartitionSeq added in v0.0.5

func (t *Table) PartitionSeq(ctx context.Context) iter.Seq2[*PartitionInfo, error]

PartitionSeq returns an iterator over per-partition row counts for the table.

func (*Table) Partitions

func (t *Table) Partitions() ([]*PartitionInfo, error)

Partitions returns per-partition row counts and compression for the table.

func (*Table) PartitionsContext added in v0.0.5

func (t *Table) PartitionsContext(ctx context.Context) ([]*PartitionInfo, error)

PartitionsContext is the context-aware variant of Partitions. A non-partitioned table still returns exactly one row (partition number 1), same as sys.partitions itself.

func (*Table) RebuildAllIndexes

func (t *Table) RebuildAllIndexes(fillFactor int) error

RebuildAllIndexes rebuilds all indexes on the table (ALTER INDEX ALL ... REBUILD).

func (*Table) RebuildAllIndexesContext

func (t *Table) RebuildAllIndexesContext(ctx context.Context, fillFactor int) error

RebuildAllIndexesContext is the context-aware variant of RebuildAllIndexes.

func (*Table) RenameColumn added in v0.0.10

func (t *Table) RenameColumn(name, newName string) error

RenameColumn renames a column using sp_rename's 'COLUMN' class.

Bare, like the rest of this family: sp_rename does not update anything that names the column. Views, procedures, functions, computed columns, indexes with a filter predicate and check constraints keep the old name in their definitions and break at their next use, and SQL Server reports nothing at rename time beyond its standing caution. Deciding whether that is acceptable is the caller's.

newName is a bare name: sp_rename refuses a qualified one for the new name, while @objname must be the three-part table.column form, which this builds.

func (*Table) RenameColumnContext added in v0.0.10

func (t *Table) RenameColumnContext(ctx context.Context, name, newName string) error

RenameColumnContext is the context-aware variant of RenameColumn.

func (*Table) RowCount

func (t *Table) RowCount() (int64, error)

RowCount returns the approximate row count using partition statistics.

func (*Table) RowCountContext

func (t *Table) RowCountContext(ctx context.Context) (int64, error)

RowCountContext is the context-aware variant of RowCount.

func (*Table) SpaceUsed added in v0.0.5

func (t *Table) SpaceUsed() (*TableSpaceInfo, error)

SpaceUsed returns space usage for the table.

func (*Table) SpaceUsedContext added in v0.0.5

func (t *Table) SpaceUsedContext(ctx context.Context) (*TableSpaceInfo, error)

SpaceUsedContext is the context-aware variant of SpaceUsed.

func (*Table) StatisticByName added in v0.0.10

func (t *Table) StatisticByName(name string) (*Statistic, error)

StatisticByName returns one statistics object on the table by name.

func (*Table) StatisticByNameContext added in v0.0.10

func (t *Table) StatisticByNameContext(ctx context.Context, name string) (*Statistic, error)

StatisticByNameContext is the context-aware variant of StatisticByName. It returns an error satisfying errors.Is(err, ErrNotFound) when the table has no such statistic.

func (*Table) StatisticSeq

func (t *Table) StatisticSeq(ctx context.Context) iter.Seq2[*Statistic, error]

StatisticSeq returns an iterator over all statistics on the table.

func (*Table) Statistics

func (t *Table) Statistics() ([]*Statistic, error)

Statistics returns all statistics objects for the table.

func (*Table) StatisticsContext

func (t *Table) StatisticsContext(ctx context.Context) ([]*Statistic, error)

StatisticsContext is the context-aware variant of Statistics.

func (*Table) TriggerSeq added in v0.0.4

func (t *Table) TriggerSeq(ctx context.Context) iter.Seq2[*Trigger, error]

TriggerSeq returns an iterator over all DML triggers attached to the table.

func (*Table) Triggers added in v0.0.4

func (t *Table) Triggers() ([]*Trigger, error)

Triggers returns all DML triggers attached to this table.

func (*Table) TriggersContext added in v0.0.4

func (t *Table) TriggersContext(ctx context.Context) ([]*Trigger, error)

TriggersContext is the context-aware variant of Triggers.

func (*Table) TruncateTable

func (t *Table) TruncateTable() error

TruncateTable truncates a table.

func (*Table) TruncateTableContext

func (t *Table) TruncateTableContext(ctx context.Context) error

TruncateTableContext is the context-aware variant of TruncateTable.

func (*Table) UpdateAllStatistics

func (t *Table) UpdateAllStatistics(samplePct int) error

UpdateAllStatistics updates all statistics on the table.

func (*Table) UpdateAllStatisticsContext

func (t *Table) UpdateAllStatisticsContext(ctx context.Context, samplePct int) error

UpdateAllStatisticsContext is the context-aware variant of UpdateAllStatistics.

func (*Table) XMLIndexSeq added in v0.0.10

func (t *Table) XMLIndexSeq(ctx context.Context) iter.Seq2[*XMLIndex, error]

XMLIndexSeq returns an iterator over all XML indexes on the table.

func (*Table) XMLIndexes added in v0.0.10

func (t *Table) XMLIndexes() ([]*XMLIndex, error)

XMLIndexes returns the XML indexes on the table, primary and secondary, in name order.

func (*Table) XMLIndexesContext added in v0.0.10

func (t *Table) XMLIndexesContext(ctx context.Context) ([]*XMLIndex, error)

XMLIndexesContext is the context-aware variant of XMLIndexes.

type TableChangeTracking added in v0.0.4

type TableChangeTracking struct {
	Schema              string
	Name                string
	Enabled             bool
	TrackColumnsUpdated bool
}

TableChangeTracking describes one user table's change tracking state.

type TableDetail added in v0.0.5

type TableDetail struct {
	SchemaOwner    string
	LockEscalation string // e.g. "TABLE", "AUTO", "DISABLE"
	UsesAnsiNulls  bool
	IsReplicated   bool
	IsTrackedByCDC bool
	TemporalType   string // e.g. "NON_TEMPORAL_TABLE", "SYSTEM_VERSIONED_TEMPORAL_TABLE"
	Durability     string // "SCHEMA_AND_DATA" or "SCHEMA_ONLY" — memory-optimized tables only
	LedgerType     string // e.g. "NON_LEDGER_TABLE", "APPEND_ONLY_LEDGER_TABLE"
	PrimaryKeyName string // "" if the table has no primary key
	DataSpace      string // filegroup (or partition scheme) backing the heap/clustered index
}

TableDetail holds the sys.tables columns and related lookups Table itself doesn't carry (Table is also used to populate the Object Explorer tree and the scripter, so it stays lean) — SSMS's Table Properties > General page's "Object details" and "Dependencies" sections.

type TableKind added in v0.0.13

type TableKind int

TableKind selects one family of tables. TableKindUser is the residue: a table that is none of the other four, which is what belongs directly under the Tables folder once the sub-folders have taken their own.

const (
	TableKindUser TableKind = iota
	TableKindSystem
	TableKindFileTable
	TableKindExternal
	TableKindGraph
)

func (TableKind) String added in v0.0.13

func (k TableKind) String() string

String names the kind for error messages.

type TableKindPresence added in v0.0.13

type TableKindPresence struct {
	System    bool
	FileTable bool
	External  bool
	Graph     bool
}

TableKindPresence reports which table families a database actually has — what a tree builder needs to decide which sub-folders to show, in one query rather than one listing per folder.

Graph is false on an instance older than SQL Server 2017 for the same reason TablesOfKind refuses the listing there: the columns do not exist, so no row can be one.

type TableSpaceInfo added in v0.0.5

type TableSpaceInfo struct {
	ReservedKB int64
	DataKB     int64
	IndexKB    int64
	LOBKB      int64
	UnusedKB   int64
	FileGroup  string
}

TableSpaceInfo holds space usage for a table (SSMS's Table Properties > Storage page), mirroring the classic sp_spaceused breakdown: DataKB is the heap/clustered index's own row data, IndexKB is every other (nonclustered) index's row data, LOBKB is off-row large-object storage, and UnusedKB is reserved-but-not-yet-used space within already allocated extents.

type TextCriterion added in v0.0.10

type TextCriterion struct {
	Op    TextOp
	Value string
}

TextCriterion is one comparison against a name or schema.

type TextOp added in v0.0.10

type TextOp int

TextOp is one comparison a text criterion makes.

const (
	TextContains TextOp = iota
	TextNotContains
	TextEquals
	TextNotEquals
)

type Trigger

type Trigger struct {
	Name       string
	TableName  string
	Schema     string
	IsEnabled  bool
	Events     []string
	Definition string
}

Trigger represents a DML trigger attached to a table.

type User

type User struct {
	Name          string
	ID            int
	UserType      string // "SQL_USER", "WINDOWS_USER", "WINDOWS_GROUP", etc.
	DefaultSchema string
	AuthType      string
	CreateDate    time.Time
	ModifyDate    time.Time
	SID           []byte
	// LoginName is the server login this user's SID matches, or empty if
	// none does — only populated by UserByNameContext (UsersContext's
	// tree-listing query doesn't join sys.server_principals). A blank
	// LoginName is ambiguous by itself: check AuthType too. A genuine
	// CREATE USER ... WITHOUT LOGIN reports AuthType "NONE", while a user
	// created FOR LOGIN whose login was later dropped keeps AuthType
	// "INSTANCE" with no matching login, i.e. orphaned.
	LoginName string
	// LoginDisabled is only meaningful when LoginName is non-empty.
	LoginDisabled bool
	// contains filtered or unexported fields
}

User mirrors Microsoft.SqlServer.Management.Smo.User.

func (*User) AddToRole

func (u *User) AddToRole(roleName string) error

AddToRole adds the user to a database role.

func (*User) AddToRoleContext added in v0.0.6

func (u *User) AddToRoleContext(ctx context.Context, roleName string) error

AddToRoleContext is the context-aware variant of AddToRole.

func (*User) Deny

func (u *User) Deny(permission ObjectPermission, objectSchema, objectName string) error

Deny denies a permission on a schema-qualified object to the user.

func (*User) DenyContext

func (u *User) DenyContext(ctx context.Context, permission ObjectPermission, objectSchema, objectName string) error

DenyContext is the context-aware variant of Deny.

func (*User) Drop

func (u *User) Drop() error

Drop drops the database user.

func (*User) DropContext added in v0.0.6

func (u *User) DropContext(ctx context.Context) error

DropContext is the context-aware variant of Drop.

func (*User) Grant

func (u *User) Grant(permission ObjectPermission, objectSchema, objectName string) error

Grant grants a permission on a schema-qualified object to the user.

func (*User) GrantContext

func (u *User) GrantContext(ctx context.Context, permission ObjectPermission, objectSchema, objectName string) error

GrantContext is the context-aware variant of Grant.

func (*User) RemoveFromRole

func (u *User) RemoveFromRole(roleName string) error

RemoveFromRole removes the user from a database role.

func (*User) RemoveFromRoleContext added in v0.0.6

func (u *User) RemoveFromRoleContext(ctx context.Context, roleName string) error

RemoveFromRoleContext is the context-aware variant of RemoveFromRole.

func (*User) Rename added in v0.0.5

func (u *User) Rename(newName string) error

Rename changes the database user's name.

func (*User) RenameContext added in v0.0.5

func (u *User) RenameContext(ctx context.Context, newName string) error

RenameContext is the context-aware variant of Rename.

func (*User) Revoke

func (u *User) Revoke(permission ObjectPermission, objectSchema, objectName string) error

Revoke revokes a permission on a schema-qualified object from the user.

func (*User) RevokeContext

func (u *User) RevokeContext(ctx context.Context, permission ObjectPermission, objectSchema, objectName string) error

RevokeContext is the context-aware variant of Revoke.

func (*User) SetDefaultSchema added in v0.0.5

func (u *User) SetDefaultSchema(schemaName string) error

SetDefaultSchema changes the user's default schema.

func (*User) SetDefaultSchemaContext added in v0.0.5

func (u *User) SetDefaultSchemaContext(ctx context.Context, schemaName string) error

SetDefaultSchemaContext is the context-aware variant of SetDefaultSchema.

func (*User) SetLogin added in v0.0.5

func (u *User) SetLogin(loginName string) error

SetLogin remaps the user to a different server login.

func (*User) SetLoginContext added in v0.0.5

func (u *User) SetLoginContext(ctx context.Context, loginName string) error

SetLoginContext is the context-aware variant of SetLogin.

type UserDBResourceGovernance added in v0.0.13

type UserDBResourceGovernance struct {
	DatabaseID int
	// LogicalDatabaseGUID and PhysicalDatabaseGUID identify the database
	// across a resize or a failover, which rewrites the physical one. Read as
	// strings: the view types them uniqueidentifier.
	LogicalDatabaseGUID  string
	PhysicalDatabaseGUID string
	ServerName           string
	DatabaseName         string
	// SLOName is the service-level objective the database runs under, e.g.
	// "MIWCOWHE4G5_INTERNAL_NPG5C_4D" on a General Purpose Gen5 4 vCore
	// Managed Instance. It is an internal identifier, not the SKU a user
	// picked — ServerResourceStat.SKU is that.
	SLOName string
	// DTULimit is the DTU allocation, and is meaningless on a vCore-based
	// Managed Instance. CPULimit is the vCore allocation.
	DTULimit int
	CPULimit int
	// MinCPU, MaxCPU and CapCPU are the resource governor's CPU percentages,
	// and MinCores the reserved core count.
	MinCPU    int
	MaxCPU    int
	CapCPU    int
	MinCores  int
	MaxDOP    int
	MinMemory int
	MaxMemory int
	// MaxSessions is the concurrent session ceiling MaxSessionPercent in
	// DatabaseResourceStat is a percentage of.
	MaxSessions        int
	MaxMemoryGrant     int
	MaxDBMemory        int
	GovernBackgroundIO bool
	// MinDBMaxSizeMB, MaxDBMaxSizeMB and DefaultDBMaxSizeMB are all zero on
	// the "Shared" SLO, which is what the instance's internal databases
	// (model_msdb, model_replicatedmaster) run under — not a failed read.
	//
	// MinDBMaxSizeMB, MaxDBMaxSizeMB and DefaultDBMaxSizeMB bound how large
	// the database may be set to grow; DBFileGrowthMB and
	// InitialDBFileSizeMB are the growth increment and starting size the
	// instance places files with, which is why New Database's file fields are
	// withheld on an Azure edition. LogSizeMB is the log's ceiling.
	MinDBMaxSizeMB      int64
	MaxDBMaxSizeMB      int64
	DefaultDBMaxSizeMB  int64
	DBFileGrowthMB      int64
	InitialDBFileSizeMB int64
	LogSizeMB           int64
	// InstanceCapCPU, InstanceMaxLogRate and InstanceMaxWorkerThreads repeat
	// the instance-wide figures from InstanceResourceGovernance, so a
	// per-database read does not need a second query to say what share of the
	// instance a database has.
	InstanceCapCPU           int
	InstanceMaxLogRate       int64
	InstanceMaxWorkerThreads int
	// ReplicaType and ReplicaRole describe the replica this row is for.
	ReplicaType        int
	MaxTransactionSize int64
	CheckpointRateMBps int
	CheckpointRateIO   int
	LastUpdatedUTC     time.Time
	// The primary_* group is the resource pool the primary replica's workload
	// group draws from.
	PrimaryGroupID          int
	PrimaryGroupMaxWorkers  int
	PrimaryMinLogRate       int64
	PrimaryMaxLogRate       int64
	PrimaryGroupMinIO       int
	PrimaryGroupMaxIO       int
	PrimaryGroupMinCPU      float64
	PrimaryGroupMaxCPU      float64
	PrimaryLogCommitFee     int
	PrimaryPoolMaxWorkers   int
	PoolMaxIO               int
	GovernDBMemoryInPool    bool
	LocalIOPS               int
	ManagedXStoreIOPS       int
	ExternalXStoreIOPS      int
	TypeLocalIOPS           int
	TypeManagedXStoreIOPS   int
	TypeExternalXStoreIOPS  int
	PFSIOPS                 int
	TypePFSIOPS             int
	DataDirectoryQuotaMB    int
	DataDirectoryUsageMB    int
	BufferPoolExtensionGB   int
	PoolMaxLogRate          int64
	PrimaryGroupMaxOutbound int
	PrimaryPoolMaxOutbound  int
	// ReplicaRole is 0 primary, 1 secondary, 2 named secondary, 3 forwarder.
	ReplicaRole      int
	TypeRBIODataIOPS int
}

UserDBResourceGovernance is one row of sys.dm_user_db_resource_governance: the limits the resource governor enforces on a single database, one row per database on the instance.

It is the database-scoped counterpart of InstanceResourceGovernance and has the same contract — these are ceilings, not readings, and change only when the database or the instance is resized. It is the scale a DatabaseResourceStat history is read against: the stats view reports percentages, and this says of what.

Unlike sys.dm_db_resource_stats, the view is *not* scoped to the connection's database: it returns every database on the instance from wherever it is read, which is why Server.UserDBResourceGovernance returns them all and Database.ResourceGovernance picks one out.

Fields are in view column order. A nullable column reads as zero, or the empty string.

type UserDefinedDataType added in v0.0.13

type UserDefinedDataType struct {
	Name       string
	Schema     string
	UserTypeID int

	// BaseType is the system type the alias is built on, as sys.types names
	// it ("varchar", "decimal", ...).
	BaseType string

	// MaxLength is the storage length in bytes, as sys.types reports it: -1
	// for a MAX type, and twice the character count for the Unicode types.
	MaxLength int
	Precision int
	Scale     int
	Collation string

	// IsNullable is the type's own nullability, which a column declaration
	// can still override.
	IsNullable bool

	// Rule and Default name the objects bound to the type with sp_bindrule
	// and sp_bindefault, empty when nothing is bound. Both mechanisms are
	// deprecated by Microsoft; a type carrying one is legacy, not a defect.
	Rule    string
	Default string
	// contains filtered or unexported fields
}

UserDefinedDataType is an alias type — a base system type with a fixed length/precision, nullability, and optionally a bound rule or default. It mirrors a sys.types row with is_user_defined = 1 and both is_table_type and is_assembly_type 0.

func (*UserDefinedDataType) Database added in v0.0.13

func (t *UserDefinedDataType) Database() *Database

Database returns the database the type belongs to.

func (*UserDefinedDataType) Drop added in v0.0.13

func (t *UserDefinedDataType) Drop() error

Drop drops the alias type.

func (*UserDefinedDataType) DropContext added in v0.0.13

func (t *UserDefinedDataType) DropContext(ctx context.Context) error

DropContext is the context-aware variant of Drop.

func (*UserDefinedDataType) FullName added in v0.0.13

func (t *UserDefinedDataType) FullName() string

FullName returns the schema-qualified, bracket-quoted name.

type UserDefinedFunction

type UserDefinedFunction struct {
	ObjectID   int
	Schema     string
	Name       string
	FuncType   string // "FN" scalar, "TF" multi-statement table-valued, "IF" inline table-valued
	Definition string
	CreateDate time.Time
	ModifyDate time.Time
}

UserDefinedFunction represents a UDF.

type UserDefinedTableType added in v0.0.13

type UserDefinedTableType struct {
	Name       string
	Schema     string
	UserTypeID int

	// TypeTableObjectID is the object_id of the *internal* table that holds
	// the type's shape. The type's columns, indexes and check constraints
	// hang off this id, not off UserTypeID and not off any id in sys.objects
	// a caller could reach by name — see ColumnsContext.
	TypeTableObjectID int

	// IsMemoryOptimized reports a memory-optimized table type (2014+). The
	// column is nullable in the catalog and reads as false where it is NULL.
	IsMemoryOptimized bool
	// contains filtered or unexported fields
}

UserDefinedTableType mirrors a sys.table_types row.

func (*UserDefinedTableType) Columns added in v0.0.13

func (t *UserDefinedTableType) Columns() ([]*Column, error)

Columns returns the table type's columns in ordinal order.

func (*UserDefinedTableType) ColumnsContext added in v0.0.13

func (t *UserDefinedTableType) ColumnsContext(ctx context.Context) ([]*Column, error)

ColumnsContext is the context-aware variant of Columns.

The columns are read through TypeTableObjectID, the internal table sys.table_types points at — a table type's columns are *not* on sys.columns under its user_type_id, and OBJECT_ID('[schema].[name]') does not resolve a type at all, so neither of the obvious lookups finds anything. A type built by hand rather than by a listing has a zero TypeTableObjectID and gets a not-found error rather than an empty list.

func (*UserDefinedTableType) Database added in v0.0.13

func (t *UserDefinedTableType) Database() *Database

Database returns the database the type belongs to.

func (*UserDefinedTableType) Drop added in v0.0.13

func (t *UserDefinedTableType) Drop() error

Drop drops the table type.

func (*UserDefinedTableType) DropContext added in v0.0.13

func (t *UserDefinedTableType) DropContext(ctx context.Context) error

DropContext is the context-aware variant of Drop.

func (*UserDefinedTableType) FullName added in v0.0.13

func (t *UserDefinedTableType) FullName() string

FullName returns the schema-qualified, bracket-quoted name.

type View

type View struct {
	ObjectID   int
	Schema     string
	Name       string
	Definition string
	CreateDate time.Time
	ModifyDate time.Time
}

View represents a database view.

type XMLIndex added in v0.0.10

type XMLIndex struct {
	Name    string
	IndexID int
	// IsPrimary is true for a primary XML index, which is the one built
	// directly on the xml column; a secondary index is built over it.
	IsPrimary bool
	// SecondaryType is PATH, VALUE or PROPERTY for a secondary index, and
	// empty for a primary one.
	SecondaryType XMLSecondaryIndexType
	// ColumnName is the xml column the index is on.
	ColumnName string
	// PrimaryIndexName is the primary XML index a secondary one is built
	// over, and empty for a primary index.
	PrimaryIndexName string
}

XMLIndex is one XML index on a table — sys.xml_indexes. It carries what sys.indexes cannot: whether the index is the table's primary XML index or a secondary one, which secondary form it is, and which primary index it is built over. A secondary XML index can only be created over an existing primary one, so a caller offering to create one has to know which primary indexes are there.

type XMLSecondaryIndexType added in v0.0.10

type XMLSecondaryIndexType string

XMLSecondaryIndexType selects which secondary XML index CREATE XML INDEX builds — the FOR clause. A secondary index is always built over an existing primary XML index (see CreateIndexRequest).

const (
	// XMLSecondaryPath indexes path/value pairs, for predicates on a path.
	XMLSecondaryPath XMLSecondaryIndexType = "PATH"
	// XMLSecondaryValue indexes value/path pairs, for predicates whose path
	// is a wildcard or a descendant axis.
	XMLSecondaryValue XMLSecondaryIndexType = "VALUE"
	// XMLSecondaryProperty indexes primary-key/path/value triples, for
	// property-bag retrieval of one row's values.
	XMLSecondaryProperty XMLSecondaryIndexType = "PROPERTY"
)

type XmlSchemaCollection added in v0.0.13

type XmlSchemaCollection struct {
	Name         string
	Schema       string
	CollectionID int
	CreateDate   time.Time
	ModifyDate   time.Time
	// contains filtered or unexported fields
}

XmlSchemaCollection mirrors a sys.xml_schema_collections row.

func (*XmlSchemaCollection) Database added in v0.0.13

func (c *XmlSchemaCollection) Database() *Database

Database returns the database the collection belongs to.

func (*XmlSchemaCollection) Definition added in v0.0.13

func (c *XmlSchemaCollection) Definition() (string, error)

Definition returns the collection's schema documents as one XML string — what CREATE XML SCHEMA COLLECTION was given, as the server reassembles it.

func (*XmlSchemaCollection) DefinitionContext added in v0.0.13

func (c *XmlSchemaCollection) DefinitionContext(ctx context.Context) (string, error)

DefinitionContext is the context-aware variant of Definition.

XML_SCHEMA_NAMESPACE takes the schema and collection name as *string literals*, not identifiers, so both are passed as parameters rather than bracket-quoted into the statement.

func (*XmlSchemaCollection) Drop added in v0.0.13

func (c *XmlSchemaCollection) Drop() error

Drop drops the XML schema collection.

func (*XmlSchemaCollection) DropContext added in v0.0.13

func (c *XmlSchemaCollection) DropContext(ctx context.Context) error

DropContext is the context-aware variant of Drop.

func (*XmlSchemaCollection) FullName added in v0.0.13

func (c *XmlSchemaCollection) FullName() string

FullName returns the schema-qualified, bracket-quoted name.

Directories

Path Synopsis
Command examples is a guided tour of gosmo: connect, inspect the instance, build a throwaway database with schemas, tables, indexes, a sequence and a procedure, script it, then drop it again.
Command examples is a guided tour of gosmo: connect, inspect the instance, build a throwaway database with schemas, tables, indexes, a sequence and a procedure, script it, then drop it again.
backup command
Command backup demonstrates gosmo's backup and restore surface: a full backup with live progress reporting, reading a backup device's headers and file list, verifying it, a differential and a log backup appended to the same media, the backup history in msdb, and a restore that relocates the database's files.
Command backup demonstrates gosmo's backup and restore surface: a full backup with live progress reporting, reading a backup device's headers and file list, verifying it, a differential and a log backup appended to the same media, the backup history in msdb, and a restore that relocates the database's files.
bulkcopy command
Command bulkcopy demonstrates Database.BulkInsert — gosmo's bcp-equivalent load path.
Command bulkcopy demonstrates Database.BulkInsert — gosmo's bcp-equivalent load path.
diagnostic command
Command diagnostic demonstrates the parts of gosmo you reach for when something is wrong or you are exploring an unfamiliar instance: structured SQL Server errors, the transient-failure test, execution plans, calling procedures with output parameters, object search and dependency graphs, the bulk catalog snapshot, and the server-health DMV reads.
Command diagnostic demonstrates the parts of gosmo you reach for when something is wrong or you are exploring an unfamiliar instance: structured SQL Server errors, the transient-failure test, execution plans, calling procedures with output parameters, object search and dependency graphs, the bulk catalog snapshot, and the server-health DMV reads.
internal/demo
Package demo holds the connection factory and output helpers the gosmo example programs share, so each example file is only about its own topic.
Package demo holds the connection factory and output helpers the gosmo example programs share, so each example file is only about its own topic.
iterators command
Command iterators demonstrates gosmo's *Seq API.
Command iterators demonstrates gosmo's *Seq API.
jobs command
Command jobs demonstrates gosmo's SQL Server Agent surface: categories, operators, a job with several steps and branching, a shared schedule attached to it, running it, reading its history, and alerts.
Command jobs demonstrates gosmo's SQL Server Agent surface: categories, operators, a job with several steps and branching, a shared schedule attached to it, running it, reading its history, and alerts.
maintain command
Command maintain demonstrates the routine-maintenance side of gosmo: index fragmentation and rebuilds, statistics with their header, histogram and density vector, database files and filegroups, space usage, database options and scoped configurations, change tracking, and Query Store.
Command maintain demonstrates the routine-maintenance side of gosmo: index fragmentation and rebuilds, statistics with their header, histogram and density vector, database files and filegroups, space usage, database options and scoped configurations, change tracking, and Query Store.
scripting command
Command scripting demonstrates the two ways gosmo produces T-SQL text instead of changing the server:
Command scripting demonstrates the two ways gosmo produces T-SQL text instead of changing the server:
security command
Command security demonstrates gosmo's principal and permission surface: creating a login, mapping it into a database as a user, role membership at both levels, granting and denying object/schema/database/server permissions, and reading the permission state back from either direction.
Command security demonstrates gosmo's principal and permission surface: creating a login, mapping it into a database as a user, role membership at both levels, granting and denying object/schema/database/server permissions, and reading the permission state back from either direction.
Package version holds gosmo's own version metadata, mirroring the same pattern gossms/internal/version/version.go uses.
Package version holds gosmo's own version metadata, mirroring the same pattern gossms/internal/version/version.go uses.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL