common

package
v1.0.10 Latest Latest
Warning

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

Go to latest
Published: Apr 3, 2026 License: GPL-3.0 Imports: 24 Imported by: 0

Documentation

Overview

Package common provides common libraries for the service.

Index

Constants

View Source
const (
	// CELAttributeResourceEnvironmentID is the environment ID of the resource.
	CELAttributeResourceEnvironmentID = "resource.environment_id"
	// CELAttributeResourceProjectID is the project ID of the resource.
	CELAttributeResourceProjectID = "resource.project_id"
	// CELAttributeResourceInstanceID is the instance ID of the resource.
	CELAttributeResourceInstanceID = "resource.instance_id"
	// CELAttributeResourceDatabaseName is the database name of the resource.
	CELAttributeResourceDatabaseName = "resource.database_name"
	// CELAttributeResourceSchemaName is the schema name of the resource.
	CELAttributeResourceSchemaName = "resource.schema_name"
	// CELAttributeResourceTableName is the table name of the resource.
	CELAttributeResourceTableName = "resource.table_name"
	// CELAttributeResourceColumnName is the column name of the resource.
	CELAttributeResourceColumnName = "resource.column_name"
	// CELAttributeResourceDBEngine is the database engine of the resource.
	CELAttributeResourceDBEngine = "resource.db_engine"
	// CELAttributeResourceDatabase is the full database name of the resource (used in IAM policy conditions).
	CELAttributeResourceDatabase = "resource.database"
	// CELAttributeResourceClassificationLevel is the classification level of the resource.
	CELAttributeResourceClassificationLevel = "resource.classification_level"
	// CELAttributeResourceDatabaseLabels is the database labels of the resource.
	CELAttributeResourceDatabaseLabels = "resource.database_labels"
)

CEL attribute names for resource scope.

View Source
const (
	// CELAttributeStatementAffectedRows is the number of affected rows by the statement.
	CELAttributeStatementAffectedRows = "statement.affected_rows"
	// CELAttributeStatementTableRows is the total number of rows in the table.
	CELAttributeStatementTableRows = "statement.table_rows"
	// CELAttributeStatementSQLType is the SQL statement type (e.g., SELECT, INSERT, UPDATE, DELETE).
	CELAttributeStatementSQLType = "statement.sql_type"
	// CELAttributeStatementText is the full text of the SQL statement.
	CELAttributeStatementText = "statement.text"
)

CEL attribute names for statement scope.

View Source
const (
	// CELAttributeRequestExpirationDays is the number of days until the request expires.
	CELAttributeRequestExpirationDays = "request.expiration_days"
	// CELAttributeRequestRole is the requested role.
	CELAttributeRequestRole = "request.role"
	// CELAttributeRequestTime is the timestamp of the request.
	CELAttributeRequestTime = "request.time"
)

CEL attribute names for request scope.

View Source
const (
	// CELAttributeLevel is the risk level (deprecated).
	CELAttributeLevel = "level"
	// CELAttributeSource is the risk source (deprecated).
	CELAttributeSource = "source"
)

CEL attribute names for approval scope (deprecated, kept for backward compatibility).

