gosmo

package module
v0.0.2 Latest Latest
Warning

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

Go to latest
Published: Jun 25, 2026 License: MIT Imports: 12 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
        +ConnectTimeout Duration
        +ApplicationName string
        +MaxOpenConns int
        +MaxIdleConns int
        +ConnMaxLifetime Duration
        +TrustServerCertificate bool
        +Encrypt string
    }

    class Server {
        -db *sql.DB
        -info *ServerInfo
        +Connect(opts) *Server
        +ConnectContext(ctx, opts) *Server
        +Close() error
        +DB() *sql.DB
        +Info() *ServerInfo
        +Name() string
        +Databases() []*Database
        +DatabaseByName(name) *Database
        +CreateDatabase(name, opts) error
        +DropDatabase(name, force) error
        +Logins() []*Login
        +CreateLogin(name, password, opts) error
        +DropLogin(name) error
        +ServerRoles() []*ServerRole
        +LinkedServers() []*LinkedServer
        +Configurations() []*Configuration
        +Jobs() []*AgentJob
        +ActiveSessions(sys) []*Session
        +KillSession(id) error
        +ReadErrorLog(n) []*ErrorLogEntry
        +MailProfiles() []*MailProfile
        +SendMail(opts) error
        +Backup(opts) error
        +Restore(opts) error
    }

    class ServerInfo {
        +Name string
        +Edition string
        +ProductVersion string
        +ProductLevel string
        +Collation string
        +IsClustered bool
        +IsHADREnabled bool
        +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
    }

    %% =========================================================
    %% 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
        +AddServerRoleMember(role) error
        +RemoveServerRoleMember(role) error
        +Drop() error
    }

    class passwordHexLiteral {
        <<internal helper>>
        Encodes plaintext password
        as UTF-16LE 0x... binary literal.
        No quoting needed — injection-proof
        for any password byte sequence.
        Used by CreateLogin and ChangePassword.
    }

    %% =========================================================
    %% 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
        +RecoveryModel() RecoveryModel
        +CompatibilityLevel() CompatibilityLevel
        +Tables() []*Table
        +TablesBySchema(schema) []*Table
        +TableByName(schema, name) *Table
        +CreateTable(req) error
        +DropTable(schema, name, cascade) error
        +Views() []*View
        +StoredProcedures() []*StoredProcedure
        +CreateStoredProcedure(schema, name, body) error
        +DropStoredProcedure(schema, name) error
        +UserDefinedFunctions() []*UserDefinedFunction
        +Schemas() []*Schema
        +CreateSchema(name, owner) error
        +DropSchema(name) error
        +Users() []*User
        +CreateUser(user, login, schema) error
        +DropUser(name) error
        +DatabaseRoles() []*DatabaseRole
        +AddRoleMember(role, member) error
        +RemoveRoleMember(role, member) error
        +FileGroups() []*FileGroup
        +Triggers() []*Trigger
        +Sequences() []*Sequence
        +Synonyms() []*Synonym
        +PartitionFunctions() []*PartitionFunction
        +PartitionSchemes() []*PartitionScheme
        +ExtendedProperties(level) []*ExtendedProperty
        +ColumnMasterKeys() []*ColumnMasterKey
        +ColumnEncryptionKeys() []*ColumnEncryptionKey
        +SecurityPolicies() []*SecurityPolicy
        +SpaceUsed() SpaceInfo
        +SetRecoveryModel(model) error
        +SetCompatibilityLevel(level) error
        +SetReadOnly(bool) error
    }

    %% =========================================================
    %% Connection helpers (internal)
    %% =========================================================
    class withConn {
        <<internal helper>>
        Acquires *sql.Conn from pool.
        Executes USE db.
        Runs callback fn(*sql.Conn).
        Releases conn via defer.
        Used by exec, scanRow, queryRow.
    }

    class rowsWithConn {
        <<internal type>>
        -Rows *sql.Rows
        -conn *sql.Conn
        +Close() error
        Closes Rows then conn atomically.
        Prevents conn leaks on early
        iteration exits or error returns.
        Returned by query().
    }

    class scanRow {
        <<internal helper>>
        Callback-style single-row query.
        conn lifetime fully internal —
        no release() needed by caller.
        Used by SpaceUsed, TableByName.
    }

    class queryRow {
        <<internal helper>>
        Returns (*sql.Row, func(), error).
        Caller MUST defer release().
        conn is held until release() fires.
        Used by scripter.go, table.go.
    }

    %% =========================================================
    %% 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
        +RowCount() int64
        +TruncateTable() error
        +FragmentationStats(mode) []*FragStat
        +RebuildAllIndexes(fillFactor) error
        +UpdateAllStatistics(samplePct) error
        +CreateIndex(req) error
        +CreateStatistic(name, cols, pct) 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
        +Collation string
    }

    class Index {
        +Name string
        +IndexID int
        +Type IndexType
        +IsClustered bool
        +IsUnique bool
        +IsPrimaryKey bool
        +IsDisabled bool
        +FillFactor int
        +KeyColumns []IndexColumn
        +IncludedColumns []IndexColumn
        +FilterDefinition string
        +Rebuild(t, fillFactor) error
        +Reorganize(t) error
        +Disable(t) error
        +Enable(t) error
        +Drop(t) error
    }

    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
        +Update(samplePct) error
        +Drop() error
    }

    %% =========================================================
    %% Scripter
    %% =========================================================
    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
    }

    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
    }

    class DatabaseRole {
        +Name string
        +ID int
        +IsFixedRole bool
        +Owner string
        +Members []string
    }

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

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

    class ServerRole {
        +Name string
        +IsFixedRole bool
        +Members []string
    }

    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
    }

    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
    }

    %% =========================================================
    %% Agent Jobs
    %% =========================================================
    class AgentJob {
        +JobID string
        +Name string
        +Enabled bool
        +Description string
        +Steps []*JobStep
        +Schedules []*JobSchedule
        +AddStep(req) error
        +AddSchedule(req) error
        +Start(stepName) error
        +Stop() error
        +Drop() error
    }

    %% =========================================================
    %% Relationships
    %% =========================================================
    ConnectionOptions --> AuthMethod : uses
    Server --> ConnectionOptions : created from
    Server --> ServerInfo : has
    Server "1" --> "*" Database : owns
    Server "1" --> "*" Login : owns
    Server "1" --> "*" ServerRole : owns
    Server "1" --> "*" LinkedServer : owns
    Server "1" --> "*" AgentJob : owns
    Server --> BackupOptions : accepts
    Server --> RestoreOptions : accepts

    Login ..> passwordHexLiteral : password encoded by

    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 ..> withConn : uses internally
    Database ..> rowsWithConn : query() returns
    Database ..> scanRow : single-row callback
    Database ..> queryRow : single-row with release()

    withConn <.. rowsWithConn : conn acquired by
    withConn <.. scanRow : delegates to
    withConn <.. queryRow : delegates to

    Table "1" --> "*" Column : has
    Table "1" --> "*" Index : has
    Table "1" --> "*" ForeignKey : has
    Table "1" --> "*" CheckConstraint : has
    Table "1" --> "*" Statistic : has

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

