gosmo

package module
v0.0.6 Latest Latest
Warning

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

Go to latest
Published: Jul 28, 2026 License: MIT Imports: 20 Imported by: 0

README

gosmo

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


Architecture

classDiagram
    %% =========================================================
    %% Top-level entry point
    %% =========================================================
    class ConnectionOptions {
        +Server string
        +Database string
        +Auth AuthMethod
        +User string
        +Password string
        +TenantID string
        +ClientID string
        +ClientCertPath string
        +AccessToken string
        +AccessTokenProvider func
        +ServerSPN string
        +Kerberos KerberosOptions
        +ConnectTimeout Duration
        +ApplicationName string
        +MaxOpenConns int
        +MaxIdleConns int
        +ConnMaxLifetime Duration
        +ConnMaxIdleTime Duration
        +SessionInitSQL string
        +TrustServerCertificate bool
        +Encrypt string
    }

    class Server {
        -db *sql.DB
        -info *ServerInfo
        +Connect(opts) *Server
        +ConnectContext(ctx, opts) *Server
        +ParseServerAddress(server) string
        +Close() error
        +DB() *sql.DB
        +Info() *ServerInfo
        +Name() string
        +CurrentDatabase() string
        +CurrentLogin() string
        +Databases() []*Database
        +DatabaseByName(name) *Database
        +Database(name) *Database
        +CreateDatabase(name, opts) error
        +DropDatabase(name, force) error
        +Logins() []*Login
        +LoginByName(name) *Login
        +Login(name) *Login
        +CreateLogin(name, password, opts) error
        +DropLogin(name) error
        +ServerRoles() []*ServerRole
        +ServerRoleByName(name) *ServerRole
        +ServerRoleMembers(role) []*RoleMember
        +AddServerRoleMember(role, member) error
        +RemoveServerRoleMember(role, member) error
        +LinkedServers() []*LinkedServer
        +Configurations() []*Configuration
        +AgentInfo() *AgentStatus
        +Jobs() []*Job
        +JobByName(name) *Job
        +CreateJob(req) *Job
        +JobHistory(limit) []*JobHistoryEntry
        +Alerts() []*Alert
        +EventAlerts() []*Alert
        +AlertByName(name) *Alert
        +CreateAlert(req) *Alert
        +Operators() []*Operator
        +OperatorByName(name) *Operator
        +CreateOperator(req) *Operator
        +Schedules() []*Schedule
        +ScheduleByName(name) *Schedule
        +CreateSchedule(req) *Schedule
        +Categories(class) []*Category
        +CreateCategory(class, name) error
        +DeleteCategory(class, name) error
        +ActiveSessions(sys) []*Session
        +KillSession(id) error
        +ReadErrorLog(n) []*ErrorLogEntry
        +MailProfiles() []*MailProfile
        +SendMail(opts) error
        +Backup(opts) error
        +Restore(opts) error
        +VerifyBackup(device) error
        +BackupHeaders(device) []*BackupHeader
        +BackupFileList(device) []*BackupFile
        +SecurityInfo() *ServerSecurityInfo
        +ServerPermissions() []*ServerPermissionEntry
        +GrantServerPermission(perm, principal) error
        +DenyServerPermission(perm, principal) error
        +RevokeServerPermission(perm, principal) error
        +ServerPermissionNames() []string
        +Credentials() []*Credential
        +MemoryStats() *ServerMemoryStats
        +Languages() []*Language
        +ProcessorInfo() *ProcessorInfo
        +DiskVolumes() []DiskVolumeInfo
    }

    class ServerInfo {
        +Name string
        +Edition string
        +ProductVersion string
        +ProductLevel string
        +Collation string
        +IsClustered bool
        +IsHADREnabled bool
        +IsSingleUser bool
        +EngineEdition int
        +OSVersion string
        +PhysicalMemoryMB int64
        +LogicalCPUCount int
        +DefaultDataPath string
        +DefaultLogPath string
        +DefaultBackupPath string
        +VersionMajor int
        +VersionMinor int
        +VersionBuild int
    }

    %% =========================================================
    %% Authentication
    %% =========================================================
    class AuthMethod {
        <<enumeration>>
        AuthSQLServer
        AuthWindows
        AuthEntraMSI
        AuthEntraServicePrincipal
        AuthEntraPassword
        AuthEntraInteractive
        AuthEntraDeviceCode
        AuthEntraDefault
        AuthEntraAzCLI
        AuthEntraAzurePipelines
        AuthEntraServicePrincipalAccessToken
        AuthEntraOnBehalfOf
    }

    class KerberosOptions {
        +ConfigFile string
        +CredCacheFile string
        +KeytabFile string
        +Realm string
        +DNSLookupKDC *bool
        +UDPPreferenceLimit int
        Native SSPI on Windows, unless set.
        Every other platform authenticates
        AuthWindows via Kerberos, using this or
        the ambient kinit cache when it is the
        zero value.
    }

    %% =========================================================
    %% Server security, permissions, memory, languages
    %% =========================================================
    class ServerSecurityInfo {
        +AuthenticationMode string
    }

    class ServerPermissionEntry {
        +Principal string
        +PrincipalType string
        +Grantor string
        +Permission string
        +State string
    }

    class Credential {
        +Name string
        +Identity string
        +CreateDate time.Time
        +ModifyDate time.Time
    }

    class ServerMemoryStats {
        +PhysicalMemoryMB int64
        +AvailableMemoryMB int64
        +TargetServerMemoryMB int64
        +TotalServerMemoryMB int64
    }

    class Language {
        +LangID int
        +Name string
        +Alias string
    }

    class ProcessorInfo {
        +CPUCount int
        +HyperthreadRatio int
        +NUMANodeCount int
        +CPUNUMANode []int
    }

    class DiskVolumeInfo {
        +MountPoint string
        +VolumeName string
        +SamplePath string
        +TotalMB float64
        +AvailableMB float64
    }

    %% =========================================================
    %% Login
    %% =========================================================
    class Login {
        +Name string
        +SID []byte
        +LoginType string
        +IsDisabled bool
        +DefaultDatabase string
        +CreateDate time.Time
        +ModifyDate time.Time
        +Enable() error
        +Disable() error
        +ChangePassword(newPassword) error
        +ChangePasswordWithOptions(pw, mustChange, unlock) error
        +AddServerRoleMember(role) error
        +RemoveServerRoleMember(role) error
        +Drop() error
        +Details() *LoginDetails
        +Rename(newName) error
        +SetDefaultDatabase(name) error
        +SetDefaultLanguage(lang) error
        +SetPasswordPolicy(checkPolicy, checkExpiration) error
        +MapCredential(credential) error
        +UnmapCredential(credential) error
        +UserMappings() []*LoginUserMapping
        +MapToDatabase(dbName, user, schema) error
        +UnmapFromDatabase(dbName) error
    }

    class LoginDetails {
        +IsLocked bool
        +IsExpired bool
        +MustChangePassword bool
        +IsPolicyChecked bool
        +IsExpirationChecked bool
        +PasswordLastSet time.Time
        +LastLogin time.Time
        +BadPasswordCount int
        +BadPasswordTime time.Time
        +DefaultLanguage string
        +CredentialName string
        +ConnectSQLState string
    }

    class LoginUserMapping {
        +Database string
        +User string
        +DefaultSchema string
        +Roles []string
    }

    class nStringLiteral {
        <<internal helper>>
        Quotes a password as an N'...'
        T-SQL string literal, escaping
        any embedded quote.
        Used by CreateLogin and ChangePassword —
        HASHED is never used, since it tells
        SQL Server the value is already one of
        its own password-hash formats, not
        cleartext.
    }

    %% =========================================================
    %% Database
    %% =========================================================
    class Database {
        -server *Server
        -name string
        -id int
        -state string
        -recoveryModel RecoveryModel
        -compatLevel CompatibilityLevel
        -collation string
        -isReadOnly bool
        -createDate time.Time
        +Name() string
        +ID() int
        +State() string
        +IsSystem() bool
        +RecoveryModel() RecoveryModel
        +CompatibilityLevel() CompatibilityLevel
        +Tables() []*Table
        +TablesBySchema(schema) []*Table
        +TableByName(schema, name) *Table
        +CreateTable(req) error
        +DropTable(schema, name, cascade) error
        +Catalog() *Catalog
        +SystemCatalog() *Catalog
        +Views() []*View
        +StoredProcedures() []*StoredProcedure
        +CreateStoredProcedure(schema, name, body) error
        +DropStoredProcedure(schema, name) error
        +UserDefinedFunctions() []*UserDefinedFunction
        +SystemViews() []*View
        +SystemStoredProcedures() []*StoredProcedure
        +SystemFunctions() []*UserDefinedFunction
        +Schemas() []*Schema
        +CreateSchema(name, owner) error
        +DropSchema(name) error
        +Users() []*User
        +UserByName(name) *User
        +CreateUser(user, login, schema) error
        +DropUser(name) error
        +DatabaseRoles() []*DatabaseRole
        +RoleByName(name) *DatabaseRole
        +RoleMembers(role) []*RoleMember
        +AddRoleMember(role, member) error
        +RemoveRoleMember(role, member) error
        +FileGroups() []*FileGroup
        +Triggers() []*Trigger
        +Sequences() []*Sequence
        +Synonyms() []*Synonym
        +PartitionFunctions() []*PartitionFunction
        +PartitionSchemes() []*PartitionScheme
        +ExtendedProperties(level) []*ExtendedProperty
        +AddExtendedProperty(name, value, level) error
        +SetExtendedProperty(name, value, level) error
        +DropExtendedProperty(name, level) error
        +ColumnMasterKeys() []*ColumnMasterKey
        +ColumnEncryptionKeys() []*ColumnEncryptionKey
        +SecurityPolicies() []*SecurityPolicy
        +SpaceUsed() SpaceInfo
        +SetRecoveryModel(model) error
        +SetCompatibilityLevel(level) error
        +SetReadOnly(bool) error
        +SetUserAccess(mode) error
        +SetOffline() error
        +SetOnline() error
        +Options() *DatabaseOptions
        +SetDatabaseOption(opt, value) error
        +SetOwner(principal) error
        +DatabaseScopedConfigs() []*DatabaseScopedConfig
        +SetDatabaseScopedConfig(name, value, forSecondary) error
        +QueryStore() *QueryStoreInfo
        +SetQueryStoreOptions(opts) error
        +FlushQueryStore() error
        +ClearQueryStore() error
        +Files() []*DatabaseFileInfo
        +AddFile(spec) error
        +AlterFile(name, m) error
        +RemoveFile(name) error
        +AddFileGroup(name) error
        +RemoveFileGroup(name) error
        +SetDefaultFileGroup(name) error
        +SetFileGroupReadOnly(name, ro) error
        +ChangeTracking() *ChangeTrackingInfo
        +SetChangeTracking(info) error
        +TableChangeTracking() []*TableChangeTracking
        +SetTableChangeTracking(schema, name, enable, cols) error
        +Dependencies(schema, name) []*Dependency
        +Dependents(schema, name) []*Dependency
        +Search(pattern) []*SearchResult
        +Permissions(schema, name) []*PermissionEntry
        +GrantPermission(schema, name, perm, principal) error
        +DenyPermission(schema, name, perm, principal) error
        +RevokePermission(schema, name, perm, principal) error
        +PermissionsForPrincipal(principal) []*PrincipalSecurable
        +SchemaPermissions(schema) []*PermissionEntry
        +GrantSchemaPermission(schema, perm, principal) error
        +DenySchemaPermission(schema, perm, principal) error
        +RevokeSchemaPermission(schema, perm, principal) error
        +DatabasePermissions() []*DatabasePermissionEntry
        +GrantDatabasePermission(perm, principal) error
        +DenyDatabasePermission(perm, principal) error
        +RevokeDatabasePermission(perm, principal) error
        +EstimatedPlan(sql) *ExecutionPlan
        +ActualPlan(sql) *ExecutionPlan
        +ExecProc(schema, name, params) ProcResult
        +BulkInsert(bc, rows) int64
    }

    %% =========================================================
    %% Connection helpers (internal)
    %% =========================================================
    class withConn {
        <<internal helper>>
        Acquires *sql.Conn from pool.
        Executes USE db, retried on a
        transient failure. Runs callback
        fn(*sql.Conn) — NOT retried, since
        fn is the caller's actual write.
        Releases conn via defer.
        Used by Database.exec.
    }

    class dbRows {
        <<internal type>>
        -Rows *sql.Rows
        -conn *sql.Conn
        +Close() error
        Closes Rows then the conn pinned
        for them. *sql.Rows.Close alone
        leaves the conn checked out of the
        pool forever. Returned by
        Database.query().
    }

    class DatabaseQueryRow {
        <<internal helper>>
        Database.queryRow(ctx, scan, q, args)
        Acquires conn, runs USE, hands the row
        to scan — all inside one retry unit.
        scan must run inside it: QueryRowContext
        never errors, only Scan does.
    }

    class ServerQuery {
        <<internal helpers>>
        Server.query(ctx, q, args)
        Server.queryRow(ctx, scan, q, args)
        Server.queryRowScan(ctx, q, args, dest)
        Server-scoped counterparts, with no USE
        to redo. queryRowScan is the bare-Scan
        convenience over queryRow.
    }

    class withRetry {
        <<internal helper>>
        Generic retry wrapper for idempotent
        reads only. 3 attempts, linear backoff
        of attempt times 50ms. Used by every
        query/queryRow helper above.
    }

    class IsRetryable {
        <<package function>>
        True for the driver's RetryableError, a
        dropped pooled connection (ErrBadConn),
        a net.Error, a corrupted TDS stream, a
        connection-severing ServerError, or EOF
        — including wrapped errors. Exported so
        callers running their own statements can
        make the same retry decision.
    }

    %% =========================================================
    %% Quoting (shared identifier / literal escaping)
    %% =========================================================
    class Quoting {
        <<package functions>>
        +QuoteName(name) string
        +QuoteLiteral(s) string
        Backed by the driver's own TSQLQuoter,
        so gosmo, its callers, and gossms share
        one quoting implementation. The internal
        quoteIdent helper delegates to QuoteName.
    }

    %% =========================================================
    %% Errors
    %% =========================================================
    class SQLError {
        +Number int32
        +State uint8
        +Class uint8
        +Message string
        +ServerName string
        +ProcName string
        +LineNo int32
        +All []SQLError
        +AsSQLError(err) *SQLError
        +Header() string
        +Error() string
        +IsError() bool
    }

    %% =========================================================
    %% Scripting pending writes (dry-run)
    %% =========================================================
    class ScriptCollector {
        -mu sync.Mutex
        +Statements []string
        +WithScript(ctx) *ScriptCollector
        Captures the exact statement(s) a set of
        pending write calls would run, without
        running them. Every write funnels through
        Server.execContext or Database.exec, the
        two chokepoints WithScript intercepts.
        Statements is mutex-guarded: one collector
        may be shared across goroutines.
    }

    %% =========================================================
    %% Database files, filegroups, and options
    %% =========================================================
    class DatabaseFileInfo {
        +FileID int
        +Name string
        +PhysicalName string
        +Type string
        +FileGroup string
        +State string
        +SizeKB int64
        +MaxSizeKB int64
        +GrowthKB int64
        +GrowthPercent int
        +IsPercentGrowth bool
    }

    class DatabaseFileSpec {
        +Name string
        +FileGroup string
        +Type string
        +Path string
        +SizeKB int64
        +GrowthKB int64
        +GrowthPercent int
        +MaxSizeKB int64
    }

    class FileModify {
        +NewName string
        +SizeKB int64
        +GrowthKB int64
        +GrowthPercent int
        +MaxSizeKB int64
    }

    class DatabaseOptions {
        +Owner string
        +PageVerify string
        +UserAccess string
        +Containment string
        +DefaultCursor string
        +SnapshotIsolation string
        +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
    }

    %% =========================================================
    %% Change tracking
    %% =========================================================
    class ChangeTrackingInfo {
        +Enabled bool
        +AutoCleanup bool
        +RetentionPeriod int
        +RetentionUnit string
    }

    class TableChangeTracking {
        +Schema string
        +Name string
        +Enabled bool
        +TrackColumnsUpdated bool
    }

    %% =========================================================
    %% Catalog snapshot (bulk table/view + column inventory)
    %% =========================================================
    class Catalog {
        +Schemas []string
        +Objects []CatalogObject
    }

    class CatalogObject {
        +ObjectID int
        +Schema string
        +Name string
        +Type CatalogObjectType
        +Columns []CatalogColumn
    }

    class CatalogColumn {
        +Name string
        +DataType DataType
        +MaxLength int
        +Precision int
        +Scale int
        +IsNullable bool
    }

    %% =========================================================
    %% Query Store and Database Scoped Configuration
    %% =========================================================
    class QueryStoreInfo {
        +DesiredState string
        +ActualState string
        +ReadOnlyReason int
        +CurrentStorageMB int64
        +MaxStorageMB int64
        +CaptureMode string
        +SizeCleanupMode string
        +StaleThresholdDays int
        +WaitStatsCaptureMode string
    }

    class DatabaseScopedConfig {
        +ID int
        +Name string
        +Value string
        +ValueForSecondary string
        +IsValueDefault bool
    }

    %% =========================================================
    %% Dependencies and object search
    %% =========================================================
    class Dependency {
        +Schema string
        +Name string
        +TypeDesc string
        +IsSchemaBound bool
    }

    class SearchResult {
        +Schema string
        +Name string
        +TypeDesc string
    }

    %% =========================================================
    %% Execution plans
    %% =========================================================
    class ExecutionPlan {
        +XML string
    }

    %% =========================================================
    %% Object and database-scoped permissions
    %% =========================================================
    class PermissionEntry {
        +Principal string
        +PrincipalType string
        +Grantor string
        +Permission ObjectPermission
        +State PermissionState
    }

    class DatabasePermissionEntry {
        +Principal string
        +PrincipalType string
        +Grantor string
        +Permission string
        +State string
    }

    class PrincipalSecurable {
        +SecurableType string
        +Schema string
        +Name string
        +Permission string
        +State string
    }

    %% =========================================================
    %% Bulk copy (fast import — bcp / SSMS "Import Data")
    %% =========================================================
    class BulkCopy {
        +Schema string
        +Table string
        +Columns []string
        +Options BulkOptions
        +SliceRows(rows) iter.Seq2
    }

    class BulkOptions {
        +CheckConstraints bool
        +FireTriggers bool
        +KeepNulls bool
        +TableLock bool
        +RowsPerBatch int
        +KilobytesPerBatch int
        +Order []string
    }

    %% =========================================================
    %% Stored-procedure execution
    %% =========================================================
    class ProcParam {
        +In(name, value) ProcParam
        +Out(name, dest) ProcParam
        +InOut(name, dest) ProcParam
    }

    class ProcResult {
        +ReturnStatus int32
    }

    %% =========================================================
    %% Table and its children
    %% =========================================================
    class Table {
        +ObjectID int
        +Schema string
        +Name string
        +CreateDate time.Time
        +ModifyDate time.Time
        +HasReplicationFilter bool
        +IsMemoryOptimized bool
        +FullName() string
        +Columns() []*Column
        +Indexes() []*Index
        +ForeignKeys() []*ForeignKey
        +CheckConstraints() []*CheckConstraint
        +Statistics() []*Statistic
        +Partitions() []*Partition
        +Triggers() []*Trigger
        +RowCount() int64
        +CountWhere(predicate) int64
        +CheckWhereSyntax(predicate) error
        +Detail() *TableDetail
        +SpaceUsed() *TableSpaceInfo
        +TruncateTable() error
        +FragmentationStats(mode) []*IndexFragmentation
        +RebuildAllIndexes(fillFactor) error
        +UpdateAllStatistics(samplePct) error
        +CreateIndex(req) error
        +CreateStatistic(name, cols, pct) error
        +AddColumn(col) error
        +AlterColumn(col) error
        +DropColumn(name) error
    }

    class Column {
        +Name string
        +OrdinalPosition int
        +DataType DataType
        +MaxLength int
        +Precision int
        +Scale int
        +IsNullable bool
        +IsIdentity bool
        +IdentitySeed int64
        +IdentityIncrement int64
        +IsComputed bool
        +ComputedText string
        +DefaultValue *ColumnDefault
        +IsRowGUID bool
        +IsPrimaryKey bool
        +Collation string
    }

    class Index {
        +Name string
        +IndexID int
        +Type IndexType
        +IsClustered bool
        +IsUnique bool
        +IsPrimaryKey bool
        +IsDisabled bool
        +FillFactor int
        +IsPadded bool
        +IgnoreDupKey bool
        +AllowRowLocks bool
        +AllowPageLocks bool
        +DataCompression string
        +KeyColumns []IndexColumn
        +IncludedColumns []IndexColumn
        +FilterDefinition string
        +Rebuild(t, fillFactor) error
        +RebuildWithOptions(t, fillFactor, padIndex, compression) error
        +Reorganize(t) error
        +Disable(t) error
        +Enable(t) error
        +Rename(t, newName) error
        +SetOptions(t, ignoreDupKey, rowLocks, pageLocks) error
        +SetLockOptions(t, rowLocks, pageLocks) error
        +SetIncludedColumns(t, columns) error
        +UpdateStatistics(t) error
        +StorageInfo(t) *IndexStorageInfo
        +Fragmentation(t, mode) *IndexFragmentation
        +Drop(t) error
    }

    class IndexStorageInfo {
        +FileGroup string
        +PartitionScheme string
        +PartitionColumn string
        +RowCount int64
        +UsedKB int64
        +ReservedKB int64
        +AvgRecordSize float64
        +Allocations []IndexAllocationUnit
    }

    class IndexAllocationUnit {
        +Type string
        +Pages int64
        +UsedKB int64
    }

    class IndexFragmentation {
        +IndexName string
        +IndexID int
        +AvgFragmentationPct float64
        +PageCount int64
        +FragmentCount int64
        +AvgPageSpaceUsedPct float64
    }

    class ForeignKey {
        +Name string
        +Columns []string
        +ReferencedTable string
        +ReferencedSchema string
        +ReferencedColumns []string
        +DeleteAction string
        +UpdateAction string
        +IsDisabled bool
    }

    class CheckConstraint {
        +Name string
        +Definition string
        +IsDisabled bool
        +Column string
    }

    class Statistic {
        +Name string
        +StatID int
        +IsAutoCreated bool
        +IsUserCreated bool
        +HasFilter bool
        +FilterDef string
        +LastUpdated time.Time
        +RowsSampled int64
        +TotalRows int64
        +Steps int
        +UnfilteredRows int64
        +NoRecompute bool
        +IsIncremental bool
        +ModificationCounter int64
        +Columns() []string
        +Header() *StatisticHeader
        +DensityVector() []*StatisticDensity
        +Histogram() []*StatisticHistogramStep
        +Update(samplePct) error
        +Drop() error
    }

    class StatisticHeader {
        +Updated string
        +Rows int64
        +RowsSampled int64
        +Steps int
        +Density float64
        +AverageKeyLength float64
        +StringIndex string
        +FilterExpression string
        +UnfilteredRows int64
        +PersistedSamplePercent float64
    }

    class StatisticDensity {
        +AllDensity float64
        +AverageLength float64
        +Columns string
    }

    class StatisticHistogramStep {
        +RangeHighKey string
        +RangeRows float64
        +EqRows float64
        +DistinctRangeRows int64
        +AvgRangeRows float64
    }

    class TableDetail {
        +SchemaOwner string
        +LockEscalation string
        +UsesAnsiNulls bool
        +IsReplicated bool
        +IsTrackedByCDC bool
        +TemporalType string
        +Durability string
        +LedgerType string
        +PrimaryKeyName string
        +DataSpace string
    }

    class TableSpaceInfo {
        +ReservedKB int64
        +DataKB int64
        +IndexKB int64
        +LOBKB int64
        +UnusedKB int64
        +FileGroup string
    }

    %% =========================================================
    %% Scripter (generates CREATE DDL for existing objects — distinct
    %% from ScriptCollector, which captures pending write statements)
    %% =========================================================
    class Scripter {
        -db *Database
        -opts ScriptOptions
        +NewScripter(db, opts) *Scripter
        +ScriptTable(schema, name) string
        +ScriptView(schema, name) string
        +ScriptStoredProcedure(schema, name) string
        +ScriptFunction(schema, name) string
        +ScriptDatabase() string
    }

    class ScriptOptions {
        +IncludeHeaders bool
        +IncludeIfNotExists bool
        +ScriptDrops bool
        +SchemaQualify bool
        +AnsiPadding bool
    }

    %% =========================================================
    %% Database objects
    %% =========================================================
    class Schema {
        +Name string
        +ID int
        +Owner string
        +ObjectCount() int
    }

    class View {
        +ObjectID int
        +Schema string
        +Name string
        +Definition string
        +CreateDate time.Time
        +ModifyDate time.Time
    }

    class StoredProcedure {
        +ObjectID int
        +Schema string
        +Name string
        +Definition string
        +CreateDate time.Time
        +ModifyDate time.Time
    }

    class UserDefinedFunction {
        +ObjectID int
        +Schema string
        +Name string
        +FuncType string
        +Definition string
        +CreateDate time.Time
        +ModifyDate time.Time
    }

    class User {
        +Name string
        +ID int
        +UserType string
        +DefaultSchema string
        +AuthType string
        +CreateDate time.Time
        +ModifyDate time.Time
        +SID []byte
        +LoginName string
        +LoginDisabled bool
        +Rename(newName) error
        +SetDefaultSchema(schemaName) error
        +SetLogin(loginName) error
    }

    class DatabaseRole {
        +Name string
        +ID int
        +IsFixedRole bool
        +Owner string
        +Members []string
        +SID []byte
        +CreateDate time.Time
        +ModifyDate time.Time
        +Rename(newName) error
        +ChangeOwner(newOwner) error
    }

    class RoleMember {
        +Name string
        +Type string
    }

    class FileGroup {
        +Name string
        +IsDefault bool
        +IsReadOnly bool
        +Files []DatabaseFile
    }

    class Trigger {
        +Name string
        +TableName string
        +Schema string
        +IsEnabled bool
        +Events []string
        +Definition string
    }

    class ServerRole {
        +ID int
        +Name string
        +IsFixedRole bool
        +Owner string
        +SID []byte
        +CreateDate time.Time
        +ModifyDate time.Time
        +Members []string
        +Rename(newName) error
        +ChangeOwner(newOwner) error
    }

    class LinkedServer {
        +Name string
        +Product string
        +Provider string
        +DataSource string
        +IsRemote bool
    }

    %% =========================================================
    %% Backup / Restore
    %% =========================================================
    class BackupOptions {
        +Database string
        +Devices []string
        +BackupType BackupType
        +CopyOnly bool
        +Compression bool
        +Checksum bool
        +Description string
        +Name string
        +MediaName string
        +Expiry time.Time
        +RetainDays int
        +BlockSize int
        +BufferCount int
        +MaxTransferSize int
        +Stats int
        +Init bool
        +Format bool
        +Progress func
        +BuildBackupStatement(opts) string
    }

    class RestoreOptions {
        +Database string
        +Devices []string
        +RestoreType RestoreType
        +RelocateFiles []RelocateFile
        +Recovery bool
        +Replace bool
        +Checksum bool
        +Stats int
        +StopAt time.Time
        +StopAtMarkName string
        +FileNumber int
        +Progress func
        +BuildRestoreStatement(opts) string
    }

    class BackupHeader {
        +BackupName string
        +Description string
        +BackupType BackupAction
        +Position int
        +DatabaseName string
        +BackupStart time.Time
        +BackupFinish time.Time
        +BackupSize int64
        +Compressed bool
        +HasChecksums bool
        +IsCopyOnly bool
        +RecoveryModel string
    }

    class BackupFile {
        +LogicalName string
        +PhysicalName string
        +Type string
        +FileGroupName string
        +Size int64
        +MaxSize int64
    }

    %% =========================================================
    %% SQL Server Agent
    %% =========================================================
    class AgentStatus {
        +Running bool
        +StatusText string
        +LastStartupTime time.Time
    }

    class Job {
        +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 string
        +LastRunDate time.Time
        +LastRunOutcome JobOutcome
        +LastRunDuration Duration
        +NextRunDate time.Time
        +CurrentState JobState
        +Steps() []*JobStep
        +AddStep(req) error
        +Schedules() []*Schedule
        +AddSchedule(req) error
        +AttachSchedule(name) error
        +DetachSchedule(name) error
        +History(limit) []*JobHistoryEntry
        +Start(stepName) error
        +Stop() error
        +Enable() error
        +Disable() error
        +Rename(newName) error
        +SetDescription(desc) error
        +SetCategory(category) error
        +SetOwner(login) error
        +SetStartStep(stepID) error
        +SetDeleteLevel(level) error
        +SetEmailNotify(operator, level) error
        +Drop() error
    }

    class JobStep {
        +StepID int
        +Name string
        +Subsystem string
        +Command string
        +Database string
        +OnSuccessAction int
        +OnSuccessStepID int
        +OnFailAction int
        +OnFailStepID int
        +LastRunOutcome JobOutcome
        +LastRunDuration int
        +RetryAttempts int
        +RetryInterval int
        +OutputFileName string
        +Flags int
        +Update(req) error
        +Delete() error
    }

    class JobHistoryEntry {
        +JobName string
        +RunDate time.Time
        +Duration Duration
        +Outcome JobOutcome
        +Message string
        +StepID int
        +StepName string
    }

    class Alert {
        +ID int
        +Name string
        +Enabled bool
        +EventSource string
        +ErrorNumber int
        +Severity int
        +DatabaseName string
        +DelayBetweenResponses Duration
        +NotificationMessage string
        +IncludeEventDescriptionIn int
        +Category string
        +JobName string
        +PerformanceCondition string
        +OccurrenceCount int
        +LastOccurrence time.Time
        +LastResponse time.Time
        +IsEventAlert() bool
        +Enable() error
        +Disable() error
        +Rename(newName) error
        +SetTrigger(errorNumber, severity) error
        +SetDatabase(dbName) error
        +SetDelay(d) error
        +SetNotificationMessage(msg) error
        +SetJobResponse(jobName) error
        +SetCategory(category) error
        +Notifications() []*AlertNotification
        +Notify(operator, method) error
        +RemoveNotify(operator) error
        +Drop() error
    }

    class AlertNotification {
        +OperatorName string
        +Method NotificationMethod
    }

    class Operator {
        +ID int
        +Name string
        +Enabled bool
        +EmailAddress string
        +PagerAddress string
        +NetSendAddress string
        +Category string
        +LastEmailDate time.Time
        +LastPagerDate time.Time
        +LastNetSendDate time.Time
        +Enable() error
        +Disable() error
        +Rename(newName) error
        +SetEmailAddress(addr) error
        +SetCategory(category) error
        +NotifyingAlerts() []*AlertNotificationRef
        +NotifyingJobs() []*JobNotificationRef
        +Drop() error
    }

    class AlertNotificationRef {
        +AlertName string
        +Method NotificationMethod
    }

    class JobNotificationRef {
        +JobName string
        +Level NotifyLevel
    }

    class Schedule {
        +ID int
        +Name string
        +Enabled bool
        +FreqType ScheduleFreqType
        +FreqInterval int
        +FreqSubdayType ScheduleSubdayType
        +FreqSubdayInterval int
        +FreqRelativeInterval int
        +FreqRecurrenceFactor int
        +ActiveStartDate time.Time
        +ActiveEndDate time.Time
        +ActiveStartTime int
        +ActiveEndTime int
        +OwnerLoginName string
        +CreateDate time.Time
        +ModifyDate time.Time
        +Description() string
        +Enable() error
        +Disable() error
        +Rename(newName) error
        +SetOwner(login) error
        +SetFrequency(f) error
        +SetActiveRange(startDate, endDate, startTime, endTime) error
        +Jobs() []*Job
        +Drop() error
    }

    class ScheduleFrequency {
        +FreqType ScheduleFreqType
        +FreqInterval int
        +FreqSubdayType ScheduleSubdayType
        +FreqSubdayInterval int
        +FreqRelativeInterval int
        +FreqRecurrenceFactor int
    }

    class Category {
        +ID int
        +Class CategoryClass
        +Name string
    }

    class ScheduleFreqType {
        <<enumeration>>
        FreqOnce
        FreqDaily
        FreqWeekly
        FreqMonthly
        FreqMonthlyRelative
        FreqAutoStart
        FreqOnIdle
    }

    class ScheduleSubdayType {
        <<enumeration>>
        SubdayOnce
        SubdaySeconds
        SubdayMinutes
        SubdayHours
    }

    class NotificationMethod {
        <<enumeration>>
        NotifyMethodEmail
        NotifyMethodPager
        NotifyMethodNetSend
        +String() string
    }

    class NotifyLevel {
        <<enumeration>>
        NotifyNever
        NotifyOnSuccess
        NotifyOnFailure
        NotifyOnComplete
    }

    class CategoryClass {
        <<enumeration>>
        CategoryClassJob
        CategoryClassAlert
        CategoryClassOperator
    }

    %% =========================================================
    %% Relationships
    %% =========================================================
    ConnectionOptions --> AuthMethod : uses
    ConnectionOptions --> KerberosOptions : configures AuthWindows via
    Server --> ConnectionOptions : created from
    Server --> ServerInfo : has
    Server "1" --> "*" Database : owns
    Server "1" --> "*" Login : owns
    Server "1" --> "*" ServerRole : owns
    Server "1" --> "*" RoleMember : ServerRoleMembers() returns
    Server "1" --> "*" LinkedServer : owns
    Server --> AgentStatus : AgentInfo() returns
    Server "1" --> "*" Job : owns
    Server "1" --> "*" Alert : owns
    Server "1" --> "*" Operator : owns
    Server "1" --> "*" Schedule : owns
    Server "1" --> "*" Category : owns
    Server "1" --> "*" JobHistoryEntry : JobHistory() returns
    Server --> BackupOptions : accepts
    Server --> RestoreOptions : accepts
    Server --> ServerSecurityInfo : has
    Server "1" --> "*" ServerPermissionEntry : grants
    Server "1" --> "*" Credential : owns
    Server --> ServerMemoryStats : has
    Server "1" --> "*" Language : lists
    Server --> ProcessorInfo : has
    Server "1" --> "*" DiskVolumeInfo : lists
    Server "1" --> "*" BackupHeader : BackupHeaders() returns
    Server "1" --> "*" BackupFile : BackupFileList() returns

    Login ..> nStringLiteral : password quoted by
    Login --> LoginDetails : has
    Login "1" --> "*" LoginUserMapping : mapped via

    Database "1" --> "*" Table : contains
    Database "1" --> "*" View : contains
    Database "1" --> "*" StoredProcedure : contains
    Database "1" --> "*" UserDefinedFunction : contains
    Database "1" --> "*" Schema : contains
    Database "1" --> "*" User : contains
    Database "1" --> "*" DatabaseRole : contains
    Database "1" --> "*" FileGroup : contains
    Database "1" --> "*" Trigger : contains
    Database "1" --> "*" DatabaseFileInfo : contains
    Database --> DatabaseOptions : has
    Database --> ChangeTrackingInfo : has
    Database "1" --> "*" TableChangeTracking : tracks
    Database "1" --> "*" Dependency : dependencies of
    Database "1" --> "*" SearchResult : search() returns
    Database --> ExecutionPlan : produces
    Database "1" --> "*" PermissionEntry : grants
    Database "1" --> "*" DatabasePermissionEntry : grants
    Database "1" --> "*" PrincipalSecurable : PermissionsForPrincipal() returns
    Database --> Catalog : Catalog()/SystemCatalog() returns
    Catalog "1" --> "*" CatalogObject : contains
    CatalogObject "1" --> "*" CatalogColumn : has
    Database --> QueryStoreInfo : has
    Database "1" --> "*" DatabaseScopedConfig : lists
    Database "1" --> "*" RoleMember : RoleMembers() returns
    Database ..> BulkCopy : bulk-loads via
    Database ..> ProcParam : executes procs with
    Database --> ProcResult : returns

    Database ..> withConn : writes run via
    Database ..> dbRows : query() returns
    Database ..> DatabaseQueryRow : single-row reads via
    Database ..> withRetry : reads retried via
    Server ..> ServerQuery : reads run via
    Server ..> withRetry : reads retried via

    withRetry <.. withConn : acquire+USE retried by
    withRetry <.. dbRows : acquire+USE+query retried by
    withRetry <.. DatabaseQueryRow : whole scan retried by
    withRetry <.. ServerQuery : whole scan retried by
    withRetry <.. IsRetryable : same failure test as

    Table "1" --> "*" Column : has
    Table "1" --> "*" Index : has
    Table "1" --> "*" ForeignKey : has
    Table "1" --> "*" CheckConstraint : has
    Table "1" --> "*" Statistic : has
    Table "1" --> "*" Trigger : has
    Table --> TableDetail : has
    Table --> TableSpaceInfo : has
    Table "1" --> "*" IndexFragmentation : FragmentationStats() returns

    Index --> IndexStorageInfo : StorageInfo() returns
    IndexStorageInfo "1" --> "*" IndexAllocationUnit : breaks down into
    Index --> IndexFragmentation : Fragmentation() returns

    Statistic --> StatisticHeader : Header() returns
    Statistic "1" --> "*" StatisticDensity : DensityVector() returns
    Statistic "1" --> "*" StatisticHistogramStep : Histogram() returns

    Job "1" --> "*" JobStep : has
    Job "1" --> "*" Schedule : attached to
    Job "1" --> "*" JobHistoryEntry : History() returns
    Job --> NotifyLevel : notified per
    Schedule --> ScheduleFrequency : SetFrequency() accepts
    Schedule --> ScheduleFreqType : recurs per
    Schedule --> ScheduleSubdayType : repeats per
    Alert "1" --> "*" AlertNotification : notifies via
    Alert --> Job : responds by running
    Operator "1" --> "*" AlertNotificationRef : notified by
    Operator "1" --> "*" JobNotificationRef : emailed by
    AlertNotification --> NotificationMethod : delivered by
    Category --> CategoryClass : classified by

    Scripter --> Database : scripts objects from
    Scripter --> ScriptOptions : configured by

    ScriptCollector ..> Server : captures writes from
    ScriptCollector ..> Database : captures writes from