View Source
const (
	WorkspaceAdmin  = "workspaceAdmin"
	WorkspaceMember = "workspaceMember"
	ProjectOwner    = "projectOwner"
)
View Source
const (
	// SystemBotID is the ID of the system robot.
	SystemBotID = 1

	// AllUsers is the email of the pseudo allUsers account.
	AllUsers = "allUsers"

	// PrincipalIDForFirstUser is the principal id for the first user in workspace.
	PrincipalIDForFirstUser = 101

	// ServiceAccountAccessKeyPrefix is the prefix for service account access key.
	ServiceAccountAccessKeyPrefix = "bbs_"
)
View Source
const (
	// DefaultProjectID is the resource ID for the default project.
	DefaultProjectID = "default"
	// DefaultTestEnvironmentID is the initial resource ID for the test environment.
	// This can be mutated by the user. But for now this is only used by onboarding flow to create
	// a test instance after first signup, so it's safe to refer it.
	DefaultTestEnvironmentID = "test"
	// DefaultProdEnvironmentID is the initial resource ID for the prod environment.
	// This can be mutated by the user. But for now this is only used by onboarding flow to create
	// a prod instance after first signup, so it's safe to refer it.
	DefaultProdEnvironmentID = "prod"
)
View Source
const (
	WorkspacePrefix            = "workspaces/"
	ProjectNamePrefix          = "projects/"
	EnvironmentNamePrefix      = "environments/"
	InstanceNamePrefix         = "instances/"
	PolicyNamePrefix           = "policies/"
	DatabaseIDPrefix           = "databases/"
	InstanceRolePrefix         = "roles/"
	UserNamePrefix             = "users/"
	IdentityProviderNamePrefix = "idps/"
	SettingNamePrefix          = "settings/"
	RolloutPrefix              = "rollouts/"
	StagePrefix                = "stages/"
	TaskPrefix                 = "tasks/"
	TaskRunPrefix              = "taskRuns/"
	PlanPrefix                 = "plans/"
	PlanCheckRunPrefix         = "planCheckRuns/"
	RolePrefix                 = "roles/"
	WebhookIDPrefix            = "webhooks/"
	SheetIDPrefix              = "sheets/"
	WorksheetIDPrefix          = "worksheets/"
	DatabaseGroupNamePrefix    = "databaseGroups/"
	SchemaNamePrefix           = "schemas/"
	TableNamePrefix            = "tables/"
	ChangelogPrefix            = "changelogs/"
	IssueNamePrefix            = "issues/"
	IssueCommentNamePrefix     = "issueComments/"
	PipelineNamePrefix         = "pipelines/"
	LogNamePrefix              = "logs/"
	BranchPrefix               = "branches/"
	DeploymentConfigPrefix     = "deploymentConfigs/"
	AuditLogPrefix             = "auditLogs/"
	GroupPrefix                = "groups/"
	ReviewConfigPrefix         = "reviewConfigs/"
	ReleaseNamePrefix          = "releases/"
	FileNamePrefix             = "files/"
	RevisionNamePrefix         = "revisions/"

	SchemaSuffix    = "/schema"
	SDLSchemaSuffix = "/sdlSchema"
	MetadataSuffix  = "/metadata"
	CatalogSuffix   = "/catalog"

	UserBindingPrefix  = "user:"
	GroupBindingPrefix = "group:"
)

nolint:revive

View Source
const (
	// MaxSheetSize is the maximum size (2M) of a sheet for displaying.
	MaxSheetSize = 2 * 1024 * 1024
	// MaxSheetCheckSize is the maximum size of a sheet for checking changes.
	MaxSheetCheckSize = 2 * 1024 * 1024
	// The maximum number of bytes for sql results in response body.
	// 100 MB.
	DefaultMaximumSQLResultSize = int64(100 * 1024 * 1024)
	// MaximumCommands is the maximum number of commands that can be executed in a single transaction.
	MaximumCommands = 200
	// MaximumAdvicePerStatus is the maximum number of advice that can be returned per status.
	MaximumAdvicePerStatus = 50
	MaximumLintExplainSize = 10

	// MinimumCompletedPlanCheckRun is the minimum number required to generate approval flow.
	MinimumCompletedPlanCheckRun = 5

	// ExternalURLPlaceholder is the docs link to configure --external-url.
	ExternalURLPlaceholder = "https://docs.bytebase.com/get-started/self-host/external-url"
)
View Source
const DefaultInstanceMaximumConnections = 10

DefaultInstanceMaximumConnections is the maximum number of connections outstanding per instance by default.

View Source
const EmptyStageID = "-"

EmptyStageID is the placeholder used for stages without environment or with deleted environments.

View Source
const (
	// ReservedTagReviewConfig is the tag for review config.
	ReservedTagReviewConfig string = "bb.tag.review_config"
)

Variables

ApprovalFactors are the variables when finding the approval template. After the risk layer removal (3.13), approval rules use the same variables as risk evaluation.

DatabaseGroupCELAttributes are the variables when evaluating database group conditions.

IAMPolicyConditionCELAttributes are the variables when evaluating IAM policy condition.

MaskingExceptionPolicyCELAttributes are the variables when evaluating masking exception.

MaskingRulePolicyCELAttributes are the variables when evaluating masking rule.

