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 ¶
- type ActiveSession
- type AuthMethod
- type BackupAction
- type BackupInfo
- type BackupOptions
- type CheckConstraint
- type Column
- type ColumnDefault
- type ColumnDefinition
- type ColumnEncryptionKey
- type ColumnMasterKey
- type CompatibilityLevel
- type ConfigurationOption
- type ConnectionOptions
- type CreateDatabaseOptions
- type CreateIndexRequest
- type CreateJobRequest
- type CreateLoginOptions
- type CreatePartitionFunctionRequest
- type CreateSequenceRequest
- type CreateTableRequest
- type DataType
- type Database
- func (d *Database) AddExtendedProperty(name, value string, level ExtendedPropertyLevel) error
- func (d *Database) AddRoleMember(roleName, memberName string) error
- func (d *Database) AddRoleMemberContext(ctx context.Context, roleName, memberName string) error
- func (d *Database) Collation() string
- func (d *Database) ColumnEncryptionKeys() ([]*ColumnEncryptionKey, error)
- func (d *Database) ColumnMasterKeys() ([]*ColumnMasterKey, error)
- func (d *Database) CompatibilityLevel() CompatibilityLevel
- func (d *Database) CreateColumnMasterKey(name, keyStoreProvider, keyPath string, enclaveComputations bool) error
- func (d *Database) CreateDate() time.Time
- func (d *Database) CreatePartitionFunction(req CreatePartitionFunctionRequest) error
- func (d *Database) CreatePartitionScheme(name, functionName string, fileGroups []string) error
- func (d *Database) CreateSchema(name, owner string) error
- func (d *Database) CreateSchemaContext(ctx context.Context, name, owner string) error
- func (d *Database) CreateSequence(req CreateSequenceRequest) error
- func (d *Database) CreateStoredProcedure(schema, name, body string) error
- func (d *Database) CreateStoredProcedureContext(ctx context.Context, schema, name, body string) error
- func (d *Database) CreateSynonym(schema, name, baseObject string) error
- func (d *Database) CreateTable(req CreateTableRequest) error
- func (d *Database) CreateTableContext(ctx context.Context, req CreateTableRequest) error
- func (d *Database) CreateUser(userName, loginName, defaultSchema string) error
- func (d *Database) CreateUserContext(ctx context.Context, userName, loginName, defaultSchema string) error
- func (d *Database) DatabaseExtendedProperties() ([]*ExtendedProperty, error)
- func (d *Database) DatabaseRoles() ([]*DatabaseRole, error)
- func (d *Database) DatabaseRolesContext(ctx context.Context) ([]*DatabaseRole, error)
- func (d *Database) DropExtendedProperty(name string, level ExtendedPropertyLevel) error
- func (d *Database) DropSchema(name string) error
- func (d *Database) DropSchemaContext(ctx context.Context, name string) error
- func (d *Database) DropStoredProcedure(schema, name string) error
- func (d *Database) DropStoredProcedureContext(ctx context.Context, schema, name string) error
- func (d *Database) DropTable(schema, name string, cascade bool) error
- func (d *Database) DropTableContext(ctx context.Context, schema, name string, cascade bool) error
- func (d *Database) DropUser(name string) error
- func (d *Database) DropUserContext(ctx context.Context, name string) error
- func (d *Database) ExtendedProperties(level ExtendedPropertyLevel) ([]*ExtendedProperty, error)
- func (d *Database) FileGroups() ([]*FileGroup, error)
- func (d *Database) FileGroupsContext(ctx context.Context) ([]*FileGroup, error)
- func (d *Database) ID() int
- func (d *Database) IsReadOnly() bool
- func (d *Database) Name() string
- func (d *Database) PartitionFunctions() ([]*PartitionFunction, error)
- func (d *Database) PartitionSchemes() ([]*PartitionScheme, error)
- func (d *Database) RecoveryModel() RecoveryModel
- func (d *Database) RemoveRoleMember(roleName, memberName string) error
- func (d *Database) RemoveRoleMemberContext(ctx context.Context, roleName, memberName string) error
- func (d *Database) RenameTable(schema, oldName, newName string) error
- func (d *Database) RenameTableContext(ctx context.Context, schema, oldName, newName string) error
- func (d *Database) SchemaSeq() iter.Seq2[*Schema, error]
- func (d *Database) Schemas() ([]*Schema, error)
- func (d *Database) SchemasContext(ctx context.Context) ([]*Schema, error)
- func (d *Database) SecurityPolicies() ([]*SecurityPolicy, error)
- func (d *Database) SequenceSeq() iter.Seq2[*Sequence, error]
- func (d *Database) Sequences() ([]*Sequence, error)
- func (d *Database) Server() *Server
- func (d *Database) SetCompatibilityLevel(level CompatibilityLevel) error
- func (d *Database) SetCompatibilityLevelContext(ctx context.Context, level CompatibilityLevel) error
- func (d *Database) SetReadOnly(readOnly bool) error
- func (d *Database) SetReadOnlyContext(ctx context.Context, readOnly bool) error
- func (d *Database) SetRecoveryModel(model RecoveryModel) error
- func (d *Database) SetRecoveryModelContext(ctx context.Context, model RecoveryModel) error
- func (d *Database) SpaceUsed() (SpaceInfo, error)
- func (d *Database) SpaceUsedContext(ctx context.Context) (SpaceInfo, error)
- func (d *Database) State() string
- func (d *Database) StoredProcedureSeq() iter.Seq2[*StoredProcedure, error]
- func (d *Database) StoredProcedures() ([]*StoredProcedure, error)
- func (d *Database) StoredProceduresContext(ctx context.Context) ([]*StoredProcedure, error)
- func (d *Database) Synonyms() ([]*Synonym, error)
- func (d *Database) TableByName(schema, name string) (*Table, error)
- func (d *Database) TableByNameContext(ctx context.Context, schema, name string) (*Table, error)
- func (d *Database) TableSeq() iter.Seq2[*Table, error]
- func (d *Database) Tables() ([]*Table, error)
- func (d *Database) TablesBySchema(schema string) ([]*Table, error)
- func (d *Database) TablesBySchemaContext(ctx context.Context, schema string) ([]*Table, error)
- func (d *Database) TablesContext(ctx context.Context) ([]*Table, error)
- func (d *Database) Triggers() ([]*Trigger, error)
- func (d *Database) TriggersContext(ctx context.Context) ([]*Trigger, error)
- func (d *Database) UserDefinedFunctions() ([]*UserDefinedFunction, error)
- func (d *Database) UserDefinedFunctionsContext(ctx context.Context) ([]*UserDefinedFunction, error)
- func (d *Database) UserSeq() iter.Seq2[*User, error]
- func (d *Database) Users() ([]*User, error)
- func (d *Database) UsersContext(ctx context.Context) ([]*User, error)
- func (d *Database) ViewSeq() iter.Seq2[*View, error]
- func (d *Database) Views() ([]*View, error)
- func (d *Database) ViewsContext(ctx context.Context) ([]*View, error)
- type DatabaseFile
- type DatabaseRole
- type ErrorLogEntry
- type ExtendedProperty
- type ExtendedPropertyLevel
- type FileGroup
- type ForeignKey
- type Index
- func (idx *Index) Disable(t *Table) error
- func (idx *Index) DisableContext(ctx context.Context, t *Table) error
- func (idx *Index) Drop(t *Table) error
- func (idx *Index) DropContext(ctx context.Context, t *Table) error
- func (idx *Index) Enable(t *Table) error
- func (idx *Index) Rebuild(t *Table, fillFactor int) error
- func (idx *Index) RebuildContext(ctx context.Context, t *Table, fillFactor int) error
- func (idx *Index) Reorganize(t *Table) error
- func (idx *Index) ReorganizeContext(ctx context.Context, t *Table) error
- type IndexColumn
- type IndexColumnDef
- type IndexFragmentation
- type IndexType
- type Job
- func (j *Job) AddSchedule(req JobScheduleRequest) error
- func (j *Job) AddScheduleContext(ctx context.Context, req JobScheduleRequest) error
- func (j *Job) AddStep(req JobStepRequest) error
- func (j *Job) AddStepContext(ctx context.Context, req JobStepRequest) error
- func (j *Job) Disable() error
- func (j *Job) Drop() error
- func (j *Job) DropContext(ctx context.Context) error
- func (j *Job) Enable() error
- func (j *Job) History(limit int) ([]*JobHistoryEntry, error)
- func (j *Job) HistoryContext(ctx context.Context, limit int) ([]*JobHistoryEntry, error)
- func (j *Job) Start(stepName string) error
- func (j *Job) StartContext(ctx context.Context, stepName string) error
- func (j *Job) Steps() ([]*JobStep, error)
- func (j *Job) StepsContext(ctx context.Context) ([]*JobStep, error)
- func (j *Job) Stop() error
- func (j *Job) StopContext(ctx context.Context) error
- type JobHistoryEntry
- type JobOutcome
- type JobScheduleRequest
- type JobState
- type JobStep
- type JobStepRequest
- type LinkedServer
- type Login
- func (l *Login) AddServerRoleMember(roleName string) error
- func (l *Login) AddServerRoleMemberContext(ctx context.Context, roleName string) error
- func (l *Login) ChangePassword(newPassword string) error
- func (l *Login) ChangePasswordContext(ctx context.Context, newPassword string) error
- func (l *Login) Disable() error
- func (l *Login) DisableContext(ctx context.Context) error
- func (l *Login) Drop() error
- func (l *Login) Enable() error
- func (l *Login) EnableContext(ctx context.Context) error
- func (l *Login) RemoveServerRoleMember(roleName string) error
- func (l *Login) RemoveServerRoleMemberContext(ctx context.Context, roleName string) error
- type MailProfile
- type ObjectPermission
- type PartitionFunction
- type PartitionInfo
- type PartitionScheme
- type PermissionState
- type RecoveryModel
- type RelocateFile
- type RestoreOptions
- type Schema
- type ScriptOptions
- type Scripter
- func (sc *Scripter) ScriptDatabase() (string, error)
- func (sc *Scripter) ScriptFunction(schema, name string) (string, error)
- func (sc *Scripter) ScriptFunctionContext(ctx context.Context, schema, name string) (string, error)
- func (sc *Scripter) ScriptStoredProcedure(schema, name string) (string, error)
- func (sc *Scripter) ScriptStoredProcedureContext(ctx context.Context, schema, name string) (string, error)
- func (sc *Scripter) ScriptTable(schema, name string) (string, error)
- func (sc *Scripter) ScriptTableContext(ctx context.Context, schema, name string) (string, error)
- func (sc *Scripter) ScriptView(schema, name string) (string, error)
- func (sc *Scripter) ScriptViewContext(ctx context.Context, schema, name string) (string, error)
- type SecurityPolicy
- type SecurityPredicate
- type Sequence
- type Server
- func (s *Server) ActiveSessions(includeSystem bool) ([]*ActiveSession, error)
- func (s *Server) ActiveSessionsContext(ctx context.Context, includeSystem bool) ([]*ActiveSession, error)
- func (s *Server) Backup(opts BackupOptions) error
- func (s *Server) BackupContext(ctx context.Context, opts BackupOptions) error
- func (s *Server) BackupHistory(databaseName string) ([]*BackupInfo, error)
- func (s *Server) BackupHistoryContext(ctx context.Context, databaseName string) ([]*BackupInfo, error)
- func (s *Server) Close() error
- func (s *Server) ConfigurationByName(name string) (*ConfigurationOption, error)
- func (s *Server) ConfigurationByNameContext(ctx context.Context, name string) (*ConfigurationOption, error)
- func (s *Server) Configurations() ([]*ConfigurationOption, error)
- func (s *Server) ConfigurationsContext(ctx context.Context) ([]*ConfigurationOption, error)
- func (s *Server) CreateDatabase(name string, opts *CreateDatabaseOptions) error
- func (s *Server) CreateDatabaseContext(ctx context.Context, name string, opts *CreateDatabaseOptions) error
- func (s *Server) CreateJob(req CreateJobRequest) (*Job, error)
- func (s *Server) CreateJobContext(ctx context.Context, req CreateJobRequest) (*Job, error)
- func (s *Server) CreateLogin(name, password string, opts *CreateLoginOptions) error
- func (s *Server) CreateLoginContext(ctx context.Context, name, password string, opts *CreateLoginOptions) error
- func (s *Server) CycleErrorLog() error
- func (s *Server) CycleErrorLogContext(ctx context.Context) error
- func (s *Server) DB() *sql.DB
- func (s *Server) DatabaseByName(name string) (*Database, error)
- func (s *Server) DatabaseByNameContext(ctx context.Context, name string) (*Database, error)
- func (s *Server) DatabaseSeq() iter.Seq2[*Database, error]
- func (s *Server) Databases() ([]*Database, error)
- func (s *Server) DatabasesContext(ctx context.Context) ([]*Database, error)
- func (s *Server) DropDatabase(name string, force bool) error
- func (s *Server) DropDatabaseContext(ctx context.Context, name string, force bool) error
- func (s *Server) DropLogin(name string) error
- func (s *Server) DropLoginContext(ctx context.Context, name string) error
- func (s *Server) Info() *ServerInfo
- func (s *Server) JobByName(name string) (*Job, error)
- func (s *Server) JobByNameContext(ctx context.Context, name string) (*Job, error)
- func (s *Server) JobSeq() iter.Seq2[*Job, error]
- func (s *Server) Jobs() ([]*Job, error)
- func (s *Server) JobsContext(ctx context.Context) ([]*Job, error)
- func (s *Server) KillSession(sessionID int) error
- func (s *Server) KillSessionContext(ctx context.Context, sessionID int) error
- func (s *Server) LinkedServers() ([]*LinkedServer, error)
- func (s *Server) LinkedServersContext(ctx context.Context) ([]*LinkedServer, error)
- func (s *Server) LoginSeq() iter.Seq2[*Login, error]
- func (s *Server) Logins() ([]*Login, error)
- func (s *Server) LoginsContext(ctx context.Context) ([]*Login, error)
- func (s *Server) MailProfiles() ([]*MailProfile, error)
- func (s *Server) MailProfilesContext(ctx context.Context) ([]*MailProfile, error)
- func (s *Server) Name() string
- func (s *Server) ReadErrorLog(logNumber int) ([]*ErrorLogEntry, error)
- func (s *Server) ReadErrorLogContext(ctx context.Context, logNumber int) ([]*ErrorLogEntry, error)
- func (s *Server) Reconfigure(override bool) error
- func (s *Server) ReconfigureContext(ctx context.Context, override bool) error
- func (s *Server) Restore(opts RestoreOptions) error
- func (s *Server) RestoreContext(ctx context.Context, opts RestoreOptions) error
- func (s *Server) SendMail(profile, recipients, subject, body string) error
- func (s *Server) SendMailContext(ctx context.Context, profile, recipients, subject, body string) error
- func (s *Server) ServerRoles() ([]*ServerRole, error)
- func (s *Server) ServerRolesContext(ctx context.Context) ([]*ServerRole, error)
- type ServerInfo
- type ServerRole
- type ServerVersion
- type SpaceInfo
- type Statistic
- type StoredProcedure
- type Synonym
- type Table
- func (t *Table) CheckConstraints() ([]*CheckConstraint, error)
- func (t *Table) CheckConstraintsContext(ctx context.Context) ([]*CheckConstraint, error)
- func (t *Table) ColumnSeq() iter.Seq2[*Column, error]
- func (t *Table) Columns() ([]*Column, error)
- func (t *Table) ColumnsContext(ctx context.Context) ([]*Column, error)
- func (t *Table) CreateIndex(req CreateIndexRequest) error
- func (t *Table) CreateIndexContext(ctx context.Context, req CreateIndexRequest) error
- func (t *Table) CreateStatistic(name string, columns []string, samplePct int) error
- func (t *Table) CreateStatisticContext(ctx context.Context, name string, columns []string, samplePct int) error
- func (t *Table) DB() *Database
- func (t *Table) ForeignKeySeq() iter.Seq2[*ForeignKey, error]
- func (t *Table) ForeignKeys() ([]*ForeignKey, error)
- func (t *Table) ForeignKeysContext(ctx context.Context) ([]*ForeignKey, error)
- func (t *Table) FragmentationStats(mode string) ([]*IndexFragmentation, error)
- func (t *Table) FragmentationStatsContext(ctx context.Context, mode string) ([]*IndexFragmentation, error)
- func (t *Table) FullName() string
- func (t *Table) IndexSeq() iter.Seq2[*Index, error]
- func (t *Table) Indexes() ([]*Index, error)
- func (t *Table) IndexesContext(ctx context.Context) ([]*Index, error)
- func (t *Table) Partitions() ([]*PartitionInfo, error)
- func (t *Table) RebuildAllIndexes(fillFactor int) error
- func (t *Table) RebuildAllIndexesContext(ctx context.Context, fillFactor int) error
- func (t *Table) RowCount() (int64, error)
- func (t *Table) RowCountContext(ctx context.Context) (int64, error)
- func (t *Table) StatisticSeq() iter.Seq2[*Statistic, error]
- func (t *Table) Statistics() ([]*Statistic, error)
- func (t *Table) StatisticsContext(ctx context.Context) ([]*Statistic, error)
- func (t *Table) TruncateTable() error
- func (t *Table) TruncateTableContext(ctx context.Context) error
- func (t *Table) UpdateAllStatistics(samplePct int) error
- func (t *Table) UpdateAllStatisticsContext(ctx context.Context, samplePct int) error
- type Trigger
- type User
- func (u *User) AddToRole(roleName string) error
- func (u *User) Deny(permission ObjectPermission, objectSchema, objectName string) error
- func (u *User) DenyContext(ctx context.Context, permission ObjectPermission, ...) error
- func (u *User) Drop() error
- func (u *User) Grant(permission ObjectPermission, objectSchema, objectName string) error
- func (u *User) GrantContext(ctx context.Context, permission ObjectPermission, ...) error
- func (u *User) RemoveFromRole(roleName string) error
- func (u *User) Revoke(permission ObjectPermission, objectSchema, objectName string) error
- func (u *User) RevokeContext(ctx context.Context, permission ObjectPermission, ...) error
- type UserDefinedFunction
- type View
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 ¶
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 ¶
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 ¶
AddRoleMember adds a user to a database role.
func (*Database) AddRoleMemberContext ¶
AddRoleMemberContext is the context-aware variant.
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 ¶
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 ¶
CreatePartitionScheme creates a partition scheme backed by a partition function.
func (*Database) CreateSchema ¶
CreateSchema creates a new schema in the database.
func (*Database) CreateSchemaContext ¶
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 ¶
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 ¶
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 ¶
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 ¶
DropSchema drops a schema from the database.
func (*Database) DropSchemaContext ¶
DropSchemaContext is the context-aware variant of DropSchema.
func (*Database) DropStoredProcedure ¶
DropStoredProcedure drops a stored procedure.
func (*Database) DropStoredProcedureContext ¶
DropStoredProcedureContext is the context-aware variant.
func (*Database) DropTable ¶
DropTable drops a table. When cascade=true it first drops all incoming foreign-key constraints.
func (*Database) DropTableContext ¶
DropTableContext is the context-aware variant of DropTable.
func (*Database) DropUserContext ¶
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 ¶
FileGroups returns all filegroups and their files.
func (*Database) FileGroupsContext ¶
FileGroupsContext is the context-aware variant of FileGroups.
func (*Database) IsReadOnly ¶
IsReadOnly reports whether the database is set to read-only.
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 ¶
RemoveRoleMember removes a user from a database role.
func (*Database) RemoveRoleMemberContext ¶
RemoveRoleMemberContext is the context-aware variant.
func (*Database) RenameTable ¶
RenameTable renames a table using sp_rename.
func (*Database) RenameTableContext ¶
RenameTableContext is the context-aware variant of RenameTable.
func (*Database) SchemasContext ¶
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 ¶
SequenceSeq returns an iterator over all sequences in the database.
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 ¶
SetReadOnly sets the database to read-only or read-write.
func (*Database) SetReadOnlyContext ¶
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) SpaceUsedContext ¶
SpaceUsedContext is the context-aware variant of SpaceUsed.
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) TableByName ¶
TableByName returns a single table by schema and name using a direct query.
func (*Database) TableByNameContext ¶
TableByNameContext is the context-aware variant of TableByName.
func (*Database) TablesBySchema ¶
TablesBySchema returns all tables in a specific schema.
func (*Database) TablesBySchemaContext ¶
TablesBySchemaContext is the context-aware variant of TablesBySchema.
func (*Database) TablesContext ¶
TablesContext is the context-aware variant of Tables.
func (*Database) TriggersContext ¶
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) UsersContext ¶
UsersContext is the context-aware variant of Users.
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 ¶
ErrorLogEntry represents one row returned by xp_readerrorlog.
type ExtendedProperty ¶
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) DisableContext ¶
func (*Index) Rebuild ¶
Rebuild rebuilds the index (ALTER INDEX ... REBUILD). Pass fillFactor=0 to keep the existing fill factor.
func (*Index) RebuildContext ¶
func (*Index) Reorganize ¶
Reorganize reorganizes the index (ALTER INDEX ... REORGANIZE).
type IndexColumn ¶
IndexColumn represents one column in an index.
type IndexColumnDef ¶
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 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) 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 ¶
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.
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 ¶
AddServerRoleMember adds this login to a server role.
func (*Login) AddServerRoleMemberContext ¶
func (*Login) ChangePassword ¶
ChangePassword changes the login's password.
func (*Login) ChangePasswordContext ¶
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) RemoveServerRoleMember ¶
RemoveServerRoleMember removes this login from a server role.
type MailProfile ¶
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 ¶
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 ¶
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 ¶
Schema mirrors Microsoft.SqlServer.Management.Smo.Schema.
func (*Schema) ChangeOwner ¶
ChangeOwner transfers schema ownership to a new principal.
func (*Schema) ChangeOwnerContext ¶
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 ¶
ScriptDatabase generates a CREATE DATABASE script for the attached database.
func (*Scripter) ScriptFunction ¶
ScriptFunction returns the CREATE FUNCTION definition.
func (*Scripter) ScriptFunctionContext ¶
ScriptFunctionContext is the context-aware variant.
func (*Scripter) ScriptStoredProcedure ¶
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 ¶
ScriptTable generates a CREATE TABLE (or DROP TABLE) script.
func (*Scripter) ScriptTableContext ¶
ScriptTableContext is the context-aware variant of ScriptTable.
func (*Scripter) ScriptView ¶
ScriptView returns the CREATE VIEW definition as stored in sys.sql_modules.
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) 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.
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) 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 (*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 ¶
CycleErrorLog closes the current error log and opens a new one. Equivalent to sp_cycle_errorlog.
func (*Server) CycleErrorLogContext ¶
func (*Server) DatabaseByName ¶
DatabaseByName returns a single database by name.
func (*Server) DatabaseByNameContext ¶
DatabaseByNameContext is the context-aware variant of DatabaseByName.
func (*Server) DatabaseSeq ¶
DatabaseSeq returns an iterator over all databases on the server. The second yield value carries any error that stopped the iteration.
func (*Server) DatabasesContext ¶
DatabasesContext returns all databases, honouring the provided context.
func (*Server) DropDatabase ¶
DropDatabase drops the named database. When force is true, active connections are terminated first.
func (*Server) DropDatabaseContext ¶
DropDatabaseContext is the context-aware variant of DropDatabase.
func (*Server) DropLoginContext ¶
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 ¶
JobByName returns a single job by name using a direct parameterised query.
func (*Server) JobByNameContext ¶
JobByNameContext is the context-aware variant of JobByName.
func (*Server) JobsContext ¶
JobsContext is the context-aware variant of Jobs.
func (*Server) KillSession ¶
KillSession terminates a session by session ID.
func (*Server) KillSessionContext ¶
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) LoginsContext ¶
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) 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 (*Server) Reconfigure ¶
Reconfigure applies pending sp_configure changes. Pass override=true to use RECONFIGURE WITH OVERRIDE (bypasses range checks).
func (*Server) ReconfigureContext ¶
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) SendMailContext ¶
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 ¶
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 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 ¶
Drop drops this statistic. Correct T-SQL syntax: DROP STATISTICS table_name.stat_name
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.
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 ¶
ColumnSeq returns an iterator over all columns in the table, in ordinal order.
func (*Table) ColumnsContext ¶
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 ¶
CreateStatistic creates a user-defined statistic on one or more columns.
func (*Table) CreateStatisticContext ¶
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 (*Table) IndexesContext ¶
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 ¶
RebuildAllIndexes rebuilds all indexes on the table (ALTER INDEX ALL ... REBUILD).
func (*Table) RebuildAllIndexesContext ¶
func (*Table) RowCountContext ¶
RowCountContext is the context-aware variant of RowCount.
func (*Table) StatisticSeq ¶
StatisticSeq returns an iterator over all statistics on the table.
func (*Table) Statistics ¶
Statistics returns all statistics objects for the table.
func (*Table) StatisticsContext ¶
StatisticsContext is the context-aware variant of Statistics.
func (*Table) TruncateTable ¶
TruncateTable truncates a table.
func (*Table) TruncateTableContext ¶
TruncateTableContext is the context-aware variant of TruncateTable.
func (*Table) UpdateAllStatistics ¶
UpdateAllStatistics updates all statistics on the table.
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) 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 (*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 (*User) RemoveFromRole ¶
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.