Security

  • Passwords are escaped, never spliced in raw. CreateLogin, ChangePassword, and ChangePasswordWithOptions quote the password as an N'...' literal through the same nStringLiteral escaping every other string literal in the package uses, so it's injection-proof regardless of password content.
  • Connection lifetimes are correctly scoped. Database.query returns a *dbRows that owns both the *sql.Rows and the *sql.Conn pinned to run its USE, closing both together — *sql.Rows.Close on its own would leave that connection checked out of the pool for good.
  • Values that can't be parameterized are validated by shape or allowlist. DDL can't parameterize keyword or literal arguments, so anything spliced into one is checked first: recovery models, data types, and backup actions against their known sets; partition function boundary values against the shape of a well-formed SQL Server literal; Query Store mode keywords and index data-compression settings against their allowlists.
  • One shared quoting implementation. QuoteName and QuoteLiteral wrap the driver's own TSQLQuoter, so gosmo's internal identifier/literal escaping — and any caller or downstream consumer (e.g. gossms) building its own DDL — go through the same tested implementation rather than a hand-rolled one.
  • Permission and SET-option names are allowlisted, not interpolated. GRANT/DENY/REVOKE and ALTER DATABASE ... SET are DDL and can't parameterize their keyword arguments; every method that accepts one (GrantServerPermission, GrantPermission, GrantDatabasePermission, SetDatabaseOption, ...) rejects any name not on its allowlist instead of splicing caller input directly into the statement.