View Source
var ProtojsonUnmarshaler = protojson.UnmarshalOptions{DiscardUnknown: true}

ProtojsonMarshaler is a global protojson marshaler with DiscardUnknown set to true.

Functions

func BackupDatabaseNameOfEngine

func BackupDatabaseNameOfEngine(e storepb.Engine) string

func ConvertANTLRLineToPosition

func ConvertANTLRLineToPosition(line int) *storepb.Position

func ConvertANTLRPositionToPosition

func ConvertANTLRPositionToPosition(a *ANTLRPosition, text string) *storepb.Position

ConvertANTLRPositionToPosition converts an ANTLRPosition to a Position in a given text. ANTLRPosition uses 1-based line and 0-based character column. Returns a Position with 1-based line and 1-based character column. Returns the end Position if the ANTLRPosition is out of the end of text, returns the previous Position if the ANTLRPosition is out of the end of a line.

func ConvertPGParserErrorCursorPosToPosition

func ConvertPGParserErrorCursorPosToPosition(cursorPos int, text string) *storepb.Position

func ConvertTiDBParserErrorPositionToPosition

func ConvertTiDBParserErrorPositionToPosition(line, column int) *storepb.Position

func ConvertToParserEngine

func ConvertToParserEngine(e storepb.Engine) (storepb.Engine, error)

func ConvertUnparsedApproval

func ConvertUnparsedApproval(expression *expr.Expr) (*exprproto.ParsedExpr, error)

ConvertUnparsedApproval converts unparsed approval to parsed format.

func EngineSupportAutoComplete

func EngineSupportAutoComplete(e storepb.Engine) bool

func EngineSupportCreateDatabase

func EngineSupportCreateDatabase(e storepb.Engine) bool

func EngineSupportMasking

func EngineSupportMasking(e storepb.Engine) bool

func EngineSupportPriorBackup

func EngineSupportPriorBackup(e storepb.Engine) bool

func EngineSupportQueryNewACL

func EngineSupportQueryNewACL(engine storepb.Engine) bool

func EngineSupportQuerySpanPlainField

func EngineSupportQuerySpanPlainField(e storepb.Engine) bool

func EngineSupportSQLReview

func EngineSupportSQLReview(engine storepb.Engine) bool

func EngineSupportStatementAdvise

func EngineSupportStatementAdvise(e storepb.Engine) bool

func EngineSupportStatementReport

func EngineSupportStatementReport(e storepb.Engine) bool

func EngineSupportSyntaxCheck

func EngineSupportSyntaxCheck(e storepb.Engine) bool

func EvalBindingCondition

func EvalBindingCondition(expr string, requestTime time.Time) (bool, error)

func FormatChangelog

func FormatChangelog(instanceID, databaseID string, changelogUID int64) string

func FormatDBErrorEmptyRowWithQuery

func FormatDBErrorEmptyRowWithQuery(query string) error

FormatDBErrorEmptyRowWithQuery formats database error that query returns empty row.

func FormatDatabase

func FormatDatabase(instance string, database string) string

func FormatEnvironment

func FormatEnvironment(resourceID string) string

func FormatGroupEmail

func FormatGroupEmail(email string) string

func FormatInstance

func FormatInstance(resourceID string) string

func FormatIssue

func FormatIssue(projectID string, issueUID int) string

func FormatMaximumSQLResultSizeMessage

func FormatMaximumSQLResultSizeMessage(limit int64) string

func FormatPlan

func FormatPlan(projectID string, planUID int64) string

func FormatPlanCheckRun

func FormatPlanCheckRun(projectID string, planUID, runUID int64) string

func FormatProject

func FormatProject(id string) string

func FormatReleaseFile

func FormatReleaseFile(release string, fileID string) string

func FormatReleaseName

func FormatReleaseName(projectID string, releaseUID int64) string

func FormatReviewConfig

func FormatReviewConfig(id string) string

func FormatRevision

func FormatRevision(instanceID, databaseID string, revisionUID int64) string

func FormatRole

func FormatRole(role string) string

func FormatRollout

func FormatRollout(projectID string, pipelineUID int) string

func FormatSheet

func FormatSheet(projectID string, sheetUID int) string

func FormatStage

func FormatStage(projectID string, pipelineUID int, stageID string) string

