Documentation
¶
Index ¶
- Constants
- Variables
- func CompareQueryFeatures(qf1, qf2 *QueryFeatures) map[string]interface{}
- func ConfigureValidationLocales(defaultLocale string, enabledLocales []string) error
- func ConvertValue(value interface{}, targetType FieldType) (interface{}, error)
- func DaysLater(days int) time.Time
- func DaysLaterUTC(days int) time.Time
- func DefaultSQLiteJSONFallbackFunctions() map[string]interface{}
- func EndOfCurrentMonth() time.Time
- func EndOfCurrentQuarter() time.Time
- func ErrCursorPrimaryValueRequired(field string) error
- func ExampleMySQLDynamicTable()
- func ExamplePostgreSQLDynamicTable()
- func ExampleSQLServerDynamicTable()
- func ExampleSQLiteDynamicTable()
- func GetEnabledValidationLocales() []string
- func GetStructFields(v interface{}) []string
- func GetStructValues(v interface{}) []interface{}
- func GetValidationLocale() string
- func JSONExtractGo(jsonText string, path string) interface{}
- func LoadAdapterRegistry(filename string) (map[string]*Config, error)
- func MonthsLater(months int) time.Time
- func MonthsLaterUTC(months int) time.Time
- func NextBillingDate(day int) time.Time
- func OneYearLater() time.Time
- func OneYearLaterUTC() time.Time
- func PrintQueryFeatureMatrix(databases ...string) string
- func RealWorldExample(repo *Repository, ctx context.Context) error
- func RegisterAdapter(factory AdapterFactory)
- func RegisterAdapterConfig(name string, config *Config) error
- func RegisterAdapterConfigs(configs map[string]*Config) error
- func RegisterAdapterConstructor(name string, ctor interface{}) error
- func RegisterCustomSQLiteDriver(driverName string, functions map[string]interface{}) error
- func RegisterSQLiteJSONFallbackDriver(driverName string, extraFunctions map[string]interface{}) error
- func RegisterSchemasIntoGlobal(schemas ...Schema)
- func RegisterValidationProfile(profile ValidationProfile) error
- func SLADeadline(hours int, workdaysOnly bool) time.Time
- func SaveConfig(filename string, config *Config) error
- func ScanStruct(row *sql.Row, dest interface{}) error
- func ScanStructs(rows *sql.Rows, dest interface{}) error
- func SetLegacyQueryBuilderWarningEnabled(enabled bool)
- func SetLowLevelTransactionWarningEnabled(enabled bool)
- func SetValidationLocale(locale string) error
- func StartOfCurrentMonth() time.Time
- func StartOfCurrentQuarter() time.Time
- func Timestamp() time.Time
- func ValidationLocaleExists(locale string) bool
- func ValidationLocaleFromContext(ctx context.Context) string
- func WithValidationLocale(ctx context.Context, locale string) context.Context
- func YearsLater(years int) time.Time
- func YearsLaterUTC(years int) time.Time
- type Action
- type Adapter
- type AdapterFactory
- type AdapterRegistryFile
- type AutoShardingManager
- type AutoShardingTemplate
- type BaseMigration
- type BaseSQLCompiler
- type BaseSchema
- func (s *BaseSchema) AddField(field *Field) *BaseSchema
- func (s *BaseSchema) AddForeignKey(name string, localFields []string, refTable string, refFields []string, ...) *BaseSchema
- func (s *BaseSchema) AddPrimaryKey(fields ...string) *BaseSchema
- func (s *BaseSchema) AddSoftDelete() *BaseSchema
- func (s *BaseSchema) AddTimestamps() *BaseSchema
- func (s *BaseSchema) AddUniqueConstraint(name string, fields ...string) *BaseSchema
- func (s *BaseSchema) BelongsTo(target Schema) *SchemaRelationBuilder
- func (s *BaseSchema) Constraints() []TableConstraint
- func (s *BaseSchema) Fields() []*Field
- func (s *BaseSchema) FindRelation(targetTable string) *SchemaRelation
- func (s *BaseSchema) GetField(name string) *Field
- func (s *BaseSchema) HasMany(target Schema) *SchemaRelationBuilder
- func (s *BaseSchema) HasOne(target Schema) *SchemaRelationBuilder
- func (s *BaseSchema) ManyToMany(target Schema) *SchemaRelationBuilder
- func (s *BaseSchema) PrimaryKeyField() *Field
- func (s *BaseSchema) Relations() []SchemaRelation
- func (s *BaseSchema) TableName() string
- type Changeset
- func (cs *Changeset) ApplyAction(action Action) *Changeset
- func (cs *Changeset) Cast(data map[string]interface{}) *Changeset
- func (cs *Changeset) Changes() map[string]interface{}
- func (cs *Changeset) ClearError(fieldName string) *Changeset
- func (cs *Changeset) Data() map[string]interface{}
- func (cs *Changeset) ErrorString() string
- func (cs *Changeset) Errors() map[string][]string
- func (cs *Changeset) ForceChanges() *Changeset
- func (cs *Changeset) Get(fieldName string) interface{}
- func (cs *Changeset) GetChange(fieldName string) interface{}
- func (cs *Changeset) GetChanged(fieldName string) (interface{}, bool)
- func (cs *Changeset) GetChangedFields() []string
- func (cs *Changeset) GetError(fieldName string) []string
- func (cs *Changeset) GetPrevious(fieldName string) interface{}
- func (cs *Changeset) HasChanged(fieldName string) bool
- func (cs *Changeset) IsValid() bool
- func (cs *Changeset) PutChange(fieldName string, value interface{}) *Changeset
- func (cs *Changeset) ToMap() map[string]interface{}
- func (cs *Changeset) Validate() *Changeset
- func (cs *Changeset) ValidateChange(fieldName string, validator Validator) *Changeset
- func (cs *Changeset) ValidateChangeWithContext(ctx context.Context, fieldName string, validator Validator) *Changeset
- func (cs *Changeset) ValidateChangeWithLocale(fieldName string, validator Validator, locale string) *Changeset
- func (cs *Changeset) ValidateExclusion(fieldName string, list []interface{}) *Changeset
- func (cs *Changeset) ValidateFormat(fieldName string, pattern string, message ...string) *Changeset
- func (cs *Changeset) ValidateInclusion(fieldName string, list []interface{}) *Changeset
- func (cs *Changeset) ValidateLength(fieldName string, min, max int) *Changeset
- func (cs *Changeset) ValidateNumber(fieldName string, opts map[string]interface{}) *Changeset
- func (cs *Changeset) ValidateRequired(fields []string) *Changeset
- func (cs *Changeset) ValidateWithContext(ctx context.Context) *Changeset
- func (cs *Changeset) ValidateWithLocale(locale string) *Changeset
- type ChangesetExecutor
- func (e *ChangesetExecutor) Delete(whereClause string, whereArgs ...interface{}) (sql.Result, error)
- func (e *ChangesetExecutor) DeleteByID(id interface{}) (sql.Result, error)
- func (e *ChangesetExecutor) Insert(cs *Changeset) (sql.Result, error)
- func (e *ChangesetExecutor) SoftDelete(whereClause string, whereArgs ...interface{}) (sql.Result, error)
- func (e *ChangesetExecutor) SoftDeleteByID(id interface{}) (sql.Result, error)
- func (e *ChangesetExecutor) Update(cs *Changeset, whereClause string, whereArgs ...interface{}) (sql.Result, error)
- func (e *ChangesetExecutor) UpdateByID(id interface{}, cs *Changeset) (sql.Result, error)
- type CompiledQuery
- type CompiledQueryCache
- type CompiledQueryCacheStats
- type CompiledQueryTemplate
- type CompositeCondition
- type CompositeTypeBuilder
- func (b *CompositeTypeBuilder) AddField(ctx context.Context, name, pgType string) error
- func (b *CompositeTypeBuilder) Build() (string, error)
- func (b *CompositeTypeBuilder) Create(ctx context.Context) error
- func (b *CompositeTypeBuilder) Drop(ctx context.Context, ifExists bool) error
- func (b *CompositeTypeBuilder) Exists(ctx context.Context) (bool, error)
- func (b *CompositeTypeBuilder) Field(name, pgType string) *CompositeTypeBuilder
- func (b *CompositeTypeBuilder) IfNotExists() *CompositeTypeBuilder
- func (b *CompositeTypeBuilder) Schema(schema string) *CompositeTypeBuilder
- type Condition
- func ActiveUsersInBusinessHours() Condition
- func ActiveUsersInBusinessHoursBy(statusField string, activeValue interface{}, timeField string, ...) Condition
- func And(conditions ...Condition) Condition
- func Between(field string, min, max interface{}) Condition
- func DateFrom(field string, start time.Time) Condition
- func DateInBusinessHours(field string, startHour, endHour int) Condition
- func DateInCurrentMonth(field string) Condition
- func DateInCurrentQuarter(field string) Condition
- func DateInLastBusinessDays(field string, days int, holidays ...time.Time) Condition
- func DateOn(field string, year, month, day int) Condition
- func DateRange(field string, start, end time.Time) Condition
- func DateTo(field string, end time.Time) Condition
- func DueSoonTasksInBusinessDays(days int, holidays ...time.Time) Condition
- func Eq(field string, value interface{}) Condition
- func EqFields(values map[string]interface{}) Condition
- func FullText(field string, query string) Condition
- func Gt(field string, value interface{}) Condition
- func Gte(field string, value interface{}) Condition
- func In(field string, values ...interface{}) Condition
- func Like(field string, pattern string) Condition
- func Lt(field string, value interface{}) Condition
- func Lte(field string, value interface{}) Condition
- func Ne(field string, value interface{}) Condition
- func Not(condition Condition) Condition
- func Or(conditions ...Condition) Condition
- func OrdersInCurrentQuarter() Condition
- func OrdersInCurrentQuarterBy(timeField string) Condition
- type ConditionTranslator
- type Config
- func DefaultConfig(adapterType string) *Config
- func GetAdapterConfig(name string) (*Config, bool)
- func LoadConfig(filename string) (*Config, error)
- func LoadConfigFromEnv(adapter string) (*Config, error)
- func LoadConfigFromEnvWithDefaults(adapter string, defaults *Config) (*Config, error)
- func LoadConfigWithDefaults(filename string, defaults *Config) (*Config, error)
- func (c *Config) ResolvedMongoConfig() *MongoConnectionConfig
- func (c *Config) ResolvedMySQLConfig() *MySQLConnectionConfig
- func (c *Config) ResolvedNeo4jConfig() *Neo4jConnectionConfig
- func (c *Config) ResolvedPostgresConfig() *PostgresConnectionConfig
- func (c *Config) ResolvedSQLServerConfig() *SQLServerConnectionConfig
- func (c *Config) ResolvedSQLiteConfig() *SQLiteConnectionConfig
- func (c *Config) ScheduledTaskFallbackEnabled() bool
- func (c *Config) Validate() error
- type ConfigFile
- type ConstrainedSchema
- type ConstraintKind
- type CountBuilder
- type CrossTableStrategy
- type CrossTableViewEntry
- type CrossTableViewRegistry
- func (r *CrossTableViewRegistry) Lookup(localTable, refTable string) (*CrossTableViewEntry, bool)
- func (r *CrossTableViewRegistry) LookupAny(tableA, tableB string) (*CrossTableViewEntry, bool)
- func (r *CrossTableViewRegistry) Register(entry *CrossTableViewEntry)
- func (r *CrossTableViewRegistry) RegisterFromSchema(schema Schema)
- type CustomFeatureProvider
- type CypherCompiler
- type CypherConditionTranslator
- type CypherWriteSummary
- type DatabaseFeatures
- func (f *DatabaseFeatures) GetFallbackStrategy(feature string) FeatureFallback
- func (f *DatabaseFeatures) GetFeatureSupport(feature string) FeatureSupport
- func (f *DatabaseFeatures) GetFeaturesByCategory(category FeatureCategory) []string
- func (f *DatabaseFeatures) HasFeature(feature string) bool
- func (f *DatabaseFeatures) SupportsFeatureWithVersion(feature, version string) bool
- type DateBuilder
- func (b *DateBuilder) AddDays(days int) *DateBuilder
- func (b *DateBuilder) AddMonths(months int) *DateBuilder
- func (b *DateBuilder) AddYears(years int) *DateBuilder
- func (b *DateBuilder) At(hour, minute, second int) *DateBuilder
- func (b *DateBuilder) Build() time.Time
- func (b *DateBuilder) EndOfMonth() *DateBuilder
- func (b *DateBuilder) EndOfQuarter() *DateBuilder
- func (b *DateBuilder) In(loc *time.Location) *DateBuilder
- func (b *DateBuilder) StartOfMonth() *DateBuilder
- func (b *DateBuilder) StartOfQuarter() *DateBuilder
- type DatePresetRegistry
- func (DatePresetRegistry) ActiveUsersInBusinessHours() Condition
- func (DatePresetRegistry) ActiveUsersInBusinessHoursBy(statusField string, activeValue interface{}, timeField string, ...) Condition
- func (DatePresetRegistry) DueSoonTasksInBusinessDays(days int, holidays ...time.Time) Condition
- func (DatePresetRegistry) OrdersInCurrentQuarter() Condition
- func (DatePresetRegistry) OrdersInCurrentQuarterBy(timeField string) Condition
- type DateShardingGranularity
- type DefaultSQLDialect
- func (d *DefaultSQLDialect) GenerateLimitOffset(limit *int, offset *int) string
- func (d *DefaultSQLDialect) GetPlaceholder(index int) string
- func (d *DefaultSQLDialect) Name() string
- func (d *DefaultSQLDialect) QuoteIdentifier(name string) string
- func (d *DefaultSQLDialect) QuoteValue(value interface{}) string
- func (d *DefaultSQLDialect) TranslateCondition(condition Condition, argIndex *int) (string, []interface{}, error)
- type DefaultSQLQueryConstructorProvider
- func (p *DefaultSQLQueryConstructorProvider) GetCapabilities() *QueryBuilderCapabilities
- func (p *DefaultSQLQueryConstructorProvider) NewQueryConstructor(schema Schema) QueryConstructor
- func (p *DefaultSQLQueryConstructorProvider) SetCompiler(compiler QueryCompiler) *DefaultSQLQueryConstructorProvider
- type DefaultSQLTranslator
- type DialectAwareQueryCompiler
- type DomainTypeBuilder
- func (b *DomainTypeBuilder) BaseType(pgType string) *DomainTypeBuilder
- func (b *DomainTypeBuilder) Build() (string, error)
- func (b *DomainTypeBuilder) Check(expression string) *DomainTypeBuilder
- func (b *DomainTypeBuilder) CheckNamed(constraintName, expression string) *DomainTypeBuilder
- func (b *DomainTypeBuilder) Create(ctx context.Context) error
- func (b *DomainTypeBuilder) Default(expr string) *DomainTypeBuilder
- func (b *DomainTypeBuilder) Drop(ctx context.Context, ifExists bool) error
- func (b *DomainTypeBuilder) Exists(ctx context.Context) (bool, error)
- func (b *DomainTypeBuilder) IfNotExists() *DomainTypeBuilder
- func (b *DomainTypeBuilder) NotNull() *DomainTypeBuilder
- func (b *DomainTypeBuilder) Schema(schema string) *DomainTypeBuilder
- type DynamicTableConfig
- func (c *DynamicTableConfig) AddField(field *DynamicTableField) *DynamicTableConfig
- func (c *DynamicTableConfig) WithDescription(desc string) *DynamicTableConfig
- func (c *DynamicTableConfig) WithOption(key string, value interface{}) *DynamicTableConfig
- func (c *DynamicTableConfig) WithParentTable(parentTable, triggerCondition string) *DynamicTableConfig
- func (c *DynamicTableConfig) WithStrategy(strategy string) *DynamicTableConfig
- type DynamicTableField
- func (f *DynamicTableField) AsNotNull() *DynamicTableField
- func (f *DynamicTableField) AsPrimaryKey() *DynamicTableField
- func (f *DynamicTableField) WithAutoinc() *DynamicTableField
- func (f *DynamicTableField) WithDefault(value interface{}) *DynamicTableField
- func (f *DynamicTableField) WithDescription(desc string) *DynamicTableField
- func (f *DynamicTableField) WithIndex() *DynamicTableField
- func (f *DynamicTableField) WithUnique() *DynamicTableField
- type DynamicTableHook
- type DynamicTableRegistry
- type EmailValidator
- type EnumTypeBuilder
- func (b *EnumTypeBuilder) Build() (string, error)
- func (b *EnumTypeBuilder) Create(ctx context.Context) error
- func (b *EnumTypeBuilder) Drop(ctx context.Context, ifExists bool) error
- func (b *EnumTypeBuilder) Exists(ctx context.Context) (bool, error)
- func (b *EnumTypeBuilder) IfNotExists() *EnumTypeBuilder
- func (b *EnumTypeBuilder) Schema(schema string) *EnumTypeBuilder
- func (b *EnumTypeBuilder) Values(vals ...string) *EnumTypeBuilder
- type FKOption
- type FeatureCategory
- type FeatureComparison
- type FeatureExecutionDecision
- type FeatureExecutionMode
- type FeatureFallback
- type FeatureSupport
- type Field
- type FieldBuilder
- func (fb *FieldBuilder) Build() *Field
- func (fb *FieldBuilder) Default(value interface{}) *FieldBuilder
- func (fb *FieldBuilder) Index() *FieldBuilder
- func (fb *FieldBuilder) Null(allow bool) *FieldBuilder
- func (fb *FieldBuilder) PrimaryKey() *FieldBuilder
- func (fb *FieldBuilder) Transform(transformer Transformer) *FieldBuilder
- func (fb *FieldBuilder) Unique() *FieldBuilder
- func (fb *FieldBuilder) Validate(validator Validator) *FieldBuilder
- type FieldType
- type ForeignKeyAction
- type ForeignKeyDef
- type FullTextRuntimeCapability
- type FullTextRuntimeInspector
- type FuzzySearchPlan
- type IDCardValidator
- type JSONRuntimeCapability
- type JSONRuntimeInspector
- type JoinBuilder
- func NewCrossJoin(schema Schema) *JoinBuilder
- func NewInnerJoin(schema Schema) *JoinBuilder
- func NewJoinBuilder(joinType string, schema Schema) *JoinBuilder
- func NewJoinWith(schema Schema) *JoinBuilder
- func NewLeftJoin(schema Schema) *JoinBuilder
- func NewOptionalJoin(schema Schema) *JoinBuilder
- func NewRequiredJoin(schema Schema) *JoinBuilder
- func NewRightJoin(schema Schema) *JoinBuilder
- type JoinSemantic
- type JoinTableDef
- type LengthValidator
- type LocalCacheStats
- type LocaleAwareValidator
- type LowercaseTransformer
- type MaxLengthValidator
- type Migration
- type MigrationInterface
- type MigrationLog
- type MigrationOperation
- type MigrationOperationKind
- type MigrationRunner
- type MigrationStatus
- type Migrator
- type MinLengthValidator
- type MongoAdapter
- func (a *MongoAdapter) Begin(ctx context.Context, opts ...interface{}) (Tx, error)
- func (a *MongoAdapter) Close() error
- func (a *MongoAdapter) Connect(ctx context.Context, config *Config) error
- func (a *MongoAdapter) Exec(ctx context.Context, sql string, args ...interface{}) (sql.Result, error)
- func (a *MongoAdapter) ExecuteCompiledFindPlan(ctx context.Context, query string) ([]map[string]interface{}, error)
- func (a *MongoAdapter) ExecuteCompiledWritePlan(ctx context.Context, query string) (*QueryConstructorExecSummary, error)
- func (a *MongoAdapter) ExecuteCustomFeature(ctx context.Context, feature string, input map[string]interface{}) (interface{}, error)
- func (a *MongoAdapter) GetDatabaseFeatures() *DatabaseFeatures
- func (a *MongoAdapter) GetQueryBuilderProvider() QueryConstructorProvider
- func (a *MongoAdapter) GetQueryFeatures() *QueryFeatures
- func (a *MongoAdapter) GetRawConn() interface{}
- func (a *MongoAdapter) HasCustomFeatureImplementation(feature string) bool
- func (a *MongoAdapter) InspectFullTextRuntime(ctx context.Context) (*FullTextRuntimeCapability, error)
- func (a *MongoAdapter) ListScheduledTasks(ctx context.Context) ([]*ScheduledTaskStatus, error)
- func (a *MongoAdapter) Ping(ctx context.Context) error
- func (a *MongoAdapter) Query(ctx context.Context, sql string, args ...interface{}) (*sql.Rows, error)
- func (a *MongoAdapter) QueryRow(ctx context.Context, sql string, args ...interface{}) *sql.Row
- func (a *MongoAdapter) RegisterScheduledTask(ctx context.Context, task *ScheduledTaskConfig) error
- func (a *MongoAdapter) UnregisterScheduledTask(ctx context.Context, taskName string) error
- type MongoCompiledFindPlan
- type MongoCompiledWritePlan
- type MongoConnectionConfig
- type MongoFactory
- type MongoLocalCache
- func (c *MongoLocalCache) ForcePreload(ctx context.Context, name, collection string, filter, projection bson.D, ...) error
- func (c *MongoLocalCache) Get(name string) ([]bson.M, bool)
- func (c *MongoLocalCache) Invalidate(name string)
- func (c *MongoLocalCache) InvalidateAll()
- func (c *MongoLocalCache) JoinWith(localDocs []bson.M, localKey, cacheName, cacheKey, asField string, many bool) []bson.M
- func (c *MongoLocalCache) Preload(ctx context.Context, name, collection string, filter, projection bson.D, ...) error
- func (c *MongoLocalCache) Stats() LocalCacheStats
- type MongoLookupStage
- type MongoQueryConstructor
- func (qb *MongoQueryConstructor) Build(ctx context.Context) (string, []interface{}, error)
- func (qb *MongoQueryConstructor) BuildFindPlan() (*MongoCompiledFindPlan, error)
- func (qb *MongoQueryConstructor) Count(fieldName ...string) QueryConstructor
- func (qb *MongoQueryConstructor) CountWith(builder *CountBuilder) QueryConstructor
- func (qb *MongoQueryConstructor) CrossJoin(table string, alias ...string) QueryConstructor
- func (qb *MongoQueryConstructor) CrossTableStrategy(strategy CrossTableStrategy) QueryConstructor
- func (qb *MongoQueryConstructor) CustomMode() QueryConstructor
- func (qb *MongoQueryConstructor) DeleteMany() *MongoQueryConstructor
- func (qb *MongoQueryConstructor) FromAlias(alias string) QueryConstructor
- func (qb *MongoQueryConstructor) GetNativeBuilder() interface{}
- func (qb *MongoQueryConstructor) InsertMany(documents []map[string]interface{}) *MongoQueryConstructor
- func (qb *MongoQueryConstructor) InsertOne(document map[string]interface{}) *MongoQueryConstructor
- func (qb *MongoQueryConstructor) Join(table, onClause string, alias ...string) QueryConstructor
- func (qb *MongoQueryConstructor) JoinWith(builder *JoinBuilder) QueryConstructor
- func (qb *MongoQueryConstructor) LeftJoin(table, onClause string, alias ...string) QueryConstructor
- func (qb *MongoQueryConstructor) Limit(count int) QueryConstructor
- func (qb *MongoQueryConstructor) Offset(count int) QueryConstructor
- func (qb *MongoQueryConstructor) OrderBy(field string, direction string) QueryConstructor
- func (qb *MongoQueryConstructor) Page(page int, pageSize int) QueryConstructor
- func (qb *MongoQueryConstructor) Paginate(builder *PaginationBuilder) QueryConstructor
- func (qb *MongoQueryConstructor) ReturnInsertedID() *MongoQueryConstructor
- func (qb *MongoQueryConstructor) ReturnWriteDetail() *MongoQueryConstructor
- func (qb *MongoQueryConstructor) RightJoin(table, onClause string, alias ...string) QueryConstructor
- func (qb *MongoQueryConstructor) Select(fields ...string) QueryConstructor
- func (qb *MongoQueryConstructor) SelectCount(ctx context.Context, repo *Repository) (int64, error)
- func (qb *MongoQueryConstructor) UpdateMany(setFields map[string]interface{}, upsert bool) *MongoQueryConstructor
- func (qb *MongoQueryConstructor) Upsert(ctx context.Context, repo *Repository, cs *Changeset, ...) (sql.Result, error)
- func (qb *MongoQueryConstructor) Where(condition Condition) QueryConstructor
- func (qb *MongoQueryConstructor) WhereAll(conditions ...Condition) QueryConstructor
- func (qb *MongoQueryConstructor) WhereAny(conditions ...Condition) QueryConstructor
- func (qb *MongoQueryConstructor) WhereWith(builder *WhereBuilder) QueryConstructor
- type MongoQueryConstructorProvider
- type MongoSortField
- type MongoTTLFeatures
- func (f *MongoTTLFeatures) DropTTLIndex(ctx context.Context, collection, indexName string) error
- func (f *MongoTTLFeatures) EnsureTTLIndex(ctx context.Context, collection, field string, expireAfter time.Duration) error
- func (f *MongoTTLFeatures) ExtendExpiry(ctx context.Context, collection string, filter bson.D, ttlField string, ...) error
- func (f *MongoTTLFeatures) InsertWithExpiry(ctx context.Context, collection string, doc bson.M, ttlField string, ...) error
- func (f *MongoTTLFeatures) ListTTLIndexes(ctx context.Context, collection string) ([]*TTLIndexInfo, error)
- type MongoVirtualView
- func (v *MongoVirtualView) Define(name, collection string, pipeline bson.A, ttl time.Duration)
- func (v *MongoVirtualView) DefinedViews() []string
- func (v *MongoVirtualView) Execute(ctx context.Context, name string) ([]bson.M, error)
- func (v *MongoVirtualView) InvalidateAll()
- func (v *MongoVirtualView) InvalidateView(name string)
- func (v *MongoVirtualView) IsCached(name string) bool
- func (v *MongoVirtualView) IsDefined(name string) bool
- func (v *MongoVirtualView) Refresh(ctx context.Context, name string) ([]bson.M, error)
- type MySQLAdapter
- func (a *MySQLAdapter) Begin(ctx context.Context, opts ...interface{}) (Tx, error)
- func (a *MySQLAdapter) Close() error
- func (a *MySQLAdapter) Connect(ctx context.Context, config *Config) error
- func (a *MySQLAdapter) Exec(ctx context.Context, query string, args ...interface{}) (sql.Result, error)
- func (a *MySQLAdapter) GetDatabaseFeatures() *DatabaseFeatures
- func (a *MySQLAdapter) GetGormDB() *gorm.DB
- func (a *MySQLAdapter) GetQueryBuilderProvider() QueryConstructorProvider
- func (a *MySQLAdapter) GetQueryFeatures() *QueryFeatures
- func (a *MySQLAdapter) GetRawConn() interface{}
- func (a *MySQLAdapter) ListScheduledTasks(ctx context.Context) ([]*ScheduledTaskStatus, error)
- func (a *MySQLAdapter) Ping(ctx context.Context) error
- func (a *MySQLAdapter) Query(ctx context.Context, query string, args ...interface{}) (*sql.Rows, error)
- func (a *MySQLAdapter) QueryRow(ctx context.Context, query string, args ...interface{}) *sql.Row
- func (a *MySQLAdapter) RegisterScheduledTask(ctx context.Context, task *ScheduledTaskConfig) error
- func (a *MySQLAdapter) UnregisterScheduledTask(ctx context.Context, taskName string) error
- type MySQLConnectionConfig
- type MySQLDialect
- type MySQLDynamicTableHook
- func (h *MySQLDynamicTableHook) CreateDynamicTable(ctx context.Context, configName string, params map[string]interface{}) (string, error)
- func (h *MySQLDynamicTableHook) GetDynamicTableConfig(ctx context.Context, configName string) (*DynamicTableConfig, error)
- func (h *MySQLDynamicTableHook) ListCreatedDynamicTables(ctx context.Context, configName string) ([]string, error)
- func (h *MySQLDynamicTableHook) ListDynamicTableConfigs(ctx context.Context) ([]*DynamicTableConfig, error)
- func (h *MySQLDynamicTableHook) RegisterDynamicTable(ctx context.Context, config *DynamicTableConfig) error
- func (h *MySQLDynamicTableHook) UnregisterDynamicTable(ctx context.Context, configName string) error
- type MySQLFactory
- type MySQLTx
- func (t *MySQLTx) Commit(ctx context.Context) error
- func (t *MySQLTx) Exec(ctx context.Context, query string, args ...interface{}) (sql.Result, error)
- func (t *MySQLTx) Query(ctx context.Context, query string, args ...interface{}) (*sql.Rows, error)
- func (t *MySQLTx) QueryRow(ctx context.Context, query string, args ...interface{}) *sql.Row
- func (t *MySQLTx) Rollback(ctx context.Context) error
- type Neo4jAdapter
- func (a *Neo4jAdapter) Begin(ctx context.Context, opts ...interface{}) (Tx, error)
- func (a *Neo4jAdapter) Close() error
- func (a *Neo4jAdapter) Connect(ctx context.Context, config *Config) error
- func (a *Neo4jAdapter) Exec(ctx context.Context, sql string, args ...interface{}) (sql.Result, error)
- func (a *Neo4jAdapter) ExecCypher(ctx context.Context, cypher string, params map[string]interface{}) (*CypherWriteSummary, error)
- func (a *Neo4jAdapter) ExecuteCustomFeature(ctx context.Context, feature string, input map[string]interface{}) (interface{}, error)
- func (a *Neo4jAdapter) GetDatabaseFeatures() *DatabaseFeatures
- func (a *Neo4jAdapter) GetQueryBuilderProvider() QueryConstructorProvider
- func (a *Neo4jAdapter) GetQueryFeatures() *QueryFeatures
- func (a *Neo4jAdapter) GetRawConn() interface{}
- func (a *Neo4jAdapter) HasCustomFeatureImplementation(feature string) bool
- func (a *Neo4jAdapter) InspectFullTextRuntime(ctx context.Context) (*FullTextRuntimeCapability, error)
- func (a *Neo4jAdapter) ListScheduledTasks(ctx context.Context) ([]*ScheduledTaskStatus, error)
- func (a *Neo4jAdapter) Ping(ctx context.Context) error
- func (a *Neo4jAdapter) Query(ctx context.Context, sql string, args ...interface{}) (*sql.Rows, error)
- func (a *Neo4jAdapter) QueryCypher(ctx context.Context, cypher string, params map[string]interface{}) ([]map[string]interface{}, error)
- func (a *Neo4jAdapter) QueryRow(ctx context.Context, sql string, args ...interface{}) *sql.Row
- func (a *Neo4jAdapter) RegisterScheduledTask(ctx context.Context, task *ScheduledTaskConfig) error
- func (a *Neo4jAdapter) UnregisterScheduledTask(ctx context.Context, taskName string) error
- type Neo4jConnectionConfig
- type Neo4jFactory
- type Neo4jQueryConstructor
- func (qb *Neo4jQueryConstructor) Build(ctx context.Context) (string, []interface{}, error)
- func (qb *Neo4jQueryConstructor) BuildIR(ctx context.Context) (*QueryIR, error)
- func (qb *Neo4jQueryConstructor) Count(fieldName ...string) QueryConstructor
- func (qb *Neo4jQueryConstructor) CountWith(builder *CountBuilder) QueryConstructor
- func (qb *Neo4jQueryConstructor) CrossJoin(table string, alias ...string) QueryConstructor
- func (qb *Neo4jQueryConstructor) CrossTableStrategy(strategy CrossTableStrategy) QueryConstructor
- func (qb *Neo4jQueryConstructor) CustomMode() QueryConstructor
- func (qb *Neo4jQueryConstructor) FromAlias(alias string) QueryConstructor
- func (qb *Neo4jQueryConstructor) GetNativeBuilder() interface{}
- func (qb *Neo4jQueryConstructor) Join(table, onClause string, alias ...string) QueryConstructor
- func (qb *Neo4jQueryConstructor) JoinWith(builder *JoinBuilder) QueryConstructor
- func (qb *Neo4jQueryConstructor) LeftJoin(table, onClause string, alias ...string) QueryConstructor
- func (qb *Neo4jQueryConstructor) Limit(count int) QueryConstructor
- func (qb *Neo4jQueryConstructor) Offset(count int) QueryConstructor
- func (qb *Neo4jQueryConstructor) OrderBy(field string, direction string) QueryConstructor
- func (qb *Neo4jQueryConstructor) Page(page int, pageSize int) QueryConstructor
- func (qb *Neo4jQueryConstructor) Paginate(builder *PaginationBuilder) QueryConstructor
- func (qb *Neo4jQueryConstructor) RightJoin(table, onClause string, alias ...string) QueryConstructor
- func (qb *Neo4jQueryConstructor) Select(fields ...string) QueryConstructor
- func (qb *Neo4jQueryConstructor) SelectCount(ctx context.Context, repo *Repository) (int64, error)
- func (qb *Neo4jQueryConstructor) Upsert(ctx context.Context, repo *Repository, cs *Changeset, ...) (sql.Result, error)
- func (qb *Neo4jQueryConstructor) Where(condition Condition) QueryConstructor
- func (qb *Neo4jQueryConstructor) WhereAll(conditions ...Condition) QueryConstructor
- func (qb *Neo4jQueryConstructor) WhereAny(conditions ...Condition) QueryConstructor
- func (qb *Neo4jQueryConstructor) WhereWith(builder *WhereBuilder) QueryConstructor
- type Neo4jQueryConstructorProvider
- type NotCondition
- type OrderBy
- type PagedQueryConstructorExecutionResult
- type PaginationBuilder
- type PaginationMode
- type PatternValidator
- type PhoneNumberValidator
- type PoolConfig
- type PostalCodeValidator
- type PostgreSQLAdapter
- func (a *PostgreSQLAdapter) Begin(ctx context.Context, opts ...interface{}) (Tx, error)
- func (a *PostgreSQLAdapter) Close() error
- func (a *PostgreSQLAdapter) Connect(ctx context.Context, config *Config) error
- func (a *PostgreSQLAdapter) Exec(ctx context.Context, query string, args ...interface{}) (sql.Result, error)
- func (a *PostgreSQLAdapter) GetDatabaseFeatures() *DatabaseFeatures
- func (a *PostgreSQLAdapter) GetGormDB() *gorm.DB
- func (a *PostgreSQLAdapter) GetQueryBuilderProvider() QueryConstructorProvider
- func (a *PostgreSQLAdapter) GetQueryFeatures() *QueryFeatures
- func (a *PostgreSQLAdapter) GetRawConn() interface{}
- func (a *PostgreSQLAdapter) InspectFullTextRuntime(ctx context.Context) (*FullTextRuntimeCapability, error)
- func (a *PostgreSQLAdapter) InspectJSONRuntime(ctx context.Context) (*JSONRuntimeCapability, error)
- func (a *PostgreSQLAdapter) ListScheduledTasks(ctx context.Context) ([]*ScheduledTaskStatus, error)
- func (a *PostgreSQLAdapter) Ping(ctx context.Context) error
- func (a *PostgreSQLAdapter) PostgresJSONType() string
- func (a *PostgreSQLAdapter) Query(ctx context.Context, query string, args ...interface{}) (*sql.Rows, error)
- func (a *PostgreSQLAdapter) QueryRow(ctx context.Context, query string, args ...interface{}) *sql.Row
- func (a *PostgreSQLAdapter) RegisterScheduledTask(ctx context.Context, task *ScheduledTaskConfig) error
- func (a *PostgreSQLAdapter) UnregisterScheduledTask(ctx context.Context, taskName string) error
- type PostgreSQLDialect
- type PostgreSQLDynamicTableHook
- func (h *PostgreSQLDynamicTableHook) CreateDynamicTable(ctx context.Context, configName string, params map[string]interface{}) (string, error)
- func (h *PostgreSQLDynamicTableHook) GetDynamicTableConfig(ctx context.Context, configName string) (*DynamicTableConfig, error)
- func (h *PostgreSQLDynamicTableHook) ListCreatedDynamicTables(ctx context.Context, configName string) ([]string, error)
- func (h *PostgreSQLDynamicTableHook) ListDynamicTableConfigs(ctx context.Context) ([]*DynamicTableConfig, error)
- func (h *PostgreSQLDynamicTableHook) RegisterDynamicTable(ctx context.Context, config *DynamicTableConfig) error
- func (h *PostgreSQLDynamicTableHook) UnregisterDynamicTable(ctx context.Context, configName string) error
- type PostgreSQLFactory
- type PostgreSQLFeatures
- func (f *PostgreSQLFeatures) CompositeType(typeName string) *CompositeTypeBuilder
- func (f *PostgreSQLFeatures) DomainType(typeName string) *DomainTypeBuilder
- func (f *PostgreSQLFeatures) EnumType(typeName string) *EnumTypeBuilder
- func (f *PostgreSQLFeatures) MaterializedView(viewName string) *PostgreSQLViewBuilder
- func (f *PostgreSQLFeatures) View(viewName string) *PostgreSQLViewBuilder
- type PostgreSQLTx
- func (t *PostgreSQLTx) Commit(ctx context.Context) error
- func (t *PostgreSQLTx) Exec(ctx context.Context, query string, args ...interface{}) (sql.Result, error)
- func (t *PostgreSQLTx) Query(ctx context.Context, query string, args ...interface{}) (*sql.Rows, error)
- func (t *PostgreSQLTx) QueryRow(ctx context.Context, query string, args ...interface{}) *sql.Row
- func (t *PostgreSQLTx) Rollback(ctx context.Context) error
- type PostgreSQLViewBuilder
- func (b *PostgreSQLViewBuilder) Args(args ...interface{}) *PostgreSQLViewBuilder
- func (b *PostgreSQLViewBuilder) As(selectSQL string) *PostgreSQLViewBuilder
- func (b *PostgreSQLViewBuilder) BuildCreate() (string, error)
- func (b *PostgreSQLViewBuilder) BuildDrop() (string, error)
- func (b *PostgreSQLViewBuilder) BuildRefresh() (string, error)
- func (b *PostgreSQLViewBuilder) Create(ctx context.Context) error
- func (b *PostgreSQLViewBuilder) CreateOnly() *PostgreSQLViewBuilder
- func (b *PostgreSQLViewBuilder) CreateOrReplace() *PostgreSQLViewBuilder
- func (b *PostgreSQLViewBuilder) Drop(ctx context.Context) error
- func (b *PostgreSQLViewBuilder) DropIfExists() *PostgreSQLViewBuilder
- func (b *PostgreSQLViewBuilder) DropStrict() *PostgreSQLViewBuilder
- func (b *PostgreSQLViewBuilder) Refresh(ctx context.Context) error
- func (b *PostgreSQLViewBuilder) RefreshConcurrently() *PostgreSQLViewBuilder
- func (b *PostgreSQLViewBuilder) Schema(schema string) *PostgreSQLViewBuilder
- func (b *PostgreSQLViewBuilder) WithCheckOption() *PostgreSQLViewBuilder
- func (b *PostgreSQLViewBuilder) WithNoData() *PostgreSQLViewBuilder
- type PostgresConnectionConfig
- type PresetRegistry
- type QueryBuilder
- func (qb *QueryBuilder) Delete(whereClause string, whereArgs ...interface{}) (sql.Result, error)
- func (qb *QueryBuilder) DeleteByID(id interface{}) (sql.Result, error)
- func (qb *QueryBuilder) Insert(cs *Changeset) (sql.Result, error)
- func (qb *QueryBuilder) Query() *QueryChain
- func (qb *QueryBuilder) Select(columns string, whereClause string, whereArgs ...interface{}) (*sql.Rows, error)
- func (qb *QueryBuilder) SelectAll() (*sql.Rows, error)
- func (qb *QueryBuilder) SelectByID(id interface{}) (*sql.Row, error)
- func (qb *QueryBuilder) SelectCount(whereClause string, whereArgs ...interface{}) (int64, error)
- func (qb *QueryBuilder) SelectOne(whereClause string, whereArgs ...interface{}) (*sql.Row, error)
- func (qb *QueryBuilder) SoftDelete(whereClause string, whereArgs ...interface{}) (sql.Result, error)
- func (qb *QueryBuilder) SoftDeleteByID(id interface{}) (sql.Result, error)
- func (qb *QueryBuilder) Transaction(fn func(*QueryBuilder) error) error
- func (qb *QueryBuilder) Update(cs *Changeset, whereClause string, whereArgs ...interface{}) (sql.Result, error)
- func (qb *QueryBuilder) UpdateByID(id interface{}, cs *Changeset) (sql.Result, error)
- func (qb *QueryBuilder) WithContext(ctx context.Context) *QueryBuilder
- type QueryBuilderCapabilities
- type QueryCacheConfig
- type QueryChain
- func (qc *QueryChain) All() (*sql.Rows, error)
- func (qc *QueryChain) Count() (int64, error)
- func (qc *QueryChain) First() (*sql.Row, error)
- func (qc *QueryChain) Limit(limit int) *QueryChain
- func (qc *QueryChain) Offset(offset int) *QueryChain
- func (qc *QueryChain) OrderBy(orderBy string) *QueryChain
- func (qc *QueryChain) Where(condition string, args ...interface{}) *QueryChain
- type QueryCompileHints
- type QueryCompiler
- type QueryConstructor
- type QueryConstructorAutoExecutionResult
- type QueryConstructorExecSummary
- type QueryConstructorExecutionResult
- type QueryConstructorProvider
- type QueryFallbackStrategy
- type QueryFeature
- type QueryFeatureCategory
- type QueryFeatures
- func GetQueryFeatures(dbType string) *QueryFeatures
- func NewMongoQueryFeatures() *QueryFeatures
- func NewMySQLQueryFeatures() *QueryFeatures
- func NewNeo4jQueryFeatures() *QueryFeatures
- func NewPostgreSQLQueryFeatures() *QueryFeatures
- func NewSQLServerQueryFeatures() *QueryFeatures
- func NewSQLiteQueryFeatures() *QueryFeatures
- func (qf *QueryFeatures) GetAlternativeSyntax(feature string) string
- func (qf *QueryFeatures) GetFallbackStrategy(feature string) QueryFallbackStrategy
- func (qf *QueryFeatures) GetFeatureNote(feature string) string
- func (qf *QueryFeatures) GetFeatureSupport(feature string) FeatureSupport
- func (qf *QueryFeatures) HasQueryFeature(feature string) bool
- func (qf *QueryFeatures) SupportsFeatureWithVersion(feature, version string) bool
- type QueryIR
- type QueryJoinIR
- type QueryJoinRelationIR
- type QueryOrderIR
- type QueryRelationThroughIR
- type QuerySourceIR
- type QueryViewRouteIR
- type RangeValidator
- type RawSQLMigration
- func (m *RawSQLMigration) AddDownSQL(sql string) *RawSQLMigration
- func (m *RawSQLMigration) AddUpSQL(sql string) *RawSQLMigration
- func (m *RawSQLMigration) Down(ctx context.Context, repo *Repository) error
- func (m *RawSQLMigration) ForAdapter(adapter string) *RawSQLMigration
- func (m *RawSQLMigration) Up(ctx context.Context, repo *Repository) error
- type RecursiveQueryBuilder
- func (b *RecursiveQueryBuilder) Anchor(sql string) *RecursiveQueryBuilder
- func (b *RecursiveQueryBuilder) Build() (string, error)
- func (b *RecursiveQueryBuilder) Columns(cols ...string) *RecursiveQueryBuilder
- func (b *RecursiveQueryBuilder) Execute(ctx context.Context) (*sql.Rows, error)
- func (b *RecursiveQueryBuilder) MaxRecursion(n int) *RecursiveQueryBuilder
- func (b *RecursiveQueryBuilder) OrderBy(expr string) *RecursiveQueryBuilder
- func (b *RecursiveQueryBuilder) Recursive(sql string) *RecursiveQueryBuilder
- func (b *RecursiveQueryBuilder) ScanRows(ctx context.Context) ([]map[string]interface{}, error)
- func (b *RecursiveQueryBuilder) Select(selectExpr string) *RecursiveQueryBuilder
- func (b *RecursiveQueryBuilder) SelectAll() *RecursiveQueryBuilder
- func (b *RecursiveQueryBuilder) Where(condition string, args ...interface{}) *RecursiveQueryBuilder
- type RegexValidator
- type RelationThrough
- type RelationType
- type RelationalSchema
- type Relationship
- type RelationshipManager
- type RelationshipStrategy
- type RelationshipSupport
- type RelationshipValidator
- type Repository
- func InitDB(configPath string) (*Repository, error)
- func InitDBFromAdapterRegistry(configPath, adapterName string) (*Repository, error)
- func InitDBFromEnv() (*Repository, error)
- func InitDBWithDefaults(adapterType string) (*Repository, error)
- func NewRepository(config *Config) (*Repository, error)
- func NewRepositoryFromAdapterConfig(name string) (*Repository, error)
- func (r *Repository) AnalyzeFuzzySearch(ctx context.Context, field, keyword, version string) (*FuzzySearchPlan, error)
- func (r *Repository) Begin(ctx context.Context, opts ...interface{}) (Tx, error)
- func (r *Repository) BuildAndCacheQuery(ctx context.Context, cacheKey string, constructor QueryConstructor) (query string, args []interface{}, cacheHit bool, err error)
- func (r *Repository) BuildAndCacheQueryTemplate(ctx context.Context, cacheKey string, constructor QueryConstructor) (query string, argCount int, cacheHit bool, err error)
- func (r *Repository) BuildFuzzyCondition(field, keyword, version string) Condition
- func (r *Repository) BuildFuzzyConditionWithContext(ctx context.Context, field, keyword, version string) (Condition, error)
- func (r *Repository) ClearCompiledQueryCache()
- func (r *Repository) Close() error
- func (r *Repository) Connect(ctx context.Context) error
- func (r *Repository) DecideFeatureExecution(feature, version string) (*FeatureExecutionDecision, error)
- func (r *Repository) Exec(ctx context.Context, sql string, args ...interface{}) (sql.Result, error)
- func (r *Repository) ExecCypher(ctx context.Context, cypher string, params map[string]interface{}) (*CypherWriteSummary, error)
- func (r *Repository) ExecWithCachedTemplate(ctx context.Context, cacheKey string, args ...interface{}) (sql.Result, error)
- func (r *Repository) ExecuteFeature(ctx context.Context, feature, version string, input map[string]interface{}) (interface{}, error)
- func (r *Repository) ExecuteQueryConstructor(ctx context.Context, constructor QueryConstructor) (*QueryConstructorExecutionResult, error)
- func (r *Repository) ExecuteQueryConstructorAuto(ctx context.Context, constructor QueryConstructor) (*QueryConstructorAutoExecutionResult, error)
- func (r *Repository) ExecuteQueryConstructorPaged(ctx context.Context, constructor QueryConstructor, page int, pageSize int) (*PagedQueryConstructorExecutionResult, error)
- func (r *Repository) ExecuteQueryConstructorPagedWithCache(ctx context.Context, cacheKeyPrefix string, constructor QueryConstructor, ...) (*PagedQueryConstructorExecutionResult, error)
- func (r *Repository) ExecuteQueryConstructorPaginated(ctx context.Context, constructor QueryConstructor, builder *PaginationBuilder) (*PagedQueryConstructorExecutionResult, error)
- func (r *Repository) ExecuteQueryConstructorPaginatedWithCache(ctx context.Context, cacheKeyPrefix string, constructor QueryConstructor, ...) (*PagedQueryConstructorExecutionResult, error)
- func (r *Repository) ExecuteQueryConstructorWithCache(ctx context.Context, cacheKey string, constructor QueryConstructor) (*QueryConstructorExecutionResult, bool, error)
- func (r *Repository) GetAdapter() Adapter
- func (r *Repository) GetCompiledQuery(cacheKey string) (*CompiledQuery, bool)
- func (r *Repository) GetCompiledQueryCacheStats() CompiledQueryCacheStats
- func (r *Repository) GetCompiledQueryTemplate(cacheKey string) (*CompiledQueryTemplate, bool)
- func (r *Repository) GetGormDB() *gorm.DB
- func (r *Repository) GetQueryBuilderCapabilities() (*QueryBuilderCapabilities, error)
- func (r *Repository) GetStartupCapabilityReport() *StartupCapabilityReport
- func (r *Repository) InvalidateCompiledQuery(cacheKey string)
- func (r *Repository) ListScheduledTasks(ctx context.Context) ([]*ScheduledTaskStatus, error)
- func (r *Repository) NewChangesetExecutor(ctx context.Context, schema Schema) (*ChangesetExecutor, error)
- func (r *Repository) NewQueryConstructor(schema Schema) (QueryConstructor, error)
- func (r *Repository) Ping(ctx context.Context) error
- func (r *Repository) Query(ctx context.Context, sql string, args ...interface{}) (*sql.Rows, error)
- func (r *Repository) QueryCypher(ctx context.Context, cypher string, params map[string]interface{}) ([]map[string]interface{}, error)
- func (r *Repository) QueryRow(ctx context.Context, sql string, args ...interface{}) *sql.Row
- func (r *Repository) QueryRowWithCachedTemplate(ctx context.Context, cacheKey string, args ...interface{}) (*sql.Row, error)
- func (r *Repository) QueryStruct(ctx context.Context, dest interface{}, sql string, args ...interface{}) error
- func (r *Repository) QueryStructs(ctx context.Context, dest interface{}, sql string, args ...interface{}) error
- func (r *Repository) QueryWithCachedTemplate(ctx context.Context, cacheKey string, args ...interface{}) (*sql.Rows, error)
- func (r *Repository) RegisterScheduledTask(ctx context.Context, task *ScheduledTaskConfig) error
- func (r *Repository) RunStartupCapabilityCheck(ctx context.Context, cfg *StartupCapabilityConfig) (*StartupCapabilityReport, error)
- func (r *Repository) StoreCompiledQuery(cacheKey string, query string, args ...interface{}) error
- func (r *Repository) StoreCompiledQueryTemplate(cacheKey string, query string, argCount int) error
- func (r *Repository) UnregisterScheduledTask(ctx context.Context, taskName string) error
- func (r *Repository) WithChangeset(ctx context.Context, schema Schema, fn func(*ChangesetExecutor) error) error
- type RequiredValidator
- type SQLDialect
- type SQLQueryConstructor
- func (qb *SQLQueryConstructor) Build(ctx context.Context) (string, []interface{}, error)
- func (qb *SQLQueryConstructor) BuildIR(ctx context.Context) (*QueryIR, error)
- func (qb *SQLQueryConstructor) Count(fieldName ...string) QueryConstructor
- func (qb *SQLQueryConstructor) CountWith(builder *CountBuilder) QueryConstructor
- func (qb *SQLQueryConstructor) CrossJoin(table string, alias ...string) QueryConstructor
- func (qb *SQLQueryConstructor) CrossTableStrategy(strategy CrossTableStrategy) QueryConstructor
- func (qb *SQLQueryConstructor) CursorPage(field string, direction string, cursorValue interface{}, ...) *SQLQueryConstructor
- func (qb *SQLQueryConstructor) CustomMode() QueryConstructor
- func (qb *SQLQueryConstructor) FromAlias(alias string) QueryConstructor
- func (qb *SQLQueryConstructor) GetNativeBuilder() interface{}
- func (qb *SQLQueryConstructor) Join(table, onClause string, alias ...string) QueryConstructor
- func (qb *SQLQueryConstructor) JoinWith(builder *JoinBuilder) QueryConstructor
- func (qb *SQLQueryConstructor) LeftJoin(table, onClause string, alias ...string) QueryConstructor
- func (qb *SQLQueryConstructor) Limit(count int) QueryConstructor
- func (qb *SQLQueryConstructor) Offset(count int) QueryConstructor
- func (qb *SQLQueryConstructor) OrderBy(field string, direction string) QueryConstructor
- func (qb *SQLQueryConstructor) Page(page int, pageSize int) QueryConstructor
- func (qb *SQLQueryConstructor) Paginate(builder *PaginationBuilder) QueryConstructor
- func (qb *SQLQueryConstructor) RightJoin(table, onClause string, alias ...string) QueryConstructor
- func (qb *SQLQueryConstructor) Select(fields ...string) QueryConstructor
- func (qb *SQLQueryConstructor) SelectCount(ctx context.Context, repo *Repository) (int64, error)
- func (qb *SQLQueryConstructor) Upsert(ctx context.Context, repo *Repository, cs *Changeset, ...) (sql.Result, error)
- func (qb *SQLQueryConstructor) Where(condition Condition) QueryConstructor
- func (qb *SQLQueryConstructor) WhereAll(conditions ...Condition) QueryConstructor
- func (qb *SQLQueryConstructor) WhereAny(conditions ...Condition) QueryConstructor
- func (qb *SQLQueryConstructor) WhereWith(builder *WhereBuilder) QueryConstructor
- type SQLServerAdapter
- func (a *SQLServerAdapter) Begin(ctx context.Context, opts ...interface{}) (Tx, error)
- func (a *SQLServerAdapter) Close() error
- func (a *SQLServerAdapter) Connect(ctx context.Context, config *Config) error
- func (a *SQLServerAdapter) Exec(ctx context.Context, query string, args ...interface{}) (sql.Result, error)
- func (a *SQLServerAdapter) GetDatabaseFeatures() *DatabaseFeatures
- func (a *SQLServerAdapter) GetGormDB() *gorm.DB
- func (a *SQLServerAdapter) GetQueryBuilderProvider() QueryConstructorProvider
- func (a *SQLServerAdapter) GetQueryFeatures() *QueryFeatures
- func (a *SQLServerAdapter) GetRawConn() interface{}
- func (a *SQLServerAdapter) InspectFullTextRuntime(ctx context.Context) (*FullTextRuntimeCapability, error)
- func (a *SQLServerAdapter) InspectJSONRuntime(ctx context.Context) (*JSONRuntimeCapability, error)
- func (a *SQLServerAdapter) ListScheduledTasks(ctx context.Context) ([]*ScheduledTaskStatus, error)
- func (a *SQLServerAdapter) Ping(ctx context.Context) error
- func (a *SQLServerAdapter) Query(ctx context.Context, query string, args ...interface{}) (*sql.Rows, error)
- func (a *SQLServerAdapter) QueryRow(ctx context.Context, query string, args ...interface{}) *sql.Row
- func (a *SQLServerAdapter) RegisterScheduledTask(ctx context.Context, task *ScheduledTaskConfig) error
- func (a *SQLServerAdapter) UnregisterScheduledTask(ctx context.Context, taskName string) error
- type SQLServerConnectionConfig
- type SQLServerDialect
- func (d *SQLServerDialect) GenerateLimitOffset(limit *int, offset *int) string
- func (d *SQLServerDialect) GetPlaceholder(index int) string
- func (d *SQLServerDialect) Name() string
- func (d *SQLServerDialect) QuoteIdentifier(name string) string
- func (d *SQLServerDialect) QuoteValue(value interface{}) string
- func (d *SQLServerDialect) SQLManyToManyStrategy() string
- func (d *SQLServerDialect) SQLRecursiveCTEDepth() int
- func (d *SQLServerDialect) SQLRecursiveCTEMaxRecursion() int
- func (d *SQLServerDialect) TranslateCondition(condition Condition, argIndex *int) (string, []interface{}, error)
- type SQLServerDynamicTableHook
- func (h *SQLServerDynamicTableHook) CreateDynamicTable(ctx context.Context, configName string, params map[string]interface{}) (string, error)
- func (h *SQLServerDynamicTableHook) GetDynamicTableConfig(ctx context.Context, configName string) (*DynamicTableConfig, error)
- func (h *SQLServerDynamicTableHook) ListCreatedDynamicTables(ctx context.Context, configName string) ([]string, error)
- func (h *SQLServerDynamicTableHook) ListDynamicTableConfigs(ctx context.Context) ([]*DynamicTableConfig, error)
- func (h *SQLServerDynamicTableHook) RegisterDynamicTable(ctx context.Context, config *DynamicTableConfig) error
- func (h *SQLServerDynamicTableHook) UnregisterDynamicTable(ctx context.Context, configName string) error
- type SQLServerFactory
- type SQLServerFeatures
- func (f *SQLServerFeatures) MergeInto(targetTable string) *SQLServerMergeBuilder
- func (f *SQLServerFeatures) RecursiveQuery(cteName string) *RecursiveQueryBuilder
- func (f *SQLServerFeatures) TempTable(name string) *SQLServerTempTableBuilder
- func (f *SQLServerFeatures) View(name string) *SQLServerViewBuilder
- type SQLServerMergeBuilder
- func (b *SQLServerMergeBuilder) Args(args ...interface{}) *SQLServerMergeBuilder
- func (b *SQLServerMergeBuilder) Build() (string, error)
- func (b *SQLServerMergeBuilder) DisableHoldLock() *SQLServerMergeBuilder
- func (b *SQLServerMergeBuilder) Execute(ctx context.Context) (sql.Result, error)
- func (b *SQLServerMergeBuilder) On(condition string) *SQLServerMergeBuilder
- func (b *SQLServerMergeBuilder) Output(outputExpr string) *SQLServerMergeBuilder
- func (b *SQLServerMergeBuilder) Query(ctx context.Context) (*sql.Rows, error)
- func (b *SQLServerMergeBuilder) SourceAlias(alias string) *SQLServerMergeBuilder
- func (b *SQLServerMergeBuilder) TargetAlias(alias string) *SQLServerMergeBuilder
- func (b *SQLServerMergeBuilder) Using(sourceSQL string) *SQLServerMergeBuilder
- func (b *SQLServerMergeBuilder) WhenMatchedUpdate(setClause string) *SQLServerMergeBuilder
- func (b *SQLServerMergeBuilder) WhenNotMatchedBySourceDelete() *SQLServerMergeBuilder
- func (b *SQLServerMergeBuilder) WhenNotMatchedInsert(columns []string, valuesExpr string) *SQLServerMergeBuilder
- type SQLServerTempTableBuilder
- func (b *SQLServerTempTableBuilder) Args(args ...interface{}) *SQLServerTempTableBuilder
- func (b *SQLServerTempTableBuilder) AsSelect(selectSQL string) *SQLServerTempTableBuilder
- func (b *SQLServerTempTableBuilder) BuildCreate() (string, error)
- func (b *SQLServerTempTableBuilder) BuildDrop() string
- func (b *SQLServerTempTableBuilder) Column(name, dataType string, nullable bool) *SQLServerTempTableBuilder
- func (b *SQLServerTempTableBuilder) Drop(ctx context.Context) error
- func (b *SQLServerTempTableBuilder) DropIfExists() *SQLServerTempTableBuilder
- func (b *SQLServerTempTableBuilder) ExecuteCreate(ctx context.Context) error
- func (b *SQLServerTempTableBuilder) Global() *SQLServerTempTableBuilder
- func (b *SQLServerTempTableBuilder) KeepIfExists() *SQLServerTempTableBuilder
- func (b *SQLServerTempTableBuilder) Local() *SQLServerTempTableBuilder
- func (b *SQLServerTempTableBuilder) TempTableName() string
- type SQLServerTempTableColumn
- type SQLServerTx
- func (t *SQLServerTx) Commit(ctx context.Context) error
- func (t *SQLServerTx) Exec(ctx context.Context, query string, args ...interface{}) (sql.Result, error)
- func (t *SQLServerTx) Query(ctx context.Context, query string, args ...interface{}) (*sql.Rows, error)
- func (t *SQLServerTx) QueryRow(ctx context.Context, query string, args ...interface{}) *sql.Row
- func (t *SQLServerTx) Rollback(ctx context.Context) error
- type SQLServerViewBuilder
- func (b *SQLServerViewBuilder) Args(args ...interface{}) *SQLServerViewBuilder
- func (b *SQLServerViewBuilder) As(selectSQL string) *SQLServerViewBuilder
- func (b *SQLServerViewBuilder) BuildCreate() (string, error)
- func (b *SQLServerViewBuilder) BuildDrop() (string, error)
- func (b *SQLServerViewBuilder) CreateOnly() *SQLServerViewBuilder
- func (b *SQLServerViewBuilder) CreateOrAlter() *SQLServerViewBuilder
- func (b *SQLServerViewBuilder) Drop(ctx context.Context) error
- func (b *SQLServerViewBuilder) DropIfExists() *SQLServerViewBuilder
- func (b *SQLServerViewBuilder) DropStrict() *SQLServerViewBuilder
- func (b *SQLServerViewBuilder) ExecuteCreate(ctx context.Context) error
- func (b *SQLServerViewBuilder) WithCheckOption() *SQLServerViewBuilder
- type SQLiteAdapter
- func (a *SQLiteAdapter) Begin(ctx context.Context, opts ...interface{}) (Tx, error)
- func (a *SQLiteAdapter) Close() error
- func (a *SQLiteAdapter) Connect(ctx context.Context, config *Config) error
- func (a *SQLiteAdapter) Exec(ctx context.Context, query string, args ...interface{}) (sql.Result, error)
- func (a *SQLiteAdapter) GetDatabaseFeatures() *DatabaseFeatures
- func (a *SQLiteAdapter) GetGormDB() *gorm.DB
- func (a *SQLiteAdapter) GetQueryBuilderProvider() QueryConstructorProvider
- func (a *SQLiteAdapter) GetQueryFeatures() *QueryFeatures
- func (a *SQLiteAdapter) GetRawConn() interface{}
- func (a *SQLiteAdapter) InspectFullTextRuntime(ctx context.Context) (*FullTextRuntimeCapability, error)
- func (a *SQLiteAdapter) ListScheduledTasks(ctx context.Context) ([]*ScheduledTaskStatus, error)
- func (a *SQLiteAdapter) Ping(ctx context.Context) error
- func (a *SQLiteAdapter) Query(ctx context.Context, query string, args ...interface{}) (*sql.Rows, error)
- func (a *SQLiteAdapter) QueryRow(ctx context.Context, query string, args ...interface{}) *sql.Row
- func (a *SQLiteAdapter) RegisterCommonSQLiteFunctions() error
- func (a *SQLiteAdapter) RegisterSQLiteAggregateFunction(fn *SQLiteAggregateFunction) error
- func (a *SQLiteAdapter) RegisterSQLiteFunction(fn *SQLiteCustomFunction) error
- func (a *SQLiteAdapter) RegisterScheduledTask(ctx context.Context, task *ScheduledTaskConfig) error
- func (a *SQLiteAdapter) UnregisterScheduledTask(ctx context.Context, taskName string) error
- type SQLiteAggregateFunction
- type SQLiteConnectionConfig
- type SQLiteCustomFunction
- type SQLiteDialect
- type SQLiteDynamicTableHook
- func (h *SQLiteDynamicTableHook) CreateDynamicTable(ctx context.Context, configName string, params map[string]interface{}) (string, error)
- func (h *SQLiteDynamicTableHook) GetDynamicTableConfig(ctx context.Context, configName string) (*DynamicTableConfig, error)
- func (h *SQLiteDynamicTableHook) ListCreatedDynamicTables(ctx context.Context, configName string) ([]string, error)
- func (h *SQLiteDynamicTableHook) ListDynamicTableConfigs(ctx context.Context) ([]*DynamicTableConfig, error)
- func (h *SQLiteDynamicTableHook) RegisterDynamicTable(ctx context.Context, config *DynamicTableConfig) error
- func (h *SQLiteDynamicTableHook) UnregisterDynamicTable(ctx context.Context, configName string) error
- type SQLiteTx
- func (t *SQLiteTx) Commit(ctx context.Context) error
- func (t *SQLiteTx) Exec(ctx context.Context, query string, args ...interface{}) (sql.Result, error)
- func (t *SQLiteTx) Query(ctx context.Context, query string, args ...interface{}) (*sql.Rows, error)
- func (t *SQLiteTx) QueryRow(ctx context.Context, query string, args ...interface{}) *sql.Row
- func (t *SQLiteTx) Rollback(ctx context.Context) error
- type ScheduledTaskConfig
- type ScheduledTaskEventListener
- type ScheduledTaskExecutor
- type ScheduledTaskStatus
- type ScheduledTaskType
- type Schema
- type SchemaMigration
- type SchemaRegistry
- type SchemaRelation
- type SchemaRelationBuilder
- func (b *SchemaRelationBuilder) Named(name string) *SchemaRelationBuilder
- func (b *SchemaRelationBuilder) Optional() *SchemaRelationBuilder
- func (b *SchemaRelationBuilder) Over(foreignKey, originKey string) *SchemaRelationBuilder
- func (b *SchemaRelationBuilder) Relation() *SchemaRelation
- func (b *SchemaRelationBuilder) Required() *SchemaRelationBuilder
- func (b *SchemaRelationBuilder) Reversible(enabled bool) *SchemaRelationBuilder
- func (b *SchemaRelationBuilder) Through(through Schema, sourceKey, targetKey string) *SchemaRelationBuilder
- type SchemaRelationshipBuilder
- func (b *SchemaRelationshipBuilder) BelongsTo(name string, toSchema Schema, foreignKey, primaryKey string) *SchemaRelationshipBuilder
- func (b *SchemaRelationshipBuilder) GetRelationships() []*Relationship
- func (b *SchemaRelationshipBuilder) HasAndBelongsToMany(name string, toSchema Schema, joinTableName string, fromForeignKey string, ...) *SchemaRelationshipBuilder
- func (b *SchemaRelationshipBuilder) HasMany(name string, toSchema Schema, foreignKey, primaryKey string) *SchemaRelationshipBuilder
- func (b *SchemaRelationshipBuilder) HasOne(name string, toSchema Schema, foreignKey, primaryKey string) *SchemaRelationshipBuilder
- type ShardingRiskLevel
- type ShardingStabilityReport
- type ShardingStabilityTool
- type ShardingTemplateKind
- type SimpleCondition
- type StartupCapabilityCheck
- type StartupCapabilityConfig
- type StartupCapabilityReport
- type TTLIndexInfo
- type TableConstraint
- type Transformer
- type TrimTransformer
- type Tx
- type TypeConversionError
- type URLValidator
- type UniqueValidator
- type ValidationConfig
- type ValidationError
- type ValidationMessages
- type ValidationProfile
- type Validator
- type ViewBuilder
- func (b *ViewBuilder) Args(args ...interface{}) *ViewBuilder
- func (b *ViewBuilder) As(selectSQL string) *ViewBuilder
- func (b *ViewBuilder) BuildCreate() (string, error)
- func (b *ViewBuilder) BuildDrop() (string, error)
- func (b *ViewBuilder) CreateOnly() *ViewBuilder
- func (b *ViewBuilder) CreateOrAlter() *ViewBuilder
- func (b *ViewBuilder) Drop(ctx context.Context) error
- func (b *ViewBuilder) DropIfExists() *ViewBuilder
- func (b *ViewBuilder) DropStrict() *ViewBuilder
- func (b *ViewBuilder) ExecuteCreate(ctx context.Context) error
- func (b *ViewBuilder) Materialized() *ViewBuilder
- func (b *ViewBuilder) WithCheckOption() *ViewBuilder
- type ViewFeatures
- type ViewHint
- type WhereBuilder
Constants ¶
const ( // StartupCapabilityJSONRuntime JSON 运行时能力。 StartupCapabilityJSONRuntime = "json_runtime" // StartupCapabilityFullTextRuntime 全文运行时能力。 StartupCapabilityFullTextRuntime = "full_text_runtime" )
const DefaultCompiledQueryCacheDefaultTTLSeconds = 0
const DefaultCompiledQueryCacheEnableMetrics = true
const DefaultCompiledQueryCacheMaxEntries = 256
Variables ¶
var ( PostgreSQLSupport = &RelationshipSupport{ OneToOne: true, OneToMany: true, ManyToMany: true, SupportsForeignKey: true, SupportsJoin: true, SupportsNested: true, Strategy: StrategyNative, } SQLServerSupport = &RelationshipSupport{ OneToOne: true, OneToMany: true, ManyToMany: true, SupportsForeignKey: true, SupportsJoin: true, SupportsNested: true, Strategy: StrategyNative, } MySQLSupport = &RelationshipSupport{ OneToOne: true, OneToMany: true, ManyToMany: false, SupportsForeignKey: true, SupportsJoin: true, SupportsNested: false, Strategy: StrategyJoinTable, } SQLiteSupport = &RelationshipSupport{ OneToOne: true, OneToMany: true, ManyToMany: false, SupportsForeignKey: false, SupportsJoin: true, SupportsNested: false, Strategy: StrategyJoinTable, } MongoDBSupport = &RelationshipSupport{ OneToOne: true, OneToMany: true, ManyToMany: true, SupportsForeignKey: false, SupportsJoin: false, SupportsNested: true, Strategy: StrategyApplication, } GraphDatabaseSupport = &RelationshipSupport{ OneToOne: true, OneToMany: true, ManyToMany: true, SupportsForeignKey: false, SupportsJoin: false, SupportsNested: true, Strategy: StrategyNative, } NoRelationshipSupport = &RelationshipSupport{ OneToOne: false, OneToMany: false, ManyToMany: false, SupportsForeignKey: false, SupportsJoin: false, SupportsNested: false, Strategy: StrategyNotSupported, } )
预定义的常见数据库支持情况
var GlobalCrossTableViewRegistry = NewCrossTableViewRegistry()
GlobalCrossTableViewRegistry 全局视图注册表,app 启动时调用 RegisterSchemasIntoGlobal 填充。
var Presets = PresetRegistry{ Date: DatePresetRegistry{}, }
Presets 全局预置入口。
Functions ¶
func CompareQueryFeatures ¶
func CompareQueryFeatures(qf1, qf2 *QueryFeatures) map[string]interface{}
CompareQueryFeatures 对比两个数据库的查询特性
func ConfigureValidationLocales ¶ added in v1.0.0
ConfigureValidationLocales 配置默认 locale 与启用的 locale 集合。 enabledLocales 为空时默认启用所有已注册 profile。
func ConvertValue ¶
ConvertValue 值类型转换
func DaysLaterUTC ¶ added in v1.0.0
DaysLaterUTC 基于当前 UTC 日期返回 N 天后日期(00:00:00 UTC)。
func DefaultSQLiteJSONFallbackFunctions ¶ added in v1.0.0
func DefaultSQLiteJSONFallbackFunctions() map[string]interface{}
DefaultSQLiteJSONFallbackFunctions 返回 SQLite JSON 降级函数集合。 当目标环境未启用 JSON1 扩展时,可使用这些函数作为兼容方案。
func EndOfCurrentMonth ¶ added in v1.0.0
EndOfCurrentMonth 返回当前月月末(本地时区,23:59:59)。
func EndOfCurrentQuarter ¶ added in v1.0.0
EndOfCurrentQuarter 返回当前季度结束时间(本地时区,23:59:59)。
func ErrCursorPrimaryValueRequired ¶ added in v1.1.1
func ExampleMySQLDynamicTable ¶
func ExampleMySQLDynamicTable()
ExampleMySQLDynamicTable MySQL 动态建表示例 场景:在电商系统中,为每个店铺创建独立的订单表来分离数据
func ExamplePostgreSQLDynamicTable ¶
func ExamplePostgreSQLDynamicTable()
ExamplePostgreSQLDynamicTable PostgreSQL 动态建表示例 场景:在 CMS 系统中,当创建自定义字段时,自动为该自定义字段创建专属表存储字段数据
func ExampleSQLServerDynamicTable ¶ added in v1.0.0
func ExampleSQLServerDynamicTable()
ExampleSQLServerDynamicTable SQL Server 动态建表示例 场景:在企业系统中,为每个业务单元创建独立的审计日志表
func ExampleSQLiteDynamicTable ¶
func ExampleSQLiteDynamicTable()
ExampleSQLiteDynamicTable SQLite 动态建表示例 场景:在日志系统中,为每个应用创建独立的日志表
func GetEnabledValidationLocales ¶ added in v1.0.0
func GetEnabledValidationLocales() []string
GetEnabledValidationLocales 获取当前启用的 locale 列表。
func GetStructFields ¶
func GetStructFields(v interface{}) []string
GetStructFields 获取结构体的字段名列表(按 eit_db/db/gorm 解析顺序)
func GetStructValues ¶
func GetStructValues(v interface{}) []interface{}
GetStructValues 获取结构体的字段值列表
func GetValidationLocale ¶ added in v1.0.0
func GetValidationLocale() string
GetValidationLocale 获取当前校验规则 locale。
func JSONExtractGo ¶ added in v1.0.0
JSONExtractGo 是一个轻量 JSON 路径提取函数。 支持路径格式:$.a.b、$.arr[0].name。
func LoadAdapterRegistry ¶
LoadAdapterRegistry 从文件加载多 Adapter 配置(支持 JSON 和 YAML)
func MonthsLater ¶ added in v1.0.0
MonthsLater 基于当前日期返回 N 个月后日期(00:00:00)。
func MonthsLaterUTC ¶ added in v1.0.0
MonthsLaterUTC 基于当前 UTC 日期返回 N 个月后日期(00:00:00 UTC)。
func NextBillingDate ¶ added in v1.0.0
NextBillingDate 返回“下一个账单日”日期(本地时区,00:00:00)。 规则:若本月账单日尚未到达(含当天)则返回本月,否则返回下月;超出月天数时自动对齐到月末。
func OneYearLater ¶ added in v1.0.0
OneYearLater 返回当前日期一年后的日期(00:00:00)。
func OneYearLaterUTC ¶ added in v1.0.0
OneYearLaterUTC 返回当前 UTC 日期一年后的日期(00:00:00 UTC)。
func PrintQueryFeatureMatrix ¶
PrintQueryFeatureMatrix 打印查询特性矩阵
func RealWorldExample ¶
func RealWorldExample(repo *Repository, ctx context.Context) error
RealWorldExample 真实业务场景示例 场景:SaaS CMS 系统 - 为每个客户项目创建独立的内容表
func RegisterAdapterConfig ¶
RegisterAdapterConfig 注册 Adapter 配置(支持多 Adapter 注册)
func RegisterAdapterConfigs ¶
RegisterAdapterConfigs 批量注册 Adapter 配置
func RegisterAdapterConstructor ¶
RegisterAdapterConstructor 使用构造函数动态注册 Adapter 允许的构造函数签名:func(*Config) (Adapter, error) 或 func(*Config) (*T, error)
func RegisterCustomSQLiteDriver ¶
RegisterCustomSQLiteDriver 注册带有自定义函数的 SQLite 驱动 这是推荐的方式来添加自定义函数支持
func RegisterSQLiteJSONFallbackDriver ¶ added in v1.0.0
func RegisterSQLiteJSONFallbackDriver(driverName string, extraFunctions map[string]interface{}) error
RegisterSQLiteJSONFallbackDriver 注册带 JSON 降级函数的 SQLite 驱动。
func RegisterSchemasIntoGlobal ¶ added in v1.0.0
func RegisterSchemasIntoGlobal(schemas ...Schema)
RegisterSchemasIntoGlobal 将多个 Schema 的 FK ViewHint 注册到全局注册表。 通常在 main() 或 app 初始化时调用一次。
db.RegisterSchemasIntoGlobal(usersSchema, ordersSchema, productSchema)
func RegisterValidationProfile ¶ added in v1.0.0
func RegisterValidationProfile(profile ValidationProfile) error
RegisterValidationProfile 注册自定义校验规则配置。
func SLADeadline ¶ added in v1.0.0
SLADeadline 返回 SLA 截止时间。 workdaysOnly 为 false:按自然时间增加小时;为 true:仅计入工作日(周一到周五)小时。
func ScanStruct ¶
ScanStruct 从 sql.Row 扫描单个结构体
func ScanStructs ¶
ScanStructs 从 sql.Rows 扫描多个结构体
func SetLegacyQueryBuilderWarningEnabled ¶ added in v1.0.0
func SetLegacyQueryBuilderWarningEnabled(enabled bool)
SetLegacyQueryBuilderWarningEnabled 设置 v1 QueryBuilder 弃用提示开关。
func SetLowLevelTransactionWarningEnabled ¶ added in v1.0.0
func SetLowLevelTransactionWarningEnabled(enabled bool)
SetLowLevelTransactionWarningEnabled 设置底层事务 Begin 的提示开关。
func SetValidationLocale ¶ added in v1.0.0
SetValidationLocale 设置当前校验规则 locale。
func StartOfCurrentMonth ¶ added in v1.0.0
StartOfCurrentMonth 返回当前月月初(本地时区,00:00:00)。
func StartOfCurrentQuarter ¶ added in v1.0.0
StartOfCurrentQuarter 返回当前季度起始时间(本地时区,00:00:00)。
func ValidationLocaleExists ¶ added in v1.0.0
ValidationLocaleExists 检查 locale 是否存在对应 profile。
func ValidationLocaleFromContext ¶ added in v1.0.0
ValidationLocaleFromContext 从上下文中获取 locale;未设置时回退全局 locale。
func WithValidationLocale ¶ added in v1.0.0
WithValidationLocale 将 locale 写入上下文,供 Changeset/Validator 联动使用。
func YearsLater ¶ added in v1.0.0
YearsLater 基于当前日期返回 N 年后日期(00:00:00)。
func YearsLaterUTC ¶ added in v1.0.0
YearsLaterUTC 基于当前 UTC 日期返回 N 年后日期(00:00:00 UTC)。
Types ¶
type Adapter ¶
type Adapter interface {
// 连接管理
Connect(ctx context.Context, config *Config) error
Close() error
Ping(ctx context.Context) error
// 事务管理
// Deprecated: 这是底层事务原语,主要供框架内部、迁移、驱动集成使用。
// 业务层写操作应优先使用 Changeset 封装入口,而不是直接手动拼事务。
Begin(ctx context.Context, opts ...interface{}) (Tx, error)
// 查询接口 (用于 SELECT)
Query(ctx context.Context, sql string, args ...interface{}) (*sql.Rows, error)
QueryRow(ctx context.Context, sql string, args ...interface{}) *sql.Row
// 执行接口 (用于 INSERT/UPDATE/DELETE)
Exec(ctx context.Context, sql string, args ...interface{}) (sql.Result, error)
// 获取底层连接(建议返回标准驱动连接,如 *sql.DB / *sql.Tx)
// 不应返回 ORM 对象,避免上层绕过能力路由与降级策略。
GetRawConn() interface{}
// 定时任务管理 - 允许数据库通过自己的方式实现后台任务
// 例如: PostgreSQL 使用触发器 + pg_cron, MySQL 使用 EVENT, 应用层使用 cron 库
RegisterScheduledTask(ctx context.Context, task *ScheduledTaskConfig) error
UnregisterScheduledTask(ctx context.Context, taskName string) error
ListScheduledTasks(ctx context.Context) ([]*ScheduledTaskStatus, error)
// QueryBuilder 提供者接口 (v0.4.1) - 中层转义层
// Adapter 通过此接口提供特定数据库的 QueryConstructor 实现
GetQueryBuilderProvider() QueryConstructorProvider
// DatabaseFeatures 声明 (v0.4.3) - 数据库特性声明
// 返回此 Adapter 支持的数据库特性集合
GetDatabaseFeatures() *DatabaseFeatures
// QueryFeatures 声明 (v0.4.4) - 查询特性声明
// 返回此数据库支持的查询构造特性(JOIN、CTE、窗口函数等)
GetQueryFeatures() *QueryFeatures
}
Adapter 定义通用的数据库适配器接口 (参考 Ecto 设计) 每个数据库实现都必须满足这个接口
type AdapterFactory ¶
AdapterFactory 适配器工厂接口
type AdapterRegistryFile ¶
AdapterRegistryFile 多 Adapter 配置文件结构
type AutoShardingManager ¶ added in v1.0.0
type AutoShardingManager struct {
// contains filtered or unexported fields
}
AutoShardingManager 自动分表管理器。 它位于动态建表上层:根据模板计算 shard,再委托 DynamicTableHook 创建/获取表。
func NewAutoShardingManager ¶ added in v1.0.0
func NewAutoShardingManager(hook DynamicTableHook, configName string, template *AutoShardingTemplate) (*AutoShardingManager, error)
NewAutoShardingManager 创建自动分表管理器。
func (*AutoShardingManager) EnsureShardTable ¶ added in v1.0.0
func (m *AutoShardingManager) EnsureShardTable(ctx context.Context, values map[string]interface{}) (string, error)
EnsureShardTable 计算分片并通过动态建表钩子确保子表可用。
func (*AutoShardingManager) ResolveShardID ¶ added in v1.0.0
func (m *AutoShardingManager) ResolveShardID(values map[string]interface{}) (string, error)
ResolveShardID 仅计算分片 ID,不触发表创建。
type AutoShardingTemplate ¶ added in v1.0.0
type AutoShardingTemplate struct {
Kind ShardingTemplateKind
KeyField string
ShardCount int
DateGranularity DateShardingGranularity
AllowedRegions map[string]struct{}
}
AutoShardingTemplate 自动分表模板。
func NewDataScaleShardingTemplate ¶ added in v1.0.0
func NewDataScaleShardingTemplate(keyField string, shardCount int) *AutoShardingTemplate
NewDataScaleShardingTemplate 基于数据规模(哈希槽)分表。
func NewDateShardingTemplate ¶ added in v1.0.0
func NewDateShardingTemplate(keyField string, granularity DateShardingGranularity) *AutoShardingTemplate
NewDateShardingTemplate 基于日期字段分表。
func NewRegionShardingTemplate ¶ added in v1.0.0
func NewRegionShardingTemplate(keyField string, allowedRegions ...string) *AutoShardingTemplate
NewRegionShardingTemplate 基于地区字段分表。
func (*AutoShardingTemplate) ResolveShardID ¶ added in v1.0.0
func (t *AutoShardingTemplate) ResolveShardID(values map[string]interface{}) (string, error)
ResolveShardID 根据模板从输入记录解析分片 ID。
type BaseMigration ¶
type BaseMigration struct {
// contains filtered or unexported fields
}
BaseMigration 基础迁移结构,提供通用字段
func NewBaseMigration ¶
func NewBaseMigration(version, description string) *BaseMigration
NewBaseMigration 创建基础迁移
type BaseSQLCompiler ¶ added in v1.0.0
type BaseSQLCompiler struct {
// contains filtered or unexported fields
}
BaseSQLCompiler 默认 SQL 编译器。 各 SQL Adapter 可在此基础上定制或替换。
func NewBaseSQLCompiler ¶ added in v1.0.0
func NewBaseSQLCompiler(dialect SQLDialect) *BaseSQLCompiler
func (*BaseSQLCompiler) SetDialect ¶ added in v1.0.0
func (c *BaseSQLCompiler) SetDialect(dialect SQLDialect)
type BaseSchema ¶
type BaseSchema struct {
// contains filtered or unexported fields
}
BaseSchema 基础模式实现
func InferSchema ¶
func InferSchema(v interface{}) (*BaseSchema, error)
InferSchema 从 Go struct 推导 Schema 支持 struct tag(优先级): 1) `eit_db:"column_name,primary_key,not_null,unique,index,auto_increment,default=...,type=..."`(推荐,避免与其他库的 `db` tag 命名冲突) 2) `db:"..."`(兼容) 3) `gorm:"column:...,primaryKey,not null,uniqueIndex,autoIncrement,default:..."`(兜底)
func (*BaseSchema) AddForeignKey ¶ added in v1.0.0
func (s *BaseSchema) AddForeignKey(name string, localFields []string, refTable string, refFields []string, onDelete, onUpdate string, opts ...FKOption) *BaseSchema
AddForeignKey 添加表级外键约束(支持复合外键)。 onDelete/onUpdate 可选值:"CASCADE", "SET NULL", "RESTRICT", "NO ACTION", ""(使用数据库默认)。 opts 可选附加 WithViewHint / WithJoinType 等函数选项以声明热点查询视图。
func (*BaseSchema) AddPrimaryKey ¶ added in v1.0.0
func (s *BaseSchema) AddPrimaryKey(fields ...string) *BaseSchema
AddPrimaryKey 添加表级主键约束(支持复合主键)
func (*BaseSchema) AddSoftDelete ¶ added in v1.0.0
func (s *BaseSchema) AddSoftDelete() *BaseSchema
AddSoftDelete 添加软删除字段 deleted_at。 默认行为: - 字段类型为 TypeTime - 可空(NULL) - 若字段已存在则跳过,避免重复添加
func (*BaseSchema) AddTimestamps ¶ added in v1.0.0
func (s *BaseSchema) AddTimestamps() *BaseSchema
AddTimestamps 添加常用时间戳字段 created_at / updated_at。 默认行为: - 字段类型为 TypeTime - 非空(NOT NULL) - 默认值为 CURRENT_TIMESTAMP - 若字段已存在则跳过,避免重复添加
func (*BaseSchema) AddUniqueConstraint ¶ added in v1.0.0
func (s *BaseSchema) AddUniqueConstraint(name string, fields ...string) *BaseSchema
AddUniqueConstraint 添加表级唯一约束(支持复合唯一)
func (*BaseSchema) BelongsTo ¶ added in v1.1.0
func (s *BaseSchema) BelongsTo(target Schema) *SchemaRelationBuilder
BelongsTo 声明本 Schema 持有外键,归属于目标 Schema(多对一)。 连接语义默认 required(本实体必须有对应父实体)。
orderSchema.BelongsTo(userSchema).Over("user_id", "id")
func (*BaseSchema) Constraints ¶ added in v1.0.0
func (s *BaseSchema) Constraints() []TableConstraint
Constraints 返回所有表级约束
func (*BaseSchema) FindRelation ¶ added in v1.1.0
func (s *BaseSchema) FindRelation(targetTable string) *SchemaRelation
FindRelation 查找本 Schema 与目标表名之间的第一个关系声明;未找到时返回 nil。
func (*BaseSchema) HasMany ¶ added in v1.1.0
func (s *BaseSchema) HasMany(target Schema) *SchemaRelationBuilder
HasMany 声明本 Schema 是"一"侧,目标 Schema 持有外键(一对多)。 连接语义默认 optional(本实体可能有 0 个目标实体)。 流式调用 .Over(foreignKey, originKey) 可声明关联字段;.Required()/.Optional() 可覆盖默认语义。
userSchema.HasMany(orderSchema).Over("user_id", "id")
func (*BaseSchema) HasOne ¶ added in v1.1.0
func (s *BaseSchema) HasOne(target Schema) *SchemaRelationBuilder
HasOne 声明本 Schema 是"一"侧,目标 Schema 持有外键(一对一)。 连接语义默认 optional(本实体可能没有对应目标实体)。
userSchema.HasOne(profileSchema).Over("user_id", "id")
func (*BaseSchema) ManyToMany ¶ added in v1.1.0
func (s *BaseSchema) ManyToMany(target Schema) *SchemaRelationBuilder
ManyToMany 声明多对多关系。 推荐配合 Through 指定中间关系(中间表/集合/边),便于各适配器做深度优化。
userSchema.ManyToMany(roleSchema).Through(userRoleSchema, "user_id", "role_id")
func (*BaseSchema) PrimaryKeyField ¶
func (s *BaseSchema) PrimaryKeyField() *Field
PrimaryKeyField 获取主键字段
func (*BaseSchema) Relations ¶ added in v1.1.0
func (s *BaseSchema) Relations() []SchemaRelation
Relations 返回本 Schema 上所有已声明的关系。
type Changeset ¶
type Changeset struct {
// contains filtered or unexported fields
}
Changeset 代表对数据的变更(参考 Ecto.Changeset)
func (*Changeset) ApplyAction ¶
ApplyAction 根据操作类型应用不同的验证逻辑
func (*Changeset) ClearError ¶
ClearError 清除错误
func (*Changeset) ForceChanges ¶
ForceChanges 强制所有字段为变更状态(用于插入操作)
func (*Changeset) GetChanged ¶
GetChanged 获取变更的字段值
func (*Changeset) GetChangedFields ¶
GetChangedFields 获取所有被修改的字段名列表
func (*Changeset) GetPrevious ¶
GetPrevious 获取变更前的值
func (*Changeset) HasChanged ¶
HasChanged 检查字段是否被修改
func (*Changeset) ValidateChange ¶
ValidateChange 验证特定字段的变更
func (*Changeset) ValidateChangeWithContext ¶ added in v1.0.0
func (cs *Changeset) ValidateChangeWithContext(ctx context.Context, fieldName string, validator Validator) *Changeset
ValidateChangeWithContext 从上下文读取 locale 验证指定字段。
func (*Changeset) ValidateChangeWithLocale ¶ added in v1.0.0
func (cs *Changeset) ValidateChangeWithLocale(fieldName string, validator Validator, locale string) *Changeset
ValidateChangeWithLocale 使用指定 locale 验证指定字段。
func (*Changeset) ValidateExclusion ¶
ValidateExclusion 验证字段值不在指定列表中
func (*Changeset) ValidateFormat ¶
ValidateFormat 验证字段格式(使用正则表达式)
func (*Changeset) ValidateInclusion ¶
ValidateInclusion 验证字段值在指定列表中
func (*Changeset) ValidateLength ¶
ValidateLength 验证字符串长度
func (*Changeset) ValidateNumber ¶
ValidateNumber 验证数字范围
func (*Changeset) ValidateRequired ¶
ValidateRequired 验证必填字段
func (*Changeset) ValidateWithContext ¶ added in v1.0.0
ValidateWithContext 从上下文读取 locale 执行验证。
func (*Changeset) ValidateWithLocale ¶ added in v1.0.0
ValidateWithLocale 使用指定 locale 执行验证。
type ChangesetExecutor ¶ added in v1.0.0
type ChangesetExecutor struct {
// contains filtered or unexported fields
}
ChangesetExecutor 面向业务层的写操作封装。 它仅暴露基于 Changeset 的常见写路径,避免业务层默认直接操作 Tx。
func (*ChangesetExecutor) Delete ¶ added in v1.0.0
func (e *ChangesetExecutor) Delete(whereClause string, whereArgs ...interface{}) (sql.Result, error)
Delete 按条件删除记录。
func (*ChangesetExecutor) DeleteByID ¶ added in v1.0.0
func (e *ChangesetExecutor) DeleteByID(id interface{}) (sql.Result, error)
DeleteByID 按 ID 删除记录。
func (*ChangesetExecutor) Insert ¶ added in v1.0.0
func (e *ChangesetExecutor) Insert(cs *Changeset) (sql.Result, error)
Insert 插入 Changeset。
func (*ChangesetExecutor) SoftDelete ¶ added in v1.0.0
func (e *ChangesetExecutor) SoftDelete(whereClause string, whereArgs ...interface{}) (sql.Result, error)
SoftDelete 软删除记录。
func (*ChangesetExecutor) SoftDeleteByID ¶ added in v1.0.0
func (e *ChangesetExecutor) SoftDeleteByID(id interface{}) (sql.Result, error)
SoftDeleteByID 按 ID 软删除记录。
func (*ChangesetExecutor) Update ¶ added in v1.0.0
func (e *ChangesetExecutor) Update(cs *Changeset, whereClause string, whereArgs ...interface{}) (sql.Result, error)
Update 按条件更新 Changeset。
func (*ChangesetExecutor) UpdateByID ¶ added in v1.0.0
func (e *ChangesetExecutor) UpdateByID(id interface{}, cs *Changeset) (sql.Result, error)
UpdateByID 按 ID 更新 Changeset。
type CompiledQuery ¶ added in v1.0.0
type CompiledQuery struct {
Query string
Args []interface{}
}
CompiledQuery 表示预编译后的查询结果。
type CompiledQueryCache ¶ added in v1.0.0
type CompiledQueryCache struct {
// contains filtered or unexported fields
}
CompiledQueryCache Repository 级别的编译结果缓存。
func NewCompiledQueryCache ¶ added in v1.0.0
func NewCompiledQueryCache() *CompiledQueryCache
NewCompiledQueryCache 创建编译查询缓存。
func NewCompiledQueryCacheWithOptions ¶ added in v1.0.0
func NewCompiledQueryCacheWithOptions(maxEntries int, defaultTTL time.Duration, enableMetrics bool) *CompiledQueryCache
NewCompiledQueryCacheWithOptions 创建指定容量、TTL 和 metrics 策略的编译查询缓存。
func NewCompiledQueryCacheWithSize ¶ added in v1.0.0
func NewCompiledQueryCacheWithSize(maxEntries int) *CompiledQueryCache
NewCompiledQueryCacheWithSize 创建指定容量的编译查询缓存。
type CompiledQueryCacheStats ¶ added in v1.0.0
type CompiledQueryCacheStats struct {
Enabled bool
Hits uint64
Misses uint64
HitRatio float64
KeysAdded uint64
KeysUpdated uint64
KeysEvicted uint64
SetsDropped uint64
SetsRejected uint64
GetsDropped uint64
GetsKept uint64
CostAdded uint64
CostEvicted uint64
RemainingCost int64
MaxCost int64
}
CompiledQueryCacheStats 表示查询缓存命中统计。
type CompiledQueryTemplate ¶ added in v1.0.0
CompiledQueryTemplate 表示可复用的查询模板(仅缓存查询文本,不缓存具体参数值)。
type CompositeCondition ¶
CompositeCondition 复合条件(AND/OR)
func (*CompositeCondition) Translate ¶
func (c *CompositeCondition) Translate(translator ConditionTranslator) (string, []interface{}, error)
func (*CompositeCondition) Type ¶
func (c *CompositeCondition) Type() string
type CompositeTypeBuilder ¶ added in v1.0.0
type CompositeTypeBuilder struct {
// contains filtered or unexported fields
}
CompositeTypeBuilder 构建 PostgreSQL COMPOSITE 类型(结构体类型)DDL。
func (*CompositeTypeBuilder) AddField ¶ added in v1.0.0
func (b *CompositeTypeBuilder) AddField(ctx context.Context, name, pgType string) error
AddField 运行时动态追加字段,等同于 ALTER TYPE ... ADD ATTRIBUTE。 若类型已存在,直接执行 DDL;若尚未创建则缓冲到 Create 时一起执行。
func (*CompositeTypeBuilder) Build ¶ added in v1.0.0
func (b *CompositeTypeBuilder) Build() (string, error)
Build 生成 CREATE TYPE ... AS (...) DDL 字符串,不执行。
func (*CompositeTypeBuilder) Create ¶ added in v1.0.0
func (b *CompositeTypeBuilder) Create(ctx context.Context) error
Create 在数据库中创建 COMPOSITE 类型。
func (*CompositeTypeBuilder) Drop ¶ added in v1.0.0
func (b *CompositeTypeBuilder) Drop(ctx context.Context, ifExists bool) error
Drop 删除 COMPOSITE 类型。
func (*CompositeTypeBuilder) Exists ¶ added in v1.0.0
func (b *CompositeTypeBuilder) Exists(ctx context.Context) (bool, error)
Exists 检查该 COMPOSITE 类型是否已存在。
func (*CompositeTypeBuilder) Field ¶ added in v1.0.0
func (b *CompositeTypeBuilder) Field(name, pgType string) *CompositeTypeBuilder
Field 添加一个字段到 COMPOSITE 类型,pgType 为 PostgreSQL 原生类型字符串。
示例:Field("latitude", "DOUBLE PRECISION").Field("longitude", "DOUBLE PRECISION")
func (*CompositeTypeBuilder) IfNotExists ¶ added in v1.0.0
func (b *CompositeTypeBuilder) IfNotExists() *CompositeTypeBuilder
IfNotExists 若类型已存在则静默跳过。
func (*CompositeTypeBuilder) Schema ¶ added in v1.0.0
func (b *CompositeTypeBuilder) Schema(schema string) *CompositeTypeBuilder
Schema 可选:指定类型所在的 schema。
type Condition ¶
type Condition interface {
// 获取条件类型
Type() string
// 将条件转换为 SQL/Cypher/etc
Translate(translator ConditionTranslator) (string, []interface{}, error)
}
Condition 条件接口 - 中层转义 Adapter 实现此接口将条件转换为数据库特定的形式
func ActiveUsersInBusinessHours ¶ added in v1.0.0
func ActiveUsersInBusinessHours() Condition
ActiveUsersInBusinessHours 预置条件:活跃用户 + 今天工作时段。 默认约定:status = "active",时间字段为 updated_at,工作时段为 09:00-18:00。
func ActiveUsersInBusinessHoursBy ¶ added in v1.0.0
func ActiveUsersInBusinessHoursBy(statusField string, activeValue interface{}, timeField string, startHour, endHour int) Condition
ActiveUsersInBusinessHoursBy 可配置版本。
func DateInBusinessHours ¶ added in v1.0.0
DateInBusinessHours 生成“当前日期工作时段”的条件(闭开区间:[start, end))。 默认基于本地时区今天,startHour/endHour 建议范围为 0-23。 当 endHour <= startHour 时,视为跨天时段(例如 22 -> 6)。
func DateInCurrentMonth ¶ added in v1.0.0
DateInCurrentMonth 生成“字段时间位于当前月”的条件(闭开区间:[monthStart, nextMonthStart))。
func DateInCurrentQuarter ¶ added in v1.0.0
DateInCurrentQuarter 生成“字段时间位于当前季度”的条件(闭开区间:[quarterStart, nextQuarterStart))。
func DateInLastBusinessDays ¶ added in v1.0.0
DateInLastBusinessDays 生成“最近 N 个工作日”的条件。 工作日定义为周一到周五;holidays 可传入节假日日期(只比较年月日)。 返回按天窗口 OR 组合条件,每天为闭开区间 [dayStart, nextDayStart)。
func DueSoonTasksInBusinessDays ¶ added in v1.0.0
DueSoonTasksInBusinessDays 预置条件:待处理任务且截止时间在未来 N 个工作日内。 默认约定:status = "pending",截止字段为 due_at。
func OrdersInCurrentQuarter ¶ added in v1.0.0
func OrdersInCurrentQuarter() Condition
OrdersInCurrentQuarter 预置条件:订单创建时间在当前季度。 默认约定:订单创建时间字段为 created_at。
func OrdersInCurrentQuarterBy ¶ added in v1.0.0
OrdersInCurrentQuarterBy 可配置版本。
type ConditionTranslator ¶
type ConditionTranslator interface {
TranslateCondition(condition Condition) (string, []interface{}, error)
TranslateComposite(operator string, conditions []Condition) (string, []interface{}, error)
}
ConditionTranslator 条件转义器接口 由每个 Adapter 的 QueryConstructor 实现
type Config ¶
type Config struct {
// 适配器类型: "sqlite" | "postgres" | "mysql" | "sqlserver" | "mongodb" | "neo4j"
Adapter string `json:"adapter" yaml:"adapter"`
// EnableScheduledTaskFallback 控制定时任务在适配器不支持时是否自动回退到应用层调度器。
// nil 表示使用默认值(true)。
EnableScheduledTaskFallback *bool `json:"enable_scheduled_task_fallback,omitempty" yaml:"enable_scheduled_task_fallback,omitempty"`
// QueryCache 控制 Repository 级查询编译缓存策略。
QueryCache *QueryCacheConfig `json:"query_cache,omitempty" yaml:"query_cache,omitempty"`
// Adapter 专属配置。
// 推荐使用这一组嵌套配置来表达连接细节,而不是把所有字段平铺到顶层。
SQLite *SQLiteConnectionConfig `json:"sqlite,omitempty" yaml:"sqlite,omitempty"`
Postgres *PostgresConnectionConfig `json:"postgres,omitempty" yaml:"postgres,omitempty"`
MySQL *MySQLConnectionConfig `json:"mysql,omitempty" yaml:"mysql,omitempty"`
SQLServer *SQLServerConnectionConfig `json:"sqlserver,omitempty" yaml:"sqlserver,omitempty"`
MongoDB *MongoConnectionConfig `json:"mongodb,omitempty" yaml:"mongodb,omitempty"`
Neo4j *Neo4jConnectionConfig `json:"neo4j,omitempty" yaml:"neo4j,omitempty"`
// SQLite 特定配置(legacy fallback)
Database string `json:"database" yaml:"database"` // 数据库文件路径或数据库名
// PostgreSQL/MySQL/SQL Server 通用配置(legacy fallback)
Host string `json:"host" yaml:"host"`
Port int `json:"port" yaml:"port"`
Username string `json:"username" yaml:"username"`
Password string `json:"password" yaml:"password"`
// PostgreSQL 特定配置(legacy fallback)
SSLMode string `json:"ssl_mode" yaml:"ssl_mode"`
// 连接池配置
Pool *PoolConfig `json:"pool" yaml:"pool"`
// 其他参数 (可选的适配器特定参数)
Options map[string]interface{} `json:"options" yaml:"options"`
// 校验规则与 locale 配置
Validation *ValidationConfig `json:"validation,omitempty" yaml:"validation,omitempty"`
// 启动期能力体检配置(strict/lenient)
StartupCapabilities *StartupCapabilityConfig `json:"startup_capabilities,omitempty" yaml:"startup_capabilities,omitempty"`
}
Config 数据库配置结构 (参考 Ecto 的 Repo 配置)
func GetAdapterConfig ¶
GetAdapterConfig 获取已注册的 Adapter 配置
func LoadConfig ¶
LoadConfig 从文件加载数据库配置(支持 JSON 和 YAML 格式)
func LoadConfigFromEnv ¶ added in v1.0.0
LoadConfigFromEnv 按 adapter 从环境变量加载数据库配置。
支持的环境变量: - PostgreSQL: POSTGRES_DSN 或 POSTGRES_HOST/PORT/USER/PASSWORD/DB/SSLMODE - MySQL: MYSQL_DSN 或 MYSQL_HOST/PORT/USER/PASSWORD/DB - SQL Server: SQLSERVER_DSN 或 SQLSERVER_HOST/PORT/USER/PASSWORD/DB - SQLite: SQLITE_DATABASE 或 SQLITE_PATH - MongoDB: MONGODB_URI + MONGODB_DATABASE/MONGODB_DB
func LoadConfigFromEnvWithDefaults ¶ added in v1.0.0
LoadConfigFromEnvWithDefaults 按 adapter 从环境变量加载数据库配置,并允许通过 defaults 指定默认值。 环境变量优先级高于 defaults;若设置了 *_DSN,则直接使用 DSN 连接细节。
func LoadConfigWithDefaults ¶
LoadConfigWithDefaults 从文件加载配置并应用默认值
func (*Config) ResolvedMongoConfig ¶ added in v1.0.0
func (c *Config) ResolvedMongoConfig() *MongoConnectionConfig
ResolvedMongoConfig 返回 MongoDB 的有效配置。
func (*Config) ResolvedMySQLConfig ¶ added in v1.0.0
func (c *Config) ResolvedMySQLConfig() *MySQLConnectionConfig
ResolvedMySQLConfig 返回 MySQL 的有效配置。
func (*Config) ResolvedNeo4jConfig ¶ added in v1.0.0
func (c *Config) ResolvedNeo4jConfig() *Neo4jConnectionConfig
ResolvedNeo4jConfig 返回 Neo4j 的有效配置。
func (*Config) ResolvedPostgresConfig ¶ added in v1.0.0
func (c *Config) ResolvedPostgresConfig() *PostgresConnectionConfig
ResolvedPostgresConfig 返回 PostgreSQL 的有效配置。
func (*Config) ResolvedSQLServerConfig ¶ added in v1.0.0
func (c *Config) ResolvedSQLServerConfig() *SQLServerConnectionConfig
ResolvedSQLServerConfig 返回 SQL Server 的有效配置。
func (*Config) ResolvedSQLiteConfig ¶ added in v1.0.0
func (c *Config) ResolvedSQLiteConfig() *SQLiteConnectionConfig
ResolvedSQLiteConfig 返回 SQLite 的有效配置。
func (*Config) ScheduledTaskFallbackEnabled ¶ added in v1.1.1
ScheduledTaskFallbackEnabled 返回定时任务回退开关的有效值。 默认 true;当显式配置为 false 时禁用回退。
type ConfigFile ¶
type ConfigFile struct {
Database *Config `yaml:"database" json:"database"`
}
ConfigFile 配置文件结构 (从 YAML 或 JSON 加载)
type ConstrainedSchema ¶ added in v1.1.0
type ConstrainedSchema interface {
Schema
Constraints() []TableConstraint
}
ConstrainedSchema 扩展 Schema,允许访问表级约束(外键、唯一约束等)。 BaseSchema 实现此接口;外部自定义 Schema 实现可选择性实现。
type ConstraintKind ¶ added in v1.0.0
type ConstraintKind string
ConstraintKind 表级约束类型
const ( ConstraintPrimaryKey ConstraintKind = "primary_key" ConstraintUnique ConstraintKind = "unique" ConstraintForeignKey ConstraintKind = "foreign_key" )
type CountBuilder ¶ added in v1.1.0
type CountBuilder struct {
// contains filtered or unexported fields
}
CountBuilder 统计投影构造器。 用于表达 COUNT(field) / COUNT(DISTINCT field) 及别名。
func NewCountBuilder ¶ added in v1.1.0
func NewCountBuilder(fieldName ...string) *CountBuilder
NewCountBuilder 创建 CountBuilder。 为空或传入 "*" 时表示 COUNT(*)。
func (*CountBuilder) As ¶ added in v1.1.0
func (b *CountBuilder) As(alias string) *CountBuilder
As 为 COUNT 投影设置别名。
func (*CountBuilder) Distinct ¶ added in v1.1.0
func (b *CountBuilder) Distinct() *CountBuilder
Distinct 切换为 COUNT(DISTINCT field)。
type CrossTableStrategy ¶ added in v1.0.0
type CrossTableStrategy string
CrossTableStrategy 跨表查询策略。
const ( // CrossTableStrategyAuto 自动策略:由方言默认行为决定(推荐默认)。 CrossTableStrategyAuto CrossTableStrategy = "auto" // CrossTableStrategyPreferTempTable 优先临时表策略(例如 SQL Server 的复杂跨表查询)。 CrossTableStrategyPreferTempTable CrossTableStrategy = "prefer_temp_table" // CrossTableStrategyForceDirectJoin 强制直接 JOIN,不走临时表改写。 CrossTableStrategyForceDirectJoin CrossTableStrategy = "force_direct_join" )
type CrossTableViewEntry ¶ added in v1.0.0
type CrossTableViewEntry struct {
// LocalTable 拥有外键的表名(FK 所在表)
LocalTable string
// RefTable 被引用的表名
RefTable string
// ViewName 已创建的视图名
ViewName string
// Materialized 是否为物化视图(PostgreSQL),影响 DROP 语句
Materialized bool
// LocalAlias 视图中本地表的别名(与 buildViewFromFKHintSQL 保持一致)
LocalAlias string
// RefAlias 视图中引用表的别名
RefAlias string
// JoinFields FK 本地列列表
JoinFields []string
// RefFields FK 引用列列表
RefFields []string
}
CrossTableViewEntry 描述一个通过视图加速的跨表关联。 由 Schema FK 的 ViewHint 声明,在 app 启动时注册到 CrossTableViewRegistry, QueryBuilder 在构建 JOIN 时自动查询并路由到视图。
type CrossTableViewRegistry ¶ added in v1.0.0
type CrossTableViewRegistry struct {
// contains filtered or unexported fields
}
CrossTableViewRegistry 跨表视图注册表(线程安全)。
典型使用流程:
- Schema 声明阶段:AddForeignKey(..., WithViewHint(...))
- App 启动:RegisterSchemasIntoGlobal(ordersSchema, ...)
- Migration Up:自动 CREATE VIEW
- 查询阶段:NewQueryConstructor(schema).Join(...) 自动路由到视图
func NewCrossTableViewRegistry ¶ added in v1.0.0
func NewCrossTableViewRegistry() *CrossTableViewRegistry
NewCrossTableViewRegistry 创建一个新的空注册表(用于测试或隔离注册)。
func (*CrossTableViewRegistry) Lookup ¶ added in v1.0.0
func (r *CrossTableViewRegistry) Lookup(localTable, refTable string) (*CrossTableViewEntry, bool)
Lookup 精确查找:以 localTable 为主表、refTable 为关联表的视图条目。 返回 (entry, true) 或 (nil, false)。
func (*CrossTableViewRegistry) LookupAny ¶ added in v1.0.0
func (r *CrossTableViewRegistry) LookupAny(tableA, tableB string) (*CrossTableViewEntry, bool)
LookupAny 双向查找:先查 (local, ref),再查反向 (ref, local)。 适用于 QueryBuilder:无论 FROM 哪张表,都能找到对应的视图。
func (*CrossTableViewRegistry) Register ¶ added in v1.0.0
func (r *CrossTableViewRegistry) Register(entry *CrossTableViewEntry)
Register 注册一条跨表视图关联。
func (*CrossTableViewRegistry) RegisterFromSchema ¶ added in v1.0.0
func (r *CrossTableViewRegistry) RegisterFromSchema(schema Schema)
RegisterFromSchema 扫描 Schema 上所有带 ViewHint 的 FK 约束并注册到本注册表。
type CustomFeatureProvider ¶ added in v1.0.0
type CustomFeatureProvider interface {
HasCustomFeatureImplementation(feature string) bool
ExecuteCustomFeature(ctx context.Context, feature string, input map[string]interface{}) (interface{}, error)
}
CustomFeatureProvider adapter 的可选扩展接口 用于声明和执行数据库原生不支持但 adapter 可自定义实现的能力。
type CypherCompiler ¶ added in v1.0.0
type CypherCompiler struct{}
CypherCompiler 将 QueryIR 编译为 Cypher。
func NewCypherCompiler ¶ added in v1.0.0
func NewCypherCompiler() *CypherCompiler
type CypherConditionTranslator ¶ added in v1.0.0
type CypherConditionTranslator struct {
// contains filtered or unexported fields
}
CypherConditionTranslator 将 Condition 转换为 Cypher 过滤表达式。
func (*CypherConditionTranslator) TranslateComposite ¶ added in v1.0.0
func (t *CypherConditionTranslator) TranslateComposite(operator string, conditions []Condition) (string, []interface{}, error)
func (*CypherConditionTranslator) TranslateCondition ¶ added in v1.0.0
func (t *CypherConditionTranslator) TranslateCondition(condition Condition) (string, []interface{}, error)
type CypherWriteSummary ¶ added in v1.0.0
type CypherWriteSummary struct {
NodesCreated int
NodesDeleted int
RelationshipsCreated int
RelationshipsDeleted int
PropertiesSet int
LabelsAdded int
LabelsRemoved int
}
CypherWriteSummary 表示 Neo4j 写入执行摘要。
type DatabaseFeatures ¶
type DatabaseFeatures struct {
// ===== 索引和约束 =====
SupportsCompositeKeys bool // 复合主键 (所有数据库都支持)
SupportsForeignKeys bool // 外键约束 (关系型数据库支持,MongoDB 不支持)
SupportsCompositeForeignKeys bool // 复合外键 (关系型数据库支持,MongoDB 不支持)
SupportsCompositeIndexes bool // 复合索引 (所有数据库都支持)
SupportsPartialIndexes bool // 部分索引 (WHERE 子句)
SupportsDeferrable bool // 延迟约束 (PostgreSQL, SQLite)
// ===== 自定义类型 =====
SupportsEnumType bool // ENUM 类型
SupportsCompositeType bool // 复合/结构体类型 (PostgreSQL)
SupportsDomainType bool // DOMAIN 类型 (PostgreSQL)
SupportsUDT bool // User-Defined Types (SQL Server, PostgreSQL)
// ===== 函数和过程 =====
SupportsStoredProcedures bool // 存储过程
SupportsFunctions bool // 自定义函数
SupportsAggregateFuncs bool // 自定义聚合函数
FunctionLanguages []string // 支持的函数语言 (如 "plpgsql", "tsql", "sql")
// ===== 高级查询 =====
SupportsWindowFunctions bool // 窗口函数 (ROW_NUMBER, RANK, etc.)
SupportsCTE bool // 公共表表达式 (WITH)
SupportsRecursiveCTE bool // 递归 CTE
SupportsMaterializedCTE bool // 物化 CTE (PostgreSQL)
// ===== JSON 支持 =====
HasNativeJSON bool // 原生 JSON 类型
SupportsJSONPath bool // JSON 路径查询
SupportsJSONIndex bool // JSON 索引
// ===== 全文搜索 =====
SupportsFullTextSearch bool // 全文搜索
FullTextLanguages []string // 支持的语言
// ===== 其他特性 =====
SupportsArrays bool // 数组类型 (PostgreSQL)
SupportsGenerated bool // 生成列 (Computed/Generated columns)
SupportsReturning bool // RETURNING 子句 (PostgreSQL, SQLite 3.35+)
SupportsUpsert bool // UPSERT 操作 (ON CONFLICT / ON DUPLICATE KEY)
SupportsListenNotify bool // LISTEN/NOTIFY (PostgreSQL)
// ===== 元信息 =====
DatabaseName string // 数据库名称
DatabaseVersion string // 版本信息
Description string // 特性描述
// 版本化能力支持(可选)
FeatureSupport map[string]FeatureSupport
// 特性降级策略(可选)
FallbackStrategies map[string]FeatureFallback
}
DatabaseFeatures 数据库特性声明 每个 Adapter 通过此结构声明其支持的数据库特性
func NewMongoDatabaseFeatures ¶
func NewMongoDatabaseFeatures() *DatabaseFeatures
NewMongoDatabaseFeatures MongoDB 数据库特性(最小占位实现)
func NewNeo4jDatabaseFeatures ¶ added in v1.0.0
func NewNeo4jDatabaseFeatures() *DatabaseFeatures
NewNeo4jDatabaseFeatures Neo4j 数据库特性声明。
func (*DatabaseFeatures) GetFallbackStrategy ¶ added in v1.0.0
func (f *DatabaseFeatures) GetFallbackStrategy(feature string) FeatureFallback
GetFallbackStrategy 获取特性降级策略
func (*DatabaseFeatures) GetFeatureSupport ¶ added in v1.0.0
func (f *DatabaseFeatures) GetFeatureSupport(feature string) FeatureSupport
GetFeatureSupport 获取特性支持详情(若未定义则回退到 HasFeature)
func (*DatabaseFeatures) GetFeaturesByCategory ¶
func (f *DatabaseFeatures) GetFeaturesByCategory(category FeatureCategory) []string
GetFeaturesByCategory 按分类获取支持的特性列表
func (*DatabaseFeatures) HasFeature ¶
func (f *DatabaseFeatures) HasFeature(feature string) bool
HasFeature 检查是否支持特定特性
func (*DatabaseFeatures) SupportsFeatureWithVersion ¶ added in v1.0.0
func (f *DatabaseFeatures) SupportsFeatureWithVersion(feature, version string) bool
SupportsFeatureWithVersion 根据实例版本判断特性是否可用(version 为空时回退常规判断)
type DateBuilder ¶ added in v1.0.0
type DateBuilder struct {
// contains filtered or unexported fields
}
DateBuilder 提供应用层日期构建能力,适合生成业务时间边界或默认时间值。
func DateByYMD ¶ added in v1.0.0
func DateByYMD(year, month, day int) *DateBuilder
DateByYMD 基于年月日创建日期构建器,时间部分默认为 00:00:00(本地时区)。
func TodayBuilder ¶ added in v1.0.0
func TodayBuilder() *DateBuilder
TodayBuilder 基于当前日期创建构建器,时间部分为 00:00:00(当前时区)。
func TodayUTCBuilder ¶ added in v1.0.0
func TodayUTCBuilder() *DateBuilder
TodayUTCBuilder 基于当前 UTC 日期创建构建器,时间部分为 00:00:00(UTC)。
func (*DateBuilder) AddDays ¶ added in v1.0.0
func (b *DateBuilder) AddDays(days int) *DateBuilder
AddDays 增加(或减少)天数。
func (*DateBuilder) AddMonths ¶ added in v1.0.0
func (b *DateBuilder) AddMonths(months int) *DateBuilder
AddMonths 增加(或减少)月数。
func (*DateBuilder) AddYears ¶ added in v1.0.0
func (b *DateBuilder) AddYears(years int) *DateBuilder
AddYears 增加(或减少)年数。
func (*DateBuilder) At ¶ added in v1.0.0
func (b *DateBuilder) At(hour, minute, second int) *DateBuilder
At 设置时分秒,便于从日期边界构造完整时间戳。
func (*DateBuilder) EndOfMonth ¶ added in v1.0.0
func (b *DateBuilder) EndOfMonth() *DateBuilder
EndOfMonth 对齐到当月月末 23:59:59。
func (*DateBuilder) EndOfQuarter ¶ added in v1.0.0
func (b *DateBuilder) EndOfQuarter() *DateBuilder
EndOfQuarter 对齐到当前季度末日 23:59:59。
func (*DateBuilder) In ¶ added in v1.0.0
func (b *DateBuilder) In(loc *time.Location) *DateBuilder
In 将构建器时间转换到指定时区。
func (*DateBuilder) StartOfMonth ¶ added in v1.0.0
func (b *DateBuilder) StartOfMonth() *DateBuilder
StartOfMonth 对齐到当月月初 00:00:00。
func (*DateBuilder) StartOfQuarter ¶ added in v1.0.0
func (b *DateBuilder) StartOfQuarter() *DateBuilder
StartOfQuarter 对齐到当前季度起始日 00:00:00。
type DatePresetRegistry ¶ added in v1.0.0
type DatePresetRegistry struct{}
DatePresetRegistry 日期相关预置工具集合。
func (DatePresetRegistry) ActiveUsersInBusinessHours ¶ added in v1.0.0
func (DatePresetRegistry) ActiveUsersInBusinessHours() Condition
ActiveUsersInBusinessHours 预置条件:活跃用户 + 今天工作时段。
func (DatePresetRegistry) ActiveUsersInBusinessHoursBy ¶ added in v1.0.0
func (DatePresetRegistry) ActiveUsersInBusinessHoursBy(statusField string, activeValue interface{}, timeField string, startHour, endHour int) Condition
ActiveUsersInBusinessHoursBy 可配置版本。
func (DatePresetRegistry) DueSoonTasksInBusinessDays ¶ added in v1.0.0
func (DatePresetRegistry) DueSoonTasksInBusinessDays(days int, holidays ...time.Time) Condition
DueSoonTasksInBusinessDays 预置条件:待处理任务且截止时间在未来 N 个工作日内。
func (DatePresetRegistry) OrdersInCurrentQuarter ¶ added in v1.0.0
func (DatePresetRegistry) OrdersInCurrentQuarter() Condition
OrdersInCurrentQuarter 预置条件:订单创建时间在当前季度。
func (DatePresetRegistry) OrdersInCurrentQuarterBy ¶ added in v1.0.0
func (DatePresetRegistry) OrdersInCurrentQuarterBy(timeField string) Condition
OrdersInCurrentQuarterBy 可配置版本。
type DateShardingGranularity ¶ added in v1.0.0
type DateShardingGranularity string
DateShardingGranularity 日期分表粒度。
const ( DateShardingByYear DateShardingGranularity = "year" DateShardingByMonth DateShardingGranularity = "month" DateShardingByDay DateShardingGranularity = "day" )
type DefaultSQLDialect ¶
type DefaultSQLDialect struct {
// contains filtered or unexported fields
}
DefaultSQLDialect 默认 SQL 方言(MySQL 兼容)
func (*DefaultSQLDialect) GenerateLimitOffset ¶
func (d *DefaultSQLDialect) GenerateLimitOffset(limit *int, offset *int) string
func (*DefaultSQLDialect) GetPlaceholder ¶
func (d *DefaultSQLDialect) GetPlaceholder(index int) string
func (*DefaultSQLDialect) Name ¶
func (d *DefaultSQLDialect) Name() string
func (*DefaultSQLDialect) QuoteIdentifier ¶
func (d *DefaultSQLDialect) QuoteIdentifier(name string) string
func (*DefaultSQLDialect) QuoteValue ¶
func (d *DefaultSQLDialect) QuoteValue(value interface{}) string
func (*DefaultSQLDialect) TranslateCondition ¶
func (d *DefaultSQLDialect) TranslateCondition(condition Condition, argIndex *int) (string, []interface{}, error)
type DefaultSQLQueryConstructorProvider ¶
type DefaultSQLQueryConstructorProvider struct {
// contains filtered or unexported fields
}
DefaultSQLQueryConstructorProvider 默认 SQL 查询构造器提供者
func NewDefaultSQLQueryConstructorProvider ¶
func NewDefaultSQLQueryConstructorProvider(dialect SQLDialect) *DefaultSQLQueryConstructorProvider
NewDefaultSQLQueryConstructorProvider 创建默认 SQL 查询构造器提供者
func (*DefaultSQLQueryConstructorProvider) GetCapabilities ¶
func (p *DefaultSQLQueryConstructorProvider) GetCapabilities() *QueryBuilderCapabilities
GetCapabilities 获取查询能力声明
func (*DefaultSQLQueryConstructorProvider) NewQueryConstructor ¶
func (p *DefaultSQLQueryConstructorProvider) NewQueryConstructor(schema Schema) QueryConstructor
NewQueryConstructor 创建新的查询构造器
func (*DefaultSQLQueryConstructorProvider) SetCompiler ¶ added in v1.0.0
func (p *DefaultSQLQueryConstructorProvider) SetCompiler(compiler QueryCompiler) *DefaultSQLQueryConstructorProvider
SetCompiler 设置该 provider 使用的查询编译器。 可用于按 adapter 方言增强 SQL 编译,或替换为其他目标语言编译器。
type DefaultSQLTranslator ¶
type DefaultSQLTranslator struct {
// contains filtered or unexported fields
}
DefaultSQLTranslator 默认 SQL 转义器
func (*DefaultSQLTranslator) TranslateComposite ¶
func (t *DefaultSQLTranslator) TranslateComposite(operator string, conditions []Condition) (string, []interface{}, error)
TranslateComposite 转义复合条件(AND/OR)
func (*DefaultSQLTranslator) TranslateCondition ¶
func (t *DefaultSQLTranslator) TranslateCondition(condition Condition) (string, []interface{}, error)
TranslateCondition 转义单个条件
type DialectAwareQueryCompiler ¶ added in v1.0.0
type DialectAwareQueryCompiler interface {
SetDialect(dialect SQLDialect)
}
DialectAwareQueryCompiler 可感知 SQL 方言的编译器。
type DomainTypeBuilder ¶ added in v1.0.0
type DomainTypeBuilder struct {
// contains filtered or unexported fields
}
DomainTypeBuilder 构建 PostgreSQL DOMAIN 类型 DDL。
func (*DomainTypeBuilder) BaseType ¶ added in v1.0.0
func (b *DomainTypeBuilder) BaseType(pgType string) *DomainTypeBuilder
BaseType 设置 DOMAIN 的基础类型,如 "TEXT"、"INTEGER"、"NUMERIC(10,2)"。
func (*DomainTypeBuilder) Build ¶ added in v1.0.0
func (b *DomainTypeBuilder) Build() (string, error)
Build 生成 CREATE DOMAIN DDL 字符串,不执行。
func (*DomainTypeBuilder) Check ¶ added in v1.0.0
func (b *DomainTypeBuilder) Check(expression string) *DomainTypeBuilder
Check 添加一个 CHECK 约束,expression 中用 VALUE 代表域的当前值。 可多次调用以附加多个约束。
示例:Check(`VALUE ~ '^[^@]+@[^@]+$'`)
func (*DomainTypeBuilder) CheckNamed ¶ added in v1.0.0
func (b *DomainTypeBuilder) CheckNamed(constraintName, expression string) *DomainTypeBuilder
CheckNamed 添加一个带命名的 CHECK 约束
示例:CheckNamed("positive", "VALUE > 0")
func (*DomainTypeBuilder) Create ¶ added in v1.0.0
func (b *DomainTypeBuilder) Create(ctx context.Context) error
Create 在数据库中创建 DOMAIN 类型。
func (*DomainTypeBuilder) Default ¶ added in v1.0.0
func (b *DomainTypeBuilder) Default(expr string) *DomainTypeBuilder
Default 设置默认值表达式(PL/pgSQL 表达式字符串)。
func (*DomainTypeBuilder) Drop ¶ added in v1.0.0
func (b *DomainTypeBuilder) Drop(ctx context.Context, ifExists bool) error
Drop 删除 DOMAIN 类型。
func (*DomainTypeBuilder) Exists ¶ added in v1.0.0
func (b *DomainTypeBuilder) Exists(ctx context.Context) (bool, error)
Exists 检查该 DOMAIN 类型是否已存在。
func (*DomainTypeBuilder) IfNotExists ¶ added in v1.0.0
func (b *DomainTypeBuilder) IfNotExists() *DomainTypeBuilder
IfNotExists 若类型已存在则静默跳过。
func (*DomainTypeBuilder) NotNull ¶ added in v1.0.0
func (b *DomainTypeBuilder) NotNull() *DomainTypeBuilder
NotNull 添加 NOT NULL 约束。
func (*DomainTypeBuilder) Schema ¶ added in v1.0.0
func (b *DomainTypeBuilder) Schema(schema string) *DomainTypeBuilder
Schema 可选:指定类型所在的 schema。
type DynamicTableConfig ¶
type DynamicTableConfig struct {
// 表名称
TableName string
// 表描述
Description string
// 表字段定义
Fields []*DynamicTableField
// 触发条件:关联的父表(当父表插入或更新时触发建表)
ParentTable string
// 触发条件:检查父表的字段值
// 例如:type = 'custom' 时才创建此动态表
TriggerCondition string
// 表创建策略:auto 自动创建,manual 手动创建
Strategy string // "auto" or "manual"
// 额外参数(适配器特定)
Options map[string]interface{}
}
DynamicTableConfig 动态表配置 定义触发条件和表的创建规则
func NewDynamicTableConfig ¶
func NewDynamicTableConfig(tableName string) *DynamicTableConfig
NewDynamicTableConfig 创建新的动态表配置
func (*DynamicTableConfig) AddField ¶
func (c *DynamicTableConfig) AddField(field *DynamicTableField) *DynamicTableConfig
AddField 添加字段到动态表配置
func (*DynamicTableConfig) WithDescription ¶
func (c *DynamicTableConfig) WithDescription(desc string) *DynamicTableConfig
WithDescription 设置描述
func (*DynamicTableConfig) WithOption ¶
func (c *DynamicTableConfig) WithOption(key string, value interface{}) *DynamicTableConfig
WithOption 设置选项
func (*DynamicTableConfig) WithParentTable ¶
func (c *DynamicTableConfig) WithParentTable(parentTable, triggerCondition string) *DynamicTableConfig
WithParentTable 设置父表(用于自动触发)
func (*DynamicTableConfig) WithStrategy ¶
func (c *DynamicTableConfig) WithStrategy(strategy string) *DynamicTableConfig
WithStrategy 设置创建策略
type DynamicTableField ¶
type DynamicTableField struct {
Name string
Type FieldType
Primary bool
Autoinc bool
Null bool
Default interface{}
Index bool
Unique bool
Description string
}
DynamicTableField 动态表的字段定义
func NewDynamicTableField ¶
func NewDynamicTableField(name string, fieldType FieldType) *DynamicTableField
NewDynamicTableField 创建新的字段
func (*DynamicTableField) AsNotNull ¶
func (f *DynamicTableField) AsNotNull() *DynamicTableField
AsNotNull 设置为 NOT NULL
func (*DynamicTableField) AsPrimaryKey ¶
func (f *DynamicTableField) AsPrimaryKey() *DynamicTableField
AsPrimaryKey 设置为主键
func (*DynamicTableField) WithAutoinc ¶
func (f *DynamicTableField) WithAutoinc() *DynamicTableField
WithAutoinc 启用自增
func (*DynamicTableField) WithDefault ¶
func (f *DynamicTableField) WithDefault(value interface{}) *DynamicTableField
WithDefault 设置默认值
func (*DynamicTableField) WithDescription ¶
func (f *DynamicTableField) WithDescription(desc string) *DynamicTableField
WithDescription 设置字段描述
func (*DynamicTableField) WithIndex ¶
func (f *DynamicTableField) WithIndex() *DynamicTableField
WithIndex 添加索引
func (*DynamicTableField) WithUnique ¶
func (f *DynamicTableField) WithUnique() *DynamicTableField
WithUnique 添加唯一约束
type DynamicTableHook ¶
type DynamicTableHook interface {
// 注册动态表配置
RegisterDynamicTable(ctx context.Context, config *DynamicTableConfig) error
// 注销动态表配置
UnregisterDynamicTable(ctx context.Context, configName string) error
// 列出所有已注册的动态表配置
ListDynamicTableConfigs(ctx context.Context) ([]*DynamicTableConfig, error)
// 获取特定的动态表配置
GetDynamicTableConfig(ctx context.Context, configName string) (*DynamicTableConfig, error)
// 手动触发动态表创建(当 Strategy = manual 时)
CreateDynamicTable(ctx context.Context, configName string, params map[string]interface{}) (string, error)
// 获取已创建的动态表列表
ListCreatedDynamicTables(ctx context.Context, configName string) ([]string, error)
}
DynamicTableHook 动态表钩子接口 实现者需要在适配器中实现此接口
type DynamicTableRegistry ¶
type DynamicTableRegistry struct {
// contains filtered or unexported fields
}
DynamicTableRegistry 动态表配置注册表
func NewDynamicTableRegistry ¶
func NewDynamicTableRegistry() *DynamicTableRegistry
NewDynamicTableRegistry 创建动态表注册表
func (*DynamicTableRegistry) Get ¶
func (r *DynamicTableRegistry) Get(name string) (*DynamicTableConfig, error)
Get 获取配置
func (*DynamicTableRegistry) List ¶
func (r *DynamicTableRegistry) List() []*DynamicTableConfig
List 列出所有配置
func (*DynamicTableRegistry) Register ¶
func (r *DynamicTableRegistry) Register(name string, config *DynamicTableConfig) error
Register 注册配置
func (*DynamicTableRegistry) Unregister ¶
func (r *DynamicTableRegistry) Unregister(name string) error
Unregister 注销配置
type EmailValidator ¶
type EmailValidator struct {
Locale string
}
EmailValidator 邮箱格式验证器
func NewEmailValidatorForLocale ¶ added in v1.0.0
func NewEmailValidatorForLocale(locale string) *EmailValidator
func (*EmailValidator) Validate ¶
func (v *EmailValidator) Validate(value interface{}) error
func (*EmailValidator) ValidateWithLocale ¶ added in v1.0.0
func (v *EmailValidator) ValidateWithLocale(value interface{}, locale string) error
type EnumTypeBuilder ¶ added in v1.0.0
type EnumTypeBuilder struct {
// contains filtered or unexported fields
}
EnumTypeBuilder 构建 PostgreSQL ENUM 类型 DDL。
func (*EnumTypeBuilder) Build ¶ added in v1.0.0
func (b *EnumTypeBuilder) Build() (string, error)
Build 生成 CREATE TYPE ... AS ENUM DDL 字符串,不执行。
func (*EnumTypeBuilder) Create ¶ added in v1.0.0
func (b *EnumTypeBuilder) Create(ctx context.Context) error
Create 在数据库中创建 ENUM 类型。 若 IfNotExists() 已设置,且类型已存在则静默跳过。
func (*EnumTypeBuilder) Drop ¶ added in v1.0.0
func (b *EnumTypeBuilder) Drop(ctx context.Context, ifExists bool) error
Drop 删除 ENUM 类型。ifExists 为 true 时使用 DROP TYPE ... CASCADE IF EXISTS。
func (*EnumTypeBuilder) Exists ¶ added in v1.0.0
func (b *EnumTypeBuilder) Exists(ctx context.Context) (bool, error)
Exists 检查该 ENUM 类型是否已存在于数据库中。
func (*EnumTypeBuilder) IfNotExists ¶ added in v1.0.0
func (b *EnumTypeBuilder) IfNotExists() *EnumTypeBuilder
IfNotExists 如果类型已存在则跳过,不报错。 实现方式:先检查 pg_type,不支持 CREATE TYPE IF NOT EXISTS 语法(PG 不支持该语法)。
func (*EnumTypeBuilder) Schema ¶ added in v1.0.0
func (b *EnumTypeBuilder) Schema(schema string) *EnumTypeBuilder
Schema 可选:指定类型所在的 schema(默认 public)。
func (*EnumTypeBuilder) Values ¶ added in v1.0.0
func (b *EnumTypeBuilder) Values(vals ...string) *EnumTypeBuilder
Values 设置枚举允许的字面值列表(顺序有意义,PostgreSQL 会按此顺序排序比较)。
type FKOption ¶ added in v1.0.0
type FKOption func(*TableConstraint)
FKOption 外键约束选项(函数选项模式)。
func WithJoinType ¶ added in v1.0.0
WithJoinType 为外键约束的视图提示指定 JOIN 类型("LEFT" / "INNER" / "RIGHT")。 仅当已通过 WithViewHint 设置视图提示时才有效。
func WithViewHint ¶ added in v1.0.0
WithViewHint 为外键约束附加视图提示,声明该关联的热点查询视图。
// 创建 user_orders_view,查询 orders JOIN users:
schema.AddForeignKey("fk_orders_users",
[]string{"user_id"}, "users", []string{"id"}, "CASCADE", "",
WithViewHint("user_orders_view", false))
type FeatureCategory ¶
type FeatureCategory string
FeatureCategory 特性分类
const ( CategoryIndexing FeatureCategory = "indexing" // 索引和约束 CategoryTypes FeatureCategory = "types" // 自定义类型 CategoryFunctions FeatureCategory = "functions" // 函数和存储过程 CategoryAdvanced FeatureCategory = "advanced" // 高级查询 CategoryJSON FeatureCategory = "json" // JSON 支持 CategoryFullText FeatureCategory = "full_text" // 全文搜索 CategoryOther FeatureCategory = "other" // 其他特性 )
type FeatureComparison ¶
type FeatureComparison struct {
Database1 string
Database2 string
CommonFeatures []string // 共同支持的特性
OnlyInFirst []string // 仅第一个数据库支持
OnlyInSecond []string // 仅第二个数据库支持
}
FeatureComparison 特性比较结果
func CompareFeatures ¶
func CompareFeatures(f1, f2 *DatabaseFeatures) *FeatureComparison
CompareFeatures 比较两个数据库的特性差异
type FeatureExecutionDecision ¶ added in v1.0.0
type FeatureExecutionDecision struct {
Mode FeatureExecutionMode
Fallback FeatureFallback
Reason string
}
FeatureExecutionDecision 功能执行决策结果
type FeatureExecutionMode ¶ added in v1.0.0
type FeatureExecutionMode string
FeatureExecutionMode 功能执行模式 native: 使用数据库原生能力 custom: 使用 adapter 自定义实现 fallback: 使用降级策略 unsupported: 不支持且无替代方案
const ( FeatureExecutionNative FeatureExecutionMode = "native" FeatureExecutionCustom FeatureExecutionMode = "custom" FeatureExecutionFallback FeatureExecutionMode = "fallback" FeatureExecutionUnsupported FeatureExecutionMode = "unsupported" )
type FeatureFallback ¶
type FeatureFallback string
FeatureFallback 特性降级策略
const ( FallbackNone FeatureFallback = "none" // 不支持,返回错误 FallbackCheckConstraint FeatureFallback = "check_constraint" // 使用 CHECK 约束 FallbackDynamicTable FeatureFallback = "dynamic_table" // 使用动态类型表 FallbackApplicationLayer FeatureFallback = "application_layer" // 应用层处理 )
type FeatureSupport ¶
type FeatureSupport struct {
Supported bool // 是否支持
MinVersion string // 最低支持版本(可选)
Notes string // 备注说明(可选)
}
FeatureSupport 特性支持建模(支持版本与备注)
type Field ¶
type Field struct {
Name string
Type FieldType
Default interface{}
Null bool
Primary bool
Autoinc bool
Index bool
Unique bool
Validators []Validator
Transformers []Transformer
}
Field 定义模式中的字段
type FieldBuilder ¶
type FieldBuilder struct {
// contains filtered or unexported fields
}
FieldBuilder 字段构造器
func (*FieldBuilder) Default ¶
func (fb *FieldBuilder) Default(value interface{}) *FieldBuilder
Default 设置默认值
func (*FieldBuilder) PrimaryKey ¶
func (fb *FieldBuilder) PrimaryKey() *FieldBuilder
PrimaryKey 标记为主键
func (*FieldBuilder) Transform ¶
func (fb *FieldBuilder) Transform(transformer Transformer) *FieldBuilder
Transform 添加转换器
func (*FieldBuilder) Validate ¶
func (fb *FieldBuilder) Validate(validator Validator) *FieldBuilder
Validate 添加验证器
type FieldType ¶
type FieldType string
FieldType 字段类型定义
const ( TypeString FieldType = "string" TypeInteger FieldType = "integer" TypeFloat FieldType = "float" TypeBoolean FieldType = "boolean" TypeTime FieldType = "time" TypeBinary FieldType = "binary" TypeDecimal FieldType = "decimal" TypeMap FieldType = "map" TypeArray FieldType = "array" TypeJSON FieldType = "json" TypeLocation FieldType = "location" )
type ForeignKeyAction ¶
type ForeignKeyAction string
const ( ActionRestrict ForeignKeyAction = "RESTRICT" ActionCascade ForeignKeyAction = "CASCADE" ActionSetNull ForeignKeyAction = "SET NULL" ActionNoAction ForeignKeyAction = "NO ACTION" )
type ForeignKeyDef ¶
type ForeignKeyDef struct {
// 源表的列
FromColumn string
// 目标表的列
ToColumn string
// 级联删除
OnDelete ForeignKeyAction
OnUpdate ForeignKeyAction
}
ForeignKeyDef 外键定义
type FullTextRuntimeCapability ¶ added in v1.0.0
type FullTextRuntimeCapability struct {
NativeSupported bool
PluginChecked bool
PluginAvailable bool
PluginName string
TokenizationSupported bool
TokenizationMode string
Notes string
}
FullTextRuntimeCapability 运行时全文检索能力探测结果
type FullTextRuntimeInspector ¶ added in v1.0.0
type FullTextRuntimeInspector interface {
InspectFullTextRuntime(ctx context.Context) (*FullTextRuntimeCapability, error)
}
FullTextRuntimeInspector 适配器可选接口:用于运行时探测全文与分词能力
type FuzzySearchPlan ¶ added in v1.0.0
FuzzySearchPlan 模糊查询执行计划
type IDCardValidator ¶ added in v1.0.0
type IDCardValidator struct {
Locale string
}
IDCardValidator 身份证号验证器(中国大陆 15/18 位) 它是 RegexValidator 的特化封装。
func NewIDCardValidatorForLocale ¶ added in v1.0.0
func NewIDCardValidatorForLocale(locale string) *IDCardValidator
func (*IDCardValidator) Validate ¶ added in v1.0.0
func (v *IDCardValidator) Validate(value interface{}) error
func (*IDCardValidator) ValidateWithLocale ¶ added in v1.0.0
func (v *IDCardValidator) ValidateWithLocale(value interface{}, locale string) error
type JSONRuntimeCapability ¶ added in v1.0.0
type JSONRuntimeCapability struct {
// JSON 函数能力是否可用(如 ISJSON/JSON_VALUE 或 json/jsonb 操作能力)。
NativeSupported bool
// 是否支持原生 JSON 数据类型(而非文本承载)。
NativeJSONTypeSupported bool
// 运行时检测到的引擎版本信息。
Version string
// 是否执行了插件检测(某些数据库 JSON 为内建能力,该值可为 false)。
PluginChecked bool
// 是否检测到插件(若插件不适用则为 false)。
PluginAvailable bool
// 检测到的插件名或说明。
PluginName string
// 额外说明(升级建议、降级建议等)。
Notes string
}
JSONRuntimeCapability JSON 能力运行时探测结果。
type JSONRuntimeInspector ¶ added in v1.0.0
type JSONRuntimeInspector interface {
InspectJSONRuntime(ctx context.Context) (*JSONRuntimeCapability, error)
}
JSONRuntimeInspector 适配器可选接口:用于运行时探测 JSON 能力。
type JoinBuilder ¶ added in v1.1.0
type JoinBuilder struct {
// contains filtered or unexported fields
}
JoinBuilder 连接构造器,携带目标 Schema,支持跨数据库通用表达。
以语义意图(JoinSemantic)驱动,无需关心 SQL JOIN 方向细节:
- SQL 后端:semantic → INNER/LEFT/CROSS JOIN;On() 字符串作为 ON 子句; Filter() 以 join alias 限定后追加到 WHERE。
- Neo4j 后端:semantic → MATCH / OPTIONAL MATCH;On() 为空时从 Schema FK 推断关系类型;Filter() 转换为节点属性过滤。
func NewCrossJoin ¶ added in v1.1.0
func NewCrossJoin(schema Schema) *JoinBuilder
NewCrossJoin 创建 CROSS JOIN builder(无 ON 条件)。
func NewInnerJoin ¶ added in v1.1.0
func NewInnerJoin(schema Schema) *JoinBuilder
NewInnerJoin 创建 INNER JOIN builder(等同于 NewRequiredJoin)。
func NewJoinBuilder ¶ added in v1.1.0
func NewJoinBuilder(joinType string, schema Schema) *JoinBuilder
NewJoinBuilder 创建 JoinBuilder(兼容旧代码;推荐改用 NewJoinWith / NewRequiredJoin / NewOptionalJoin)。
func NewJoinWith ¶ added in v1.1.0
func NewJoinWith(schema Schema) *JoinBuilder
NewJoinWith 创建 Schema 感知 JoinBuilder,语义由 Schema FK 关系自动推断。 FK 字段 Null:true → 自动使用 optional(LEFT JOIN / OPTIONAL MATCH);否则 → required。 可通过 .Required() / .Optional() 显式覆盖。
func NewLeftJoin ¶ added in v1.1.0
func NewLeftJoin(schema Schema) *JoinBuilder
NewLeftJoin 创建 LEFT JOIN builder(等同于 NewOptionalJoin)。
func NewOptionalJoin ¶ added in v1.1.0
func NewOptionalJoin(schema Schema) *JoinBuilder
NewOptionalJoin 创建语义为"可选匹配"的 JoinBuilder(SQL: LEFT JOIN;Neo4j: OPTIONAL MATCH)。
func NewRequiredJoin ¶ added in v1.1.0
func NewRequiredJoin(schema Schema) *JoinBuilder
NewRequiredJoin 创建语义为"必须匹配"的 JoinBuilder(SQL: INNER JOIN;Neo4j: MATCH)。
func NewRightJoin ¶ added in v1.1.0
func NewRightJoin(schema Schema) *JoinBuilder
NewRightJoin 创建 RIGHT JOIN builder。 注意:RIGHT JOIN 在 NoSQL 适配器中无方向概念,统一视为 optional 语义,跨数据库均安全。
func (*JoinBuilder) As ¶ added in v1.1.0
func (b *JoinBuilder) As(alias string) *JoinBuilder
As 设置连接别名。
func (*JoinBuilder) Filter ¶ added in v1.1.0
func (b *JoinBuilder) Filter(conds ...Condition) *JoinBuilder
Filter 追加对连接目标实体的过滤条件。 SQL: 以 join alias 限定后追加到 WHERE 子句。 Neo4j: 转换为对连接节点的属性过滤(WHERE alias.prop op val)。
func (*JoinBuilder) On ¶ added in v1.1.0
func (b *JoinBuilder) On(expr string) *JoinBuilder
On 设置连接表达式。 SQL: 直接作为 ON <expr>,例如 "users.id = orders.user_id"。 Neo4j: 关系模式字符串,例如 "->[:OWNS]->" 或 "<-[:BELONGS_TO]-"。 为空时 Neo4j 编译器自动从目标 Schema 的 FK 约束推断关系类型。
func (*JoinBuilder) Optional ¶ added in v1.1.0
func (b *JoinBuilder) Optional() *JoinBuilder
Optional 显式设置语义为"可选匹配",覆盖自动推断。
func (*JoinBuilder) Required ¶ added in v1.1.0
func (b *JoinBuilder) Required() *JoinBuilder
Required 显式设置语义为"必须匹配",覆盖自动推断。
type JoinSemantic ¶ added in v1.1.0
type JoinSemantic string
JoinSemantic 表达 JOIN 的语义意图,与 SQL 方言和数据库类型无关。 适配器根据此语义自行选择最优实现(JOIN 关键词、关系模式、MATCH 类型等)。
const ( // JoinSemanticRequired 必须匹配:双方都必须存在(SQL: INNER JOIN;Neo4j: MATCH)。 JoinSemanticRequired JoinSemantic = "required" // JoinSemanticOptional 连接目标可不存在(SQL: LEFT JOIN;Neo4j: OPTIONAL MATCH)。 JoinSemanticOptional JoinSemantic = "optional" // JoinSemanticCross 笛卡尔积(SQL: CROSS JOIN;Neo4j: 独立 MATCH)。 JoinSemanticCross JoinSemantic = "cross" // JoinSemanticInfer 由 Schema FK 关系自动推断(默认值): // FK 字段 Null:true → JoinSemanticOptional;否则 → JoinSemanticRequired。 JoinSemanticInfer JoinSemantic = "" )
type JoinTableDef ¶
type JoinTableDef struct {
// 关联表名称
TableName string
// 源表外键列和目标表外键列
FromForeignKey string
ToForeignKey string
// 额外的列(如时间戳等)
ExtraColumns []*Field
}
JoinTableDef 关联表定义(多对多)
type LengthValidator ¶
LengthValidator 长度验证器
func (*LengthValidator) Validate ¶
func (v *LengthValidator) Validate(value interface{}) error
type LocalCacheStats ¶ added in v1.0.0
LocalCacheStats 返回当前缓存状态统计(总条目数、已过期、有效)。
type LocaleAwareValidator ¶ added in v1.0.0
LocaleAwareValidator 可感知 locale 的验证器接口。
type LowercaseTransformer ¶
type LowercaseTransformer struct{}
LowercaseTransformer 小写转换器
func (*LowercaseTransformer) Transform ¶
func (t *LowercaseTransformer) Transform(value interface{}) (interface{}, error)
type MaxLengthValidator ¶
type MaxLengthValidator struct {
Length int
}
MaxLengthValidator 最大长度验证器
func (*MaxLengthValidator) Validate ¶
func (v *MaxLengthValidator) Validate(value interface{}) error
type Migration ¶
type Migration struct {
// 版本号 (时间戳格式): 20260131100000
Version string
// 描述
Description string
// 迁移的 SQL 语句
UpSQL []string
// 回滚的 SQL 语句
DownSQL []string
}
Migration 表示一个数据库迁移
type MigrationInterface ¶
type MigrationInterface interface {
// Up 执行迁移
Up(ctx context.Context, repo *Repository) error
// Down 回滚迁移
Down(ctx context.Context, repo *Repository) error
// Version 返回迁移版本号(通常是时间戳)
Version() string
// Description 返回迁移描述
Description() string
}
Migration 接口 - 每个迁移文件都需要实现这个接口
type MigrationLog ¶
MigrationLog 迁移日志记录
type MigrationOperation ¶ added in v1.0.3
type MigrationOperation struct {
Kind MigrationOperationKind
Version string
Description string
AppliedAt time.Time
}
MigrationOperation 是迁移执行层的统一操作描述。 v1.1 起,迁移运行器应只表达操作意图,不直接拼接方言 SQL。
type MigrationOperationKind ¶ added in v1.0.3
type MigrationOperationKind string
MigrationOperationKind 表示迁移操作类型。
const ( MigrationOpRecordApplied MigrationOperationKind = "record_applied" MigrationOpRemoveApplied MigrationOperationKind = "remove_applied" )
type MigrationRunner ¶
type MigrationRunner struct {
// contains filtered or unexported fields
}
MigrationRunner 迁移运行器
func NewMigrationRunner ¶
func NewMigrationRunner(repo *Repository) *MigrationRunner
NewMigrationRunner 创建迁移运行器
func (*MigrationRunner) Down ¶
func (r *MigrationRunner) Down(ctx context.Context) error
Down 回滚最后一个迁移
func (*MigrationRunner) Register ¶
func (r *MigrationRunner) Register(migration MigrationInterface)
Register 注册迁移
func (*MigrationRunner) Status ¶
func (r *MigrationRunner) Status(ctx context.Context) ([]MigrationStatus, error)
Status 显示迁移状态
type MigrationStatus ¶
MigrationStatus 迁移状态
type Migrator ¶
type Migrator struct {
// contains filtered or unexported fields
}
Migrator 迁移器
type MinLengthValidator ¶
type MinLengthValidator struct {
Length int
}
MinLengthValidator 最小长度验证器
func (*MinLengthValidator) Validate ¶
func (v *MinLengthValidator) Validate(value interface{}) error
type MongoAdapter ¶
type MongoAdapter struct {
// contains filtered or unexported fields
}
MongoAdapter MongoDB 适配器(最小可用版本:连接/健康检查)
func NewMongoAdapter ¶
func NewMongoAdapter(config *Config) (*MongoAdapter, error)
NewMongoAdapter 创建 MongoAdapter(不建立连接)
func (*MongoAdapter) Begin ¶
func (a *MongoAdapter) Begin(ctx context.Context, opts ...interface{}) (Tx, error)
Begin MongoDB 不支持 SQL 事务接口
func (*MongoAdapter) Connect ¶
func (a *MongoAdapter) Connect(ctx context.Context, config *Config) error
Connect 建立 MongoDB 连接
func (*MongoAdapter) Exec ¶
func (a *MongoAdapter) Exec(ctx context.Context, sql string, args ...interface{}) (sql.Result, error)
Exec MongoDB 不支持 SQL Exec
func (*MongoAdapter) ExecuteCompiledFindPlan ¶ added in v1.0.0
func (a *MongoAdapter) ExecuteCompiledFindPlan(ctx context.Context, query string) ([]map[string]interface{}, error)
ExecuteCompiledFindPlan 执行由 MongoQueryConstructor 生成的 Find 计划。
func (*MongoAdapter) ExecuteCompiledWritePlan ¶ added in v1.0.0
func (a *MongoAdapter) ExecuteCompiledWritePlan(ctx context.Context, query string) (*QueryConstructorExecSummary, error)
ExecuteCompiledWritePlan 执行由 MongoQueryConstructor 生成的写入计划。
func (*MongoAdapter) ExecuteCustomFeature ¶ added in v1.0.0
func (a *MongoAdapter) ExecuteCustomFeature(ctx context.Context, feature string, input map[string]interface{}) (interface{}, error)
ExecuteCustomFeature 执行 MongoDB 的自定义能力(当前提供 document join 方案)
func (*MongoAdapter) GetDatabaseFeatures ¶
func (a *MongoAdapter) GetDatabaseFeatures() *DatabaseFeatures
GetDatabaseFeatures MongoDB 特性声明(最小实现)
func (*MongoAdapter) GetQueryBuilderProvider ¶
func (a *MongoAdapter) GetQueryBuilderProvider() QueryConstructorProvider
GetQueryBuilderProvider 返回 MongoDB BSON Query Builder Provider。
func (*MongoAdapter) GetQueryFeatures ¶
func (a *MongoAdapter) GetQueryFeatures() *QueryFeatures
GetQueryFeatures MongoDB 查询特性声明(最小实现)
func (*MongoAdapter) GetRawConn ¶
func (a *MongoAdapter) GetRawConn() interface{}
GetRawConn 返回 mongo.Client
func (*MongoAdapter) HasCustomFeatureImplementation ¶ added in v1.0.0
func (a *MongoAdapter) HasCustomFeatureImplementation(feature string) bool
HasCustomFeatureImplementation 声明 MongoDB 可用的自定义能力
func (*MongoAdapter) InspectFullTextRuntime ¶ added in v1.0.0
func (a *MongoAdapter) InspectFullTextRuntime(ctx context.Context) (*FullTextRuntimeCapability, error)
InspectFullTextRuntime MongoDB 运行时全文能力说明。 这里不依赖插件检测,默认给出应用层分词可用的能力声明。
func (*MongoAdapter) ListScheduledTasks ¶
func (a *MongoAdapter) ListScheduledTasks(ctx context.Context) ([]*ScheduledTaskStatus, error)
ListScheduledTasks MongoDB 暂不支持定时任务
func (*MongoAdapter) Query ¶
func (a *MongoAdapter) Query(ctx context.Context, sql string, args ...interface{}) (*sql.Rows, error)
Query MongoDB 不支持 SQL Query
func (*MongoAdapter) RegisterScheduledTask ¶
func (a *MongoAdapter) RegisterScheduledTask(ctx context.Context, task *ScheduledTaskConfig) error
RegisterScheduledTask MongoDB 暂不支持定时任务
func (*MongoAdapter) UnregisterScheduledTask ¶
func (a *MongoAdapter) UnregisterScheduledTask(ctx context.Context, taskName string) error
UnregisterScheduledTask MongoDB 暂不支持定时任务
type MongoCompiledFindPlan ¶ added in v1.0.0
type MongoCompiledFindPlan struct {
Collection string `json:"collection"`
Filter map[string]interface{} `json:"filter"`
Projection []string `json:"projection,omitempty"`
Sort []MongoSortField `json:"sort,omitempty"`
Limit *int `json:"limit,omitempty"`
Offset *int `json:"offset,omitempty"`
Lookups []MongoLookupStage `json:"lookups,omitempty"` // $lookup 聚合阶段参数列表
}
MongoCompiledFindPlan 是 Mongo QueryConstructor 编译后的可执行计划。
type MongoCompiledWritePlan ¶ added in v1.0.0
type MongoCompiledWritePlan struct {
Operation string `json:"operation"`
Collection string `json:"collection"`
Filter map[string]interface{} `json:"filter,omitempty"`
Update map[string]interface{} `json:"update,omitempty"`
Document map[string]interface{} `json:"document,omitempty"`
Documents []map[string]interface{} `json:"documents,omitempty"`
Upsert bool `json:"upsert,omitempty"`
ReturnInsertedID bool `json:"return_inserted_id,omitempty"`
ReturnWriteDetail bool `json:"return_write_detail,omitempty"`
}
MongoCompiledWritePlan 是 Mongo 写入计划。 Operation 支持 insert_one / insert_many / update_many / delete_many。
type MongoConnectionConfig ¶ added in v1.0.0
type MongoConnectionConfig struct {
URI string `json:"uri,omitempty" yaml:"uri,omitempty"`
Database string `json:"database,omitempty" yaml:"database,omitempty"`
RelationJoinStrategy string `json:"relation_join_strategy,omitempty" yaml:"relation_join_strategy,omitempty"` // "lookup" | "pipeline"
HideThroughArtifacts *bool `json:"hide_through_artifacts,omitempty" yaml:"hide_through_artifacts,omitempty"` // 默认 true
}
MongoConnectionConfig MongoDB 连接配置。
type MongoFactory ¶
type MongoFactory struct{}
MongoFactory AdapterFactory 实现
func (*MongoFactory) Name ¶
func (f *MongoFactory) Name() string
type MongoLocalCache ¶ added in v1.0.0
type MongoLocalCache struct {
// contains filtered or unexported fields
}
MongoLocalCache 提供"预加载集合到内存"的本地缓存能力, 用于替代 MongoDB 代价高昂的 $lookup 连表操作和全文搜索预热。
典型场景:
- 字典表、角色权限表等体积小且读多写少的集合:整体预加载后做应用层 JOIN, 避免每次请求都触发 $lookup aggregation。
- 应用层全文搜索预热:把需要搜索的文档拉进内存,配合 fuzzy 搜索库使用。
并发安全:内部使用 sync.RWMutex,多读单写,读路径无锁争用。
示例:
cache, ok := db.GetMongoLocalCache(repo.GetAdapter())
_ = cache.Preload(ctx, "roles", "roles", nil, nil, 10*time.Minute)
roles, _ := cache.Get("roles")
// 应用层 JOIN:把用户列表的 role_id 字段和已缓存的 roles 集合关联
enriched := cache.JoinWith(users, "role_id", "roles", "_id", "role", false)
func GetMongoLocalCache ¶ added in v1.0.0
func GetMongoLocalCache(adapter Adapter) (*MongoLocalCache, bool)
GetMongoLocalCache 从 Adapter 获取 MongoLocalCache。 若 adapter 不是 *MongoAdapter,返回 (nil, false)。
func (*MongoLocalCache) ForcePreload ¶ added in v1.0.0
func (c *MongoLocalCache) ForcePreload(ctx context.Context, name, collection string, filter, projection bson.D, ttl time.Duration) error
ForcePreload 无视缓存状态,强制重新从 MongoDB 拉取数据并刷新本地缓存。
func (*MongoLocalCache) Get ¶ added in v1.0.0
func (c *MongoLocalCache) Get(name string) ([]bson.M, bool)
Get 获取已预加载的文档列表。 若缓存不存在或已过期返回 (nil, false)。
func (*MongoLocalCache) Invalidate ¶ added in v1.0.0
func (c *MongoLocalCache) Invalidate(name string)
Invalidate 删除指定名称的本地缓存条目(下次 Preload 会重新从 MongoDB 拉取)。
func (*MongoLocalCache) InvalidateAll ¶ added in v1.0.0
func (c *MongoLocalCache) InvalidateAll()
InvalidateAll 清空所有本地缓存条目。
func (*MongoLocalCache) JoinWith ¶ added in v1.0.0
func (c *MongoLocalCache) JoinWith(localDocs []bson.M, localKey, cacheName, cacheKey, asField string, many bool) []bson.M
JoinWith 对 localDocs 做应用层等值 JOIN,替代代价高昂的 MongoDB $lookup。
- localDocs: 主集合已查询出的文档列表(不会被修改)
- localKey: 主文档中的连接字段名(如 "role_id")
- cacheName: 维表在本地缓存中的标识符(通过 Preload 加载)
- cacheKey: 维表文档中的匹配字段名(如 "_id")
- asField: JOIN 结果写入主文档的字段名(如 "role")
- many: true = 1:N(结果为 []bson.M 切片),false = N:1(结果为首个匹配文档或 nil)
返回注入了 asField 字段的新文档列表。若缓存不存在或已过期,原样返回 localDocs。
示例(N:1,每个 user 对应一个 role):
enriched := cache.JoinWith(users, "role_id", "roles", "_id", "role", false)
func (*MongoLocalCache) Preload ¶ added in v1.0.0
func (c *MongoLocalCache) Preload(ctx context.Context, name, collection string, filter, projection bson.D, ttl time.Duration) error
Preload 按需预加载集合数据到本地内存(若缓存未过期则直接复用,不发起网络请求)。
- name: 本地缓存标识符(可与集合名不同,用于 JoinWith 等 API 的 cacheName 参数)
- collection: MongoDB 集合名
- filter: BSON 过滤条件(nil 表示加载集合全量文档)
- projection: BSON 字段投影(nil 表示返回全部字段)
- ttl: 缓存有效期(<= 0 表示永不自动过期)
func (*MongoLocalCache) Stats ¶ added in v1.0.0
func (c *MongoLocalCache) Stats() LocalCacheStats
Stats 返回缓存条目的当前统计信息。
type MongoLookupStage ¶ added in v1.1.0
type MongoLookupStage struct {
From string `json:"from"` // 目标集合名
LocalField string `json:"localField"` // 本集合中的连接字段
ForeignField string `json:"foreignField"` // 目标集合中的连接字段
As string `json:"as"` // 输出数组字段名(alias)
Semantic JoinSemantic `json:"semantic"` // optional → 保留空数组;required → 需过滤
ThroughArtifact bool `json:"throughArtifact,omitempty"` // true 表示中间关系临时字段
}
MongoLookupStage 描述一个 MongoDB $lookup 聚合阶段的参数。 对于 required 语义(BelongsTo):调用方应在 $lookup 后追加 $unwind{preserveNullAndEmptyArrays:false} 以过滤掉无匹配文档(等价于 INNER JOIN)。 对于 optional 语义(HasMany/HasOne):无需额外处理(等价于 LEFT JOIN/OPTIONAL MATCH)。
type MongoQueryConstructor ¶ added in v1.0.0
type MongoQueryConstructor struct {
// contains filtered or unexported fields
}
MongoQueryConstructor MongoDB BSON 查询构造器。 目标是复用统一 QueryConstructor 接口,在 Mongo 下编译为 BSON Find 计划。
func NewMongoQueryConstructor ¶ added in v1.0.0
func NewMongoQueryConstructor(schema Schema) *MongoQueryConstructor
func (*MongoQueryConstructor) Build ¶ added in v1.0.0
func (qb *MongoQueryConstructor) Build(ctx context.Context) (string, []interface{}, error)
func (*MongoQueryConstructor) BuildFindPlan ¶ added in v1.0.0
func (qb *MongoQueryConstructor) BuildFindPlan() (*MongoCompiledFindPlan, error)
func (*MongoQueryConstructor) Count ¶ added in v1.1.0
func (qb *MongoQueryConstructor) Count(fieldName ...string) QueryConstructor
func (*MongoQueryConstructor) CountWith ¶ added in v1.1.0
func (qb *MongoQueryConstructor) CountWith(builder *CountBuilder) QueryConstructor
func (*MongoQueryConstructor) CrossJoin ¶ added in v1.0.0
func (qb *MongoQueryConstructor) CrossJoin(table string, alias ...string) QueryConstructor
func (*MongoQueryConstructor) CrossTableStrategy ¶ added in v1.0.0
func (qb *MongoQueryConstructor) CrossTableStrategy(strategy CrossTableStrategy) QueryConstructor
func (*MongoQueryConstructor) CustomMode ¶ added in v1.1.0
func (qb *MongoQueryConstructor) CustomMode() QueryConstructor
func (*MongoQueryConstructor) DeleteMany ¶ added in v1.0.0
func (qb *MongoQueryConstructor) DeleteMany() *MongoQueryConstructor
DeleteMany 设置写入计划为批量删除。 filter 默认取 Where 条件生成的 BSON 过滤器。
func (*MongoQueryConstructor) FromAlias ¶ added in v1.0.0
func (qb *MongoQueryConstructor) FromAlias(alias string) QueryConstructor
func (*MongoQueryConstructor) GetNativeBuilder ¶ added in v1.0.0
func (qb *MongoQueryConstructor) GetNativeBuilder() interface{}
func (*MongoQueryConstructor) InsertMany ¶ added in v1.0.0
func (qb *MongoQueryConstructor) InsertMany(documents []map[string]interface{}) *MongoQueryConstructor
InsertMany 设置写入计划为批量插入。
func (*MongoQueryConstructor) InsertOne ¶ added in v1.0.0
func (qb *MongoQueryConstructor) InsertOne(document map[string]interface{}) *MongoQueryConstructor
InsertOne 设置写入计划为单文档插入。
func (*MongoQueryConstructor) Join ¶ added in v1.0.0
func (qb *MongoQueryConstructor) Join(table, onClause string, alias ...string) QueryConstructor
func (*MongoQueryConstructor) JoinWith ¶ added in v1.1.0
func (qb *MongoQueryConstructor) JoinWith(builder *JoinBuilder) QueryConstructor
func (*MongoQueryConstructor) LeftJoin ¶ added in v1.0.0
func (qb *MongoQueryConstructor) LeftJoin(table, onClause string, alias ...string) QueryConstructor
func (*MongoQueryConstructor) Limit ¶ added in v1.0.0
func (qb *MongoQueryConstructor) Limit(count int) QueryConstructor
func (*MongoQueryConstructor) Offset ¶ added in v1.0.0
func (qb *MongoQueryConstructor) Offset(count int) QueryConstructor
func (*MongoQueryConstructor) OrderBy ¶ added in v1.0.0
func (qb *MongoQueryConstructor) OrderBy(field string, direction string) QueryConstructor
func (*MongoQueryConstructor) Page ¶ added in v1.1.1
func (qb *MongoQueryConstructor) Page(page int, pageSize int) QueryConstructor
func (*MongoQueryConstructor) Paginate ¶ added in v1.1.1
func (qb *MongoQueryConstructor) Paginate(builder *PaginationBuilder) QueryConstructor
func (*MongoQueryConstructor) ReturnInsertedID ¶ added in v1.0.0
func (qb *MongoQueryConstructor) ReturnInsertedID() *MongoQueryConstructor
ReturnInsertedID 请求在写入结果中附加 inserted_id / inserted_ids(仅插入操作有效)。
func (*MongoQueryConstructor) ReturnWriteDetail ¶ added in v1.0.0
func (qb *MongoQueryConstructor) ReturnWriteDetail() *MongoQueryConstructor
ReturnWriteDetail 请求在写入结果中附加详细信息(matched/modified/upserted/deleted 等)。
func (*MongoQueryConstructor) RightJoin ¶ added in v1.0.0
func (qb *MongoQueryConstructor) RightJoin(table, onClause string, alias ...string) QueryConstructor
func (*MongoQueryConstructor) Select ¶ added in v1.0.0
func (qb *MongoQueryConstructor) Select(fields ...string) QueryConstructor
func (*MongoQueryConstructor) SelectCount ¶ added in v1.1.0
func (qb *MongoQueryConstructor) SelectCount(ctx context.Context, repo *Repository) (int64, error)
func (*MongoQueryConstructor) UpdateMany ¶ added in v1.0.0
func (qb *MongoQueryConstructor) UpdateMany(setFields map[string]interface{}, upsert bool) *MongoQueryConstructor
UpdateMany 设置写入计划为批量更新。 filter 默认取 Where 条件生成的 BSON 过滤器。
func (*MongoQueryConstructor) Upsert ¶ added in v1.1.0
func (qb *MongoQueryConstructor) Upsert(ctx context.Context, repo *Repository, cs *Changeset, conflictColumns ...string) (sql.Result, error)
func (*MongoQueryConstructor) Where ¶ added in v1.0.0
func (qb *MongoQueryConstructor) Where(condition Condition) QueryConstructor
func (*MongoQueryConstructor) WhereAll ¶ added in v1.0.0
func (qb *MongoQueryConstructor) WhereAll(conditions ...Condition) QueryConstructor
func (*MongoQueryConstructor) WhereAny ¶ added in v1.0.0
func (qb *MongoQueryConstructor) WhereAny(conditions ...Condition) QueryConstructor
func (*MongoQueryConstructor) WhereWith ¶ added in v1.1.0
func (qb *MongoQueryConstructor) WhereWith(builder *WhereBuilder) QueryConstructor
type MongoQueryConstructorProvider ¶ added in v1.0.0
type MongoQueryConstructorProvider struct{}
MongoQueryConstructorProvider MongoDB 查询构造器提供者。
func NewMongoQueryConstructorProvider ¶ added in v1.0.0
func NewMongoQueryConstructorProvider() *MongoQueryConstructorProvider
func (*MongoQueryConstructorProvider) GetCapabilities ¶ added in v1.0.0
func (p *MongoQueryConstructorProvider) GetCapabilities() *QueryBuilderCapabilities
func (*MongoQueryConstructorProvider) NewQueryConstructor ¶ added in v1.0.0
func (p *MongoQueryConstructorProvider) NewQueryConstructor(schema Schema) QueryConstructor
type MongoSortField ¶ added in v1.0.0
type MongoSortField struct {
Field string `json:"field"`
Direction int `json:"direction"` // 1=ASC, -1=DESC
}
MongoSortField 表示 Mongo 排序字段。
type MongoTTLFeatures ¶ added in v1.0.0
type MongoTTLFeatures struct {
// contains filtered or unexported fields
}
MongoTTLFeatures 提供 MongoDB TTL 索引管理和文档过期时间设置的特色能力。
MongoDB 原生支持 TTL 索引:在 Date 类型字段上建立 expireAfterSeconds 索引后, MongoDB 后台线程每 60 秒轮询一次,自动删除已过期的文档。
适用场景:Session token、临时验证码、速率限制计数器、日志保留策略等。
示例:
ttlFeat, ok := db.GetMongoTTLFeatures(repo.GetAdapter())
if !ok { ... }
_ = ttlFeat.EnsureTTLIndex(ctx, "sessions", "expires_at", 0) // 精准到期
_ = ttlFeat.InsertWithExpiry(ctx, "sessions", bson.M{"token": "abc"}, "expires_at",
time.Now().Add(30*time.Minute))
func GetMongoTTLFeatures ¶ added in v1.0.0
func GetMongoTTLFeatures(adapter Adapter) (*MongoTTLFeatures, bool)
GetMongoTTLFeatures 从 Adapter 获取 MongoDB TTL 特性视图。 若 adapter 不是 *MongoAdapter,返回 (nil, false)。
func (*MongoTTLFeatures) DropTTLIndex ¶ added in v1.0.0
func (f *MongoTTLFeatures) DropTTLIndex(ctx context.Context, collection, indexName string) error
DropTTLIndex 删除指定名称的 TTL 索引。
func (*MongoTTLFeatures) EnsureTTLIndex ¶ added in v1.0.0
func (f *MongoTTLFeatures) EnsureTTLIndex(ctx context.Context, collection, field string, expireAfter time.Duration) error
EnsureTTLIndex 在集合的指定字段上幂等地创建 TTL 索引。
- collection: MongoDB 集合名
- field: 必须是 BSON Date 类型字段(如 "expires_at"、"created_at")
- expireAfter: 文档超过字段记录时间后延迟多久被删除(0 = 精准到期)
若同名/同字段索引已存在(IndexOptionsConflict code 85/86),视为幂等成功。
func (*MongoTTLFeatures) ExtendExpiry ¶ added in v1.0.0
func (f *MongoTTLFeatures) ExtendExpiry(ctx context.Context, collection string, filter bson.D, ttlField string, newExpiry time.Time) error
ExtendExpiry 更新符合 filter 的文档的过期时间字段,实现 TTL 续期。
- filter: 用于定位目标文档的 BSON 过滤条件
- ttlField: 文档中表示过期时间点的字段名
- newExpiry: 新的过期时间点
func (*MongoTTLFeatures) InsertWithExpiry ¶ added in v1.0.0
func (f *MongoTTLFeatures) InsertWithExpiry(ctx context.Context, collection string, doc bson.M, ttlField string, expiresAt time.Time) error
InsertWithExpiry 插入一个文档并自动设置过期时间字段。
- collection: MongoDB 集合名
- doc: 要插入的文档(会被写入 ttlField 字段,调用方 doc 也会被修改)
- ttlField: 文档中表示过期时间点的字段名(须与对应 TTL 索引字段一致)
- expiresAt: 文档应在此时间点被 MongoDB 自动删除
func (*MongoTTLFeatures) ListTTLIndexes ¶ added in v1.0.0
func (f *MongoTTLFeatures) ListTTLIndexes(ctx context.Context, collection string) ([]*TTLIndexInfo, error)
ListTTLIndexes 列出指定集合上所有带 expireAfterSeconds 的 TTL 索引。
type MongoVirtualView ¶ added in v1.0.0
type MongoVirtualView struct {
// contains filtered or unexported fields
}
MongoVirtualView 用进程内存缓存模拟 MongoDB "物化视图"。
思路:将一条 Aggregation Pipeline 的执行结果按 TTL 缓存在进程内, 避免每次查询都触发完整的 aggregation,同时无需在数据库层维护物化视图 DDL。
与 SQL 物化视图的对比:
- SQL 物化视图:结果存储在数据库磁盘,需手动 REFRESH 或定时刷新。
- MongoVirtualView:结果缓存在应用进程内存,按 TTL 自动过期后重拉,免 DDL。
适用场景:报表汇总快照、权限角色预计算、低频变化但高频读取的聚合结果。
示例:
vv, ok := db.GetMongoVirtualView(repo.GetAdapter())
vv.Define("active_user_count", "users",
bson.A{
bson.D{{Key: "$match", Value: bson.D{{Key: "active", Value: true}}}},
bson.D{{Key: "$count", Value: "count"}},
},
5*time.Minute,
)
docs, err := vv.Execute(ctx, "active_user_count")
func GetMongoVirtualView ¶ added in v1.0.0
func GetMongoVirtualView(adapter Adapter) (*MongoVirtualView, bool)
GetMongoVirtualView 从 Adapter 获取 MongoVirtualView。 若 adapter 不是 *MongoAdapter,返回 (nil, false)。
func (*MongoVirtualView) Define ¶ added in v1.0.0
Define 注册一个虚拟视图定义(仅注册,不执行聚合)。
- name: 视图标识符,Execute/Refresh/InvalidateView 时使用
- collection: 聚合操作的源集合名
- pipeline: MongoDB Aggregation Pipeline(bson.A,即 []interface{})
- ttl: 结果缓存时长(<= 0 表示永不自动过期,直到 Refresh 或 InvalidateView)
重复调用 Define 同名视图会覆盖原定义(同时清除旧缓存)。
func (*MongoVirtualView) DefinedViews ¶ added in v1.0.0
func (v *MongoVirtualView) DefinedViews() []string
DefinedViews 返回所有已注册的视图名称列表。
func (*MongoVirtualView) Execute ¶ added in v1.0.0
Execute 返回虚拟视图的文档列表。
- 首次调用(或缓存已过期):执行 Aggregation Pipeline 并缓存结果。
- TTL 内再次调用:直接返回缓存,不发起 MongoDB 请求。
func (*MongoVirtualView) InvalidateAll ¶ added in v1.0.0
func (v *MongoVirtualView) InvalidateAll()
InvalidateAll 清除所有视图缓存。
func (*MongoVirtualView) InvalidateView ¶ added in v1.0.0
func (v *MongoVirtualView) InvalidateView(name string)
InvalidateView 清除指定视图的内存缓存(下次 Execute 会重新执行 Pipeline)。
func (*MongoVirtualView) IsCached ¶ added in v1.0.0
func (v *MongoVirtualView) IsCached(name string) bool
IsCached 检查指定视图是否有未过期的内存缓存。
func (*MongoVirtualView) IsDefined ¶ added in v1.0.0
func (v *MongoVirtualView) IsDefined(name string) bool
IsDefined 检查指定名称的视图是否已通过 Define 注册。
type MySQLAdapter ¶
type MySQLAdapter struct {
// contains filtered or unexported fields
}
MySQLAdapter MySQL 数据库适配器
func (*MySQLAdapter) Begin ¶
func (a *MySQLAdapter) Begin(ctx context.Context, opts ...interface{}) (Tx, error)
Begin 开始事务
func (*MySQLAdapter) Connect ¶
func (a *MySQLAdapter) Connect(ctx context.Context, config *Config) error
Connect 连接到 MySQL 数据库
func (*MySQLAdapter) Exec ¶
func (a *MySQLAdapter) Exec(ctx context.Context, query string, args ...interface{}) (sql.Result, error)
Exec 执行操作 (INSERT/UPDATE/DELETE)
func (*MySQLAdapter) GetDatabaseFeatures ¶
func (a *MySQLAdapter) GetDatabaseFeatures() *DatabaseFeatures
GetDatabaseFeatures 返回 MySQL 数据库特性
func (*MySQLAdapter) GetGormDB ¶
func (a *MySQLAdapter) GetGormDB() *gorm.DB
GetGormDB 获取GORM实例(用于直接访问GORM) Deprecated: Adapter 层不再暴露 GORM 连接。
func (*MySQLAdapter) GetQueryBuilderProvider ¶
func (a *MySQLAdapter) GetQueryBuilderProvider() QueryConstructorProvider
GetQueryBuilderProvider 返回查询构造器提供者
func (*MySQLAdapter) GetQueryFeatures ¶
func (a *MySQLAdapter) GetQueryFeatures() *QueryFeatures
GetQueryFeatures 返回 MySQL 的查询特性
func (*MySQLAdapter) GetRawConn ¶
func (a *MySQLAdapter) GetRawConn() interface{}
GetRawConn 获取底层连接 (返回 *sql.DB)
func (*MySQLAdapter) ListScheduledTasks ¶
func (a *MySQLAdapter) ListScheduledTasks(ctx context.Context) ([]*ScheduledTaskStatus, error)
ListScheduledTasks MySQL 适配器暂不支持
func (*MySQLAdapter) Query ¶
func (a *MySQLAdapter) Query(ctx context.Context, query string, args ...interface{}) (*sql.Rows, error)
Query 执行查询 (返回多行)
func (*MySQLAdapter) RegisterScheduledTask ¶
func (a *MySQLAdapter) RegisterScheduledTask(ctx context.Context, task *ScheduledTaskConfig) error
RegisterScheduledTask MySQL 适配器暂不支持通过 EVENT 方式实现定时任务 建议在应用层使用 cron 库处理定时任务
func (*MySQLAdapter) UnregisterScheduledTask ¶
func (a *MySQLAdapter) UnregisterScheduledTask(ctx context.Context, taskName string) error
UnregisterScheduledTask MySQL 适配器暂不支持
type MySQLConnectionConfig ¶ added in v1.0.0
type MySQLConnectionConfig struct {
Host string `json:"host,omitempty" yaml:"host,omitempty"`
Port int `json:"port,omitempty" yaml:"port,omitempty"`
Username string `json:"username,omitempty" yaml:"username,omitempty"`
Password string `json:"password,omitempty" yaml:"password,omitempty"`
Database string `json:"database,omitempty" yaml:"database,omitempty"`
DSN string `json:"dsn,omitempty" yaml:"dsn,omitempty"`
}
MySQLConnectionConfig MySQL 连接配置。
type MySQLDialect ¶
type MySQLDialect struct {
DefaultSQLDialect
}
MySQL 方言
func NewMySQLDialect ¶
func NewMySQLDialect() *MySQLDialect
type MySQLDynamicTableHook ¶
type MySQLDynamicTableHook struct {
// contains filtered or unexported fields
}
MySQLDynamicTableHook MySQL 动态表钩子实现 使用 GORM 的 hook 机制实现基于触发的动态建表
func NewMySQLDynamicTableHook ¶
func NewMySQLDynamicTableHook(adapter *MySQLAdapter) *MySQLDynamicTableHook
NewMySQLDynamicTableHook 创建 MySQL 动态表钩子
func (*MySQLDynamicTableHook) CreateDynamicTable ¶
func (h *MySQLDynamicTableHook) CreateDynamicTable(ctx context.Context, configName string, params map[string]interface{}) (string, error)
CreateDynamicTable 手动创建动态表 返回实际创建的表名称
func (*MySQLDynamicTableHook) GetDynamicTableConfig ¶
func (h *MySQLDynamicTableHook) GetDynamicTableConfig(ctx context.Context, configName string) (*DynamicTableConfig, error)
GetDynamicTableConfig 获取特定的动态表配置
func (*MySQLDynamicTableHook) ListCreatedDynamicTables ¶
func (h *MySQLDynamicTableHook) ListCreatedDynamicTables(ctx context.Context, configName string) ([]string, error)
ListCreatedDynamicTables 获取已创建的动态表列表
func (*MySQLDynamicTableHook) ListDynamicTableConfigs ¶
func (h *MySQLDynamicTableHook) ListDynamicTableConfigs(ctx context.Context) ([]*DynamicTableConfig, error)
ListDynamicTableConfigs 列出所有已注册的动态表配置
func (*MySQLDynamicTableHook) RegisterDynamicTable ¶
func (h *MySQLDynamicTableHook) RegisterDynamicTable(ctx context.Context, config *DynamicTableConfig) error
RegisterDynamicTable 注册动态表配置 对于自动策略,在 GORM hook 中注册事件处理
func (*MySQLDynamicTableHook) UnregisterDynamicTable ¶
func (h *MySQLDynamicTableHook) UnregisterDynamicTable(ctx context.Context, configName string) error
UnregisterDynamicTable 注销动态表配置
type MySQLFactory ¶
type MySQLFactory struct{}
MySQLFactory MySQL 适配器工厂
type MySQLTx ¶
type MySQLTx struct {
// contains filtered or unexported fields
}
MySQLTx MySQL 事务实现
type Neo4jAdapter ¶ added in v1.0.0
type Neo4jAdapter struct {
// contains filtered or unexported fields
}
Neo4jAdapter Neo4j 适配器(最小可用版本:连接/健康检查/能力声明)。
func NewNeo4jAdapter ¶ added in v1.0.0
func NewNeo4jAdapter(config *Config) (*Neo4jAdapter, error)
NewNeo4jAdapter 创建 Neo4jAdapter(不建立连接)。
func (*Neo4jAdapter) Begin ¶ added in v1.0.0
func (a *Neo4jAdapter) Begin(ctx context.Context, opts ...interface{}) (Tx, error)
Begin Neo4j 不支持 SQL 事务接口。
func (*Neo4jAdapter) Close ¶ added in v1.0.0
func (a *Neo4jAdapter) Close() error
Close 关闭 Neo4j 连接。
func (*Neo4jAdapter) Connect ¶ added in v1.0.0
func (a *Neo4jAdapter) Connect(ctx context.Context, config *Config) error
Connect 建立 Neo4j 连接。
func (*Neo4jAdapter) Exec ¶ added in v1.0.0
func (a *Neo4jAdapter) Exec(ctx context.Context, sql string, args ...interface{}) (sql.Result, error)
Exec Neo4j 不支持 SQL Exec 接口。
func (*Neo4jAdapter) ExecCypher ¶ added in v1.0.0
func (a *Neo4jAdapter) ExecCypher(ctx context.Context, cypher string, params map[string]interface{}) (*CypherWriteSummary, error)
ExecCypher 执行写类型 Cypher,并返回写入摘要。
func (*Neo4jAdapter) ExecuteCustomFeature ¶ added in v1.0.0
func (a *Neo4jAdapter) ExecuteCustomFeature(ctx context.Context, feature string, input map[string]interface{}) (interface{}, error)
ExecuteCustomFeature 执行 Neo4j 自定义能力(返回可执行 Cypher/说明)。
func (*Neo4jAdapter) GetDatabaseFeatures ¶ added in v1.0.0
func (a *Neo4jAdapter) GetDatabaseFeatures() *DatabaseFeatures
GetDatabaseFeatures 返回 Neo4j 数据库特性声明。
func (*Neo4jAdapter) GetQueryBuilderProvider ¶ added in v1.0.0
func (a *Neo4jAdapter) GetQueryBuilderProvider() QueryConstructorProvider
GetQueryBuilderProvider 返回 Neo4j Cypher Query Builder Provider。
func (*Neo4jAdapter) GetQueryFeatures ¶ added in v1.0.0
func (a *Neo4jAdapter) GetQueryFeatures() *QueryFeatures
GetQueryFeatures 返回 Neo4j 查询特性声明。
func (*Neo4jAdapter) GetRawConn ¶ added in v1.0.0
func (a *Neo4jAdapter) GetRawConn() interface{}
GetRawConn 返回底层 Neo4j Driver。
func (*Neo4jAdapter) HasCustomFeatureImplementation ¶ added in v1.0.0
func (a *Neo4jAdapter) HasCustomFeatureImplementation(feature string) bool
HasCustomFeatureImplementation 声明 Neo4j 可用的自定义能力。
func (*Neo4jAdapter) InspectFullTextRuntime ¶ added in v1.0.0
func (a *Neo4jAdapter) InspectFullTextRuntime(ctx context.Context) (*FullTextRuntimeCapability, error)
InspectFullTextRuntime 探测 Neo4j 全文能力(需要全文索引)。
func (*Neo4jAdapter) ListScheduledTasks ¶ added in v1.0.0
func (a *Neo4jAdapter) ListScheduledTasks(ctx context.Context) ([]*ScheduledTaskStatus, error)
ListScheduledTasks Neo4j 暂不支持定时任务接口。
func (*Neo4jAdapter) Ping ¶ added in v1.0.0
func (a *Neo4jAdapter) Ping(ctx context.Context) error
Ping 检查 Neo4j 连接可用性。
func (*Neo4jAdapter) Query ¶ added in v1.0.0
func (a *Neo4jAdapter) Query(ctx context.Context, sql string, args ...interface{}) (*sql.Rows, error)
Query Neo4j 不支持 SQL Query 接口。
func (*Neo4jAdapter) QueryCypher ¶ added in v1.0.0
func (a *Neo4jAdapter) QueryCypher(ctx context.Context, cypher string, params map[string]interface{}) ([]map[string]interface{}, error)
QueryCypher 执行读类型 Cypher,并返回记录列表。
func (*Neo4jAdapter) RegisterScheduledTask ¶ added in v1.0.0
func (a *Neo4jAdapter) RegisterScheduledTask(ctx context.Context, task *ScheduledTaskConfig) error
RegisterScheduledTask Neo4j 暂不支持定时任务接口。
func (*Neo4jAdapter) UnregisterScheduledTask ¶ added in v1.0.0
func (a *Neo4jAdapter) UnregisterScheduledTask(ctx context.Context, taskName string) error
UnregisterScheduledTask Neo4j 暂不支持定时任务接口。
type Neo4jConnectionConfig ¶ added in v1.0.0
type Neo4jConnectionConfig struct {
URI string `json:"uri,omitempty" yaml:"uri,omitempty"`
Username string `json:"username,omitempty" yaml:"username,omitempty"`
Password string `json:"password,omitempty" yaml:"password,omitempty"`
Database string `json:"database,omitempty" yaml:"database,omitempty"`
}
Neo4jConnectionConfig Neo4j 连接配置。
type Neo4jFactory ¶ added in v1.0.0
type Neo4jFactory struct{}
Neo4jFactory AdapterFactory 实现。
func (*Neo4jFactory) Create ¶ added in v1.0.0
func (f *Neo4jFactory) Create(config *Config) (Adapter, error)
func (*Neo4jFactory) Name ¶ added in v1.0.0
func (f *Neo4jFactory) Name() string
type Neo4jQueryConstructor ¶ added in v1.0.0
type Neo4jQueryConstructor struct {
// contains filtered or unexported fields
}
Neo4jQueryConstructor 面向 Neo4j 的 Cypher 查询构造器。
func NewNeo4jQueryConstructor ¶ added in v1.0.0
func NewNeo4jQueryConstructor(schema Schema) *Neo4jQueryConstructor
func NewNeo4jQueryConstructorWithCompiler ¶ added in v1.0.0
func NewNeo4jQueryConstructorWithCompiler(schema Schema, compiler QueryCompiler) *Neo4jQueryConstructor
func (*Neo4jQueryConstructor) Build ¶ added in v1.0.0
func (qb *Neo4jQueryConstructor) Build(ctx context.Context) (string, []interface{}, error)
func (*Neo4jQueryConstructor) BuildIR ¶ added in v1.0.0
func (qb *Neo4jQueryConstructor) BuildIR(ctx context.Context) (*QueryIR, error)
func (*Neo4jQueryConstructor) Count ¶ added in v1.1.0
func (qb *Neo4jQueryConstructor) Count(fieldName ...string) QueryConstructor
func (*Neo4jQueryConstructor) CountWith ¶ added in v1.1.0
func (qb *Neo4jQueryConstructor) CountWith(builder *CountBuilder) QueryConstructor
func (*Neo4jQueryConstructor) CrossJoin ¶ added in v1.0.0
func (qb *Neo4jQueryConstructor) CrossJoin(table string, alias ...string) QueryConstructor
func (*Neo4jQueryConstructor) CrossTableStrategy ¶ added in v1.0.0
func (qb *Neo4jQueryConstructor) CrossTableStrategy(strategy CrossTableStrategy) QueryConstructor
func (*Neo4jQueryConstructor) CustomMode ¶ added in v1.1.0
func (qb *Neo4jQueryConstructor) CustomMode() QueryConstructor
func (*Neo4jQueryConstructor) FromAlias ¶ added in v1.0.0
func (qb *Neo4jQueryConstructor) FromAlias(alias string) QueryConstructor
func (*Neo4jQueryConstructor) GetNativeBuilder ¶ added in v1.0.0
func (qb *Neo4jQueryConstructor) GetNativeBuilder() interface{}
func (*Neo4jQueryConstructor) Join ¶ added in v1.0.0
func (qb *Neo4jQueryConstructor) Join(table, onClause string, alias ...string) QueryConstructor
func (*Neo4jQueryConstructor) JoinWith ¶ added in v1.1.0
func (qb *Neo4jQueryConstructor) JoinWith(builder *JoinBuilder) QueryConstructor
JoinWith 使用 JoinBuilder 进行 Schema 感知的连接。 Neo4j 端:label 取自 Schema.TableName();On() 为空时从 Schema FK 约束推断关系类型; Filter() 条件在 WHERE 子句中以 join alias 限定输出。
func (*Neo4jQueryConstructor) LeftJoin ¶ added in v1.0.0
func (qb *Neo4jQueryConstructor) LeftJoin(table, onClause string, alias ...string) QueryConstructor
func (*Neo4jQueryConstructor) Limit ¶ added in v1.0.0
func (qb *Neo4jQueryConstructor) Limit(count int) QueryConstructor
func (*Neo4jQueryConstructor) Offset ¶ added in v1.0.0
func (qb *Neo4jQueryConstructor) Offset(count int) QueryConstructor
func (*Neo4jQueryConstructor) OrderBy ¶ added in v1.0.0
func (qb *Neo4jQueryConstructor) OrderBy(field string, direction string) QueryConstructor
func (*Neo4jQueryConstructor) Page ¶ added in v1.1.1
func (qb *Neo4jQueryConstructor) Page(page int, pageSize int) QueryConstructor
func (*Neo4jQueryConstructor) Paginate ¶ added in v1.1.1
func (qb *Neo4jQueryConstructor) Paginate(builder *PaginationBuilder) QueryConstructor
func (*Neo4jQueryConstructor) RightJoin ¶ added in v1.0.0
func (qb *Neo4jQueryConstructor) RightJoin(table, onClause string, alias ...string) QueryConstructor
func (*Neo4jQueryConstructor) Select ¶ added in v1.0.0
func (qb *Neo4jQueryConstructor) Select(fields ...string) QueryConstructor
func (*Neo4jQueryConstructor) SelectCount ¶ added in v1.1.0
func (qb *Neo4jQueryConstructor) SelectCount(ctx context.Context, repo *Repository) (int64, error)
func (*Neo4jQueryConstructor) Upsert ¶ added in v1.1.0
func (qb *Neo4jQueryConstructor) Upsert(ctx context.Context, repo *Repository, cs *Changeset, conflictColumns ...string) (sql.Result, error)
func (*Neo4jQueryConstructor) Where ¶ added in v1.0.0
func (qb *Neo4jQueryConstructor) Where(condition Condition) QueryConstructor
func (*Neo4jQueryConstructor) WhereAll ¶ added in v1.0.0
func (qb *Neo4jQueryConstructor) WhereAll(conditions ...Condition) QueryConstructor
func (*Neo4jQueryConstructor) WhereAny ¶ added in v1.0.0
func (qb *Neo4jQueryConstructor) WhereAny(conditions ...Condition) QueryConstructor
func (*Neo4jQueryConstructor) WhereWith ¶ added in v1.1.0
func (qb *Neo4jQueryConstructor) WhereWith(builder *WhereBuilder) QueryConstructor
type Neo4jQueryConstructorProvider ¶ added in v1.0.0
type Neo4jQueryConstructorProvider struct {
// contains filtered or unexported fields
}
Neo4jQueryConstructorProvider Neo4j 查询构造器提供者。
func NewNeo4jQueryConstructorProvider ¶ added in v1.0.0
func NewNeo4jQueryConstructorProvider() *Neo4jQueryConstructorProvider
func (*Neo4jQueryConstructorProvider) GetCapabilities ¶ added in v1.0.0
func (p *Neo4jQueryConstructorProvider) GetCapabilities() *QueryBuilderCapabilities
func (*Neo4jQueryConstructorProvider) NewQueryConstructor ¶ added in v1.0.0
func (p *Neo4jQueryConstructorProvider) NewQueryConstructor(schema Schema) QueryConstructor
func (*Neo4jQueryConstructorProvider) SetCompiler ¶ added in v1.0.0
func (p *Neo4jQueryConstructorProvider) SetCompiler(compiler QueryCompiler) *Neo4jQueryConstructorProvider
type NotCondition ¶
type NotCondition struct {
Condition Condition
}
NotCondition 非条件
func (*NotCondition) Translate ¶
func (c *NotCondition) Translate(translator ConditionTranslator) (string, []interface{}, error)
func (*NotCondition) Type ¶
func (c *NotCondition) Type() string
type PagedQueryConstructorExecutionResult ¶ added in v1.1.1
type PagedQueryConstructorExecutionResult struct {
Statement string
Args []interface{}
Rows []map[string]interface{}
Total int64
Page int
PageSize int
Offset int
TotalPages int
HasNext bool
HasPrevious bool
QueryCacheHit bool
CountCacheHit bool
}
PagedQueryConstructorExecutionResult 表示带分页元信息的统一执行结果。
type PaginationBuilder ¶ added in v1.1.1
type PaginationBuilder struct {
Mode PaginationMode
Page int
PageSize int
CursorField string
CursorDirection string
CursorValue interface{}
CursorPrimaryValue interface{}
}
PaginationBuilder 定义跨后端统一分页语义,不绑定 SQL 细节。
func NewCursorPaginationBuilder ¶ added in v1.1.1
func NewCursorPaginationBuilder(field string, direction string, cursorValue interface{}, cursorPrimaryValue interface{}, pageSize int) *PaginationBuilder
func NewPaginationBuilder ¶ added in v1.1.1
func NewPaginationBuilder(page int, pageSize int) *PaginationBuilder
func (*PaginationBuilder) CursorBy ¶ added in v1.1.1
func (b *PaginationBuilder) CursorBy(field string, direction string, cursorValue interface{}, cursorPrimaryValue interface{}) *PaginationBuilder
func (*PaginationBuilder) OffsetOnly ¶ added in v1.1.1
func (b *PaginationBuilder) OffsetOnly() *PaginationBuilder
func (*PaginationBuilder) WithMode ¶ added in v1.1.1
func (b *PaginationBuilder) WithMode(mode PaginationMode) *PaginationBuilder
type PaginationMode ¶ added in v1.1.1
type PaginationMode string
const ( PaginationModeAuto PaginationMode = "auto" PaginationModeOffset PaginationMode = "offset" PaginationModeCursor PaginationMode = "cursor" )
type PatternValidator ¶
type PatternValidator struct {
Pattern string
}
PatternValidator 正则验证器
func (*PatternValidator) Validate ¶
func (v *PatternValidator) Validate(value interface{}) error
type PhoneNumberValidator ¶ added in v1.0.0
type PhoneNumberValidator struct {
Locale string
}
PhoneNumberValidator 手机号/电话号码格式验证器 它是 RegexValidator 的特化封装。
func NewPhoneNumberValidatorForLocale ¶ added in v1.0.0
func NewPhoneNumberValidatorForLocale(locale string) *PhoneNumberValidator
func (*PhoneNumberValidator) Validate ¶ added in v1.0.0
func (v *PhoneNumberValidator) Validate(value interface{}) error
func (*PhoneNumberValidator) ValidateWithLocale ¶ added in v1.0.0
func (v *PhoneNumberValidator) ValidateWithLocale(value interface{}, locale string) error
type PoolConfig ¶
type PoolConfig struct {
MaxConnections int `json:"max_connections" yaml:"max_connections"`
MinConnections int `json:"min_connections" yaml:"min_connections"`
ConnectTimeout int `json:"connect_timeout" yaml:"connect_timeout"` // 秒
IdleTimeout int `json:"idle_timeout" yaml:"idle_timeout"` // 秒
MaxLifetime int `json:"max_lifetime" yaml:"max_lifetime"` // 秒
}
PoolConfig 连接池配置 (参考 Ecto 的设计)
type PostalCodeValidator ¶ added in v1.0.0
type PostalCodeValidator struct {
Locale string
}
PostalCodeValidator 邮政编码验证器(中国大陆 6 位) 它是 RegexValidator 的特化封装。
func NewPostalCodeValidatorForLocale ¶ added in v1.0.0
func NewPostalCodeValidatorForLocale(locale string) *PostalCodeValidator
func (*PostalCodeValidator) Validate ¶ added in v1.0.0
func (v *PostalCodeValidator) Validate(value interface{}) error
func (*PostalCodeValidator) ValidateWithLocale ¶ added in v1.0.0
func (v *PostalCodeValidator) ValidateWithLocale(value interface{}, locale string) error
type PostgreSQLAdapter ¶
type PostgreSQLAdapter struct {
// contains filtered or unexported fields
}
PostgreSQLAdapter PostgreSQL 数据库适配器
func (*PostgreSQLAdapter) Begin ¶
func (a *PostgreSQLAdapter) Begin(ctx context.Context, opts ...interface{}) (Tx, error)
Begin 开始事务
func (*PostgreSQLAdapter) Connect ¶
func (a *PostgreSQLAdapter) Connect(ctx context.Context, config *Config) error
Connect 连接到 PostgreSQL 数据库
func (*PostgreSQLAdapter) Exec ¶
func (a *PostgreSQLAdapter) Exec(ctx context.Context, query string, args ...interface{}) (sql.Result, error)
Exec 执行操作 (INSERT/UPDATE/DELETE)
func (*PostgreSQLAdapter) GetDatabaseFeatures ¶
func (a *PostgreSQLAdapter) GetDatabaseFeatures() *DatabaseFeatures
GetDatabaseFeatures 返回 PostgreSQL 数据库特性
func (*PostgreSQLAdapter) GetGormDB ¶
func (a *PostgreSQLAdapter) GetGormDB() *gorm.DB
GetGormDB 获取GORM实例(用于直接访问GORM) Deprecated: Adapter 层不再暴露 GORM 连接。
func (*PostgreSQLAdapter) GetQueryBuilderProvider ¶
func (a *PostgreSQLAdapter) GetQueryBuilderProvider() QueryConstructorProvider
GetQueryBuilderProvider 返回查询构造器提供者
func (*PostgreSQLAdapter) GetQueryFeatures ¶
func (a *PostgreSQLAdapter) GetQueryFeatures() *QueryFeatures
GetQueryFeatures 返回 PostgreSQL 的查询特性
func (*PostgreSQLAdapter) GetRawConn ¶
func (a *PostgreSQLAdapter) GetRawConn() interface{}
GetRawConn 获取底层连接 (返回 *sql.DB)
func (*PostgreSQLAdapter) InspectFullTextRuntime ¶ added in v1.0.0
func (a *PostgreSQLAdapter) InspectFullTextRuntime(ctx context.Context) (*FullTextRuntimeCapability, error)
InspectFullTextRuntime 检查 PostgreSQL 全文能力与常见分词插件(zhparser/pg_jieba/pgroonga)。 约定:当调用方要求插件分词加速时,若插件不存在可据此降级。
func (*PostgreSQLAdapter) InspectJSONRuntime ¶ added in v1.0.0
func (a *PostgreSQLAdapter) InspectJSONRuntime(ctx context.Context) (*JSONRuntimeCapability, error)
InspectJSONRuntime 检查 PostgreSQL JSON 能力(json/jsonb 类型可用性)。
func (*PostgreSQLAdapter) ListScheduledTasks ¶
func (a *PostgreSQLAdapter) ListScheduledTasks(ctx context.Context) ([]*ScheduledTaskStatus, error)
ListScheduledTasks 列出所有已注册的定时任务 PostgreSQL 版本返回空列表,因为存储过程的管理比较复杂
func (*PostgreSQLAdapter) Ping ¶
func (a *PostgreSQLAdapter) Ping(ctx context.Context) error
Ping 测试数据库连接
func (*PostgreSQLAdapter) PostgresJSONType ¶ added in v1.0.0
func (a *PostgreSQLAdapter) PostgresJSONType() string
PostgresJSONType 返回 PostgreSQL 的 JSON 字段映射类型。 默认使用 jsonb;可通过 config.Options["postgres_json_type"] 或 config.Options["json_type"] 配置为 json。
func (*PostgreSQLAdapter) Query ¶
func (a *PostgreSQLAdapter) Query(ctx context.Context, query string, args ...interface{}) (*sql.Rows, error)
Query 执行查询 (返回多行)
func (*PostgreSQLAdapter) QueryRow ¶
func (a *PostgreSQLAdapter) QueryRow(ctx context.Context, query string, args ...interface{}) *sql.Row
QueryRow 执行查询 (返回单行)
func (*PostgreSQLAdapter) RegisterScheduledTask ¶
func (a *PostgreSQLAdapter) RegisterScheduledTask(ctx context.Context, task *ScheduledTaskConfig) error
RegisterScheduledTask 在 PostgreSQL 中注册定时任务 使用 PostgreSQL 的触发器 + 函数来实现按月自动创建表的功能
func (*PostgreSQLAdapter) UnregisterScheduledTask ¶
func (a *PostgreSQLAdapter) UnregisterScheduledTask(ctx context.Context, taskName string) error
UnregisterScheduledTask 注销定时任务
type PostgreSQLDialect ¶
type PostgreSQLDialect struct {
DefaultSQLDialect
// contains filtered or unexported fields
}
PostgreSQL 方言
func NewPostgreSQLDialect ¶
func NewPostgreSQLDialect() *PostgreSQLDialect
func (*PostgreSQLDialect) GetPlaceholder ¶
func (d *PostgreSQLDialect) GetPlaceholder(index int) string
func (*PostgreSQLDialect) QuoteIdentifier ¶
func (d *PostgreSQLDialect) QuoteIdentifier(name string) string
type PostgreSQLDynamicTableHook ¶
type PostgreSQLDynamicTableHook struct {
// contains filtered or unexported fields
}
PostgreSQLDynamicTableHook PostgreSQL 动态表钩子实现 使用触发器和自定义函数实现自动化动态建表
func NewPostgreSQLDynamicTableHook ¶
func NewPostgreSQLDynamicTableHook(adapter *PostgreSQLAdapter) *PostgreSQLDynamicTableHook
NewPostgreSQLDynamicTableHook 创建 PostgreSQL 动态表钩子
func (*PostgreSQLDynamicTableHook) CreateDynamicTable ¶
func (h *PostgreSQLDynamicTableHook) CreateDynamicTable(ctx context.Context, configName string, params map[string]interface{}) (string, error)
CreateDynamicTable 手动创建动态表 返回实际创建的表名称
func (*PostgreSQLDynamicTableHook) GetDynamicTableConfig ¶
func (h *PostgreSQLDynamicTableHook) GetDynamicTableConfig(ctx context.Context, configName string) (*DynamicTableConfig, error)
GetDynamicTableConfig 获取特定的动态表配置
func (*PostgreSQLDynamicTableHook) ListCreatedDynamicTables ¶
func (h *PostgreSQLDynamicTableHook) ListCreatedDynamicTables(ctx context.Context, configName string) ([]string, error)
ListCreatedDynamicTables 获取已创建的动态表列表
func (*PostgreSQLDynamicTableHook) ListDynamicTableConfigs ¶
func (h *PostgreSQLDynamicTableHook) ListDynamicTableConfigs(ctx context.Context) ([]*DynamicTableConfig, error)
ListDynamicTableConfigs 列出所有已注册的动态表配置
func (*PostgreSQLDynamicTableHook) RegisterDynamicTable ¶
func (h *PostgreSQLDynamicTableHook) RegisterDynamicTable(ctx context.Context, config *DynamicTableConfig) error
RegisterDynamicTable 注册动态表配置 对于自动策略,创建触发器和存储函数来自动化建表
func (*PostgreSQLDynamicTableHook) UnregisterDynamicTable ¶
func (h *PostgreSQLDynamicTableHook) UnregisterDynamicTable(ctx context.Context, configName string) error
UnregisterDynamicTable 注销动态表配置
type PostgreSQLFactory ¶
type PostgreSQLFactory struct{}
PostgreSQLFactory PostgreSQL 适配器工厂
type PostgreSQLFeatures ¶ added in v1.0.0
type PostgreSQLFeatures struct {
// contains filtered or unexported fields
}
PostgreSQLFeatures 提供 PostgreSQL 特有的高级数据库功能。 通过 GetPostgreSQLFeatures(adapter) 获取实例,非 PostgreSQL 适配器返回 false。
示例:
features, ok := db.GetPostgreSQLFeatures(repo.GetAdapter())
if !ok {
return errors.New("not PostgreSQL")
}
// ENUM 类型
err = features.EnumType("order_status").
Values("pending", "processing", "shipped", "delivered", "cancelled").
IfNotExists().
Create(ctx)
// DOMAIN 类型
err = features.DomainType("email_address").
BaseType("TEXT").
NotNull().
Check(`VALUE ~ '^[^@\s]+@[^@\s]+\.[^@\s]+$'`).
Create(ctx)
// COMPOSITE 类型
err = features.CompositeType("geo_point").
Field("lat", "DOUBLE PRECISION").
Field("lng", "DOUBLE PRECISION").
Create(ctx)
func GetPostgreSQLFeatures ¶ added in v1.0.0
func GetPostgreSQLFeatures(adapter Adapter) (*PostgreSQLFeatures, bool)
GetPostgreSQLFeatures 从 Adapter 中提取 PostgreSQLFeatures。 若传入的不是 *PostgreSQLAdapter,则 ok == false。
func (*PostgreSQLFeatures) CompositeType ¶ added in v1.0.0
func (f *PostgreSQLFeatures) CompositeType(typeName string) *CompositeTypeBuilder
CompositeType 开始构建一个 PostgreSQL COMPOSITE 自定义类型(结构体类型)。 COMPOSITE 类型可以作为列类型或函数返回类型使用。
生成的 DDL 示例:
CREATE TYPE "address" AS (
street TEXT,
city VARCHAR(100),
zip CHAR(6)
)
func (*PostgreSQLFeatures) DomainType ¶ added in v1.0.0
func (f *PostgreSQLFeatures) DomainType(typeName string) *DomainTypeBuilder
DomainType 开始构建一个 PostgreSQL DOMAIN 自定义类型。 DOMAIN 是对已有基础类型的约束包装,可以附加 NOT NULL 和 CHECK 约束。
生成的 DDL 示例:
CREATE DOMAIN "email_address" AS TEXT NOT NULL
CHECK (VALUE ~ '^[^@\s]+@[^@\s]+\.[^@\s]+$')
func (*PostgreSQLFeatures) EnumType ¶ added in v1.0.0
func (f *PostgreSQLFeatures) EnumType(typeName string) *EnumTypeBuilder
EnumType 开始构建一个 PostgreSQL ENUM 自定义类型。
生成的 DDL 示例:
CREATE TYPE "order_status" AS ENUM ('pending', 'processing', 'shipped')
func (*PostgreSQLFeatures) MaterializedView ¶ added in v1.0.0
func (f *PostgreSQLFeatures) MaterializedView(viewName string) *PostgreSQLViewBuilder
MaterializedView 开始构建 PostgreSQL 物化视图。
func (*PostgreSQLFeatures) View ¶ added in v1.0.0
func (f *PostgreSQLFeatures) View(viewName string) *PostgreSQLViewBuilder
View 开始构建一个 PostgreSQL 普通视图。 默认使用 CREATE OR REPLACE VIEW。
type PostgreSQLTx ¶
type PostgreSQLTx struct {
// contains filtered or unexported fields
}
PostgreSQLTx PostgreSQL 事务实现
func (*PostgreSQLTx) Exec ¶
func (t *PostgreSQLTx) Exec(ctx context.Context, query string, args ...interface{}) (sql.Result, error)
Exec 在事务中执行
func (*PostgreSQLTx) Query ¶
func (t *PostgreSQLTx) Query(ctx context.Context, query string, args ...interface{}) (*sql.Rows, error)
Query 在事务中查询
type PostgreSQLViewBuilder ¶ added in v1.0.0
type PostgreSQLViewBuilder struct {
// contains filtered or unexported fields
}
PostgreSQLViewBuilder 构建 PostgreSQL 视图(普通视图/物化视图)DDL。
func (*PostgreSQLViewBuilder) Args ¶ added in v1.0.0
func (b *PostgreSQLViewBuilder) Args(args ...interface{}) *PostgreSQLViewBuilder
Args 设置执行创建语句时的参数。
func (*PostgreSQLViewBuilder) As ¶ added in v1.0.0
func (b *PostgreSQLViewBuilder) As(selectSQL string) *PostgreSQLViewBuilder
As 设置视图定义 SQL(AS 后的 SELECT 语句)。
func (*PostgreSQLViewBuilder) BuildCreate ¶ added in v1.0.0
func (b *PostgreSQLViewBuilder) BuildCreate() (string, error)
BuildCreate 生成创建视图 DDL。
func (*PostgreSQLViewBuilder) BuildDrop ¶ added in v1.0.0
func (b *PostgreSQLViewBuilder) BuildDrop() (string, error)
BuildDrop 生成删除视图 DDL。
func (*PostgreSQLViewBuilder) BuildRefresh ¶ added in v1.0.0
func (b *PostgreSQLViewBuilder) BuildRefresh() (string, error)
BuildRefresh 生成刷新物化视图 DDL。
func (*PostgreSQLViewBuilder) Create ¶ added in v1.0.0
func (b *PostgreSQLViewBuilder) Create(ctx context.Context) error
Create 执行创建视图。
func (*PostgreSQLViewBuilder) CreateOnly ¶ added in v1.0.0
func (b *PostgreSQLViewBuilder) CreateOnly() *PostgreSQLViewBuilder
CreateOnly 强制使用 CREATE VIEW(仅普通视图)。
func (*PostgreSQLViewBuilder) CreateOrReplace ¶ added in v1.0.0
func (b *PostgreSQLViewBuilder) CreateOrReplace() *PostgreSQLViewBuilder
CreateOrReplace 使用 CREATE OR REPLACE VIEW(仅普通视图,默认)。
func (*PostgreSQLViewBuilder) Drop ¶ added in v1.0.0
func (b *PostgreSQLViewBuilder) Drop(ctx context.Context) error
Drop 执行删除视图。
func (*PostgreSQLViewBuilder) DropIfExists ¶ added in v1.0.0
func (b *PostgreSQLViewBuilder) DropIfExists() *PostgreSQLViewBuilder
DropIfExists 删除视图时使用 IF EXISTS(默认)。
func (*PostgreSQLViewBuilder) DropStrict ¶ added in v1.0.0
func (b *PostgreSQLViewBuilder) DropStrict() *PostgreSQLViewBuilder
DropStrict 删除视图时不使用 IF EXISTS。
func (*PostgreSQLViewBuilder) Refresh ¶ added in v1.0.0
func (b *PostgreSQLViewBuilder) Refresh(ctx context.Context) error
Refresh 执行刷新物化视图。
func (*PostgreSQLViewBuilder) RefreshConcurrently ¶ added in v1.0.0
func (b *PostgreSQLViewBuilder) RefreshConcurrently() *PostgreSQLViewBuilder
RefreshConcurrently 启用并发刷新(REFRESH MATERIALIZED VIEW CONCURRENTLY)。
func (*PostgreSQLViewBuilder) Schema ¶ added in v1.0.0
func (b *PostgreSQLViewBuilder) Schema(schema string) *PostgreSQLViewBuilder
Schema 指定视图所在 schema(默认 public)。
func (*PostgreSQLViewBuilder) WithCheckOption ¶ added in v1.0.0
func (b *PostgreSQLViewBuilder) WithCheckOption() *PostgreSQLViewBuilder
WithCheckOption 为普通视图添加 WITH CHECK OPTION。
func (*PostgreSQLViewBuilder) WithNoData ¶ added in v1.0.0
func (b *PostgreSQLViewBuilder) WithNoData() *PostgreSQLViewBuilder
WithNoData 为物化视图添加 WITH NO DATA。
type PostgresConnectionConfig ¶ added in v1.0.0
type PostgresConnectionConfig struct {
Host string `json:"host,omitempty" yaml:"host,omitempty"`
Port int `json:"port,omitempty" yaml:"port,omitempty"`
Username string `json:"username,omitempty" yaml:"username,omitempty"`
Password string `json:"password,omitempty" yaml:"password,omitempty"`
Database string `json:"database,omitempty" yaml:"database,omitempty"`
SSLMode string `json:"ssl_mode,omitempty" yaml:"ssl_mode,omitempty"`
DSN string `json:"dsn,omitempty" yaml:"dsn,omitempty"`
}
PostgresConnectionConfig PostgreSQL 连接配置。
type PresetRegistry ¶ added in v1.0.0
type PresetRegistry struct {
Date DatePresetRegistry
}
PresetRegistry 统一预置工具入口。 后续可继续扩展为 Presets.User / Presets.Order / Presets.Task 等模块。 约束:这里仅放应用层语义预置(adapter-agnostic)。 例如 Mongo pipeline / collection / BSON 这类 Adapter 细节不应进入 Presets, 需放在各 Adapter 自己的能力层实现与文档中。
type QueryBuilder ¶
type QueryBuilder struct {
// contains filtered or unexported fields
}
QueryBuilder 查询构建器 (使用 Changeset 进行数据操作) Deprecated: QueryBuilder(v1) 仅保留兼容,建议使用 Repository.NewQueryConstructor() 创建 v2 查询构造器。
func NewQueryBuilder ¶
func NewQueryBuilder(schema Schema, repo *Repository) *QueryBuilder
NewQueryBuilder 创建查询构建器 Deprecated: 使用 Repository.NewQueryConstructor(schema) 获取 v2 查询构造器。
func (*QueryBuilder) Delete ¶
func (qb *QueryBuilder) Delete(whereClause string, whereArgs ...interface{}) (sql.Result, error)
Delete 删除数据
func (*QueryBuilder) DeleteByID ¶
func (qb *QueryBuilder) DeleteByID(id interface{}) (sql.Result, error)
DeleteByID 按 ID 删除数据
func (*QueryBuilder) Insert ¶
func (qb *QueryBuilder) Insert(cs *Changeset) (sql.Result, error)
Insert 插入数据
func (*QueryBuilder) Select ¶
func (qb *QueryBuilder) Select(columns string, whereClause string, whereArgs ...interface{}) (*sql.Rows, error)
Select 查询数据
func (*QueryBuilder) SelectAll ¶
func (qb *QueryBuilder) SelectAll() (*sql.Rows, error)
SelectAll 查询所有数据
func (*QueryBuilder) SelectByID ¶
func (qb *QueryBuilder) SelectByID(id interface{}) (*sql.Row, error)
SelectByID 按 ID 查询单条数据
func (*QueryBuilder) SelectCount ¶
func (qb *QueryBuilder) SelectCount(whereClause string, whereArgs ...interface{}) (int64, error)
SelectCount 查询数据总数
func (*QueryBuilder) SelectOne ¶
func (qb *QueryBuilder) SelectOne(whereClause string, whereArgs ...interface{}) (*sql.Row, error)
SelectOne 查询单条数据
func (*QueryBuilder) SoftDelete ¶
func (qb *QueryBuilder) SoftDelete(whereClause string, whereArgs ...interface{}) (sql.Result, error)
SoftDelete 软删除数据 (仅适用于有 deleted_at 字段的表)
func (*QueryBuilder) SoftDeleteByID ¶
func (qb *QueryBuilder) SoftDeleteByID(id interface{}) (sql.Result, error)
SoftDeleteByID 按 ID 软删除数据
func (*QueryBuilder) Transaction ¶
func (qb *QueryBuilder) Transaction(fn func(*QueryBuilder) error) error
Transaction 事务操作
func (*QueryBuilder) Update ¶
func (qb *QueryBuilder) Update(cs *Changeset, whereClause string, whereArgs ...interface{}) (sql.Result, error)
Update 更新数据
func (*QueryBuilder) UpdateByID ¶
func (qb *QueryBuilder) UpdateByID(id interface{}, cs *Changeset) (sql.Result, error)
UpdateByID 按 ID 更新数据
func (*QueryBuilder) WithContext ¶
func (qb *QueryBuilder) WithContext(ctx context.Context) *QueryBuilder
WithContext 设置上下文
type QueryBuilderCapabilities ¶
type QueryBuilderCapabilities struct {
// 支持的条件操作
SupportsEq bool
SupportsNe bool
SupportsGt bool
SupportsLt bool
SupportsGte bool
SupportsLte bool
SupportsIn bool
SupportsBetween bool
SupportsLike bool
SupportsAnd bool
SupportsOr bool
SupportsNot bool
// 支持的查询特性
SupportsSelect bool // 字段选择
SupportsOrderBy bool // 排序
SupportsLimit bool // LIMIT
SupportsOffset bool // OFFSET
SupportsJoin bool // JOIN(关系查询)
SupportsSubquery bool // 子查询
// 优化特性
SupportsQueryPlan bool // 查询计划分析
SupportsIndex bool // 索引提示
// 原生查询支持
SupportsNativeQuery bool // 是否支持原生查询(如 Cypher)
NativeQueryLang string // 原生查询语言名称(如 "cypher")
// 其他标记
Description string // 此 Adapter 的简要描述
}
QueryBuilderCapabilities 查询构造器能力声明 声明此 Adapter 的 QueryBuilder 支持哪些操作和优化
func DefaultQueryBuilderCapabilities ¶
func DefaultQueryBuilderCapabilities() *QueryBuilderCapabilities
DefaultQueryBuilderCapabilities 返回默认的查询能力(SQL 兼容)
type QueryCacheConfig ¶ added in v1.0.0
type QueryCacheConfig struct {
MaxEntries int `json:"max_entries,omitempty" yaml:"max_entries,omitempty"`
DefaultTTLSeconds int `json:"default_ttl_seconds,omitempty" yaml:"default_ttl_seconds,omitempty"`
EnableMetrics bool `json:"enable_metrics,omitempty" yaml:"enable_metrics,omitempty"`
}
QueryCacheConfig Repository 查询编译缓存配置。
type QueryChain ¶
type QueryChain struct {
// contains filtered or unexported fields
}
QueryChain 链式查询构建器 Deprecated: QueryChain 属于 v1 兼容层,建议迁移到 v2 QueryConstructor 链式 API。
func (*QueryChain) Where ¶
func (qc *QueryChain) Where(condition string, args ...interface{}) *QueryChain
Where 添加 WHERE 条件
type QueryCompileHints ¶ added in v1.0.0
type QueryCompileHints struct {
UseTempTable bool
TempTable string
ViewRoute *QueryViewRouteIR
}
QueryCompileHints 编译阶段提示信息。
type QueryCompiler ¶ added in v1.0.0
type QueryCompiler interface {
Compile(ctx context.Context, ir *QueryIR) (string, []interface{}, error)
}
QueryCompiler 查询编译器接口。 Builder 负责构造 IR,Compiler 负责将 IR 编译为目标数据库语言。
type QueryConstructor ¶
type QueryConstructor interface {
// 条件查询
Where(condition Condition) QueryConstructor
WhereWith(builder *WhereBuilder) QueryConstructor
// 多条件 AND 组合
WhereAll(conditions ...Condition) QueryConstructor
// 多条件 OR 组合
WhereAny(conditions ...Condition) QueryConstructor
// 字段选择
Select(fields ...string) QueryConstructor
Count(fieldName ...string) QueryConstructor
CountWith(builder *CountBuilder) QueryConstructor
// 排序
OrderBy(field string, direction string) QueryConstructor // direction: "ASC" | "DESC"
// 分页
Limit(count int) QueryConstructor
Offset(count int) QueryConstructor
Page(page int, pageSize int) QueryConstructor
Paginate(builder *PaginationBuilder) QueryConstructor
// 跨表查询(raw string JOIN)
FromAlias(alias string) QueryConstructor
Join(table, onClause string, alias ...string) QueryConstructor
LeftJoin(table, onClause string, alias ...string) QueryConstructor
RightJoin(table, onClause string, alias ...string) QueryConstructor
CrossJoin(table string, alias ...string) QueryConstructor
// JoinWith 使用 JoinBuilder 进行 Schema 感知的跨表连接。
// SQL 后端:从 Schema.TableName() 取表名;Filter 条件追加到 WHERE。
// Neo4j 后端:从 Schema FK 约束推断关系类型(On 为空时自动推断);
// Filter 条件转换为对连接节点的属性过滤。
JoinWith(builder *JoinBuilder) QueryConstructor
// 跨表查询策略(方言级默认 + 显式覆盖)
CrossTableStrategy(strategy CrossTableStrategy) QueryConstructor
CustomMode() QueryConstructor
// 构建查询
Build(ctx context.Context) (string, []interface{}, error)
// 统计结果数量(忽略当前分页设置)
SelectCount(ctx context.Context, repo *Repository) (int64, error)
// UPSERT(支持方言原生语法;不支持时事务模拟)
Upsert(ctx context.Context, repo *Repository, cs *Changeset, conflictColumns ...string) (sql.Result, error)
// 获取底层查询构造器(用于 Adapter 特定优化)
GetNativeBuilder() interface{}
}
QueryConstructor 查询构造器接口 - 顶层 API 用户通过此接口构建查询,具体实现由适配器提供
type QueryConstructorAutoExecutionResult ¶ added in v1.0.0
type QueryConstructorAutoExecutionResult struct {
Mode string
Statement string
Args []interface{}
Rows []map[string]interface{}
Exec *QueryConstructorExecSummary
}
QueryConstructorAutoExecutionResult 表示 QueryConstructor 自动路由执行结果。 Mode=query 表示查询结果在 Rows;Mode=exec 表示写入摘要在 Exec 中。
type QueryConstructorExecSummary ¶ added in v1.0.0
type QueryConstructorExecSummary struct {
RowsAffected int64
LastInsertID *int64
Counters map[string]int
Details map[string]interface{}
}
QueryConstructorExecSummary 表示写入执行摘要。
type QueryConstructorExecutionResult ¶ added in v1.0.0
type QueryConstructorExecutionResult struct {
Statement string
Args []interface{}
Rows []map[string]interface{}
}
QueryConstructorExecutionResult 表示 QueryConstructor 统一执行结果。
type QueryConstructorProvider ¶
type QueryConstructorProvider interface {
// 创建新的查询构造器
NewQueryConstructor(schema Schema) QueryConstructor
// 获取此 Adapter 的查询能力声明
GetCapabilities() *QueryBuilderCapabilities
}
QueryConstructorProvider 查询构造器提供者接口 - 中层转义层 每个 Adapter 实现此接口,提供数据库特定的 QueryConstructor
type QueryFallbackStrategy ¶
type QueryFallbackStrategy string
QueryFallbackStrategy 查询特性不支持时的降级策略
const ( // 不支持,无替代方案 QueryFallbackNone QueryFallbackStrategy = "none" // 在应用层处理(客户端过滤/排序等) QueryFallbackApplicationLayer QueryFallbackStrategy = "application_layer" // 通过数据库自定义函数降级(如 SQLite 注册 JSON_EXTRACT_GO) QueryFallbackCustomFunction QueryFallbackStrategy = "custom_function" // 使用替代语法(例如 SQL Server vs PostgreSQL) QueryFallbackAlternativeSyntax QueryFallbackStrategy = "alternative_syntax" // 分解为多个简单查询 QueryFallbackMultiQuery QueryFallbackStrategy = "multi_query" // 使用临时表 QueryFallbackTemporaryTable QueryFallbackStrategy = "temporary_table" )
type QueryFeature ¶
type QueryFeature struct {
Name string // 特性名称(如 "IN_RANGE_QUERY")
Supported bool // 是否支持
Fallback QueryFallbackStrategy // 不支持时的降级策略
Notes string // 备注说明
SQLExamples map[string]string // 各数据库的 SQL 示例 (数据库名 => SQL)
}
QueryFeature 单个查询特性描述
type QueryFeatureCategory ¶
type QueryFeatureCategory string
QueryFeatureCategory 查询特性分类
const ( // 基础查询操作 QueryCategoryBasicOps QueryFeatureCategory = "basic_operations" // JOIN 操作 QueryCategoryJoinOps QueryFeatureCategory = "join_operations" // 高级查询特性 QueryCategoryAdvancedQueries QueryFeatureCategory = "advanced_queries" // 聚合和分析 QueryCategoryAggregation QueryFeatureCategory = "aggregation" // 文本搜索 QueryCategoryTextSearch QueryFeatureCategory = "text_search" // JSON 相关操作 QueryCategoryJSON QueryFeatureCategory = "json_operations" )
type QueryFeatures ¶
type QueryFeatures struct {
// 基础查询特性
SupportsIN bool // IN (value1, value2, ...) 范围查询
SupportsNotIN bool // NOT IN 查询
SupportsBetween bool // BETWEEN 查询
SupportsLike bool // LIKE 模式匹配
SupportsDistinct bool // DISTINCT 去重
SupportsGroupBy bool // GROUP BY 分组
SupportsHaving bool // HAVING 条件过滤
// JOIN 操作
SupportsInnerJoin bool // INNER JOIN
SupportsLeftJoin bool // LEFT JOIN
SupportsRightJoin bool // RIGHT JOIN
SupportsCrossJoin bool // CROSS JOIN
SupportsFullOuterJoin bool // FULL OUTER JOIN
SupportsSelfJoin bool // 自连接
// 高级查询特性
SupportsCTE bool // 公用表表达式 (WITH ... AS)
SupportsRecursiveCTE bool // 递归 CTE
SupportsWindowFunc bool // 窗口函数 (ROW_NUMBER, RANK, etc)
SupportsSubquery bool // 子查询
SupportsUnion bool // UNION / UNION ALL
SupportsExcept bool // EXCEPT / MINUS
SupportsIntersect bool // INTERSECT
// 聚合和分析函数
SupportsOrderByInAggregate bool // 聚合函数中的 ORDER BY (如 STRING_AGG(...ORDER BY...))
SupportsArrayAggregate bool // 数组聚合
SupportsStringAggregate bool // 字符串聚合
// 文本搜索
SupportsFullTextSearch bool // 全文搜索
SupportsRegexMatch bool // 正则表达式匹配
SupportsFuzzyMatch bool // 模糊匹配
// JSON 操作
SupportsJSONPath bool // JSON 路径提取
SupportsJSONType bool // JSON 数据类型
SupportsJSONOperators bool // JSON 运算符
SupportsJSONAgg bool // JSON 聚合
// 案例表达式
SupportsCase bool // CASE WHEN THEN ELSE END
SupportsCaseWithElse bool // CASE 带 ELSE
// 其他特性
SupportsLimit bool // LIMIT 限制行数
SupportsOffset bool // OFFSET 偏移
SupportsOrderBy bool // ORDER BY 排序
SupportsNulls bool // IS NULL / IS NOT NULL
SupportsCastType bool // CAST(...AS type)
SupportsCoalesce bool // COALESCE 函数
// 特殊数据库特性
SupportsIfExists bool // IF EXISTS 子句
SupportsInsertIgnore bool // INSERT IGNORE (MySQL) 或 ON CONFLICT (PostgreSQL)
SupportsUpsert bool // INSERT ... ON DUPLICATE KEY UPDATE 或 ON CONFLICT
// ==================== VIEW 支持 ====================
SupportsView bool // 是否支持 VIEW
SupportsMaterializedView bool // 物化视图支持(如 PostgreSQL)
SupportsViewForPreload bool // 是否支持用 VIEW 实现 Preload 优化
// ==================== 多 Adapter 路由优化信息 ====================
// Search 操作优化
SearchOptimizationSupported bool // 该 adapter 是否支持 search
SearchOptimizationIsOptimal bool // 是否是 search 的最优 adapter
SearchOptimizationPriority int // 路由优先级 (1=最优, 2=次优, 3=备选)
// Recursive 查询优化
RecursiveOptimizationSupported bool // 是否支持递归查询
RecursiveOptimizationIsOptimal bool // 是否是递归查询的最优 adapter
RecursiveOptimizationPriority int // 路由优先级
RecursiveOptimizationHasNativeSyntax bool // 是否有原生递归语法(否则需要补偿)
// Adapter 功能标签
AdapterTags []string // 功能标签,如 ["text_search", "graph", "relational", "time_series"]
// 优化说明
OptimizationNotes map[string]string // 各种优化信息的说明
// 映射:特性名 => 降级策略
FallbackStrategies map[string]QueryFallbackStrategy
// 特性说明
FeatureNotes map[string]string
// 替代语法映射
AlternativeSyntax map[string]string
// 版本化特性支持(可选)
FeatureSupport map[string]FeatureSupport
}
QueryFeatures 数据库查询特性集合
func GetQueryFeatures ¶
func GetQueryFeatures(dbType string) *QueryFeatures
GetQueryFeatures 获取数据库的查询特性
func NewMongoQueryFeatures ¶
func NewMongoQueryFeatures() *QueryFeatures
NewMongoQueryFeatures MongoDB 查询特性(最小占位实现)
func NewMySQLQueryFeatures ¶
func NewMySQLQueryFeatures() *QueryFeatures
NewMySQLQueryFeatures MySQL 查询特性
func NewNeo4jQueryFeatures ¶ added in v1.0.0
func NewNeo4jQueryFeatures() *QueryFeatures
NewNeo4jQueryFeatures Neo4j 查询特性(Cypher 能力映射)。
func NewPostgreSQLQueryFeatures ¶
func NewPostgreSQLQueryFeatures() *QueryFeatures
NewPostgreSQLQueryFeatures PostgreSQL 查询特性
func NewSQLServerQueryFeatures ¶
func NewSQLServerQueryFeatures() *QueryFeatures
NewSQLServerQueryFeatures SQL Server 查询特性
func NewSQLiteQueryFeatures ¶
func NewSQLiteQueryFeatures() *QueryFeatures
NewSQLiteQueryFeatures SQLite 查询特性
func (*QueryFeatures) GetAlternativeSyntax ¶
func (qf *QueryFeatures) GetAlternativeSyntax(feature string) string
GetAlternativeSyntax 获取替代语法
func (*QueryFeatures) GetFallbackStrategy ¶
func (qf *QueryFeatures) GetFallbackStrategy(feature string) QueryFallbackStrategy
GetFallbackStrategy 获取不支持特性时的降级策略
func (*QueryFeatures) GetFeatureNote ¶
func (qf *QueryFeatures) GetFeatureNote(feature string) string
GetFeatureNote 获取特性说明
func (*QueryFeatures) GetFeatureSupport ¶
func (qf *QueryFeatures) GetFeatureSupport(feature string) FeatureSupport
GetFeatureSupport 获取特性支持详情(若未定义则返回零值)
func (*QueryFeatures) HasQueryFeature ¶
func (qf *QueryFeatures) HasQueryFeature(feature string) bool
HasQueryFeature 检查是否支持某个查询特性
func (*QueryFeatures) SupportsFeatureWithVersion ¶
func (qf *QueryFeatures) SupportsFeatureWithVersion(feature, version string) bool
SupportsFeatureWithVersion 根据版本判断特性支持(version 为空时退回到常规判断)
type QueryIR ¶ added in v1.0.0
type QueryIR struct {
Source QuerySourceIR
Projections []string
Conditions []Condition
OrderBys []QueryOrderIR
Limit *int
Offset *int
Joins []QueryJoinIR
CrossTableStrategy CrossTableStrategy
Hints QueryCompileHints
}
QueryIR 表示查询的中间表示(IR),用于解耦构建阶段与目标语言编译阶段。
type QueryJoinIR ¶ added in v1.0.0
type QueryJoinIR struct {
JoinType string
Semantic JoinSemantic // 语义意图(来自 JoinBuilder.semantic);"" 表示 raw Join 或未设置
Relation *QueryJoinRelationIR
Table string
Schema Schema // Schema 引用,来自 JoinBuilder,nil 表示 raw string JOIN
Alias string
OnClause string
Filters []Condition // 对连接目标实体的额外过滤条件(各后端自行处理)
}
QueryJoinIR 连接信息。
type QueryJoinRelationIR ¶ added in v1.1.0
type QueryJoinRelationIR struct {
Type RelationType
Name string
Direction string // "forward" | "reverse"
Reversible bool
ResolvedBy string // "relation_registry" | "foreign_key"
Through *QueryRelationThroughIR
}
QueryJoinRelationIR 关系元数据(用于适配器优化)。 例如: - SQL Server 可基于 ManyToMany + Through 选择递归 CTE 或中间表路径。 - Neo4j 可基于 Through 将中间关系映射为边/路径展开。 - Mongo 可生成多段 $lookup 管道。
type QueryOrderIR ¶ added in v1.0.0
QueryOrderIR 排序信息。
type QueryRelationThroughIR ¶ added in v1.1.0
QueryRelationThroughIR 多对多中间关系元数据。
type QuerySourceIR ¶ added in v1.0.0
type QuerySourceIR struct {
Table string
Alias string
Schema Schema // Schema 引用,nil 表示非 Schema 感知模式
}
QuerySourceIR 查询数据源。
type QueryViewRouteIR ¶ added in v1.0.0
QueryViewRouteIR 视图路由提示。
type RangeValidator ¶ added in v1.0.0
RangeValidator 数值范围验证器(闭区间)
func NewMaxRangeValidator ¶ added in v1.0.0
func NewMaxRangeValidator(max float64) *RangeValidator
func NewMinRangeValidator ¶ added in v1.0.0
func NewMinRangeValidator(min float64) *RangeValidator
func NewRangeValidator ¶ added in v1.0.0
func NewRangeValidator(min, max float64) *RangeValidator
func (*RangeValidator) Validate ¶ added in v1.0.0
func (v *RangeValidator) Validate(value interface{}) error
type RawSQLMigration ¶
type RawSQLMigration struct {
*BaseMigration
// contains filtered or unexported fields
}
RawSQLMigration 原始 SQL 迁移
func NewRawSQLMigration ¶
func NewRawSQLMigration(version, description string) *RawSQLMigration
NewRawSQLMigration 创建原始 SQL 迁移
func (*RawSQLMigration) AddDownSQL ¶
func (m *RawSQLMigration) AddDownSQL(sql string) *RawSQLMigration
AddDownSQL 添加 Down SQL
func (*RawSQLMigration) AddUpSQL ¶
func (m *RawSQLMigration) AddUpSQL(sql string) *RawSQLMigration
AddUpSQL 添加 Up SQL
func (*RawSQLMigration) Down ¶
func (m *RawSQLMigration) Down(ctx context.Context, repo *Repository) error
Down 回滚迁移
func (*RawSQLMigration) ForAdapter ¶
func (m *RawSQLMigration) ForAdapter(adapter string) *RawSQLMigration
ForAdapter 指定 adapter
func (*RawSQLMigration) Up ¶
func (m *RawSQLMigration) Up(ctx context.Context, repo *Repository) error
Up 执行迁移
type RecursiveQueryBuilder ¶ added in v1.0.0
type RecursiveQueryBuilder struct {
// contains filtered or unexported fields
}
RecursiveQueryBuilder 构建 SQL Server T-SQL 递归 CTE 查询。
生成的 T-SQL 格式:
WITH [cte_name] ([col1], [col2], ...) AS (
<anchor> -- 锚定成员(基准结果集)
UNION ALL
<recursive> -- 递归成员(自我引用 CTE)
)
SELECT <select> FROM [cte_name]
OPTION (MAXRECURSION <n>)
func (*RecursiveQueryBuilder) Anchor ¶ added in v1.0.0
func (b *RecursiveQueryBuilder) Anchor(sql string) *RecursiveQueryBuilder
Anchor 设置递归 CTE 的锚定成员(基准查询,非递归部分)。 应为完整的 SELECT 语句,不含 UNION。
func (*RecursiveQueryBuilder) Build ¶ added in v1.0.0
func (b *RecursiveQueryBuilder) Build() (string, error)
Build 生成最终的 T-SQL 字符串。不执行查询,可用于日志或调试。
func (*RecursiveQueryBuilder) Columns ¶ added in v1.0.0
func (b *RecursiveQueryBuilder) Columns(cols ...string) *RecursiveQueryBuilder
Columns 可选:显式声明 CTE 的列名列表(对应 WITH name (col1, col2) AS ...)。 若不调用则不生成列名声明,由 anchor SELECT 决定列名。
func (*RecursiveQueryBuilder) Execute ¶ added in v1.0.0
Execute 构建并执行递归 CTE 查询,返回原始 *sql.Rows。 调用方负责关闭 rows(defer rows.Close())。
func (*RecursiveQueryBuilder) MaxRecursion ¶ added in v1.0.0
func (b *RecursiveQueryBuilder) MaxRecursion(n int) *RecursiveQueryBuilder
MaxRecursion 设置 OPTION(MAXRECURSION n)。 n = 0 表示不限制(等同于 OPTION(MAXRECURSION 0));默认为 100(SQL Server 默认)。
func (*RecursiveQueryBuilder) OrderBy ¶ added in v1.0.0
func (b *RecursiveQueryBuilder) OrderBy(expr string) *RecursiveQueryBuilder
OrderBy 设置最终 SELECT 的 ORDER BY 子句(不含 ORDER BY 关键字)。
示例:OrderBy("depth ASC, name")
func (*RecursiveQueryBuilder) Recursive ¶ added in v1.0.0
func (b *RecursiveQueryBuilder) Recursive(sql string) *RecursiveQueryBuilder
Recursive 设置递归成员(自我引用上一步结果的查询)。 应为完整的 SELECT 语句,JOIN 部分引用 cteName。
func (*RecursiveQueryBuilder) ScanRows ¶ added in v1.0.0
func (b *RecursiveQueryBuilder) ScanRows(ctx context.Context) ([]map[string]interface{}, error)
ScanRows 是 Execute 的便捷包装,将每一行扫描为 map[string]interface{}。 适合字段集不确定的场景;对于已知结构推荐直接使用 Execute 手动 Scan。
func (*RecursiveQueryBuilder) Select ¶ added in v1.0.0
func (b *RecursiveQueryBuilder) Select(selectExpr string) *RecursiveQueryBuilder
Select 设置从 CTE 中最终 SELECT 的列表达式,如 "id, name, depth"。 若不调用,默认使用 SELECT *。
func (*RecursiveQueryBuilder) SelectAll ¶ added in v1.0.0
func (b *RecursiveQueryBuilder) SelectAll() *RecursiveQueryBuilder
SelectAll 设置最终查询为 SELECT *(默认行为,显式调用以提高可读性)。
func (*RecursiveQueryBuilder) Where ¶ added in v1.0.0
func (b *RecursiveQueryBuilder) Where(condition string, args ...interface{}) *RecursiveQueryBuilder
Where 设置最终 SELECT 的 WHERE 过滤条件(不含 WHERE 关键字)。 参数化值使用 @p1、@p2 ... 作为占位符(SQL Server 风格)。
示例:Where("depth <= @p1", 3)
type RegexValidator ¶ added in v1.0.0
RegexValidator 通用正则验证器
func (*RegexValidator) Validate ¶ added in v1.0.0
func (v *RegexValidator) Validate(value interface{}) error
type RelationThrough ¶ added in v1.1.0
type RelationThrough struct {
Schema Schema // 中间关系 Schema(优先)
Table string // 中间关系表/集合名(Schema 为空时兜底)
SourceKey string // source -> through 的连接键
TargetKey string // through -> target 的连接键
}
RelationThrough 声明多对多关系的中间关系信息。
SQL 可将 Table 视为中间表(可做递归 CTE / join 表优化); Neo4j 可将其映射为边关系类型或中间节点; Mongo 可将其用于两段 $lookup 管道。
type RelationType ¶
type RelationType string
const ( OneToOne RelationType = "one_to_one" OneToMany RelationType = "one_to_many" ManyToOne RelationType = "many_to_one" ManyToMany RelationType = "many_to_many" )
const ( // RelationHasMany 一对多:本 Schema 是"一"侧,目标 Schema 持有外键(FK 在目标侧)。 // 连接时默认 optional(本实体可能有 0 个目标实体)。 RelationHasMany RelationType = "has_many" // RelationHasOne 一对一:本 Schema 是"一"侧,目标 Schema 持有外键(FK 在目标侧)。 // 连接时默认 optional(本实体可能没有对应目标实体)。 RelationHasOne RelationType = "has_one" // RelationBelongsTo 多对一:本 Schema 持有外键(FK 在本侧),目标 Schema 是"一"侧。 // 连接时默认 required(本实体必须有对应父实体)。 RelationBelongsTo RelationType = "belongs_to" // RelationManyToMany 多对多:通常需要 Through 中间关系(中间表/中间边)。 // 连接时默认 optional。 RelationManyToMany RelationType = ManyToMany )
Schema 关系类型常量(ORM 风格,用于 SchemaRelation 关系注册表)。 使用与 relationship.go 中相同的 RelationType 类型,添加 HasMany/HasOne/BelongsTo 语义。
type RelationalSchema ¶ added in v1.1.0
type RelationalSchema interface {
Schema
Relations() []SchemaRelation
FindRelation(targetTable string) *SchemaRelation
}
RelationalSchema 扩展 Schema,支持显式关系注册(HasMany / HasOne / BelongsTo)。 BaseSchema 实现此接口;关系注册优先于 FK 约束用于连接语义推断和跨集合关联。
type Relationship ¶
type Relationship struct {
// 关系名称(用于查询时引用)
Name string
// 源表和目标表
FromSchema Schema
ToSchema Schema
// 关系类型
Type RelationType
// 外键定义
ForeignKey *ForeignKeyDef
// 关联表(仅用于多对多)
JoinTable *JoinTableDef
}
Relationship 表示表之间的关系定义
type RelationshipManager ¶
type RelationshipManager interface {
// 获取该 Adapter 的关系支持能力
GetRelationshipSupport() *RelationshipSupport
// 创建关系(创建外键、中间表等)
CreateRelationship(ctx context.Context, rel *Relationship) error
// 删除关系
DropRelationship(ctx context.Context, fromTable, relName string) error
// 查询关系(带关联数据)
QueryWithRelation(ctx context.Context, schema Schema, rel *Relationship, query string, args ...interface{}) (interface{}, error)
// 检查关系是否存在
HasRelationship(ctx context.Context, fromTable, relName string) (bool, error)
}
RelationshipManager Adapter 需要实现的关系管理接口
type RelationshipStrategy ¶
type RelationshipStrategy string
const ( // 原生支持(PostgreSQL, SQL Server) StrategyNative RelationshipStrategy = "native" // 通过中间表模拟多对多(MySQL, SQLite) StrategyJoinTable RelationshipStrategy = "join_table" // 通过外键实现关系(所有关系型数据库) StrategyForeignKey RelationshipStrategy = "foreign_key" // 应用层实现(非关系型数据库) StrategyApplication RelationshipStrategy = "application" // 完全不支持 StrategyNotSupported RelationshipStrategy = "not_supported" )
type RelationshipSupport ¶
type RelationshipSupport struct {
// 基础关系类型支持
OneToOne bool
OneToMany bool
ManyToMany bool
// 关系特性
SupportsForeignKey bool // 是否支持外键约束
SupportsJoin bool // 是否支持 JOIN 操作
SupportsNested bool // 是否支持嵌套关系查询
// 实现方式
Strategy RelationshipStrategy // 如何实现关系
}
RelationshipSupport 关系支持能力声明
type RelationshipValidator ¶
type RelationshipValidator struct {
// contains filtered or unexported fields
}
RelationshipValidator 用于验证关系定义的有效性和兼容性
func NewRelationshipValidator ¶
func NewRelationshipValidator(support *RelationshipSupport) *RelationshipValidator
NewRelationshipValidator 创建验证器
func (*RelationshipValidator) CanJoin ¶
func (v *RelationshipValidator) CanJoin() bool
CanJoin 检查是否可以执行 JOIN 操作
func (*RelationshipValidator) GetSupportSummary ¶
func (v *RelationshipValidator) GetSupportSummary() map[string]bool
GetSupportSummary 获取支持情况的总结
func (*RelationshipValidator) NeedsManyToManyEmulation ¶
func (v *RelationshipValidator) NeedsManyToManyEmulation(rel *Relationship) bool
NeedsManyToManyEmulation 检查是否需要多对多转发
func (*RelationshipValidator) ValidateRelationship ¶
func (v *RelationshipValidator) ValidateRelationship(rel *Relationship) error
ValidateRelationship 验证单个关系是否在 Adapter 支持范围内
type Repository ¶
type Repository struct {
// contains filtered or unexported fields
}
Repository 数据库仓储对象 (类似 Ecto.Repo)
func InitDB ¶
func InitDB(configPath string) (*Repository, error)
InitDB 使用配置文件初始化数据库 这是推荐的使用方式,遵循 Ecto 的依赖注入模式
func InitDBFromAdapterRegistry ¶
func InitDBFromAdapterRegistry(configPath, adapterName string) (*Repository, error)
InitDBFromAdapterRegistry 从多 Adapter 配置文件初始化指定 adapter configPath: YAML/JSON 配置文件路径 adapterName: 在 adapters 中注册的名称
func InitDBFromEnv ¶
func InitDBFromEnv() (*Repository, error)
InitDBFromEnv 使用环境变量初始化数据库 环境变量:
DB_ADAPTER: 适配器类型 (sqlite/postgres/mysql) DB_PATH: SQLite 数据库文件路径 DB_HOST: 数据库主机 DB_PORT: 数据库端口 DB_USER: 数据库用户名 DB_PASSWORD: 数据库密码 DB_NAME: 数据库名称 DB_SSL_MODE: PostgreSQL SSL 模式
func InitDBWithDefaults ¶
func InitDBWithDefaults(adapterType string) (*Repository, error)
InitDBWithDefaults 使用默认配置初始化数据库
func NewRepository ¶
func NewRepository(config *Config) (*Repository, error)
NewRepository 创建新的仓储实例 (通过配置注入)
func NewRepositoryFromAdapterConfig ¶
func NewRepositoryFromAdapterConfig(name string) (*Repository, error)
NewRepositoryFromAdapterConfig 通过已注册的 Adapter 配置创建 Repository
func (*Repository) AnalyzeFuzzySearch ¶ added in v1.0.0
func (r *Repository) AnalyzeFuzzySearch(ctx context.Context, field, keyword, version string) (*FuzzySearchPlan, error)
AnalyzeFuzzySearch 根据数据库能力(含运行时插件探测)生成模糊查询计划。
func (*Repository) Begin ¶
func (r *Repository) Begin(ctx context.Context, opts ...interface{}) (Tx, error)
Begin 开始事务 Deprecated: 这是底层事务原语,主要供迁移/框架集成使用。 业务层应优先使用 Repository.WithChangeset,以避免绕过 Changeset 校验与写入封装。
func (*Repository) BuildAndCacheQuery ¶ added in v1.0.0
func (r *Repository) BuildAndCacheQuery(ctx context.Context, cacheKey string, constructor QueryConstructor) (query string, args []interface{}, cacheHit bool, err error)
BuildAndCacheQuery 编译查询并缓存;命中缓存时直接返回。 返回值 cacheHit=true 表示直接复用缓存,无需再次 Build。
func (*Repository) BuildAndCacheQueryTemplate ¶ added in v1.0.0
func (r *Repository) BuildAndCacheQueryTemplate(ctx context.Context, cacheKey string, constructor QueryConstructor) (query string, argCount int, cacheHit bool, err error)
BuildAndCacheQueryTemplate 编译查询模板并缓存;命中缓存时直接返回模板。 与 BuildAndCacheQuery 的区别是该 API 不缓存具体参数值,仅缓存 query 文本和参数位个数。
func (*Repository) BuildFuzzyCondition ¶ added in v1.0.0
func (r *Repository) BuildFuzzyCondition(field, keyword, version string) Condition
BuildFuzzyCondition 构建兼容模糊查询条件: - 支持 full_text_search 时使用 FullText - 不支持时自动降级为 LIKE '%keyword%' version 用于版本化能力判断(可为空)
func (*Repository) BuildFuzzyConditionWithContext ¶ added in v1.0.0
func (r *Repository) BuildFuzzyConditionWithContext(ctx context.Context, field, keyword, version string) (Condition, error)
BuildFuzzyConditionWithContext 构建兼容模糊查询条件(带上下文能力探测)
func (*Repository) ClearCompiledQueryCache ¶ added in v1.0.0
func (r *Repository) ClearCompiledQueryCache()
ClearCompiledQueryCache 清空 Repository 的查询编译缓存。
func (*Repository) DecideFeatureExecution ¶ added in v1.0.0
func (r *Repository) DecideFeatureExecution(feature, version string) (*FeatureExecutionDecision, error)
DecideFeatureExecution 决策某功能应走原生、自定义、降级或报错
func (*Repository) ExecCypher ¶ added in v1.0.0
func (r *Repository) ExecCypher(ctx context.Context, cypher string, params map[string]interface{}) (*CypherWriteSummary, error)
ExecCypher 在 Repository 上执行 Neo4j 写查询。
func (*Repository) ExecWithCachedTemplate ¶ added in v1.0.0
func (r *Repository) ExecWithCachedTemplate(ctx context.Context, cacheKey string, args ...interface{}) (sql.Result, error)
ExecWithCachedTemplate 使用缓存模板执行写操作。
func (*Repository) ExecuteFeature ¶ added in v1.0.0
func (r *Repository) ExecuteFeature(ctx context.Context, feature, version string, input map[string]interface{}) (interface{}, error)
ExecuteFeature 尝试执行功能;仅在 custom 模式下真正执行。 native/fallback/unsupported 会返回解释性错误,便于上层路由决策。
func (*Repository) ExecuteQueryConstructor ¶ added in v1.0.0
func (r *Repository) ExecuteQueryConstructor(ctx context.Context, constructor QueryConstructor) (*QueryConstructorExecutionResult, error)
ExecuteQueryConstructor 执行 QueryConstructor,自动路由 SQL/Neo4j/MongoDB。 - SQL 适配器:执行 Query 并将结果扫描为 []map[string]interface{} - Neo4j 适配器:执行 QueryCypher 并返回记录 - MongoDB 适配器:执行 BSON Find 计划并返回文档
func (*Repository) ExecuteQueryConstructorAuto ¶ added in v1.0.0
func (r *Repository) ExecuteQueryConstructorAuto(ctx context.Context, constructor QueryConstructor) (*QueryConstructorAutoExecutionResult, error)
ExecuteQueryConstructorAuto 执行 QueryConstructor,自动识别读/写语义并路由到 adapter。
路由规则: - SQL:SELECT/WITH...SELECT 走 Query,其他语句走 Exec - Neo4j:MATCH/OPTIONAL MATCH/RETURN/CALL...YIELD 走 Query,其余走 ExecCypher - MongoDB:支持由 MongoQueryConstructor 生成的 MONGO_FIND:: 查询计划(query)与 MONGO_WRITE:: 写入计划(exec)
func (*Repository) ExecuteQueryConstructorPaged ¶ added in v1.1.1
func (r *Repository) ExecuteQueryConstructorPaged(ctx context.Context, constructor QueryConstructor, page int, pageSize int) (*PagedQueryConstructorExecutionResult, error)
ExecuteQueryConstructorPaged 执行分页查询,并返回总数与分页元信息。
func (*Repository) ExecuteQueryConstructorPagedWithCache ¶ added in v1.1.1
func (r *Repository) ExecuteQueryConstructorPagedWithCache(ctx context.Context, cacheKeyPrefix string, constructor QueryConstructor, page int, pageSize int) (*PagedQueryConstructorExecutionResult, error)
ExecuteQueryConstructorPagedWithCache 执行分页查询,并为分页查询与 count 查询接入编译缓存。
func (*Repository) ExecuteQueryConstructorPaginated ¶ added in v1.1.1
func (r *Repository) ExecuteQueryConstructorPaginated(ctx context.Context, constructor QueryConstructor, builder *PaginationBuilder) (*PagedQueryConstructorExecutionResult, error)
ExecuteQueryConstructorPaginated 使用统一分页语义执行查询(offset/cursor/auto)。
func (*Repository) ExecuteQueryConstructorPaginatedWithCache ¶ added in v1.1.1
func (r *Repository) ExecuteQueryConstructorPaginatedWithCache(ctx context.Context, cacheKeyPrefix string, constructor QueryConstructor, builder *PaginationBuilder) (*PagedQueryConstructorExecutionResult, error)
ExecuteQueryConstructorPaginatedWithCache 使用统一分页语义执行查询,并为分页查询与 count 查询接入编译缓存。
func (*Repository) ExecuteQueryConstructorWithCache ¶ added in v1.0.0
func (r *Repository) ExecuteQueryConstructorWithCache(ctx context.Context, cacheKey string, constructor QueryConstructor) (*QueryConstructorExecutionResult, bool, error)
ExecuteQueryConstructorWithCache 执行 QueryConstructor,并在编译阶段接入缓存。 返回 cacheHit=true 表示复用了已缓存的编译结果。
func (*Repository) GetAdapter ¶
func (r *Repository) GetAdapter() Adapter
GetAdapter 获取底层适配器 (用于高级操作)
func (*Repository) GetCompiledQuery ¶ added in v1.0.0
func (r *Repository) GetCompiledQuery(cacheKey string) (*CompiledQuery, bool)
GetCompiledQuery 从缓存读取已编译查询。
func (*Repository) GetCompiledQueryCacheStats ¶ added in v1.0.0
func (r *Repository) GetCompiledQueryCacheStats() CompiledQueryCacheStats
GetCompiledQueryCacheStats 返回查询缓存命中统计。
func (*Repository) GetCompiledQueryTemplate ¶ added in v1.0.0
func (r *Repository) GetCompiledQueryTemplate(cacheKey string) (*CompiledQueryTemplate, bool)
GetCompiledQueryTemplate 从缓存读取查询模板。
func (*Repository) GetGormDB ¶
func (r *Repository) GetGormDB() *gorm.DB
GetGormDB 从 Repository 获取 GORM 实例 Deprecated: 为了保持 Adapter 与 ORM 解耦,此方法始终返回 nil。
func (*Repository) GetQueryBuilderCapabilities ¶ added in v1.0.0
func (r *Repository) GetQueryBuilderCapabilities() (*QueryBuilderCapabilities, error)
GetQueryBuilderCapabilities 获取当前适配器的查询构造能力声明
func (*Repository) GetStartupCapabilityReport ¶ added in v1.0.0
func (r *Repository) GetStartupCapabilityReport() *StartupCapabilityReport
GetStartupCapabilityReport 返回最近一次启动体检报告。
func (*Repository) InvalidateCompiledQuery ¶ added in v1.0.0
func (r *Repository) InvalidateCompiledQuery(cacheKey string)
InvalidateCompiledQuery 删除指定缓存键。
func (*Repository) ListScheduledTasks ¶
func (r *Repository) ListScheduledTasks(ctx context.Context) ([]*ScheduledTaskStatus, error)
ListScheduledTasks 列出所有已注册的定时任务
func (*Repository) NewChangesetExecutor ¶ added in v1.0.0
func (r *Repository) NewChangesetExecutor(ctx context.Context, schema Schema) (*ChangesetExecutor, error)
NewChangesetExecutor 创建面向业务层的 Changeset 执行器。
func (*Repository) NewQueryConstructor ¶ added in v1.0.0
func (r *Repository) NewQueryConstructor(schema Schema) (QueryConstructor, error)
NewQueryConstructor 创建 v2 查询构造器(推荐)
func (*Repository) QueryCypher ¶ added in v1.0.0
func (r *Repository) QueryCypher(ctx context.Context, cypher string, params map[string]interface{}) ([]map[string]interface{}, error)
QueryCypher 在 Repository 上执行 Neo4j 读查询。
func (*Repository) QueryRowWithCachedTemplate ¶ added in v1.0.0
func (r *Repository) QueryRowWithCachedTemplate(ctx context.Context, cacheKey string, args ...interface{}) (*sql.Row, error)
QueryRowWithCachedTemplate 使用缓存模板执行单行查询。
func (*Repository) QueryStruct ¶
func (r *Repository) QueryStruct(ctx context.Context, dest interface{}, sql string, args ...interface{}) error
QueryStruct 查询单个结构体 自动将查询结果映射到结构体
func (*Repository) QueryStructs ¶
func (r *Repository) QueryStructs(ctx context.Context, dest interface{}, sql string, args ...interface{}) error
QueryStructs 查询多个结构体 自动将查询结果映射到结构体切片
func (*Repository) QueryWithCachedTemplate ¶ added in v1.0.0
func (r *Repository) QueryWithCachedTemplate(ctx context.Context, cacheKey string, args ...interface{}) (*sql.Rows, error)
QueryWithCachedTemplate 使用缓存模板执行查询。
func (*Repository) RegisterScheduledTask ¶
func (r *Repository) RegisterScheduledTask(ctx context.Context, task *ScheduledTaskConfig) error
RegisterScheduledTask 注册定时任务 支持按月自动创建表等后台任务,具体实现由各个适配器决定:
- PostgreSQL: 使用触发器和 pg_cron 扩展
- MySQL: 使用 MySQL EVENT
- SQLite/其他: 建议由应用层通过 cron 库处理
func (*Repository) RunStartupCapabilityCheck ¶ added in v1.0.0
func (r *Repository) RunStartupCapabilityCheck(ctx context.Context, cfg *StartupCapabilityConfig) (*StartupCapabilityReport, error)
RunStartupCapabilityCheck 执行启动期能力体检并根据 strict/lenient 决策。
func (*Repository) StoreCompiledQuery ¶ added in v1.0.0
func (r *Repository) StoreCompiledQuery(cacheKey string, query string, args ...interface{}) error
StoreCompiledQuery 手动写入一条编译查询到缓存。
func (*Repository) StoreCompiledQueryTemplate ¶ added in v1.0.0
func (r *Repository) StoreCompiledQueryTemplate(cacheKey string, query string, argCount int) error
StoreCompiledQueryTemplate 手动写入一条查询模板到缓存。
func (*Repository) UnregisterScheduledTask ¶
func (r *Repository) UnregisterScheduledTask(ctx context.Context, taskName string) error
UnregisterScheduledTask 注销定时任务
func (*Repository) WithChangeset ¶ added in v1.0.0
func (r *Repository) WithChangeset(ctx context.Context, schema Schema, fn func(*ChangesetExecutor) error) error
WithChangeset 在单个事务内执行一组基于 Changeset 的写操作。 这是业务层推荐的多步写入入口。
type RequiredValidator ¶
type RequiredValidator struct{}
RequiredValidator 必填验证器
func (*RequiredValidator) Validate ¶
func (v *RequiredValidator) Validate(value interface{}) error
type SQLDialect ¶
type SQLDialect interface {
// 获取方言名称
Name() string
// 转义标识符(表名、列名)
QuoteIdentifier(name string) string
// 转义字符串值
QuoteValue(value interface{}) string
// 返回参数化占位符(? 或 $1 等)
GetPlaceholder(index int) string
// 生成 LIMIT/OFFSET 子句
GenerateLimitOffset(limit *int, offset *int) string
// 转换条件为 SQL(可选的方言特定优化)
TranslateCondition(condition Condition, argIndex *int) (string, []interface{}, error)
}
SQLDialect SQL 方言接口 不同的数据库可以实现此接口来提供方言特定的 SQL 生成
type SQLQueryConstructor ¶
type SQLQueryConstructor struct {
// contains filtered or unexported fields
}
SQLQueryConstructor SQL 查询构造器 - 底层执行层 实现 QueryConstructor 接口,生成标准 SQL 每个 Adapter 可以通过继承和覆写方法来实现方言特定的 SQL 生成
func NewSQLQueryConstructor ¶
func NewSQLQueryConstructor(schema Schema, dialect SQLDialect) *SQLQueryConstructor
NewSQLQueryConstructor 创建新的 SQL 查询构造器
func NewSQLQueryConstructorWithCompiler ¶ added in v1.0.0
func NewSQLQueryConstructorWithCompiler(schema Schema, dialect SQLDialect, compiler QueryCompiler) *SQLQueryConstructor
NewSQLQueryConstructorWithCompiler 使用指定编译器创建查询构造器。 若 compiler 为 nil,则默认使用 BaseSQLCompiler。
func (*SQLQueryConstructor) Build ¶
func (qb *SQLQueryConstructor) Build(ctx context.Context) (string, []interface{}, error)
Build 构建 SQL 查询
func (*SQLQueryConstructor) BuildIR ¶ added in v1.0.0
func (qb *SQLQueryConstructor) BuildIR(ctx context.Context) (*QueryIR, error)
BuildIR 构建独立查询 IR(中间表示)。 该方法不会生成最终 SQL/Cypher,便于后续接入多语言编译器。
func (*SQLQueryConstructor) Count ¶ added in v1.1.0
func (qb *SQLQueryConstructor) Count(fieldName ...string) QueryConstructor
func (*SQLQueryConstructor) CountWith ¶ added in v1.1.0
func (qb *SQLQueryConstructor) CountWith(builder *CountBuilder) QueryConstructor
func (*SQLQueryConstructor) CrossJoin ¶ added in v1.0.0
func (qb *SQLQueryConstructor) CrossJoin(table string, alias ...string) QueryConstructor
CrossJoin 添加 CROSS JOIN(可选别名,无 ON 条件)。
func (*SQLQueryConstructor) CrossTableStrategy ¶ added in v1.0.0
func (qb *SQLQueryConstructor) CrossTableStrategy(strategy CrossTableStrategy) QueryConstructor
CrossTableStrategy 设置跨表查询策略。
func (*SQLQueryConstructor) CursorPage ¶ added in v1.1.1
func (qb *SQLQueryConstructor) CursorPage(field string, direction string, cursorValue interface{}, cursorPrimaryValue interface{}, pageSize int) *SQLQueryConstructor
CursorPage 使用游标分页替代大 OFFSET,要求首个排序字段与游标字段一致。 当排序字段不是主键时,需要同时提供 cursorPrimaryValue 作为稳定 tie-breaker。
func (*SQLQueryConstructor) CustomMode ¶ added in v1.1.0
func (qb *SQLQueryConstructor) CustomMode() QueryConstructor
func (*SQLQueryConstructor) FromAlias ¶ added in v1.0.0
func (qb *SQLQueryConstructor) FromAlias(alias string) QueryConstructor
FromAlias 为主表设置别名,便于跨表查询中进行字段映射。
func (*SQLQueryConstructor) GetNativeBuilder ¶
func (qb *SQLQueryConstructor) GetNativeBuilder() interface{}
GetNativeBuilder 获取底层查询构造器(返回自身)
func (*SQLQueryConstructor) Join ¶ added in v1.0.0
func (qb *SQLQueryConstructor) Join(table, onClause string, alias ...string) QueryConstructor
Join 添加 INNER JOIN。 若 alias 为空,则在 PostgreSQL/SQL Server 下会自动生成别名并采用 AS 语法。
func (*SQLQueryConstructor) JoinWith ¶ added in v1.1.0
func (qb *SQLQueryConstructor) JoinWith(builder *JoinBuilder) QueryConstructor
JoinWith 使用 JoinBuilder 进行 Schema 感知的跨表连接。 表名从 builder.schema.TableName() 取得;Filter() 条件以 join alias(或表名)限定后追加到 WHERE。
func (*SQLQueryConstructor) LeftJoin ¶ added in v1.0.0
func (qb *SQLQueryConstructor) LeftJoin(table, onClause string, alias ...string) QueryConstructor
LeftJoin 添加 LEFT JOIN。
func (*SQLQueryConstructor) Limit ¶
func (qb *SQLQueryConstructor) Limit(count int) QueryConstructor
Limit 限制行数
func (*SQLQueryConstructor) Offset ¶
func (qb *SQLQueryConstructor) Offset(count int) QueryConstructor
Offset 偏移行数
func (*SQLQueryConstructor) OrderBy ¶
func (qb *SQLQueryConstructor) OrderBy(field string, direction string) QueryConstructor
OrderBy 排序
func (*SQLQueryConstructor) Page ¶ added in v1.1.1
func (qb *SQLQueryConstructor) Page(page int, pageSize int) QueryConstructor
Page 按页设置 LIMIT/OFFSET。
func (*SQLQueryConstructor) Paginate ¶ added in v1.1.1
func (qb *SQLQueryConstructor) Paginate(builder *PaginationBuilder) QueryConstructor
func (*SQLQueryConstructor) RightJoin ¶ added in v1.0.0
func (qb *SQLQueryConstructor) RightJoin(table, onClause string, alias ...string) QueryConstructor
RightJoin 添加 RIGHT JOIN。
func (*SQLQueryConstructor) Select ¶
func (qb *SQLQueryConstructor) Select(fields ...string) QueryConstructor
Select 选择字段
func (*SQLQueryConstructor) SelectCount ¶ added in v1.1.0
func (qb *SQLQueryConstructor) SelectCount(ctx context.Context, repo *Repository) (int64, error)
SelectCount 统计匹配记录数,忽略当前构造器上的分页设置。
func (*SQLQueryConstructor) Upsert ¶ added in v1.1.0
func (qb *SQLQueryConstructor) Upsert(ctx context.Context, repo *Repository, cs *Changeset, conflictColumns ...string) (sql.Result, error)
Upsert 基于 Changeset 执行 upsert。 支持方言原生 upsert;不支持时回退到事务模拟(先 UPDATE,后 INSERT)。
func (*SQLQueryConstructor) Where ¶
func (qb *SQLQueryConstructor) Where(condition Condition) QueryConstructor
Where 添加单个条件
func (*SQLQueryConstructor) WhereAll ¶
func (qb *SQLQueryConstructor) WhereAll(conditions ...Condition) QueryConstructor
WhereAll 添加多个 AND 条件
func (*SQLQueryConstructor) WhereAny ¶
func (qb *SQLQueryConstructor) WhereAny(conditions ...Condition) QueryConstructor
WhereAny 添加多个 OR 条件
func (*SQLQueryConstructor) WhereWith ¶ added in v1.1.0
func (qb *SQLQueryConstructor) WhereWith(builder *WhereBuilder) QueryConstructor
type SQLServerAdapter ¶
type SQLServerAdapter struct {
// contains filtered or unexported fields
}
SQLServerAdapter SQL Server 数据库适配器
func (*SQLServerAdapter) Begin ¶
func (a *SQLServerAdapter) Begin(ctx context.Context, opts ...interface{}) (Tx, error)
Begin 开始事务
func (*SQLServerAdapter) Connect ¶
func (a *SQLServerAdapter) Connect(ctx context.Context, config *Config) error
Connect 连接到 SQL Server 数据库
func (*SQLServerAdapter) Exec ¶
func (a *SQLServerAdapter) Exec(ctx context.Context, query string, args ...interface{}) (sql.Result, error)
Exec 执行操作 (INSERT/UPDATE/DELETE)
func (*SQLServerAdapter) GetDatabaseFeatures ¶
func (a *SQLServerAdapter) GetDatabaseFeatures() *DatabaseFeatures
GetDatabaseFeatures 返回 SQL Server 数据库特性
func (*SQLServerAdapter) GetGormDB ¶
func (a *SQLServerAdapter) GetGormDB() *gorm.DB
GetGormDB 获取GORM实例(用于直接访问GORM) Deprecated: Adapter 层不再暴露 GORM 连接。
func (*SQLServerAdapter) GetQueryBuilderProvider ¶
func (a *SQLServerAdapter) GetQueryBuilderProvider() QueryConstructorProvider
GetQueryBuilderProvider 返回查询构造器提供者
func (*SQLServerAdapter) GetQueryFeatures ¶
func (a *SQLServerAdapter) GetQueryFeatures() *QueryFeatures
GetQueryFeatures 返回 SQL Server 的查询特性
func (*SQLServerAdapter) GetRawConn ¶
func (a *SQLServerAdapter) GetRawConn() interface{}
GetRawConn 获取底层连接 (返回 *sql.DB)
func (*SQLServerAdapter) InspectFullTextRuntime ¶ added in v1.0.0
func (a *SQLServerAdapter) InspectFullTextRuntime(ctx context.Context) (*FullTextRuntimeCapability, error)
InspectFullTextRuntime 检查 SQL Server Full-Text Search 是否安装。
func (*SQLServerAdapter) InspectJSONRuntime ¶ added in v1.0.0
func (a *SQLServerAdapter) InspectJSONRuntime(ctx context.Context) (*JSONRuntimeCapability, error)
InspectJSONRuntime 检查 SQL Server JSON 运行时能力。 说明:SQL Server 的 JSON 函数能力为内建能力(2016+),并非独立插件生态。
func (*SQLServerAdapter) ListScheduledTasks ¶
func (a *SQLServerAdapter) ListScheduledTasks(ctx context.Context) ([]*ScheduledTaskStatus, error)
ListScheduledTasks SQL Server 适配器暂不支持
func (*SQLServerAdapter) Ping ¶
func (a *SQLServerAdapter) Ping(ctx context.Context) error
Ping 测试数据库连接
func (*SQLServerAdapter) Query ¶
func (a *SQLServerAdapter) Query(ctx context.Context, query string, args ...interface{}) (*sql.Rows, error)
Query 执行查询 (返回多行)
func (*SQLServerAdapter) QueryRow ¶
func (a *SQLServerAdapter) QueryRow(ctx context.Context, query string, args ...interface{}) *sql.Row
QueryRow 执行查询 (返回单行)
func (*SQLServerAdapter) RegisterScheduledTask ¶
func (a *SQLServerAdapter) RegisterScheduledTask(ctx context.Context, task *ScheduledTaskConfig) error
RegisterScheduledTask SQL Server 适配器支持 SQL Server Agent 方式的定时任务 注意:需要 SQL Server Agent 服务运行,且用户需要相应权限
func (*SQLServerAdapter) UnregisterScheduledTask ¶
func (a *SQLServerAdapter) UnregisterScheduledTask(ctx context.Context, taskName string) error
UnregisterScheduledTask SQL Server 适配器暂不支持
type SQLServerConnectionConfig ¶ added in v1.0.0
type SQLServerConnectionConfig struct {
Host string `json:"host,omitempty" yaml:"host,omitempty"`
Port int `json:"port,omitempty" yaml:"port,omitempty"`
Username string `json:"username,omitempty" yaml:"username,omitempty"`
Password string `json:"password,omitempty" yaml:"password,omitempty"`
Database string `json:"database,omitempty" yaml:"database,omitempty"`
DSN string `json:"dsn,omitempty" yaml:"dsn,omitempty"`
ManyToManyStrategy string `json:"many_to_many_strategy,omitempty" yaml:"many_to_many_strategy,omitempty"` // "direct_join" | "recursive_cte"
RecursiveCTEDepth int `json:"recursive_cte_depth,omitempty" yaml:"recursive_cte_depth,omitempty"` // 默认 8
RecursiveCTEMaxRecursion int `json:"recursive_cte_max_recursion,omitempty" yaml:"recursive_cte_max_recursion,omitempty"` // 默认 100
}
SQLServerConnectionConfig SQL Server 连接配置。
type SQLServerDialect ¶
type SQLServerDialect struct {
// contains filtered or unexported fields
}
SQL Server 方言
func NewSQLServerDialect ¶
func NewSQLServerDialect() *SQLServerDialect
func NewSQLServerDialectWithManyToManyStrategy ¶ added in v1.1.0
func NewSQLServerDialectWithManyToManyStrategy(strategy string) *SQLServerDialect
func NewSQLServerDialectWithOptions ¶ added in v1.1.0
func NewSQLServerDialectWithOptions(strategy string, recursiveCTEDepth int, maxRecursion int) *SQLServerDialect
func (*SQLServerDialect) GenerateLimitOffset ¶
func (d *SQLServerDialect) GenerateLimitOffset(limit *int, offset *int) string
SQL Server 使用 OFFSET...ROWS FETCH...ROWS ONLY 语法
func (*SQLServerDialect) GetPlaceholder ¶
func (d *SQLServerDialect) GetPlaceholder(index int) string
SQL Server 使用 @p1, @p2 形式的参数
func (*SQLServerDialect) Name ¶
func (d *SQLServerDialect) Name() string
func (*SQLServerDialect) QuoteIdentifier ¶
func (d *SQLServerDialect) QuoteIdentifier(name string) string
SQL Server 使用方括号引用标识符
func (*SQLServerDialect) QuoteValue ¶
func (d *SQLServerDialect) QuoteValue(value interface{}) string
func (*SQLServerDialect) SQLManyToManyStrategy ¶ added in v1.1.0
func (d *SQLServerDialect) SQLManyToManyStrategy() string
func (*SQLServerDialect) SQLRecursiveCTEDepth ¶ added in v1.1.0
func (d *SQLServerDialect) SQLRecursiveCTEDepth() int
func (*SQLServerDialect) SQLRecursiveCTEMaxRecursion ¶ added in v1.1.0
func (d *SQLServerDialect) SQLRecursiveCTEMaxRecursion() int
func (*SQLServerDialect) TranslateCondition ¶
func (d *SQLServerDialect) TranslateCondition(condition Condition, argIndex *int) (string, []interface{}, error)
type SQLServerDynamicTableHook ¶ added in v1.0.0
type SQLServerDynamicTableHook struct {
// contains filtered or unexported fields
}
SQLServerDynamicTableHook SQL Server 动态表钩子实现。 使用原生 Trigger + T-SQL Procedure 方案实现自动建表。
func NewSQLServerDynamicTableHook ¶ added in v1.0.0
func NewSQLServerDynamicTableHook(adapter *SQLServerAdapter) *SQLServerDynamicTableHook
NewSQLServerDynamicTableHook 创建 SQL Server 动态表钩子。
func (*SQLServerDynamicTableHook) CreateDynamicTable ¶ added in v1.0.0
func (h *SQLServerDynamicTableHook) CreateDynamicTable(ctx context.Context, configName string, params map[string]interface{}) (string, error)
CreateDynamicTable 手动创建动态表。
func (*SQLServerDynamicTableHook) GetDynamicTableConfig ¶ added in v1.0.0
func (h *SQLServerDynamicTableHook) GetDynamicTableConfig(ctx context.Context, configName string) (*DynamicTableConfig, error)
GetDynamicTableConfig 获取特定的动态表配置。
func (*SQLServerDynamicTableHook) ListCreatedDynamicTables ¶ added in v1.0.0
func (h *SQLServerDynamicTableHook) ListCreatedDynamicTables(ctx context.Context, configName string) ([]string, error)
ListCreatedDynamicTables 获取已创建的动态表列表。
func (*SQLServerDynamicTableHook) ListDynamicTableConfigs ¶ added in v1.0.0
func (h *SQLServerDynamicTableHook) ListDynamicTableConfigs(ctx context.Context) ([]*DynamicTableConfig, error)
ListDynamicTableConfigs 列出所有已注册的动态表配置。
func (*SQLServerDynamicTableHook) RegisterDynamicTable ¶ added in v1.0.0
func (h *SQLServerDynamicTableHook) RegisterDynamicTable(ctx context.Context, config *DynamicTableConfig) error
RegisterDynamicTable 注册动态表配置。
func (*SQLServerDynamicTableHook) UnregisterDynamicTable ¶ added in v1.0.0
func (h *SQLServerDynamicTableHook) UnregisterDynamicTable(ctx context.Context, configName string) error
UnregisterDynamicTable 注销动态表配置。
type SQLServerFactory ¶
type SQLServerFactory struct{}
SQLServerFactory SQL Server 适配器工厂
type SQLServerFeatures ¶ added in v1.0.0
type SQLServerFeatures struct {
// contains filtered or unexported fields
}
SQLServerFeatures 提供 SQL Server 特有的高级数据库功能。 通过 GetSQLServerFeatures(adapter) 获取实例,非 SQL Server 返回 false。
示例:
features, ok := db.GetSQLServerFeatures(repo.GetAdapter())
if !ok {
return errors.New("not SQL Server")
}
rows, err := features.RecursiveQuery("org_tree").
Anchor("SELECT id, name, parent_id, 0 AS depth FROM departments WHERE parent_id IS NULL").
Recursive("SELECT d.id, d.name, d.parent_id, t.depth+1 FROM departments d JOIN org_tree t ON d.parent_id = t.id").
SelectAll().
MaxRecursion(50).
Execute(ctx)
func GetSQLServerFeatures ¶ added in v1.0.0
func GetSQLServerFeatures(adapter Adapter) (*SQLServerFeatures, bool)
GetSQLServerFeatures 从 Adapter 中提取 SQLServerFeatures。 若传入的不是 *SQLServerAdapter,则 ok == false。
func (*SQLServerFeatures) MergeInto ¶ added in v1.0.0
func (f *SQLServerFeatures) MergeInto(targetTable string) *SQLServerMergeBuilder
MergeInto 开始构建 SQL Server MERGE 语句(常用于 Upsert / 同步)。
示例:
err := features.MergeInto("dbo.users").
Using("(SELECT 1 AS id, N'Alice' AS name) AS s").
On("t.[id] = s.[id]").
WhenMatchedUpdate("t.[name] = s.[name]").
WhenNotMatchedInsert([]string{"id", "name"}, "s.[id], s.[name]").
Execute(ctx)
func (*SQLServerFeatures) RecursiveQuery ¶ added in v1.0.0
func (f *SQLServerFeatures) RecursiveQuery(cteName string) *RecursiveQueryBuilder
RecursiveQuery 开始构建一个递归 CTE 查询(WITH ... UNION ALL ...)。 cteName 是 CTE 的名称,在 T-SQL 中作为临时视图引用。
func (*SQLServerFeatures) TempTable ¶ added in v1.0.0
func (f *SQLServerFeatures) TempTable(name string) *SQLServerTempTableBuilder
TempTable 开始构建 SQL Server 临时表(默认局部临时表 #name)。
对跨语句/跨连接场景,建议使用 Global() 生成全局临时表 ##name。
func (*SQLServerFeatures) View ¶ added in v1.0.0
func (f *SQLServerFeatures) View(name string) *SQLServerViewBuilder
View 开始构建 SQL Server 视图语句。 默认使用 CREATE OR ALTER VIEW,便于幂等更新。
type SQLServerMergeBuilder ¶ added in v1.0.0
type SQLServerMergeBuilder struct {
// contains filtered or unexported fields
}
SQLServerMergeBuilder 构建 SQL Server MERGE 语句。
func (*SQLServerMergeBuilder) Args ¶ added in v1.0.0
func (b *SQLServerMergeBuilder) Args(args ...interface{}) *SQLServerMergeBuilder
Args 设置 Execute 时传递给 Query/Exec 的参数。
func (*SQLServerMergeBuilder) Build ¶ added in v1.0.0
func (b *SQLServerMergeBuilder) Build() (string, error)
Build 生成完整 MERGE T-SQL。
func (*SQLServerMergeBuilder) DisableHoldLock ¶ added in v1.0.0
func (b *SQLServerMergeBuilder) DisableHoldLock() *SQLServerMergeBuilder
DisableHoldLock 关闭 WITH (HOLDLOCK) 提示。
func (*SQLServerMergeBuilder) On ¶ added in v1.0.0
func (b *SQLServerMergeBuilder) On(condition string) *SQLServerMergeBuilder
On 设置目标与源的匹配条件。
func (*SQLServerMergeBuilder) Output ¶ added in v1.0.0
func (b *SQLServerMergeBuilder) Output(outputExpr string) *SQLServerMergeBuilder
Output 设置 OUTPUT 子句(例如 "$action, inserted.id")。
func (*SQLServerMergeBuilder) SourceAlias ¶ added in v1.0.0
func (b *SQLServerMergeBuilder) SourceAlias(alias string) *SQLServerMergeBuilder
SourceAlias 设置源别名(默认 s)。
func (*SQLServerMergeBuilder) TargetAlias ¶ added in v1.0.0
func (b *SQLServerMergeBuilder) TargetAlias(alias string) *SQLServerMergeBuilder
TargetAlias 设置目标表别名(默认 t)。
func (*SQLServerMergeBuilder) Using ¶ added in v1.0.0
func (b *SQLServerMergeBuilder) Using(sourceSQL string) *SQLServerMergeBuilder
Using 设置 MERGE USING 源(通常是子查询 + 别名)。 例如:"(SELECT ... ) AS s"。
func (*SQLServerMergeBuilder) WhenMatchedUpdate ¶ added in v1.0.0
func (b *SQLServerMergeBuilder) WhenMatchedUpdate(setClause string) *SQLServerMergeBuilder
WhenMatchedUpdate 设置匹配后 UPDATE 子句(仅 SET 部分)。 例如:"t.[name] = s.[name], t.[updated_at] = SYSUTCDATETIME()"。
func (*SQLServerMergeBuilder) WhenNotMatchedBySourceDelete ¶ added in v1.0.0
func (b *SQLServerMergeBuilder) WhenNotMatchedBySourceDelete() *SQLServerMergeBuilder
WhenNotMatchedBySourceDelete 设置源不存在时删除目标数据。
func (*SQLServerMergeBuilder) WhenNotMatchedInsert ¶ added in v1.0.0
func (b *SQLServerMergeBuilder) WhenNotMatchedInsert(columns []string, valuesExpr string) *SQLServerMergeBuilder
WhenNotMatchedInsert 设置未匹配时 INSERT 子句。 columns 是目标列列表,valuesExpr 是 VALUES(...) 内表达式。
type SQLServerTempTableBuilder ¶ added in v1.0.0
type SQLServerTempTableBuilder struct {
// contains filtered or unexported fields
}
SQLServerTempTableBuilder 构建 SQL Server 临时表语句。 默认创建局部临时表(#name),可通过 Global() 切换为全局临时表(##name)。
func (*SQLServerTempTableBuilder) Args ¶ added in v1.0.0
func (b *SQLServerTempTableBuilder) Args(args ...interface{}) *SQLServerTempTableBuilder
Args 设置 Execute 时参数。
func (*SQLServerTempTableBuilder) AsSelect ¶ added in v1.0.0
func (b *SQLServerTempTableBuilder) AsSelect(selectSQL string) *SQLServerTempTableBuilder
AsSelect 使用 SELECT ... INTO 临时表(自动忽略 Column 定义)。
func (*SQLServerTempTableBuilder) BuildCreate ¶ added in v1.0.0
func (b *SQLServerTempTableBuilder) BuildCreate() (string, error)
BuildCreate 生成创建临时表 SQL。
func (*SQLServerTempTableBuilder) BuildDrop ¶ added in v1.0.0
func (b *SQLServerTempTableBuilder) BuildDrop() string
BuildDrop 生成删除临时表 SQL。
func (*SQLServerTempTableBuilder) Column ¶ added in v1.0.0
func (b *SQLServerTempTableBuilder) Column(name, dataType string, nullable bool) *SQLServerTempTableBuilder
Column 添加列定义。
func (*SQLServerTempTableBuilder) Drop ¶ added in v1.0.0
func (b *SQLServerTempTableBuilder) Drop(ctx context.Context) error
Drop 执行删除临时表 SQL。
func (*SQLServerTempTableBuilder) DropIfExists ¶ added in v1.0.0
func (b *SQLServerTempTableBuilder) DropIfExists() *SQLServerTempTableBuilder
DropIfExists 创建前先执行 IF OBJECT_ID(tempdb..) IS NOT NULL DROP TABLE。
func (*SQLServerTempTableBuilder) ExecuteCreate ¶ added in v1.0.0
func (b *SQLServerTempTableBuilder) ExecuteCreate(ctx context.Context) error
ExecuteCreate 执行创建临时表 SQL。
func (*SQLServerTempTableBuilder) Global ¶ added in v1.0.0
func (b *SQLServerTempTableBuilder) Global() *SQLServerTempTableBuilder
Global 使用全局临时表(##name)。
func (*SQLServerTempTableBuilder) KeepIfExists ¶ added in v1.0.0
func (b *SQLServerTempTableBuilder) KeepIfExists() *SQLServerTempTableBuilder
KeepIfExists 保留已存在临时表,不自动 Drop。
func (*SQLServerTempTableBuilder) Local ¶ added in v1.0.0
func (b *SQLServerTempTableBuilder) Local() *SQLServerTempTableBuilder
Local 使用局部临时表(#name,默认)。
func (*SQLServerTempTableBuilder) TempTableName ¶ added in v1.0.0
func (b *SQLServerTempTableBuilder) TempTableName() string
TempTableName 返回实际临时表名(#xxx 或 ##xxx)。
type SQLServerTempTableColumn ¶ added in v1.0.0
type SQLServerTx ¶
type SQLServerTx struct {
// contains filtered or unexported fields
}
SQLServerTx SQL Server 事务实现
func (*SQLServerTx) Exec ¶
func (t *SQLServerTx) Exec(ctx context.Context, query string, args ...interface{}) (sql.Result, error)
Exec 在事务中执行
func (*SQLServerTx) Query ¶
func (t *SQLServerTx) Query(ctx context.Context, query string, args ...interface{}) (*sql.Rows, error)
Query 在事务中查询
type SQLServerViewBuilder ¶ added in v1.0.0
type SQLServerViewBuilder struct {
// contains filtered or unexported fields
}
SQLServerViewBuilder 构建 SQL Server VIEW 语句。
func (*SQLServerViewBuilder) Args ¶ added in v1.0.0
func (b *SQLServerViewBuilder) Args(args ...interface{}) *SQLServerViewBuilder
Args 设置创建视图 SQL 的参数(一般较少使用)。
func (*SQLServerViewBuilder) As ¶ added in v1.0.0
func (b *SQLServerViewBuilder) As(selectSQL string) *SQLServerViewBuilder
As 设置视图查询定义(AS 后的 SELECT 语句)。
func (*SQLServerViewBuilder) BuildCreate ¶ added in v1.0.0
func (b *SQLServerViewBuilder) BuildCreate() (string, error)
BuildCreate 生成 CREATE/ALTER VIEW SQL。
func (*SQLServerViewBuilder) BuildDrop ¶ added in v1.0.0
func (b *SQLServerViewBuilder) BuildDrop() (string, error)
BuildDrop 生成 DROP VIEW SQL。
func (*SQLServerViewBuilder) CreateOnly ¶ added in v1.0.0
func (b *SQLServerViewBuilder) CreateOnly() *SQLServerViewBuilder
CreateOnly 使用 CREATE VIEW(若视图已存在会报错)。
func (*SQLServerViewBuilder) CreateOrAlter ¶ added in v1.0.0
func (b *SQLServerViewBuilder) CreateOrAlter() *SQLServerViewBuilder
CreateOrAlter 使用 CREATE OR ALTER VIEW(默认)。
func (*SQLServerViewBuilder) Drop ¶ added in v1.0.0
func (b *SQLServerViewBuilder) Drop(ctx context.Context) error
Drop 执行 DROP VIEW。
func (*SQLServerViewBuilder) DropIfExists ¶ added in v1.0.0
func (b *SQLServerViewBuilder) DropIfExists() *SQLServerViewBuilder
DropIfExists 删除视图时使用 IF EXISTS(默认 true)。
func (*SQLServerViewBuilder) DropStrict ¶ added in v1.0.0
func (b *SQLServerViewBuilder) DropStrict() *SQLServerViewBuilder
DropStrict 删除视图时不使用 IF EXISTS。
func (*SQLServerViewBuilder) ExecuteCreate ¶ added in v1.0.0
func (b *SQLServerViewBuilder) ExecuteCreate(ctx context.Context) error
ExecuteCreate 执行 CREATE/ALTER VIEW。
func (*SQLServerViewBuilder) WithCheckOption ¶ added in v1.0.0
func (b *SQLServerViewBuilder) WithCheckOption() *SQLServerViewBuilder
WithCheckOption 在视图尾部追加 WITH CHECK OPTION。
type SQLiteAdapter ¶
type SQLiteAdapter struct {
// contains filtered or unexported fields
}
SQLiteAdapter SQLite 数据库适配器
func NewSQLiteAdapter ¶
func NewSQLiteAdapter(config *Config) (*SQLiteAdapter, error)
NewSQLiteAdapter 创建 SQLite 适配器
func (*SQLiteAdapter) Begin ¶
func (a *SQLiteAdapter) Begin(ctx context.Context, opts ...interface{}) (Tx, error)
Begin 开始事务
func (*SQLiteAdapter) Connect ¶
func (a *SQLiteAdapter) Connect(ctx context.Context, config *Config) error
Connect 连接到 SQLite 数据库
func (*SQLiteAdapter) Exec ¶
func (a *SQLiteAdapter) Exec(ctx context.Context, query string, args ...interface{}) (sql.Result, error)
Exec 执行操作 (INSERT/UPDATE/DELETE)
func (*SQLiteAdapter) GetDatabaseFeatures ¶
func (a *SQLiteAdapter) GetDatabaseFeatures() *DatabaseFeatures
GetDatabaseFeatures 返回 SQLite 数据库特性
func (*SQLiteAdapter) GetGormDB ¶
func (a *SQLiteAdapter) GetGormDB() *gorm.DB
GetGormDB 获取GORM实例(用于直接访问GORM) Deprecated: Adapter 层不再暴露 GORM 连接。
func (*SQLiteAdapter) GetQueryBuilderProvider ¶
func (a *SQLiteAdapter) GetQueryBuilderProvider() QueryConstructorProvider
GetQueryBuilderProvider 返回查询构造器提供者
func (*SQLiteAdapter) GetQueryFeatures ¶
func (a *SQLiteAdapter) GetQueryFeatures() *QueryFeatures
GetQueryFeatures 返回 SQLite 的查询特性
func (*SQLiteAdapter) GetRawConn ¶
func (a *SQLiteAdapter) GetRawConn() interface{}
GetRawConn 获取底层连接 (返回 *sql.DB)
func (*SQLiteAdapter) InspectFullTextRuntime ¶ added in v1.0.0
func (a *SQLiteAdapter) InspectFullTextRuntime(ctx context.Context) (*FullTextRuntimeCapability, error)
InspectFullTextRuntime 检查 SQLite 是否编译启用了 FTS3/4/5。
func (*SQLiteAdapter) ListScheduledTasks ¶
func (a *SQLiteAdapter) ListScheduledTasks(ctx context.Context) ([]*ScheduledTaskStatus, error)
ListScheduledTasks SQLite 适配器暂不支持
func (*SQLiteAdapter) Query ¶
func (a *SQLiteAdapter) Query(ctx context.Context, query string, args ...interface{}) (*sql.Rows, error)
Query 执行查询 (返回多行)
func (*SQLiteAdapter) RegisterCommonSQLiteFunctions ¶
func (a *SQLiteAdapter) RegisterCommonSQLiteFunctions() error
RegisterCommonSQLiteFunctions 注册常用的 SQLite 自定义函数
func (*SQLiteAdapter) RegisterSQLiteAggregateFunction ¶
func (a *SQLiteAdapter) RegisterSQLiteAggregateFunction(fn *SQLiteAggregateFunction) error
RegisterSQLiteAggregateFunction 注册自定义聚合函数
func (*SQLiteAdapter) RegisterSQLiteFunction ¶
func (a *SQLiteAdapter) RegisterSQLiteFunction(fn *SQLiteCustomFunction) error
RegisterSQLiteFunction 注册 SQLite 自定义函数 这允许在 SQLite 中使用 Go 编写的函数,性能优于应用层处理
注意:此功能需要在连接时通过 sql.OpenDB 使用自定义连接器 由于 GORM 的封装,当前实现有限制,建议直接使用 sql.DB
func (*SQLiteAdapter) RegisterScheduledTask ¶
func (a *SQLiteAdapter) RegisterScheduledTask(ctx context.Context, task *ScheduledTaskConfig) error
RegisterScheduledTask SQLite 适配器暂不支持通过触发器方式实现定时任务 建议在应用层使用 cron 库处理定时任务
func (*SQLiteAdapter) UnregisterScheduledTask ¶
func (a *SQLiteAdapter) UnregisterScheduledTask(ctx context.Context, taskName string) error
UnregisterScheduledTask SQLite 适配器暂不支持
type SQLiteAggregateFunction ¶
type SQLiteAggregateFunction struct {
Name string
NumArgs int
Step func(ctx interface{}, args ...interface{}) (interface{}, error) // 每行调用
Final func(ctx interface{}) (interface{}, error) // 最终结果
}
SQLiteAggregateFunction 自定义聚合函数定义
type SQLiteConnectionConfig ¶ added in v1.0.0
type SQLiteConnectionConfig struct {
Path string `json:"path,omitempty" yaml:"path,omitempty"`
DSN string `json:"dsn,omitempty" yaml:"dsn,omitempty"`
}
SQLiteConnectionConfig SQLite 连接配置。
type SQLiteCustomFunction ¶
type SQLiteCustomFunction struct {
Name string // 函数名称
NumArgs int // 参数数量 (-1 表示可变参数)
Pure bool // 是否为纯函数(无副作用)
Impl func(args ...interface{}) (interface{}, error) // 函数实现
}
SQLiteCustomFunction 自定义函数定义
type SQLiteDialect ¶
type SQLiteDialect struct {
DefaultSQLDialect
}
SQLite 方言
func NewSQLiteDialect ¶
func NewSQLiteDialect() *SQLiteDialect
type SQLiteDynamicTableHook ¶
type SQLiteDynamicTableHook struct {
// contains filtered or unexported fields
}
SQLiteDynamicTableHook SQLite 动态表钩子实现 使用 GORM 的 hook 机制实现基于触发的动态建表
func NewSQLiteDynamicTableHook ¶
func NewSQLiteDynamicTableHook(adapter *SQLiteAdapter) *SQLiteDynamicTableHook
NewSQLiteDynamicTableHook 创建 SQLite 动态表钩子
func (*SQLiteDynamicTableHook) CreateDynamicTable ¶
func (h *SQLiteDynamicTableHook) CreateDynamicTable(ctx context.Context, configName string, params map[string]interface{}) (string, error)
CreateDynamicTable 手动创建动态表 返回实际创建的表名称
func (*SQLiteDynamicTableHook) GetDynamicTableConfig ¶
func (h *SQLiteDynamicTableHook) GetDynamicTableConfig(ctx context.Context, configName string) (*DynamicTableConfig, error)
GetDynamicTableConfig 获取特定的动态表配置
func (*SQLiteDynamicTableHook) ListCreatedDynamicTables ¶
func (h *SQLiteDynamicTableHook) ListCreatedDynamicTables(ctx context.Context, configName string) ([]string, error)
ListCreatedDynamicTables 获取已创建的动态表列表
func (*SQLiteDynamicTableHook) ListDynamicTableConfigs ¶
func (h *SQLiteDynamicTableHook) ListDynamicTableConfigs(ctx context.Context) ([]*DynamicTableConfig, error)
ListDynamicTableConfigs 列出所有已注册的动态表配置
func (*SQLiteDynamicTableHook) RegisterDynamicTable ¶
func (h *SQLiteDynamicTableHook) RegisterDynamicTable(ctx context.Context, config *DynamicTableConfig) error
RegisterDynamicTable 注册动态表配置 对于自动策略,在 GORM hook 中注册事件处理
func (*SQLiteDynamicTableHook) UnregisterDynamicTable ¶
func (h *SQLiteDynamicTableHook) UnregisterDynamicTable(ctx context.Context, configName string) error
UnregisterDynamicTable 注销动态表配置
type SQLiteTx ¶
type SQLiteTx struct {
// contains filtered or unexported fields
}
SQLiteTx SQLite 事务实现
type ScheduledTaskConfig ¶
type ScheduledTaskConfig struct {
// 任务的唯一标识符(如 "monthly_page_logs")
Name string
// 任务类型
Type ScheduledTaskType
// 任务的 Cron 表达式(如 "0 0 1 * *" 表示每月1号0点)
// 某些数据库实现可能不使用此字段
CronExpression string
// 任务特定的配置参数,根据任务类型而定
// 对于 TaskTypeMonthlyTableCreation,应包含:
// - tableName: string - 表名前缀
// - monthFormat: string - 月份格式(如 "2006_01")
// - fieldDefinitions: string - 表字段定义(SQL DDL)
Config map[string]interface{}
// 任务描述
Description string
// 是否启用此任务
Enabled bool
}
ScheduledTaskConfig 定时任务配置 这个结构体定义了要执行的定时任务的参数,不同的数据库适配器 可以根据不同的实现方式(如 PostgreSQL 触发器、应用层 cron)来处理
func (*ScheduledTaskConfig) GetMonthlyTableConfig ¶
func (c *ScheduledTaskConfig) GetMonthlyTableConfig() map[string]interface{}
GetMonthlyTableConfig 便捷方法:获取按月创建表的配置
func (*ScheduledTaskConfig) Validate ¶
func (c *ScheduledTaskConfig) Validate() error
Validate 验证任务配置的有效性
type ScheduledTaskEventListener ¶
type ScheduledTaskEventListener interface {
OnTaskRegistered(ctx context.Context, config *ScheduledTaskConfig) error
OnTaskUnregistered(ctx context.Context, taskName string) error
OnTaskExecutionStarted(ctx context.Context, taskName string) error
OnTaskExecutionCompleted(ctx context.Context, taskName string, err error) error
}
ScheduledTaskEventListener 定时任务事件监听器接口 用于监听定时任务的生命周期事件
type ScheduledTaskExecutor ¶
type ScheduledTaskExecutor interface {
// Execute 执行定时任务
// taskName: 任务名称
// config: 完整的任务配置
Execute(ctx context.Context, taskName string, config *ScheduledTaskConfig) error
}
ScheduledTaskExecutor 定时任务执行器接口 由应用层实现,用于执行不同类型的定时任务
type ScheduledTaskStatus ¶
type ScheduledTaskStatus struct {
// 任务名称
Name string
// 任务类型
Type ScheduledTaskType
// 是否正在运行
Running bool
// 上次执行时间(Unix 时间戳)
LastExecutedAt int64
// 下次执行时间(Unix 时间戳,如果适用)
NextExecutedAt int64
// 任务创建者信息(可选)
CreatedAt int64
// 额外的状态信息
Info map[string]interface{}
}
ScheduledTaskStatus 定时任务执行状态
type ScheduledTaskType ¶
type ScheduledTaskType string
ScheduledTaskType 定时任务类型枚举
const ( // TaskTypeMonthlyTableCreation 按月自动创建表的任务 TaskTypeMonthlyTableCreation ScheduledTaskType = "monthly_table_creation" )
type Schema ¶
type Schema interface {
// 获取模式名称(表名)
TableName() string
// 获取所有字段
Fields() []*Field
// 获取字段
GetField(name string) *Field
// 获取主键字段
PrimaryKeyField() *Field
}
Schema 定义数据模式接口 (参考 Ecto.Schema)
type SchemaMigration ¶
type SchemaMigration struct {
*BaseMigration
// contains filtered or unexported fields
}
SchemaMigration 基于 Schema 的迁移
func NewSchemaMigration ¶
func NewSchemaMigration(version, description string) *SchemaMigration
NewSchemaMigration 创建基于 Schema 的迁移
func (*SchemaMigration) CreateTable ¶
func (m *SchemaMigration) CreateTable(schema Schema) *SchemaMigration
CreateTable 添加要创建的表
func (*SchemaMigration) Down ¶
func (m *SchemaMigration) Down(ctx context.Context, repo *Repository) error
Down 回滚迁移
func (*SchemaMigration) DropTable ¶
func (m *SchemaMigration) DropTable(schema Schema) *SchemaMigration
DropTable 添加要删除的表
func (*SchemaMigration) Up ¶
func (m *SchemaMigration) Up(ctx context.Context, repo *Repository) error
Up 执行迁移
type SchemaRegistry ¶
type SchemaRegistry struct {
// contains filtered or unexported fields
}
SchemaRegistry Schema 注册表,便于查找和管理多个 Schema
func (*SchemaRegistry) GetAllSchemaNames ¶
func (r *SchemaRegistry) GetAllSchemaNames() []string
GetAllSchemaNames 获取所有已注册的 Schema 名称
func (*SchemaRegistry) Register ¶
func (r *SchemaRegistry) Register(name string, schema Schema)
Register 注册一个 Schema
type SchemaRelation ¶ added in v1.1.0
type SchemaRelation struct {
Type RelationType
TargetSchema Schema
Name string // 关系名称(适配器可据此映射关系类型/边类型)
ForeignKey string // 持有 FK 的一侧字段名
OriginKey string // 被引用的一侧字段名(通常是 PK)
Through *RelationThrough
Reversible bool // 一对一可逆标记(或显式声明允许反向路径优化)
// contains filtered or unexported fields
}
SchemaRelation 声明两个 Schema 之间的关系。
字段语义:
- HasMany / HasOne:FK 在目标 Schema 侧;ForeignKey 是目标侧字段,OriginKey 是本侧字段(通常是 PK)。
- BelongsTo:FK 在本 Schema 侧;ForeignKey 是本侧字段,OriginKey 是目标侧字段(通常是 PK)。
适配器行为:
- SQL:自然使用 FK 约束;关系声明补充语义推断。
- Neo4j:ForeignKey/OriginKey 是逻辑字段,关系以边(edge)存储;不物化为节点属性。
- MongoDB:适配器根据 ForeignKey/OriginKey 生成 $lookup 管道;字段是否物化由适配器自决。
func (*SchemaRelation) Semantic ¶ added in v1.1.0
func (r *SchemaRelation) Semantic() JoinSemantic
Semantic 根据关系类型和显式覆盖推断 JoinSemantic。
func (*SchemaRelation) SemanticFromSource ¶ added in v1.1.0
func (r *SchemaRelation) SemanticFromSource() JoinSemantic
SemanticFromSource 从"源"的视角推断语义: 当 source 连接到 join Schema,而 join Schema 声明了指向 source 的关系时使用。 规则:join BelongsTo source → source 视角为 optional(source 可能有 0 个 join)
join HasMany/HasOne source → source 视角为 required(source 是 join 的父实体,join 必有 FK)
type SchemaRelationBuilder ¶ added in v1.1.0
type SchemaRelationBuilder struct {
// contains filtered or unexported fields
}
SchemaRelationBuilder 关系声明的流式构造器,通过 HasMany/HasOne/BelongsTo 创建。
func (*SchemaRelationBuilder) Named ¶ added in v1.1.0
func (b *SchemaRelationBuilder) Named(name string) *SchemaRelationBuilder
Named 为关系声明一个语义名称。 适配器可将其映射为底层关系类型(例如 Neo4j 边类型)。
func (*SchemaRelationBuilder) Optional ¶ added in v1.1.0
func (b *SchemaRelationBuilder) Optional() *SchemaRelationBuilder
Optional 显式覆盖为 optional 语义(不论关系类型默认值)。
func (*SchemaRelationBuilder) Over ¶ added in v1.1.0
func (b *SchemaRelationBuilder) Over(foreignKey, originKey string) *SchemaRelationBuilder
Over 声明关联字段。 foreignKey 是持有 FK 的一侧字段名;originKey 是被引用的一侧字段名(通常是 PK)。 HasMany/HasOne:foreignKey 在目标侧,originKey 在本侧。 BelongsTo:foreignKey 在本侧,originKey 在目标侧。
func (*SchemaRelationBuilder) Relation ¶ added in v1.1.0
func (b *SchemaRelationBuilder) Relation() *SchemaRelation
Relation 返回构建好的 SchemaRelation(主要用于测试断言)。
func (*SchemaRelationBuilder) Required ¶ added in v1.1.0
func (b *SchemaRelationBuilder) Required() *SchemaRelationBuilder
Required 显式覆盖为 required 语义(不论关系类型默认值)。
func (*SchemaRelationBuilder) Reversible ¶ added in v1.1.0
func (b *SchemaRelationBuilder) Reversible(enabled bool) *SchemaRelationBuilder
Reversible 标记该关系允许反向路径优化(典型用于一对一)。
func (*SchemaRelationBuilder) Through ¶ added in v1.1.0
func (b *SchemaRelationBuilder) Through(through Schema, sourceKey, targetKey string) *SchemaRelationBuilder
Through 声明多对多关系使用的中间关系(中间表/集合/边)。 sourceKey 表示 source -> through 的连接键,targetKey 表示 through -> target 的连接键。
type SchemaRelationshipBuilder ¶
type SchemaRelationshipBuilder struct {
// contains filtered or unexported fields
}
SchemaRelationshipBuilder Schema 中的关系构建
func NewSchemaRelationshipBuilder ¶
func NewSchemaRelationshipBuilder(schema *BaseSchema) *SchemaRelationshipBuilder
NewSchemaRelationshipBuilder 创建关系构建器
func (*SchemaRelationshipBuilder) BelongsTo ¶
func (b *SchemaRelationshipBuilder) BelongsTo(name string, toSchema Schema, foreignKey, primaryKey string) *SchemaRelationshipBuilder
BelongsTo 定义多对一关系(反向一对多)
func (*SchemaRelationshipBuilder) GetRelationships ¶
func (b *SchemaRelationshipBuilder) GetRelationships() []*Relationship
GetRelationships 获取所有关系
func (*SchemaRelationshipBuilder) HasAndBelongsToMany ¶
func (b *SchemaRelationshipBuilder) HasAndBelongsToMany( name string, toSchema Schema, joinTableName string, fromForeignKey string, toForeignKey string, ) *SchemaRelationshipBuilder
HasAndBelongsToMany 定义多对多关系
func (*SchemaRelationshipBuilder) HasMany ¶
func (b *SchemaRelationshipBuilder) HasMany(name string, toSchema Schema, foreignKey, primaryKey string) *SchemaRelationshipBuilder
HasMany 定义一对多关系
func (*SchemaRelationshipBuilder) HasOne ¶
func (b *SchemaRelationshipBuilder) HasOne(name string, toSchema Schema, foreignKey, primaryKey string) *SchemaRelationshipBuilder
HasOne 定义一对一关系
type ShardingRiskLevel ¶ added in v1.0.0
type ShardingRiskLevel string
ShardingRiskLevel 分表稳定性风险等级。
const ( ShardingRiskLow ShardingRiskLevel = "low" ShardingRiskMedium ShardingRiskLevel = "medium" ShardingRiskHigh ShardingRiskLevel = "high" )
type ShardingStabilityReport ¶ added in v1.0.0
type ShardingStabilityReport struct {
TemplateKind ShardingTemplateKind
SampleCount int
UniqueShards []string
Deterministic bool
ShardLoads map[string]int
HotShards []string
Recommendations []string
RiskLevel ShardingRiskLevel
Errors []string
Warnings []string
}
ShardingStabilityReport 分表稳定性报告。
func (*ShardingStabilityReport) CanRelease ¶ added in v1.0.0
func (r *ShardingStabilityReport) CanRelease() bool
CanRelease 判断该分表策略是否满足发布门禁。 规则: - 存在错误 -> 不可发布 - RiskLevel == high -> 不可发布 - 其他情况可发布(包含 medium,建议人工确认)
func (*ShardingStabilityReport) ReleaseBlockReasons ¶ added in v1.0.0
func (r *ShardingStabilityReport) ReleaseBlockReasons() []string
ReleaseBlockReasons 返回阻断发布的原因列表。
type ShardingStabilityTool ¶ added in v1.0.0
type ShardingStabilityTool struct{}
ShardingStabilityTool 分表稳定性检查工具。
func NewShardingStabilityTool ¶ added in v1.0.0
func NewShardingStabilityTool() *ShardingStabilityTool
NewShardingStabilityTool 创建分表稳定性检查工具。
func (*ShardingStabilityTool) ValidateShardNaming ¶ added in v1.0.0
func (t *ShardingStabilityTool) ValidateShardNaming(baseTableName string, shardIDs []string) []error
ValidateShardNaming 检查分表命名稳定性,确保生成的表名可预测且只包含安全字符。
func (*ShardingStabilityTool) ValidateTemplate ¶ added in v1.0.0
func (t *ShardingStabilityTool) ValidateTemplate(template *AutoShardingTemplate, samples []map[string]interface{}, maxShards int) *ShardingStabilityReport
ValidateTemplate 使用样本数据验证分表模板的稳定性。
type ShardingTemplateKind ¶ added in v1.0.0
type ShardingTemplateKind string
ShardingTemplateKind 分表模板类型。
const ( ShardingByDataScale ShardingTemplateKind = "data_scale" ShardingByDate ShardingTemplateKind = "date" ShardingByRegion ShardingTemplateKind = "region" )
type SimpleCondition ¶
type SimpleCondition struct {
Field string
Operator string // "eq", "ne", "gt", "lt", "gte", "lte", "in", "like", "between", "full_text"
Value interface{}
}
SimpleCondition 简单条件(字段 操作符 值)
func (*SimpleCondition) Translate ¶
func (c *SimpleCondition) Translate(translator ConditionTranslator) (string, []interface{}, error)
func (*SimpleCondition) Type ¶
func (c *SimpleCondition) Type() string
type StartupCapabilityCheck ¶ added in v1.0.0
type StartupCapabilityCheck struct {
Name string `json:"name"`
EffectiveMode string `json:"effective_mode"`
Required bool `json:"required"`
Supported bool `json:"supported"`
InspectorAvailable bool `json:"inspector_available"`
Status string `json:"status"`
Notes string `json:"notes,omitempty"`
Error string `json:"error,omitempty"`
}
StartupCapabilityCheck 单项能力检查结果。
type StartupCapabilityConfig ¶ added in v1.0.0
type StartupCapabilityConfig struct {
// 模式:strict | lenient(默认 lenient)
Mode string `json:"mode" yaml:"mode"`
// 按能力覆盖模式(strict | lenient)。
// 可用于“全局 lenient,但对 json_runtime 强制 strict”。
CapabilityModes map[string]string `json:"capability_modes,omitempty" yaml:"capability_modes,omitempty"`
// 需要检查的能力名;为空时默认检查 json_runtime 和 full_text_runtime。
Inspect []string `json:"inspect,omitempty" yaml:"inspect,omitempty"`
// 必须满足的能力名(strict 模式下不满足将失败)。
Required []string `json:"required,omitempty" yaml:"required,omitempty"`
}
StartupCapabilityConfig 启动期能力体检配置。
type StartupCapabilityReport ¶ added in v1.0.0
type StartupCapabilityReport struct {
Adapter string `json:"adapter"`
Mode string `json:"mode"`
GeneratedAt string `json:"generated_at"`
Checks []StartupCapabilityCheck `json:"checks"`
}
StartupCapabilityReport 启动体检报告。
type TTLIndexInfo ¶ added in v1.0.0
type TTLIndexInfo struct {
// Name 索引名称(MongoDB 自动生成或指定)
Name string
// Field 建立 TTL 索引的字段名
Field string
// ExpireAfter 文档字段时间到达后再延迟多久删除(0 表示精准到期即删)
ExpireAfter time.Duration
}
TTLIndexInfo 描述一个 TTL 索引的元信息。
type TableConstraint ¶ added in v1.0.0
type TableConstraint struct {
Name string
Kind ConstraintKind
Fields []string
// 外键专属字段(Kind == ConstraintForeignKey 时有效)
RefTable string // 被引用表名
RefFields []string // 被引用列名(顺序与 Fields 对应)
OnDelete string // "CASCADE" | "SET NULL" | "RESTRICT" | "NO ACTION" | ""
OnUpdate string // "CASCADE" | "SET NULL" | "RESTRICT" | "NO ACTION" | ""
// Neo4jRelType 可选:在 Neo4j 中对应的关系类型(如 "FOLLOWS"、"OWNS")。
// 仅当 Kind == ConstraintForeignKey 时有效。
// 空时由 Neo4j 编译器根据约束名推断(去除 "fk_"/"rel_" 等常见前缀后转大写)。
Neo4jRelType string
// 可选:外键热点查询视图声明(仅当 Kind == ConstraintForeignKey 时有意义)
ViewHint *ViewHint
}
TableConstraint 表级约束定义(用于复合主键、复合唯一约束、复合外键等)
type Transformer ¶
type Transformer interface {
// 转换值
Transform(value interface{}) (interface{}, error)
}
Transformer 转换器接口
type TrimTransformer ¶
type TrimTransformer struct{}
TrimTransformer 字符串修剪转换器
func (*TrimTransformer) Transform ¶
func (t *TrimTransformer) Transform(value interface{}) (interface{}, error)
type Tx ¶
type Tx interface {
Commit(ctx context.Context) error
Rollback(ctx context.Context) error
// 事务中的查询和执行
Query(ctx context.Context, sql string, args ...interface{}) (*sql.Rows, error)
QueryRow(ctx context.Context, sql string, args ...interface{}) *sql.Row
Exec(ctx context.Context, sql string, args ...interface{}) (sql.Result, error)
}
Tx 定义事务接口
type TypeConversionError ¶
TypeConversionError 类型转换错误
func (*TypeConversionError) Error ¶
func (e *TypeConversionError) Error() string
type URLValidator ¶ added in v1.0.0
type URLValidator struct {
Locale string
}
URLValidator URL 格式验证器(http/https) 它是 RegexValidator 的特化封装。
func NewURLValidatorForLocale ¶ added in v1.0.0
func NewURLValidatorForLocale(locale string) *URLValidator
func (*URLValidator) Validate ¶ added in v1.0.0
func (v *URLValidator) Validate(value interface{}) error
func (*URLValidator) ValidateWithLocale ¶ added in v1.0.0
func (v *URLValidator) ValidateWithLocale(value interface{}, locale string) error
type UniqueValidator ¶
UniqueValidator 唯一性验证器
func (*UniqueValidator) Validate ¶
func (v *UniqueValidator) Validate(value interface{}) error
type ValidationConfig ¶ added in v1.0.0
type ValidationConfig struct {
// 默认 locale(例如: zh-CN / en-US)
DefaultLocale string `json:"default_locale" yaml:"default_locale"`
// 启用的 locale 列表;支持同时启用多个 locale
EnabledLocales []string `json:"enabled_locales" yaml:"enabled_locales"`
}
ValidationConfig 校验 locale 配置
type ValidationError ¶
ValidationError 验证错误
func NewValidationError ¶
func NewValidationError(code, message string) *ValidationError
NewValidationError 创建验证错误
func (*ValidationError) Error ¶
func (e *ValidationError) Error() string
type ValidationMessages ¶ added in v1.0.0
type ValidationMessages struct {
EmailInvalidType string
EmailInvalidValue string
PhoneInvalidType string
PhoneInvalidValue string
URLInvalidType string
URLInvalidValue string
PostalInvalidType string
PostalInvalidValue string
IDCardInvalidType string
IDCardInvalidValue string
}
ValidationMessages 校验消息模板。
type ValidationProfile ¶ added in v1.0.0
type ValidationProfile struct {
Locale string
EmailPattern string
PhonePattern string
URLPattern string
PostalCodePattern string
IDCardPattern string
Messages ValidationMessages
}
ValidationProfile 区域化校验规则配置。
type Validator ¶
type Validator interface {
// 验证值,返回错误信息或 nil
Validate(value interface{}) error
}
Validator 验证器接口
type ViewBuilder ¶ added in v1.0.0
type ViewBuilder struct {
// contains filtered or unexported fields
}
ViewBuilder 构建通用 VIEW DDL。
func (*ViewBuilder) Args ¶ added in v1.0.0
func (b *ViewBuilder) Args(args ...interface{}) *ViewBuilder
Args 设置 ExecuteCreate 时传入的参数。
func (*ViewBuilder) As ¶ added in v1.0.0
func (b *ViewBuilder) As(selectSQL string) *ViewBuilder
As 设置视图定义 SQL(AS 后的 SELECT 语句)。
func (*ViewBuilder) BuildCreate ¶ added in v1.0.0
func (b *ViewBuilder) BuildCreate() (string, error)
BuildCreate 生成 CREATE/ALTER VIEW DDL。
func (*ViewBuilder) BuildDrop ¶ added in v1.0.0
func (b *ViewBuilder) BuildDrop() (string, error)
BuildDrop 生成 DROP VIEW DDL。
func (*ViewBuilder) CreateOnly ¶ added in v1.0.0
func (b *ViewBuilder) CreateOnly() *ViewBuilder
CreateOnly 强制使用 CREATE VIEW。
func (*ViewBuilder) CreateOrAlter ¶ added in v1.0.0
func (b *ViewBuilder) CreateOrAlter() *ViewBuilder
CreateOrAlter 使用各数据库等价语法:
- SQL Server: CREATE OR ALTER VIEW
- PostgreSQL/MySQL: CREATE OR REPLACE VIEW
- SQLite: 不支持(会在 BuildCreate 报错)
func (*ViewBuilder) Drop ¶ added in v1.0.0
func (b *ViewBuilder) Drop(ctx context.Context) error
Drop 执行删除视图。
func (*ViewBuilder) DropIfExists ¶ added in v1.0.0
func (b *ViewBuilder) DropIfExists() *ViewBuilder
DropIfExists 删除视图时使用 IF EXISTS(默认)。
func (*ViewBuilder) DropStrict ¶ added in v1.0.0
func (b *ViewBuilder) DropStrict() *ViewBuilder
DropStrict 删除视图时不使用 IF EXISTS。
func (*ViewBuilder) ExecuteCreate ¶ added in v1.0.0
func (b *ViewBuilder) ExecuteCreate(ctx context.Context) error
ExecuteCreate 执行创建视图。
func (*ViewBuilder) Materialized ¶ added in v1.0.0
func (b *ViewBuilder) Materialized() *ViewBuilder
Materialized 切换为物化视图(仅 PostgreSQL)。
func (*ViewBuilder) WithCheckOption ¶ added in v1.0.0
func (b *ViewBuilder) WithCheckOption() *ViewBuilder
WithCheckOption 追加 WITH CHECK OPTION(SQLite 不支持)。
type ViewFeatures ¶ added in v1.0.0
type ViewFeatures struct {
// contains filtered or unexported fields
}
ViewFeatures 提供跨数据库的 VIEW 功能统一入口。
目标是把视图能力放在通用特性层:
- SQL Server / PostgreSQL: 增强支持(replace/alter 更完整)
- MySQL / SQLite: 基础支持(创建/删除)
- MongoDB: 不支持
使用示例:
vf, ok := db.GetViewFeatures(repo.GetAdapter())
if !ok {
return errors.New("adapter does not support view features")
}
err := vf.View("report_user_stats").
As("SELECT id, name FROM users WHERE active = 1").
ExecuteCreate(ctx)
func GetViewFeatures ¶ added in v1.0.0
func GetViewFeatures(adapter Adapter) (*ViewFeatures, bool)
GetViewFeatures 从 Adapter 中提取通用 ViewFeatures。
func (*ViewFeatures) View ¶ added in v1.0.0
func (f *ViewFeatures) View(name string) *ViewBuilder
View 开始构建一个通用视图。
type ViewHint ¶ added in v1.0.0
type ViewHint struct {
// ViewName 视图名称;空时自动生成为 "<localTable>_<refTable>_view"。
ViewName string
// Materialized 是否物化视图(PostgreSQL MATERIALIZED VIEW)。
// SQL Server 忽略此标志,始终创建普通视图。
Materialized bool
// Columns 视图 SELECT 的列表达式列表;空表示 "local_alias.*, ref_alias.*"。
// 建议指定明确的列以避免歧义,例如 []string{"o.id AS order_id", "u.name"}。
Columns []string
// JoinType LEFT/RIGHT/INNER;空时默认为 INNER。
JoinType string
}
ViewHint 外键约束上的视图提示,声明该关联应创建(或复用)的跨表视图。 适用于高热点跨表查询场景,由 Migration 阶段自动生成视图 DDL, 运行时由 QueryBuilder 自动路由到视图而非直接 JOIN。
type WhereBuilder ¶ added in v1.1.0
type WhereBuilder struct {
// contains filtered or unexported fields
}
WhereBuilder 条件构造器(独立于 QueryConstructor)。 可先构造完整条件树,再一次性注入 Where 子句。
func NewWhereBuilder ¶ added in v1.1.0
func NewWhereBuilder(condition Condition) *WhereBuilder
NewWhereBuilder 创建独立 WhereBuilder。
func (*WhereBuilder) And ¶ added in v1.1.0
func (b *WhereBuilder) And(condition Condition) *WhereBuilder
And 追加 AND 条件。
func (*WhereBuilder) Build ¶ added in v1.1.0
func (b *WhereBuilder) Build() Condition
Build 返回构造后的根条件。
func (*WhereBuilder) Or ¶ added in v1.1.0
func (b *WhereBuilder) Or(condition Condition) *WhereBuilder
Or 追加 OR 条件。
Source Files
¶
- DYNAMIC_TABLE_QUICK_REFERENCE.go
- adapter.go
- auto_sharding.go
- changeset.go
- changeset_executor.go
- config.go
- cross_table_view_registry.go
- database_features.go
- date_condition_presets.go
- date_conditions.go
- dynamic_table.go
- dynamic_table_examples.go
- feature_execution.go
- framework_tables.go
- fuzzy_query.go
- gorm_integration.go
- init_adapter.go
- json_runtime.go
- migration.go
- migration_adapter_name.go
- migration_ir.go
- migration_schema_runtime.go
- migration_v2.go
- mongo_adapter.go
- mongo_features.go
- mongo_local_cache.go
- mongo_query_builder.go
- mongo_ttl.go
- mongo_virtual_view.go
- mysql_adapter.go
- mysql_dynamic_table.go
- neo4j_adapter.go
- neo4j_features.go
- neo4j_query_builder.go
- pagination_cursor_shared.go
- postgres_adapter.go
- postgres_dynamic_table.go
- postgres_features.go
- presets.go
- query_builder.go
- query_builder_v2.go
- query_cache.go
- query_features.go
- query_ir.go
- reflection.go
- relationship.go
- scheduled_task.go
- scheduled_task_fallback.go
- schema.go
- sqlite_adapter.go
- sqlite_custom_functions.go
- sqlite_dynamic_table.go
- sqlserver_adapter.go
- sqlserver_dynamic_table.go
- sqlserver_features.go
- startup_capability.go
- time_builder.go
- validators.go
- view_features.go