Packages

Path Purpose
/ All SMO types and logic
examples/ Full end-to-end demo

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)

Feature map

Server
SMO equivalent gosmo
Server.Databases srv.Databases() / srv.Database(name) (no-I/O handle)
Current database srv.CurrentDatabase()
Current login (SUSER_NAME()) srv.CurrentLogin()
Server.Logins srv.Logins() / srv.LoginByName(name) / srv.Login(name) (no-I/O handle)
Server.Roles srv.ServerRoles() / srv.ServerRoleByName(name) / srv.ServerRoleMembers(role)
Server role administration role.Rename(newName) / role.ChangeOwner(owner) / srv.Add|RemoveServerRoleMember(role, member)
Server.LinkedServers srv.LinkedServers()
Server.Configuration srv.Configurations()
Server.JobServer (Agent) see SQL Server Agent below
Active sessions srv.ActiveSessions(includeSystem)
Kill session srv.KillSession(id)
Error log srv.ReadErrorLog(n)
Database Mail srv.MailProfiles() / srv.SendMail(...)
Create login (safe) srv.CreateLogin(name, password, opts)
Authentication mode srv.SecurityInfo()
Server-level permissions srv.ServerPermissions() / srv.Grant|Deny|RevokeServerPermission(...) / srv.ServerPermissionNames()
Credentials srv.Credentials()
Live memory stats srv.MemoryStats()
Languages srv.Languages()
Processors / NUMA topology srv.ProcessorInfo()
Disk volumes srv.DiskVolumes()
Verify / inspect a backup device srv.VerifyBackup(device) / srv.BackupHeaders(device) / srv.BackupFileList(device)
Database
SMO equivalent gosmo
Is a system database db.IsSystem()
Database.Tables db.Tables() / db.TablesBySchema(schema)
Bulk table/view + column snapshot db.Catalog() (user objects) / db.SystemCatalog() (sys schema)
Database.Views db.Views()
Database.StoredProcedures db.StoredProcedures()
Database.UserDefinedFunctions db.UserDefinedFunctions()
System Views/Procedures/Functions db.SystemViews() / db.SystemStoredProcedures() / db.SystemFunctions()
Database.Schemas db.Schemas() / schema.ObjectCount()
Database.Users db.Users() / db.UserByName(name)
Database user administration user.Rename(newName) / user.SetDefaultSchema(schemaName) / user.SetLogin(loginName)
Database.Roles db.DatabaseRoles() / db.RoleByName(name) / db.RoleMembers(roleName)
Database role administration role.Rename(newName) / role.ChangeOwner(newOwner)
Database.FileGroups db.FileGroups()
Database.Triggers db.Triggers()
Database.Sequences db.Sequences()
Database.Synonyms db.Synonyms()
Partition functions db.PartitionFunctions()
Partition schemes db.PartitionSchemes()
Extended properties db.ExtendedProperties(level) / db.AddExtendedProperty(...) / db.SetExtendedProperty(...) / db.DropExtendedProperty(...)
Column master keys db.ColumnMasterKeys()
Column encryption keys db.ColumnEncryptionKeys()
Security policies (RLS) db.SecurityPolicies()
Database.RecoveryModel db.SetRecoveryModel(model)
Database.CompatibilityLevel db.SetCompatibilityLevel(level)
Space used db.SpaceUsed()
ALTER DATABASE SET options db.Options() / db.SetDatabaseOption(opt, value)
Restrict access (single/multi/restricted user) db.SetUserAccess(mode)
Take offline / bring online db.SetOffline() / db.SetOnline()
Change ownership db.SetOwner(principal)
Database Scoped Configuration db.DatabaseScopedConfigs() / db.SetDatabaseScopedConfig(name, value, forSecondary)
Query Store db.QueryStore() / db.SetQueryStoreOptions(opts) / db.FlushQueryStore() / db.ClearQueryStore()
Every file, incl. log db.Files()
Add / alter / remove file db.AddFile(spec) / db.AlterFile(name, m) / db.RemoveFile(name)
Add / remove filegroup db.AddFileGroup(name) / db.RemoveFileGroup(name)
Filegroup default / read-only db.SetDefaultFileGroup(name) / db.SetFileGroupReadOnly(name, ro)
CREATE DATABASE file placement CreateDatabaseOptions.PrimaryFile / .LogFile (*DatabaseFileSpec)
Change tracking db.ChangeTracking() / db.SetChangeTracking(info)
Table change tracking db.TableChangeTracking() / db.SetTableChangeTracking(...)
Database-level permissions db.DatabasePermissions() / db.Grant|Deny|RevokeDatabasePermission(...)
Table
SMO equivalent gosmo
Table.Columns t.Columns()
Table.Indexes t.Indexes()
Table.ForeignKeys t.ForeignKeys()
Table.Checks t.CheckConstraints()
Table.Statistics t.Statistics()
Table.Partitions t.Partitions()
Table.Triggers t.Triggers()
Table.RowCount t.RowCount()
Rows matching a filter predicate t.CountWhere(predicate)
Validate a filter predicate t.CheckWhereSyntax(predicate)
Object details (lock escalation, ANSI_NULLS, CDC, temporal, ledger, ...) t.Detail()
Space used (sp_spaceused-style) t.SpaceUsed()
Truncate t.TruncateTable()
Fragmentation t.FragmentationStats(mode)
Rebuild all indexes t.RebuildAllIndexes(fillFactor)
Update all statistics t.UpdateAllStatistics(samplePct)
Create index t.CreateIndex(req)
Add column t.AddColumn(col)
Alter column t.AlterColumn(col)
Drop column t.DropColumn(name)
Index
gosmo
idx.Rebuild(t, fillFactor)
idx.RebuildWithOptions(t, fillFactor, padIndex, dataCompression)
idx.Reorganize(t)
idx.Disable(t) / idx.Enable(t)
idx.Rename(t, newName) — also renames a PK/UNIQUE constraint
idx.SetOptions(t, ignoreDupKey, allowRowLocks, allowPageLocks)
idx.SetLockOptions(t, allowRowLocks, allowPageLocks) — no IGNORE_DUP_KEY, which a PK/UNIQUE-backing index rejects
idx.SetIncludedColumns(t, columns) — via CREATE INDEX ... DROP_EXISTING
idx.UpdateStatistics(t)
idx.StorageInfo(t) — filegroup, partitioning, allocation-unit space
idx.Fragmentation(t, mode) — one index (t.FragmentationStats(mode) does all)
idx.Drop(t)
Statistics
SSMS equivalent gosmo
Statistics of a table t.Statistics() / t.CreateStatistic(name, cols, pct)
Statistic's key columns st.Columns()
DBCC SHOW_STATISTICS header st.Header()*StatisticHeader
... density vector st.DensityVector()[]*StatisticDensity
... histogram st.Histogram()[]*StatisticHistogramStep
Update / drop st.Update(samplePct) / st.Drop()
Login
gosmo
srv.CreateLogin(name, password, opts)
login.ChangePassword(newPassword)
login.Enable() / login.Disable()
login.AddServerRoleMember(role)
login.RemoveServerRoleMember(role)
login.Drop()
login.Rename(newName)
login.SetDefaultDatabase(name) / login.SetDefaultLanguage(name)
login.SetPasswordPolicy(checkPolicy, checkExpiration)
login.ChangePasswordWithOptions(pw, mustChange, unlock)
login.MapCredential(name) / login.UnmapCredential(name)
login.Details() — locked/expired/policy/last-login status
login.UserMappings() / login.MapToDatabase(...) / login.UnmapFromDatabase(db)
Dependencies, search, permissions, and execution plans
SMO / SSMS equivalent gosmo
Object dependencies (uses) db.Dependencies(schema, name)
Object dependencies (used by) db.Dependents(schema, name)
Object search db.Search(pattern)
Object permissions db.Permissions(schema, name)
Grant / deny / revoke db.GrantPermission(...) / db.DenyPermission(...) / db.RevokePermission(...)
Schema permissions db.SchemaPermissions(schema)
Grant / deny / revoke (schema) db.GrantSchemaPermission(...) / db.DenySchemaPermission(...) / db.RevokeSchemaPermission(...)
Every securable one principal holds db.PermissionsForPrincipal(principal)
Permission-name catalogs (for pickers) gosmo.ObjectPermissionNames() / SchemaPermissionNames() / DatabasePermissionNames() / ServerPermissionNames()
Estimated execution plan db.EstimatedPlan(sql) (SET SHOWPLAN_XML, statement not run)
Actual execution plan db.ActualPlan(sql) (SET STATISTICS XML, statement runs)
Scripter
sc := gosmo.NewScripter(db, gosmo.DefaultScriptOptions())
ddl, _ := sc.ScriptTable("dbo", "MyTable")
ddl, _ := sc.ScriptView("dbo", "MyView")
ddl, _ := sc.ScriptStoredProcedure("dbo", "MyProc")
ddl, _ := sc.ScriptFunction("dbo", "MyFunc")
ddl, _ := sc.ScriptDatabase()
Scripting pending writes (WithScript)