stageID is task environmentID.

func FormatStageID

func FormatStageID(environment string) string

FormatStageID returns the stage ID, using EmptyStageID placeholder if environment is empty.

func FormatTask

func FormatTask(projectID string, pipelineUID int, stageID string, taskUID int) string

stageID is task environmentID.

func FormatTaskRun

func FormatTaskRun(projectID string, pipelineUID int, stageID string, taskUID, taskRunUID int) string

stageID is task environmentID.

func FormatUserEmail

func FormatUserEmail(email string) string

func FormatUserUID

func FormatUserUID(uid int) string

func FormatWorkspace

func FormatWorkspace(id string) string

func GetEnvironmentID

func GetEnvironmentID(name string) (string, error)

GetEnvironmentID returns the environment ID from a resource name.

func GetGroupEmail

func GetGroupEmail(name string) (string, error)

GetGroupEmail returns the group email.

func GetIdentityProviderID

func GetIdentityProviderID(name string) (string, error)

GetIdentityProviderID returns the identity provider ID from a resource name.

func GetInstanceDatabaseChangelogUID

func GetInstanceDatabaseChangelogUID(name string) (string, string, int64, error)

GetInstanceDatabaseChangelogUID returns the instance ID, database ID, and changelog UID from a resource name.

func GetInstanceDatabaseID

func GetInstanceDatabaseID(name string) (string, string, error)

GetInstanceDatabaseID returns the instance ID and database ID from a resource name.

func GetInstanceDatabaseRevisionID

func GetInstanceDatabaseRevisionID(name string) (string, string, int64, error)

GetInstanceDatabaseRevisionID returns the instance ID, database ID, and revision UID from a resource name.

func GetInstanceID

func GetInstanceID(name string) (string, error)

GetInstanceID returns the instance ID from a resource name.

func GetIssueID

func GetIssueID(name string) (int, error)

GetIssueID returns the issue ID from a resource name.

func GetNameParentTokens

func GetNameParentTokens(name string, tokenPrefixes ...string) ([]string, error)

GetNameParentTokens returns the tokens from a resource name.

func GetPolicyResourceTypeAndResource

func GetPolicyResourceTypeAndResource(requestName string) (storepb.Policy_Resource, *string, error)

func GetPostgresSocketDir

func GetPostgresSocketDir() string

GetPostgresSocketDir returns the postgres socket directory of Bytebase.

func GetProjectID

func GetProjectID(name string) (string, error)

GetProjectID returns the project ID from a resource name.

func GetProjectIDDatabaseGroupID

func GetProjectIDDatabaseGroupID(name string) (string, string, error)

GetProjectIDDatabaseGroupID returns the project ID and database group ID from a resource name.

func GetProjectIDIssueUID

func GetProjectIDIssueUID(name string) (string, int, error)

GetProjectIDIssueUID returns the project ID and issue UID from the issue name.

func GetProjectIDIssueUIDIssueCommentUID

func GetProjectIDIssueUIDIssueCommentUID(name string) (string, int, int, error)

GetProjectIDIssueUIDIssueCommentUID returns the project ID, issue UID and issue comment UID from the issue comment name.

func GetProjectIDPlanID

func GetProjectIDPlanID(name string) (string, int64, error)

GetProjectIDPlanID returns the project ID and plan ID from a resource name.

func GetProjectIDPlanIDPlanCheckRunID

func GetProjectIDPlanIDPlanCheckRunID(name string) (string, int, int, error)

GetProjectIDPlanIDPlanCheckRunID returns the project ID, plan ID and plan check run ID from a resource name.

func GetProjectIDRolloutID

func GetProjectIDRolloutID(name string) (string, int, error)

GetProjectIDRolloutID returns the project ID and rollout ID from a resource name.

func GetProjectIDRolloutIDMaybeStageID

func GetProjectIDRolloutIDMaybeStageID(name string) (string, int, *string, error)

GetProjectIDRolloutIDMaybeStageID returns the project ID, rollout ID, and maybe stage ID from a resource name.

func GetProjectIDRolloutIDMaybeStageIDMaybeTaskID

func GetProjectIDRolloutIDMaybeStageIDMaybeTaskID(name string) (string, int, *string, *int, error)

GetProjectIDRolloutIDMaybeStageIDMaybeTaskID returns the project ID, rollout ID, and maybe stage ID and maybe task ID from a resource name.

func GetProjectIDRolloutIDStageIDMaybeTaskID

func GetProjectIDRolloutIDStageIDMaybeTaskID(name string) (string, int, string, *int, error)

GetProjectIDRolloutIDStageIDMaybeTaskID returns the project ID, rollout ID, and maybe stage ID and maybe task ID from a resource name.

func GetProjectIDRolloutIDStageIDTaskID

func GetProjectIDRolloutIDStageIDTaskID(name string) (string, int, string, int, error)

GetProjectIDRolloutIDStageIDTaskID returns the project ID, rollout ID, stage ID, and task ID from a resource name.

func GetProjectIDRolloutIDStageIDTaskIDTaskRunID

func GetProjectIDRolloutIDStageIDTaskIDTaskRunID(name string) (string, int, string, int, int, error)

GetProjectIDRolloutIDStageIDTaskIDTaskRunID returns the project ID, rollout ID, stage ID, task ID and task run ID from a resource name.

func GetProjectIDWebhookID

func GetProjectIDWebhookID(name string) (string, string, error)

GetProjectIDWebhookID returns the project ID and webhook ID from a resource name.

func GetProjectReleaseUID

func GetProjectReleaseUID(name string) (string, int64, error)

func GetProjectReleaseUIDFile

func GetProjectReleaseUIDFile(name string) (string, int64, string, error)

func GetProjectResourceIDSheetUID

func GetProjectResourceIDSheetUID(name string) (string, int, error)

GetProjectResourceIDSheetUID returns the project ID and sheet UID from a resource name.

func GetReviewConfigID

func GetReviewConfigID(name string) (string, error)

GetReviewConfigID returns the review config id from a resource name.

func GetRiskLevelFromStatementTypes

func GetRiskLevelFromStatementTypes(statementTypes []string) storepb.RiskLevel

GetRiskLevelFromStatementTypes returns the highest risk level for the given statement types.

func GetRoleID

func GetRoleID(name string) (string, error)

GetRoleID returns the role ID from a resource name.

func GetSchemaTableName

func GetSchemaTableName(name string) (string, string, error)

GetSchemaTableName returns the schema and table names from a resource name.

func GetSetServiceDataFromContext

func GetSetServiceDataFromContext(ctx context.Context) (func(a *anypb.Any), bool)

func GetSettingName

func GetSettingName(name string) (string, error)

GetSettingName returns the setting name from a resource name.

func GetUIDFromName

func GetUIDFromName(name, prefix string) (int, error)

GetUIDFromName returns the UID from a resource name.

func GetUserEmail

func GetUserEmail(name string) (string, error)

GetUserEmail returns the user email from a resource name.

func GetUserID

func GetUserID(name string) (int, error)

GetUserID returns the user ID from a resource name.

func GetWorksheetUID

func GetWorksheetUID(name string) (int, error)

GetWorksheetUID returns the worksheet UID from a resource name.

func HasPrefixes

func HasPrefixes(src string, prefixes ...string) bool

HasPrefixes returns true if the string s has any of the given prefixes.

func IsDev

func IsDev() bool

func IsNil

func IsNil(val any) bool

func IsNonTransactionStatement

func IsNonTransactionStatement(stmt string) bool

IsNonTransactionStatement checks if a PostgreSQL statement cannot run inside a transaction block.

func IsSpaceOrSemicolon

func IsSpaceOrSemicolon(r rune) bool

IsSpaceOrSemicolon checks if the rune is a space or a semicolon.

func NewP

func NewP[T any](x T) *T

func NormalizeExternalURL

func NormalizeExternalURL(url string) (string, error)

NormalizeExternalURL will format the external url.

func Obfuscate

func Obfuscate(src, seed string) string

Obfuscate obfuscates a string with a seed string.

func RandomString

func RandomString(n int) (string, error)

RandomString returns a random string with length n.

func Retry

func Retry(ctx context.Context, fn func() error) error

Retry uses exponential backoff with timeout.

func SanitizeUTF8String

func SanitizeUTF8String(s string) string