Security

  • Passwords are never interpolated into SQL strings. CreateLogin and ChangePassword encode the password as a UTF-16LE binary literal (0x...), making them injection-proof regardless of password content.
  • Connection lifetimes are correctly scoped. Every query() call returns a rowsWithConn that holds the underlying *sql.Conn and releases it atomically on Close(), preventing silent connection leaks on early iteration exits.

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()
Server.Logins srv.Logins()
Server.Roles srv.ServerRoles()
Server.LinkedServers srv.LinkedServers()
Server.Configuration srv.Configurations()
Server.JobServer.Jobs srv.Jobs()
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)
Database
SMO equivalent gosmo
Database.Tables db.Tables() / db.TablesBySchema(schema)
Database.Views db.Views()
Database.StoredProcedures db.StoredProcedures()
Database.UserDefinedFunctions db.UserDefinedFunctions()
Database.Schemas db.Schemas()
Database.Users db.Users()
Database.Roles db.DatabaseRoles()
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)
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()
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.RowCount t.RowCount()
Truncate t.TruncateTable()
Fragmentation t.FragmentationStats(mode)
Rebuild all indexes t.RebuildAllIndexes(fillFactor)
Update all statistics t.UpdateAllStatistics(samplePct)
Create index t.CreateIndex(req)
Index
gosmo
idx.Rebuild(t, fillFactor)
idx.Reorganize(t)
idx.Disable(t) / idx.Enable(t)
idx.Drop(t)
Login
gosmo
srv.CreateLogin(name, password, opts)
login.ChangePassword(newPassword)
login.Enable() / login.Disable()
login.AddServerRoleMember(role)
login.RemoveServerRoleMember(role)
login.Drop()
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()
Backup & Restore
srv.Backup(gosmo.BackupOptions{
    Database: "MyDB",
    Devices:  []string{`C:\Backups\MyDB.bak`},
    CopyOnly: true,
})

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,
})
Agent Jobs
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.AddSchedule(gosmo.JobScheduleRequest{
    Name:            "Every night at 2am",
    Enabled:         true,
    FreqType:        4,     // daily
    FreqInterval:    1,
    FreqSubdayType:  1,     // once
    ActiveStartTime: 20000, // 02:00:00
})
job.Start("")

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