Distinct from the Scripter above (which generates CREATE DDL for objects that already exist): WithScript captures the exact statement(s) a set of pending write calls would run, without running them — for an editor-style "preview the SQL" or "script my changes instead of applying them" action.

ctx, script := gosmo.WithScript(context.Background())

srv.GrantServerPermissionContext(ctx, "CONNECT SQL", "app_user")
db.SetDatabaseOptionContext(ctx, gosmo.DBOptAutoShrink, "ON")

for _, stmt := range script.Statements {
    fmt.Println(stmt) // never executed against the server
}

Every write method in the package funnels through one of two chokepoints (Server.execContext, Database.exec); WithScript intercepts there, so this works for any write call, not just an allowlisted subset. Database- scoped statements carry their own USE [db]; prefix, since the caller may run the resulting script against a session scoped to a different database (or none) than the one that produced it. Read methods are unaffected — only the two exec chokepoints consult the collector.

Backup & Restore
srv.Backup(gosmo.BackupOptions{
    Database: "MyDB",
    Devices:  []string{`C:\Backups\MyDB.bak`},
    CopyOnly: true,
    // Optional: receive "N percent processed" notices as the backup runs
    // (Stats defaults to 10 automatically once Progress is set).
    Progress: func(pct int, message string) { fmt.Println(pct, message) },
})

srv.Restore(gosmo.RestoreOptions{
    Database: "MyDB_Restored",
    Devices:  []string{`C:\Backups\MyDB.bak`},
    RelocateFiles: []gosmo.RelocateFile{
        {LogicalName: "MyDB",     PhysicalName: `C:\Data\MyDB.mdf`},
        {LogicalName: "MyDB_log", PhysicalName: `C:\Data\MyDB.ldf`},
    },
    Recovery: true,
    Replace:  true,
    // Optional: same progress callback as Backup, above.
    Progress: func(pct int, message string) { fmt.Println(pct, message) },
})

// Inspect a backup device before restoring — SSMS's Restore Database
// dialog's backup-set/file picker.
headers, _ := srv.BackupHeaders(`C:\Backups\MyDB.bak`)
files, _ := srv.BackupFileList(`C:\Backups\MyDB.bak`)
err := srv.VerifyBackup(`C:\Backups\MyDB.bak`)
SQL Server Agent

Everything under SSMS's SQL Server Agent node that a SQL-only client can reach: jobs and their steps, shared schedules, alerts, operators, and the categories they're filed under. WMI alerts and performance-condition alerts are visible but not manageable — see Features intentionally excluded.

// Is Agent even running? (Reported, not inferred from a failed call.)
status, _ := srv.AgentInfo()
fmt.Println(status.Running, status.StatusText, status.LastStartupTime)
Jobs and steps
job, _ := srv.CreateJob(gosmo.CreateJobRequest{Name: "NightlyBackup", Enabled: true})
job.AddStep(gosmo.JobStepRequest{
    Name:            "Run backup",
    Subsystem:       "TSQL",
    Command:         "EXEC dbo.RunNightlyBackup",
    Database:        "MyDB",
    OnSuccessAction: 1,
    OnFailAction:    2,
})
job.SetEmailNotify("DBA on call", gosmo.NotifyOnFailure)
job.Start("")

// Edit or remove a step in place.
steps, _ := job.Steps()
steps[0].Update(gosmo.JobStepRequest{ /* ... */ })
steps[0].Delete()

// History, per job or across every job at once.
entries, _ := job.History(50)
recent, _ := srv.JobHistory(200)
Shared schedules

A schedule is an object in its own right, shared by any number of jobs — Job.AddSchedule creates one and attaches it in a single step, while AttachSchedule/DetachSchedule wire up (or unwire) one that already exists without creating or deleting it.

sched, _ := srv.CreateSchedule(gosmo.CreateScheduleRequest{
    Name:            "Weeknights at 2am",
    Enabled:         true,
    FreqType:        gosmo.FreqWeekly,
    FreqInterval:    gosmo.WeekdayMonday | gosmo.WeekdayTuesday | gosmo.WeekdayWednesday |
                     gosmo.WeekdayThursday | gosmo.WeekdayFriday,
    FreqSubdayType:  gosmo.SubdayOnce,
    ActiveStartTime: 20000, // HHMMSS — 02:00:00
})

job.AttachSchedule(sched.Name)
// "Occurs every week on Monday, Tuesday, Wednesday, Thursday, Friday at
// 02:00:00. Schedule is active from 2026-07-28."
fmt.Println(sched.Description())

jobs, _ := sched.Jobs() // which jobs this schedule drives
Alerts and operators
op, _ := srv.CreateOperator(gosmo.CreateOperatorRequest{
    Name:         "DBA on call",
    Enabled:      true,
    EmailAddress: "dba@example.com",
})

alert, _ := srv.CreateAlert(gosmo.CreateAlertRequest{
    Name:     "Severity 17+",
    Enabled:  true,
    Severity: 17,
})
alert.Notify(op.Name, gosmo.NotifyMethodEmail)
alert.SetJobResponse("NightlyBackup") // run a job in response

// The "referenced by" direction, for an operator's properties page.
alerts, _ := op.NotifyingAlerts()
notified, _ := op.NotifyingJobs()

// Only the alerts gosmo can fully manage (no WMI, no perf counters).
manageable, _ := srv.EventAlerts()
Categories
cats, _ := srv.Categories(gosmo.CategoryClassJob)
srv.CreateCategory(gosmo.CategoryClassAlert, "Storage")
srv.DeleteCategory(gosmo.CategoryClassAlert, "Storage")
Bulk copy

Streams rows into a table over the TDS bulk-copy protocol — the same fast path bcp and SSMS's "Import Data" use, far faster than row-by-row INSERTs.

n, err := db.BulkInsert(gosmo.BulkCopy{
    Table:   "Orders",
    Columns: []string{"OrderID", "CustomerID", "OrderDate"},
    Options: gosmo.BulkOptions{TableLock: true},
}, gosmo.SliceRows(rows)) // or your own iter.Seq2[[]any, error], e.g. a CSV reader
Execute stored procedures

Runs a stored procedure as an RPC, so OUTPUT parameters and the return status come back to the caller — unlike a plain db.Exec-style call.

var rowsAffected int
result, err := db.ExecProc("dbo", "usp_UpdateStock",
    gosmo.In("ProductID", 42),
    gosmo.Out("RowsAffected", &rowsAffected),
)
fmt.Println(result.ReturnStatus, rowsAffected)

Errors

AsSQLError unwraps a driver error into a structured SQLError — number, severity class, state, originating procedure/line, and (for a batch that raised more than one) the full All list — without callers needing to import the underlying driver package themselves.

if _, err := db.CreateTable(req); err != nil {
    if sqlErr, ok := gosmo.AsSQLError(err); ok {
        fmt.Println(sqlErr.Header()) // "Msg 2714, Level 16, State 6, Line 1"
    }
}

Authentication

ConnectionOptions.Auth selects the authentication method:

Constant When to use
AuthSQLServer (default) SQL Server login + password
AuthWindows Windows / Kerberos (domain-joined host)
AuthEntraMSI Azure Managed Identity (system- or user-assigned)
AuthEntraServicePrincipal Service principal with secret or certificate
AuthEntraPassword Entra ID user + password (non-interactive)
AuthEntraInteractive Browser-based interactive login
AuthEntraDeviceCode Device code flow
AuthEntraDefault Default credential chain (env → MSI → AzCLI)
AuthEntraAzCLI az login credential
AuthEntraAzurePipelines Azure DevOps pipeline OIDC