SanitizeUTF8String returns a copy of the string s with each run of invalid or unprintable UTF-8 byte sequences replaced by its hexadecimal representation string.

func TrimStatement

func TrimStatement(statement string) string

TrimStatement trims the unused characters from the statement.

func TrimSuffix

func TrimSuffix(name, suffix string) (string, error)

TrimSuffix trims the suffix from the name and returns the trimmed name.

func TrimSuffixAndGetInstanceDatabaseID

func TrimSuffixAndGetInstanceDatabaseID(name string, suffix string) (string, string, error)

TrimSuffixAndGetInstanceDatabaseID trims the suffix from the name and returns the instance ID and database ID.

func TruncateString

func TruncateString(str string, limit int) (string, bool)

TruncateString truncates the string to have a maximum length of `limit` characters.

func TruncateStringWithDescription

func TruncateStringWithDescription(str string) string

TruncateStringWithDescription tries to truncate the string and append "... (view details in Bytebase)" if truncated.

func Unobfuscate

func Unobfuscate(dst, seed string) (string, error)

Unobfuscate unobfuscates a string with a seed string.

func ValidateGroupCELExpr

func ValidateGroupCELExpr(expr string) (cel.Program, error)

ValidateGroupCELExpr validates group expr.

func ValidateMaskingExceptionCELExpr

func ValidateMaskingExceptionCELExpr(expression *expr.Expr) (cel.Program, error)

ValidateMaskingExceptionCELExpr validates masking exception expr.

func ValidateMaskingRuleCELExpr

func ValidateMaskingRuleCELExpr(expr string) (cel.Program, error)

ValidateMaskingRuleCELExpr validates masking rule expr.

func ValidatePhone

func ValidatePhone(phone string) error

ValidatePhone validates the phone number.

func ValidateProjectMemberCELExpr

func ValidateProjectMemberCELExpr(expression *expr.Expr) (cel.Program, error)

func WithSetServiceData

func WithSetServiceData(ctx context.Context, setServiceData func(a *anypb.Any)) context.Context

Types

type ANTLRPosition

type ANTLRPosition struct {
	// Line position in a text (one-based).
	Line int32
	// Column position in a text (zero-based), equivalent to character offset.
	Column int32
}

ANTLRPosition is a position in a text expressed as one-based line and zero-based column character (code point) offset integrated with ANTLR4.

type AuthContext

type AuthContext struct {
	Audit                  bool
	AllowWithoutCredential bool
	Permission             string
	AuthMethod             AuthMethod
	Resources              []*Resource
}

func GetAuthContextFromContext

func GetAuthContextFromContext(ctx context.Context) (*AuthContext, bool)

func (*AuthContext) GetProjectResources

func (c *AuthContext) GetProjectResources() []string

func (*AuthContext) HasWorkspaceResource

func (c *AuthContext) HasWorkspaceResource() bool

type AuthMethod

type AuthMethod int
const (
	AuthMethodUnspecified AuthMethod = iota
	AuthMethodIAM
	AuthMethodCustom
)

type Code

type Code int

Code is the error code.

const (
	// 0 ~ 99 general error.
	Ok             Code = 0
	Internal       Code = 1
	NotAuthorized  Code = 2
	Invalid        Code = 3
	NotFound       Code = 4
	Conflict       Code = 5
	NotImplemented Code = 6
	SizeExceeded   Code = 7

	// 101 ~ 199 db error.
	DBConnectionFailure Code = 101
	DBExecutionError    Code = 102

	// 201 db migration error
	// Db migration is a core feature, so we separate it from the db error.
	MigrationSchemaMissing  Code = 201
	MigrationAlreadyApplied Code = 202
	MigrationOutOfOrder     Code = 203
	// MigrationBaselineMissing is no longer used.
	// MigrationBaselineMissing Code = 204.
	MigrationPending Code = 205
	MigrationFailed  Code = 206

	// 301 task error.
	TaskTimingNotAllowed Code = 301

	// 401 task sql type error.
	TaskTypeNotDML         Code = 401
	TaskTypeNotDDL         Code = 402
	TaskTypeDropDatabase   Code = 403
	TaskTypeCreateDatabase Code = 404
	TaskTypeDropTable      Code = 405
	TaskTypeDropIndex      Code = 406
	TaskTypeDropColumn     Code = 407
	TaskTypeDropPrimaryKey Code = 408
	TaskTypeDropForeignKey Code = 409
	TaskTypeDropCheck      Code = 410
)

Application error codes.

func ErrorCode

func ErrorCode(err error) Code

ErrorCode unwraps an application error and returns its code. Non-application errors always return EINTERNAL.

func (Code) Int

func (c Code) Int() int

Int returns the int type of code.

func (Code) Int32

func (c Code) Int32() int32

Int32 returns the int32 type of code.

type ContextKey

type ContextKey int

ContextKey is the key type of context value.

const (
	// UserContextKey is the key name used to store user message in the context.
	UserContextKey ContextKey = iota
	AuthContextKey
	ServiceDataKey
)

type Error

type Error struct {
	// Machine-readable error code.
	Code Code

	// Embedded error.
	Err error
}

Error represents an application-specific error. Application errors can be unwrapped by the caller to extract out the code & message.

Any non-application error (such as a disk error) should be reported as an Internal error and the human user should only see "Internal error" as the message. These low-level internal error details should only be logged and reported to the operator of the application (not the end user).

func Errorf

func Errorf(code Code, format string, args ...any) *Error

Errorf is a helper function to create an Error with given code and formatted message.

func Wrap

func Wrap(err error, code Code) *Error

Wrap is a helper function to wrap an Error with given code.

func Wrapf

func Wrapf(err error, code Code, format string, args ...any) *Error

Wrapf is a helper function to wrap an Error with given code and formatted message.

func (*Error) Error

func (e *Error) Error() string

Error implements the error interface. Not used by the application otherwise.

type IsolationLevel

type IsolationLevel string

IsolationLevel represents the transaction isolation level.

const (
	// IsolationLevelDefault uses the database's default isolation level.
	IsolationLevelDefault IsolationLevel = ""
	// IsolationLevelReadUncommitted allows dirty reads.
	IsolationLevelReadUncommitted IsolationLevel = "READ UNCOMMITTED"
	// IsolationLevelReadCommitted prevents dirty reads.
	IsolationLevelReadCommitted IsolationLevel = "READ COMMITTED"
	// IsolationLevelRepeatableRead prevents dirty reads and non-repeatable reads.
	IsolationLevelRepeatableRead IsolationLevel = "REPEATABLE READ"
	// IsolationLevelSerializable provides the highest isolation level.
	IsolationLevelSerializable IsolationLevel = "SERIALIZABLE"
)

type QueryExportFactors

type QueryExportFactors struct {
	Databases []string
}

QueryExportFactors is the factors for query and export.

func GetQueryExportFactors

func GetQueryExportFactors(expression string) (*QueryExportFactors, error)

GetQueryExportFactors is used to get risk factors from query and export expressions.

type ReleaseMode

type ReleaseMode string

ReleaseMode is the mode for release, such as dev or release.

const (
	// ReleaseModeProd is the prod mode.
	ReleaseModeProd ReleaseMode = "prod"
	// ReleaseModeDev is the dev mode.
	ReleaseModeDev ReleaseMode = "dev"
)

type Resource

type Resource struct {
	Type      string
	Name      string
	ProjectID string
	Workspace bool
}

type TransactionConfig

type TransactionConfig struct {
	Mode      TransactionMode
	Isolation IsolationLevel
}

TransactionConfig represents the complete transaction configuration.

type TransactionMode

type TransactionMode string

TransactionMode represents the transaction execution mode for a migration script.

const (
	// TransactionModeOn wraps the script in a single transaction.
	TransactionModeOn TransactionMode = "on"
	// TransactionModeOff executes the script's statements sequentially in auto-commit mode.
	TransactionModeOff TransactionMode = "off"
	// TransactionModeUnspecified means no explicit mode was specified.
	TransactionModeUnspecified TransactionMode = ""
)

func GetDefaultTransactionMode

func GetDefaultTransactionMode() TransactionMode

GetDefaultTransactionMode returns the default transaction mode. All engines default to "on" (transactional) for safety and backward compatibility. Users can explicitly set "-- txn-mode = off" when needed for engines with limited transactional DDL support.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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