Connection helpers (internal)

Helper Purpose
withConn Acquires a *sql.Conn, runs USE <db>, executes a callback, then releases the conn.
query Returns *rowsWithConn; Close() releases both rows and the underlying connection.
queryRow Returns (*sql.Row, func(), error); always defer release() before scanning.
scanRow Callback-style single-row helper; conn is fully internal, no release needed.
exec Thin wrapper over withConn for non-SELECT statements.

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

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

Documentation

Overview

Package smo 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

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

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 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 OS Kerberos/NTLM ticket (on-premises, domain-joined host).
	// No credentials needed; leave User and Password empty.
	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"
)

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%).
	Stats int
}

BackupOptions configures a BACKUP DATABASE or BACKUP LOG operation.

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
}

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.

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.

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
)

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

	// ApplicationClientID is the AAD enterprise application client ID registered
	// by the tenant admin to allow interactive / device-code flows.
	ApplicationClientID string

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

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)

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 CreateDatabaseOptions

type CreateDatabaseOptions struct {
	Collation     string
	RecoveryModel RecoveryModel
	CompatLevel   CompatibilityLevel
}

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

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

AddExtendedProperty adds or updates an extended property on an object.

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

func (d *Database) Collation() string

Collation returns the database collation name.

func (*Database) ColumnEncryptionKeys

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

ColumnEncryptionKeys returns all column encryption keys in the database.

func (*Database) ColumnMasterKeys

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

ColumnMasterKeys returns all column master keys in the database.

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

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

CreatePartitionScheme creates a partition scheme backed by a partition function.

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

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

DropExtendedProperty drops an extended property from an object.

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

func (d *Database) ExtendedProperties(level ExtendedPropertyLevel) ([]*ExtendedProperty, error)

ExtendedProperties returns the extended properties for a specific object.

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

func (d *Database) Name() string

Name returns the database name.

func (*Database) PartitionFunctions

func (d *Database) PartitionFunctions() ([]*PartitionFunction, error)

PartitionFunctions returns all partition functions in the database.

func (*Database) PartitionSchemes

func (d *Database) PartitionSchemes() ([]*PartitionScheme, error)

PartitionSchemes returns all partition schemes in the database.