AuthWindows uses native SSPI on Windows. On every other platform it authenticates via Kerberos instead — run kinit first for ambient single sign-on, or set ConnectionOptions.Kerberos (KerberosOptions) for a keytab, realm, credential cache, or custom krb5.conf. ConnectionOptions.ServerSPN overrides the target SPN when the driver's own derivation from the address doesn't match (e.g. a load balancer or CNAME in front of the instance).

ConnectionOptions.AccessTokenProvider, when set, is called to obtain a bearer token for each new pooled connection — use it instead of the static AccessToken field for tokens that expire during the connection's lifetime (Entra tokens are good for roughly an hour). It takes precedence over both AccessToken and Auth.

ConnectionOptions.SessionInitSQL runs on every pooled connection right after it is reset, before the first query — the equivalent of SSMS's Query Execution SET options (e.g. "SET ARITHABORT ON; SET ANSI_NULLS ON").

gosmo.ParseServerAddress(server) parses any address form SSMS's own "Server name" field accepts — host, host:port, host,port, host\instance, host\instance,port — into (host, instance, port). Exported so a caller building its own connection-address UI can reuse the same parsing Connect/ConnectContext rely on internally.


Connection helpers (internal)

A Database-scoped call has to run USE <db> on the same connection as its statement, so it can't use the pool directly — it pins a *sql.Conn for the duration. Server-scoped calls have no USE to redo and go straight to the pool.

Helper Purpose
Database.withConn Acquires a *sql.Conn and runs USE <db> (retried), then hands it to a callback (not retried — the callback is the caller's write), releasing the conn on return.
Database.query Returns *dbRows, whose Close() closes the rows and the conn pinned for them. *sql.Rows.Close alone would leak that conn out of the pool permanently.
Database.queryRow Takes a func(*sql.Row) error scan callback and runs acquire + USE + scan as one retried unit. The scan has to be inside it: QueryRowContext never returns an error, so a scan run afterwards would never be retried.
Database.exec Thin wrapper over withConn for non-SELECT statements; also where WithScript intercepts database-scoped writes.
Server.query Server-scoped rows-returning read, retried — no USE, so a plain *sql.Rows is enough.
Server.queryRow Server-scoped single-row read, same scan-callback shape and reason as Database.queryRow.
Server.queryRowScan queryRow convenience for a plain row.Scan(dest...), sparing the caller a closure.
withRetry Retries each of the read helpers above up to 3 times (linear backoff) on a transient/dropped-connection failure — reads only, since retrying is only safe when the operation is idempotent.

gosmo.IsRetryable(err) exposes the same transient-failure test withRetry uses, for callers running their own statements outside gosmo's query helpers.


Running the example

export MSSQL_SERVER="localhost:1433"
export MSSQL_USER="sa"
export MSSQL_PASSWORD="YourPassword"
go run ./examples/main.go

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
  • Windows Event Log reading
  • Registry reads for SQL Server configuration outside sys.configurations
  • 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.

Variables

This section is empty.

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.

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. nchar/nvarchar store max_length in bytes (2 per character).

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

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

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.

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 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 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) — 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" (matching sp_add_alert/sp_update_alert's own
	// @include_event_description_in parameter, not the column, which has
	// no "_in" suffix — confirmed live against SQL Server 2025: the column
	// and the stored-procedure parameter names genuinely diverge here).
	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 (confirmed absent against a live SQL Server 2025 on Linux instance, 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() 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", live-verified) 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 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.
	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 uses Windows SSO federated with Entra (on-premises AD
	// joined to Azure AD). No credentials needed.
	AuthEntraIntegrated

	// AuthEntraInteractive opens a browser for interactive sign-in (human only).
	// Set ConnectionOptions.ApplicationClientID if required by the tenant.
	AuthEntraInteractive

	// AuthEntraDeviceCode prints a device code for human sign-in on another device.
	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.
	// Requires SYSTEM_ACCESSTOKEN and SYSTEM_OIDCREQUESTURI env vars.
	AuthEntraAzurePipelines

	// AuthEntraOnBehalfOf uses the OAuth 2.0 on-behalf-of flow.
	// Set ConnectionOptions.AccessToken to the inbound user assertion.
	AuthEntraOnBehalfOf
)

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 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
	// 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
	// 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 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 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 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 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       string
	EncryptionAlgorithm string
	// contains filtered or unexported fields
}

ColumnEncryptionKey mirrors sys.column_encryption_keys.

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.

type ColumnMasterKey

type ColumnMasterKey struct {
	Name                     string
	ID                       int
	KeyStoreProviderName     string
	KeyPath                  string
	AllowEnclaveComputations bool
	// 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 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

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, or Entra app client ID,
	// 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. Required for service principal
	// methods when the tenant differs from the server tenant.
	TenantID string

	// ClientID selects a user-assigned Managed Identity when Auth=AuthEntraMSI.
	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 AuthEntraOnBehalfOf.
	// It 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 AAD enterprise application client ID registered
	// by the tenant admin to allow interactive / device-code flows.
	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" - always encrypt
	// "false" - no encryption
	// "disable" - no encryption (legacy alias)
	// "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 the Kubernetes service account token file
	// for Auth=AuthEntraMSI (Workload Identity).
	TokenFilePath string

	// 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

	// 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
}

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>[@<tenant-id>]", Password: "<client-secret>"
TenantID: "<tenant-id>"

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

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

type CreateIndexRequest struct {
	Name             string
	Type             IndexType
	IsUnique         bool
	KeyColumns       []IndexColumnDef
	IncludedColumns  []string
	FilterDefinition string
	FillFactor       int
	Online           bool
	SortInTempDB     bool
}

CreateIndexRequest describes a new index to create.

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
}

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 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 {
	Name       string
	Identity   string
	CreateDate time.Time
	ModifyDate time.Time
}

Credential mirrors a row from sys.credentials — used to populate a Login's "Map to credential" dropdown.

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) 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) 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) 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) Collation

func (d *Database) Collation() string

Collation returns the database collation name.

func (*Database) ColumnEncryptionKeySeq added in v0.0.5

func (d *Database) ColumnEncryptionKeySeq() 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) ColumnMasterKeySeq added in v0.0.5

func (d *Database) ColumnMasterKeySeq() 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) CompatibilityLevel

func (d *Database) CompatibilityLevel() CompatibilityLevel

CompatibilityLevel returns the database compatibility level.

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.

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) CreateDate

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

CreateDate returns the date the database was created.

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) 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() 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() 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() 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() 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) 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) 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) 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) 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(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(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) 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) 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) DropStoredProcedure

func (d *Database) DropStoredProcedure(schema, name string) error

DropStoredProcedure drops a stored procedure.

func (*Database) DropStoredProcedureContext

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

DropStoredProcedureContext is the context-aware variant.

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.

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

func (*Database) ExtendedPropertySeq added in v0.0.6

func (d *Database) ExtendedPropertySeq(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) FileGroupSeq added in v0.0.6

func (d *Database) FileGroupSeq() 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() 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) 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) 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) 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) 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) 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) 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) Name

func (d *Database) Name() string

Name returns the database name.

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) PartitionFunctionSeq added in v0.0.5

func (d *Database) PartitionFunctionSeq() 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) PartitionSchemeSeq added in v0.0.5

func (d *Database) PartitionSchemeSeq() 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(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(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) 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) RecoveryModel

func (d *Database) RecoveryModel() RecoveryModel

RecoveryModel returns the database recovery model.

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) 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) 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) 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) 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) 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(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) SchemaPermissionSeq added in v0.0.6

func (d *Database) SchemaPermissionSeq(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() 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 (case-insensitivity follows the database's own collation), matching SSMS's Object Explorer Details search box.

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.

func (*Database) SearchSeq added in v0.0.6

func (d *Database) SearchSeq(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) SecurityPolicySeq added in v0.0.5

func (d *Database) SecurityPolicySeq() iter.Seq2[*SecurityPolicy, error]

SecurityPolicySeq returns an iterator over all security policies in the database.

func (*Database) SequenceSeq

func (d *Database) SequenceSeq() 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.

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) 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() 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) SynonymSeq added in v0.0.5

func (d *Database) SynonymSeq() 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) SystemFunctionSeq added in v0.0.5

func (d *Database) SystemFunctionSeq() 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) SystemStoredProcedureSeq added in v0.0.5

func (d *Database) SystemStoredProcedureSeq() 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) SystemViewSeq added in v0.0.5

func (d *Database) SystemViewSeq() 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) TableByName

func (d *Database) TableByName(schema, name string) (*Table, error)

TableByName returns a single table by schema and name using a direct query.

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) TableChangeTrackingSeq added in v0.0.4

func (d *Database) TableChangeTrackingSeq() iter.Seq2[*TableChangeTracking, error]

TableChangeTrackingSeq returns an iterator over every user table's change tracking state.

func (*Database) TableSeq

func (d *Database) TableSeq() iter.Seq2[*Table, error]

TableSeq returns an iterator over all user tables in the database.

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(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) TriggerSeq added in v0.0.6

func (d *Database) TriggerSeq() 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) UserDefinedFunctionSeq added in v0.0.6

func (d *Database) UserDefinedFunctionSeq() 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) UserSeq

func (d *Database) UserSeq() 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() 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.

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
	// 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 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 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) 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    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" (verified live), 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 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 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 ErrorLogEntry

type ErrorLogEntry struct {
	LogDate string
	Process string
	Text    string
}

ErrorLogEntry represents one row returned by xp_readerrorlog.

type ExecutionPlan added in v0.0.4

type ExecutionPlan struct {
	// XML is the plan in SQL Server's "Showplan XML" format — the same
	// document SSMS parses to draw its graphical plan.
	XML string
}

ExecutionPlan holds one captured execution plan.

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 FileGroup

type FileGroup struct {
	Name       string
	IsDefault  bool
	IsReadOnly bool
	Files      []DatabaseFile
}

FileGroup represents a SQL Server filegroup.

type FileModify added in v0.0.4

type FileModify struct {
	NewName       string
	SizeKB        int64
	GrowthKB      int64
	GrowthPercent int
	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 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
}

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

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

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

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

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"), live-verified against a real PK-backed index.

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"
)

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

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

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

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)

func (*Job) HistorySeq added in v0.0.6

func (j *Job) HistorySeq(limit int) iter.Seq2[*JobHistoryEntry, error]

HistorySeq returns an iterator over this job's most recent history entries, up to limit.

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) ScheduleSeq added in v0.0.6

func (j *Job) ScheduleSeq() 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

func (*Job) StepSeq added in v0.0.6

func (j *Job) StepSeq() 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)

func (*Job) Stop

func (j *Job) Stop() error

Stop stops a running job.

func (*Job) StopContext

func (j *Job) StopContext(ctx context.Context) error

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 mirrors the current_execution_status values in msdb.dbo.sysjobactivity.

const (
	JobStateIdle                        JobState = 1
	JobStateSuspended                   JobState = 2
	JobStateExecuting                   JobState = 4
	JobStateWaitingForWorker            JobState = 5
	JobStateBetweenRetries              JobState = 6
	JobStateCancelling                  JobState = 7
	JobStatePerformingCompletionActions JobState = 8
	JobStateRunning                     JobState = 10
)

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
	LastRunDuration int
	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, since the exact
	// bit assignments are worth confirming against a live server before
	// being exposed that way.
	Flags 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.

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.
	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 string
}

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 Login

type Login struct {
	Name            string
	SID             []byte
	LoginType       string // "SQL_LOGIN", "WINDOWS_LOGIN", "WINDOWS_GROUP"
	IsDisabled      bool
	DefaultDatabase string
	CreateDate      time.Time
	ModifyDate      time.Time
	// 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

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

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

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

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) 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() 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).

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 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 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() 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() 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 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 PermissionState

type PermissionState string

PermissionState represents GRANT / DENY / REVOKE.

const (
	PermissionGrant  PermissionState = "GRANT"
	PermissionDeny   PermissionState = "DENY"
	PermissionRevoke PermissionState = "REVOKE"
)

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 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      string // "OFF", "ON"
	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 string // "OFF", "ON"
	// 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 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) or LOG.
	Action BackupAction
	// Devices is one or more backup file paths (required).
	Devices []string
	// 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
	// StopAt performs a point-in-time restore.
	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 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() 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

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.

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 {
	// IncludeHeaders adds an informational header comment.
	IncludeHeaders bool
	// IncludeIfNotExists wraps DDL in an existence check.
	IncludeIfNotExists bool
	// ScriptDrops emits DROP statements instead of CREATE statements.
	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 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) ScriptDatabase

func (sc *Scripter) ScriptDatabase() (string, error)

ScriptDatabase generates a CREATE DATABASE script for the attached database.

func (*Scripter) ScriptFunction

func (sc *Scripter) ScriptFunction(schema, name string) (string, error)

ScriptFunction returns the CREATE FUNCTION definition.

func (*Scripter) ScriptFunctionContext

func (sc *Scripter) ScriptFunctionContext(ctx context.Context, schema, name string) (string, error)

ScriptFunctionContext is the context-aware variant.

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

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 SecurityPolicy

type SecurityPolicy struct {
	Name                string
	Schema              string
	ObjectID            int
	IsEnabled           bool
	IsNotForReplication 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.

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 (*Server) ActiveSessionSeq added in v0.0.6

func (s *Server) ActiveSessionSeq(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) 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() 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) 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) BackupFileList added in v0.0.5

func (s *Server) BackupFileList(device string) ([]*BackupFile, error)

BackupFileList reads the database files contained in the backup set on a backup device (RESTORE FILELISTONLY).

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) BackupFileSeq added in v0.0.5

func (s *Server) BackupFileSeq(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(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.

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

func (*Server) BackupHistorySeq added in v0.0.6

func (s *Server) BackupHistorySeq(databaseName string) iter.Seq2[*BackupInfo, error]

BackupHistorySeq returns an iterator over databaseName's backup/restore history, as recorded in msdb.

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(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() 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) 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) 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) 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"), confirmed live against a real server. SSMS's own New Job dialog does this same enlistment implicitly; 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 SQL Server or Windows login. Pass an empty password to create a Windows login (FROM WINDOWS).

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.

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) CredentialSeq added in v0.0.4

func (s *Server) CredentialSeq() 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) 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.

func (*Server) CycleErrorLogContext

func (s *Server) CycleErrorLogContext(ctx context.Context) error

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) DatabaseByName

func (s *Server) DatabaseByName(name string) (*Database, error)

DatabaseByName returns a single database by name.

func (*Server) DatabaseByNameContext

func (s *Server) DatabaseByNameContext(ctx context.Context, name string) (*Database, error)

DatabaseByNameContext is the context-aware variant of DatabaseByName.

func (*Server) DatabaseSeq

func (s *Server) DatabaseSeq() 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) 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) DiskVolumeSeq added in v0.0.5

func (s *Server) DiskVolumeSeq() 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.

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) EventAlertSeq added in v0.0.6

func (s *Server) EventAlertSeq() 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) 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.

Live-verified: 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") — a real restriction, not something gosmo enforces itself — so every statement here is prefixed with USE master in the same batch. Sent as one round trip, this doesn't leave the connection's database context changed for whatever runs next: database/sql doesn't guarantee this exact pooled connection is reused for the caller's next call, and even if it is, that next call is a fresh statement/batch that sets its own context if it needs to.

func (*Server) Info

func (s *Server) Info() *ServerInfo

Info returns cached server metadata (version, edition, paths ...).

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(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() 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

func (*Server) LanguageSeq added in v0.0.4

func (s *Server) LanguageSeq() 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) LinkedServerSeq added in v0.0.6

func (s *Server) LinkedServerSeq() 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() 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.

func (*Server) MailProfileSeq added in v0.0.6

func (s *Server) MailProfileSeq() 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)

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) 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() 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)

func (*Server) ReadErrorLogSeq added in v0.0.6

func (s *Server) ReadErrorLogSeq(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) 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

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) 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) 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) 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() 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

func (*Server) ServerPermissionSeq added in v0.0.4

func (s *Server) ServerPermissionSeq() 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) 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(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() 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) 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.

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.

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     int
	OSVersion         string
	Platform          string
	MaxConnections    int
	PhysicalMemoryMB  int64
	LogicalCPUCount   int
	DefaultDataPath   string
	DefaultLogPath    string
	DefaultBackupPath string
}

ServerInfo holds basic information about the connected SQL Server instance.

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 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) 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 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 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
)

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 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() 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() 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

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() iter.Seq2[*StatisticHistogramStep, error]

HistogramSeq returns an iterator over this statistic's histogram steps.

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

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 Table

type Table struct {
	ObjectID             int
	Schema               string
	Name                 string
	CreateDate           time.Time
	ModifyDate           time.Time
	HasReplicationFilter bool
	IsMemoryOptimized    bool
	// contains filtered or unexported fields
}

Table mirrors Microsoft.SqlServer.Management.Smo.Table.

func (*Table) AddColumn added in v0.0.4

func (t *Table) AddColumn(col ColumnDefinition) error

AddColumn adds a new column to the table (ALTER TABLE ... ADD).

func (*Table) AddColumnContext added in v0.0.4

func (t *Table) AddColumnContext(ctx context.Context, col ColumnDefinition) error

AddColumnContext is the context-aware variant of AddColumn.

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 (identity) or the default constraint (DropColumn/AddColumn) 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() 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() 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

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.

func (*Table) CreateStatisticContext

func (t *Table) CreateStatisticContext(ctx context.Context, name string, columns []string, samplePct int) error

func (*Table) DB

func (t *Table) DB() *Database

DB returns the parent Database.

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 drops a column from the table (ALTER TABLE ... DROP COLUMN), first dropping its default constraint, if it has one — SQL Server refuses to drop a column that a default constraint still references.

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) ForeignKeySeq

func (t *Table) ForeignKeySeq() 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)

func (*Table) FragmentationStatsSeq added in v0.0.6

func (t *Table) FragmentationStatsSeq(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) IndexSeq

func (t *Table) IndexSeq() 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.

func (*Table) PartitionSeq added in v0.0.5

func (t *Table) PartitionSeq() 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

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) StatisticSeq

func (t *Table) StatisticSeq() 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() 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

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 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 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 only 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) —
	// verified live these two cases are in fact distinguishable, unlike
	// what an earlier version of this comment assumed.
	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

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

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

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 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 View

type View struct {
	ObjectID   int
	Schema     string
	Name       string
	Definition string
	CreateDate time.Time
	ModifyDate time.Time
}

View represents a database view.

Directories

Path Synopsis
Package main demonstrates every authentication method and major feature of the gosmo library.
Package main demonstrates every authentication method and major feature of the gosmo library.
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