func (*Database) RecoveryModel

func (d *Database) RecoveryModel() RecoveryModel

RecoveryModel returns the database recovery model.

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

func (d *Database) SecurityPolicies() ([]*SecurityPolicy, error)

SecurityPolicies returns 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) Server

func (d *Database) Server() *Server

Server returns the parent Server.

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

func (d *Database) Synonyms() ([]*Synonym, error)

Synonyms returns all synonyms in the database.

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

func (d *Database) TablesContext(ctx context.Context) ([]*Table, error)

TablesContext is the context-aware variant of Tables.

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

type DatabaseRole struct {
	Name        string
	ID          int
	IsFixedRole bool
	Owner       string
	Members     []string
	// contains filtered or unexported fields
}

DatabaseRole represents a database-level role.

type ErrorLogEntry

type ErrorLogEntry struct {
	LogDate string
	Process string
	Text    string
}

ErrorLogEntry represents one row returned by xp_readerrorlog.

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
	Files     []DatabaseFile
}

FileGroup represents a SQL Server filegroup.

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

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
}

IndexFragmentation holds fragmentation statistics for one index.

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

func (j *Job) Disable() error

Disable disables the job.

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) 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) 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) 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 {
	RunDate  time.Time
	Duration time.Duration
	Outcome  JobOutcome
	Message  string
	StepID   int
	StepName string
}

JobHistoryEntry represents one row from msdb.dbo.sysjobhistory.

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
	OnSuccessAction int
	OnFailAction    int
	LastRunOutcome  JobOutcome
	LastRunDuration int
	RetryAttempts   int
	RetryInterval   int
	// contains filtered or unexported fields
}

JobStep represents one step of an agent job.

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
	OnFailAction    int
	RetryAttempts   int
	// RetryInterval is in minutes.
	RetryInterval int
}

JobStepRequest describes a step to add to a job.

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 never interpolated into the SQL string. It is encoded as a UTF-16LE hex literal so the statement is injection-proof regardless of the password content.

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

func (l *Login) Enable() error

Enable enables the login.

func (*Login) EnableContext

func (l *Login) EnableContext(ctx context.Context) error

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

type MailProfile

type MailProfile struct {
	ProfileID   int
	Name        string
	Description string
	IsDefault   bool
}

MailProfile represents an msdb Database Mail profile.

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

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

func (pf *PartitionFunction) MergeRange(value string) error

MergeRange removes a boundary value from the partition function.

func (*PartitionFunction) SplitRange

func (pf *PartitionFunction) SplitRange(value string) error

SplitRange adds a new boundary value to the partition function.

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.

type PermissionState

type PermissionState string

PermissionState represents GRANT / DENY / REVOKE.

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

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.
	Stats int
	// StopAt performs a point-in-time restore.
	StopAt *time.Time
}

RestoreOptions configures a RESTORE DATABASE or RESTORE LOG operation.

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.

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

func (p *SecurityPolicy) Drop() error

Drop drops the security policy.

func (*SecurityPolicy) Enable

func (p *SecurityPolicy) Enable() error

Enable enables the security policy.

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

func (seq *Sequence) NextValue() (int64, error)

NextValue retrieves the next value from the sequence.

func (*Sequence) Restart

func (seq *Sequence) Restart(value int64) error

Restart restarts the sequence at the given value.

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

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 interpolated into the SQL string. Instead it is encoded as a UTF-16LE hex literal and passed with the HASHED keyword via a pre-computed binary value, which is injection-proof regardless of the password content.

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

func (s *Server) Name() string

Name returns the SQL Server instance name.

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

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

type ServerRole struct {
	Name        string
	IsFixedRole bool
	Members     []string
}

ServerRole represents a server-level role.

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
}

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

Statistic mirrors sys.stats for a table.

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

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

func (t *Table) Partitions() ([]*PartitionInfo, error)

Partitions returns per-partition row counts and compression for the table.

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

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.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL