orm

package module
v0.0.0-...-7d43b46 Latest Latest
Warning

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

Go to latest
Published: Aug 26, 2026 License: Apache-2.0 Imports: 17 Imported by: 0

README

Goark ORM

Goark ORM 是可独立使用的数据映射模块,同时也可以接入 Goark 生态。目标是提供 Go 原生实体映射、查询构建、事务集成和可测试数据访问边界。

当前状态

本仓库已落地第一版 ORM 元数据与生成器基础能力,orm.APIVersion 当前为 v1。V1 公共契约采用兼容优先策略:已导出的运行时接口、元数据结构、生成器输入模型和 CLI 主命令保持向后兼容;新增能力优先通过可选字段、可选参数、独立适配层或新接口扩展。详细边界见 docs/api-compatibility.md。已支持:

  • 实体 //goark-orm:entity 与严格 goark-orm struct tag 解析。
  • Mapper //goark-orm:mapperselectinsertupdatedeletecall 方法注解扫描,注解 SQL 支持 <script> 动态节点和显式 SQL Provider。
  • XML Mapper 静态语句、动态 SQL 基础节点、callparameterresultSetbindselectKeydatabaseIdresultMapconstructor/idArg/argassociationcollectionextendsautoMappingdiscriminatorcolumnPrefixnotNullColumn 元数据和 namespace/类型一致性校验。
  • XML 与注解在同一个 Mapper 接口中混用。
  • 生成 RegisterGoarkORMMetadata、实体 RowScanner、Mapper 实现、分页 Mapper 签名、Cursor/ResultHandler 流式 Mapper 签名、BaseMapper/Service 工厂和 orm.Session 调用代码。
  • Mapper 接口支持本包内接口嵌入,生成期会展平公共方法并按当前 Mapper namespace 绑定 Statement。
  • 独立 goark-orm CLI,可不安装 Goark 主 CLI 直接生成代码;支持 --config JSON 配置文件批量生成多 package,并提供 --validate--dry-run--check--diff 作为本地生成一致性门禁。
  • ormgen 提供 TemplateRendererSchemaIntrospectorSQLSchemaIntrospector、多数据库 SQLSchemaDialectReverseEngineerWithRenderer,可由外部数据库适配层或业务测试包做 schema 反向工程与自定义模板渲染;支持反向工程生成实体 struct、命名策略、忽略列、列过滤和列级覆盖,core 不直接依赖数据库驱动。
  • ormgen 提供 DetectSchemaDrift / ValidateSchemaDrift,可把已注册实体元数据与 SchemaIntrospector 读取到的真实 schema 做表、列、主键、自增、空值、长度/精度和数据库类型差异检测。
  • ormtest 提供环境变量门控的真实数据库兼容性测试套件,调用方在自己的测试二进制中显式 blank import 驱动后即可复用 ping、setup/cleanup、查询、分页、写语句、批处理、TypeHandler 和 callable statement 用例;标准 PG/MySQL 兼容矩阵可直接通过 RunCompatibilitySuiteFromEnv 启用。
  • database/sql Session、独立 Configuration、MyBatis-Plus 风格 GlobalConfig / DbConfigDialectDialectCapabilitiesExecutorType.SIMPLE/REUSE#{name} / #{user.name} 安全参数编译、MyBatis 风格 param1 / _parameter / list 别名、生成主键回填和显式注册 RowScanner 优先的基础结果扫描。
  • MyBatis 风格 statement 级 timeoutfetchSizeresultSetTyperesultOrderedkeyColumn 执行选项;语句级声明优先于全局默认值,并通过可选执行器接口传递给驱动适配层。
  • MyBatis 风格 MyBatisConfigMyBatisSettingsMyBatisEnvironmentTypeAliasMapperRef Go 化配置模型,可显式构建运行期 Configuration
  • MyBatis ${} 原样替换的 Go 化安全版本:默认拒绝普通字符串,只允许 RawSQLToken,内置 RawIdentifierRawOrderBy 白名单 token。
  • XML 动态 SQL 支持 sql/includebindifwheresettrimforeachchoose/when/otherwisetest 表达式支持安全 OGNL:括号、and/ornot/!、比较别名、四则运算、取模、三元表达式、in/not in、列表字面量、empty、确定性参数路径和白名单只读方法。
  • 存储过程支持 StatementCommandCallStatementTypeCallable、IN/OUT/INOUT 参数、sql.Out 绑定、按声明顺序扫描多个结果集,以及生成 Mapper 侧 orm.Call 调用代码。
  • MyBatis-Plus 风格 BaseMapper 通用 CRUD、QueryWrapper 条件构造器和 Page 分页模型。
  • MyBatis-Plus 风格 ServiceQueryChainUpdateChain,覆盖常用 IService / chain wrapper 操作,包括 ListByMapRemoveByMapGetMapGetObjPageMapsFirstMapsObjs 等便捷方法。
  • MyBatis-Plus 风格 SQLInjectorDb 快捷门面和 EnumValuer 枚举入库值接口。
  • MyBatis-Plus 风格 IDType 主键策略:AUTOINPUTASSIGN_IDASSIGN_UUID
  • DbConfig 支持全局主键策略、tablePrefix、schema、logicDeleteField、logicDeleteValue、logicNotDeleteValue、insertStrategy、updateStrategy 和 whereStrategy。
  • 实体字段支持 key-columnnumeric-scaleconditionselect=falseinsert-strategyupdate-strategywhere-strategy 元数据;BaseMapper 会按字段/全局 insert/update 策略过滤通用 INSERT/UPDATE 列。
  • BaseMapper 支持 SelectOneSelectCountSelectMapsSelectObjsSelectByMapSelectMapsPageDeleteByMapDeleteBatchIDsSaveOrUpdate
  • BaseMapper / Service 支持实体条件查询:SelectListByEntitySelectCountByEntityDeleteByEntityListByEntityCountByEntityRemoveByEntity,字段 condition / where-strategy 会参与 WHERE 构造。
  • BaseMapper 已支持逻辑删除、UpdateByID 乐观锁、created-at / updated-at 自动时间字段。
  • MyBatis-Plus 风格 MetaObjectHandler 自动填充,支持 fill='insert'fill='update'fill='insert_update',可用于 BaseMapper 和普通 Mapper 写语句。
  • QueryWrapper / UpdateWrapper 支持嵌套条件、EXISTS / NOT EXISTSApplyLastBetweenNotBetweenNotLikeLikeLeftLikeRightNotIn,查询 Wrapper 额外支持 GroupBy / Having / Select / AllEq / 条件化 OrderBy
  • UpdateWrapperTypedField 和生成期 UserTypedFields 字段常量,支持局部更新、类型化字段引用、SetSQLSetIncrBySetDecrBy
  • Registry / Session 级 TypeHandler SPI,支持 RegisterTypeHandlers / WithTypeHandlers 批量装配和 NewTypeHandler 函数适配器;内建基于 ByteDance Sonic 的 json 处理器,以及 timedecimalstringboolbytes 处理器。
  • SQLSession 执行器/StatementHandler/ParameterHandler/ResultSetHandler SPI、拦截器链,以及 BlockAttack、SQL Observer、租户条件/INSERT 字段注入、数据权限条件、动态表名、分页和实体语义内置拦截器。
  • SQLSession 支持 StatementExecutorStatementHandlerParameterHandlerResultSetHandler 四层 middleware,业务可用 decorator 方式扩展执行、编译、参数绑定和结果映射链路。
  • Registry.RegisterRowScanner 支持显式注册生成式实体行扫描器,普通实体查询、存储过程多结果集、无 TypeHandler 的简单 ResultMap 和关闭自动映射的 association ResultMap 会先走 RowScanner,collection、discriminator、nested select、TypeHandler 字段和未注册实体保持反射 fallback。
  • 非观测 SQL 治理拦截器:SQLGuardRule / NewSQLGuardInterceptor 可组合业务规则,NewIllegalSQLInterceptor 默认拒绝多语句、顶层 SELECT * 和无 WHERE 写语句,NewReadOnlyInterceptor 可保护只读会话。
  • Mapper 注解和 XML 语句支持 interceptorIgnore,可按语句跳过 block-attacktenantdata-permissiondynamic-tablepaginationentity-semanticsql-guardillegal-sqlread-onlyall
  • 独立 SQLSessionFactoryTransactionTransactionFactoryTxSessionInTx 回调事务模型。
  • 多数据源路由层:RoutingSessionRoutingSessionFactoryWithDataSourceReadWriteDataSourceResolverStatementDataSourceResolver 可把生成 Mapper 调用转发到不同逻辑数据源。
  • Go 原生错误层级:ErrConfigurationErrRegistryErrStatementNotFoundErrBindingErrMappingErrExecutorErrTooManyResults 均可通过 errors.Is 归类,通过 errors.As 读取结构化上下文。
  • BatchSession 批处理执行器、Flush / Clear、事务内批处理和查询前自动 flush。
  • Session/Statement 级一级缓存配置,写操作、提交、回滚和关闭时自动失效。
  • Mapper namespace 级二级缓存 SPI、默认内存 LRU 缓存、XML <cache> / <cache-ref>blocking=true 并发 miss 合并、CacheStatsProvider 统计快照,以及 statement 级 useCache / flushCache 策略。
  • ResultMap 支持 constructor 字段映射、显式/自动映射开关、内联 association/collection 扫描、columnPrefixnotNullColumn、collection 多行聚合、discriminator 运行期 case 分派,以及 select 嵌套查询 eager 和显式 lazy 回填;嵌套查询支持复合列参数并在单次父查询内复用相同参数结果,降低 N+1 重复查询。
  • ResultHandlerQueryCursorQueryEachRowCursor 支持逐行流式查询;游标查询不写入一级缓存和二级缓存,并拒绝需要多行聚合的 collection resultMap。生成 Mapper 可直接声明 Cursor 返回或 ResultHandler 回调签名。
  • Lazy[T]LazySlice[T] 支持 fetchType="lazy" 的 Go 化显式延迟加载;业务必须调用 Load(ctx) 触发查询,不使用透明代理。
  • 二级缓存采用 MyBatis 风格事务语义:自动提交直接生效,事务内查询缓存和写入失效都延迟到 Commit 后发布,Rollback 丢弃待发布变更。

Goark 生态集成后续按类似 mybatis-spring 的适配层推进,goark-orm core 不直接依赖 goark/db

模块路径

module goark.dev/orm

规划边界

  • 实体映射、字段元数据和查询构建边界
  • 独立 Session 生命周期、事务抽象、错误分类和上下文取消
  • 未来通过独立适配层对接 goark/db
  • 可生成、可测试、低反射的数据访问路径

非目标

  • 不克隆 JPA/Hibernate 的运行时代理和复杂持久化上下文
  • 不提交临时 SQL、迁移草稿或数据库私有脚本

快速检查

GOWORK=off go test ./...
GOWORK=off go vet ./...
GOWORK=off go test -run '^$' -bench . -benchmem ./

发布前本地门禁:

GOWORK=off ./scripts/verify-release.sh

真实数据库兼容性套件默认跳过;需要时设置 GOARK_ORM_INTEGRATION_DRIVERGOARK_ORM_INTEGRATION_DSN,并在调用方测试二进制中显式注册数据库驱动。数据库方言和验证矩阵见 docs/database-matrix.md

生成示例:

goark-orm generate orm --dir internal/user --output internal/user/zz_goark_orm_user_gen.go

生成文件会包含实体字段常量、类型化字段常量、BaseMapper 工厂和 Service 工厂。业务代码可以直接使用字段常量,不需要手写列名:

userMapper, err := NewUserBaseMapper(session)
if err != nil {
	return err
}

page, err := userMapper.SelectPage(
	ctx,
	orm.NewPageRequest(1, 20),
	orm.NewQueryWrapper[User]().
		Eq(UserFields.Status, "ACTIVE").
		OrderByAsc(UserFields.ID),
)
if err != nil {
	return err
}
_ = page

多包生成建议提交 JSON 配置文件:

{
  "databaseId": "postgres",
  "typeHandlers": ["json", "decimal"],
  "packages": [
    {
      "dir": "internal/user",
      "output": "internal/user/zz_goark_orm_user_gen.go"
    },
    {
      "dir": "internal/order"
    }
  ]
}
goark-orm generate orm --config goark-orm.json
goark-orm generate orm --config goark-orm.json --check
goark-orm generate orm --config goark-orm.json --diff

需要接入数据库反向工程时,可在业务侧或独立 adapter 实现 ormgen.SchemaIntrospector,也可以把已注册驱动的 *sql.DB / *sql.Tx 交给 ormgen.NewSQLSchemaIntrospector。schema 中间模型交给 ormgen.ReverseEngineer / ormgen.Render,或者用 ormgen.ReverseEngineerWithRenderer 直接走自定义模板;goark-orm core 不 blank import 具体数据库驱动、不提交 schema 脚本。

反向工程默认会声明实体 struct,并生成严格 goark-orm tag、字段常量、类型化字段常量、BaseMapper 和 Service 工厂。已有实体由源码扫描路径生成时不会重复声明 struct。复杂命名或字段策略可通过显式选项控制:

model, err := ormgen.ReverseEngineer(ctx, introspector, ormgen.ReverseEngineerSpec{
	PackageName:   "account",
	DatabaseID:    "postgres",
	Schema:        "public",
	TablePrefix:   "sys_",
	IgnoreColumns: []string{"sys_user.password_hash"},
	ColumnOverrides: map[string]ormgen.SchemaColumnOverride{
		"profile": {
			GoType:        "map[string]any",
			TypeHandler:   "json",
			WhereStrategy: orm.FieldStrategyNotNull,
		},
	},
})
if err != nil {
	return err
}
source, err := ormgen.Render(model)
if err != nil {
	return err
}
_ = source

已有实体元数据也可以反向校验真实库结构:

report, err := ormgen.DetectSchemaDrift(ctx, introspector, registry, ormgen.SchemaIntrospectionRequest{
	DatabaseID: "postgres",
	Schema:     "public",
})
if err != nil {
	return err
}
if report.HasDrift() {
	return report
}

真实数据库测试建议放在业务侧或本地 Mac 测试包中,由测试包显式注册驱动,再复用 ormtest 套件。setup/cleanup SQL 可通过环境变量传入 JSON 字符串数组或 GOARK_ORM_INTEGRATION_SQL_SEPARATOR 分隔文本,仓库不保存私有 SQL:

package user_test

import (
	"testing"

	_ "github.com/jackc/pgx/v5/stdlib"
	"goark.dev/orm/ormtest"
)

func TestORMDatabaseCompatibility(t *testing.T) {
	ormtest.RunCompatibilitySuiteFromEnv(t)
}

存储过程使用显式 call 语句,不通过运行时扫描发现 Mapper。OUT / INOUT 参数必须绑定到指针参数,多结果集必须声明名称并绑定到对应的 slice 指针:

//goark-orm:call(sql="call report_users(#{status}, #{total})", parameters="status:IN,total:OUT:BIGINT", resultSets="users:User,roles:Role")
ReportUsers(ctx context.Context, status string, total *int64, users *[]User, roles *[]Role) error

等价 XML 写法:

<call id="ReportUsers" statementType="CALLABLE">
  call report_users(#{status}, #{total})
  <parameter property="status" mode="IN"/>
  <parameter property="total" mode="OUT" jdbcType="BIGINT"/>
  <resultSet name="users" resultType="User"/>
  <resultSet name="roles" resultType="Role"/>
</call>

语句级执行选项可在注解或 XML 中直接声明。timeout 兼容 MyBatis 的秒数,也支持 Go duration 字符串:

//goark-orm:select(sql="select id, name from sys_user where id = #{id}", timeout="2s", fetchSize=128, resultSetType="FORWARD_ONLY")
FindByID(ctx context.Context, id int64) (*User, error)
<select id="FindByID" resultType="User" timeout="2" fetchSize="128" resultSetType="FORWARD_ONLY">
  select id, name from sys_user where id = #{id}
</select>

局部更新可以使用 UpdateWrapper

rows, err := userMapper.UpdateWithWrapper(
	ctx,
	orm.NewUpdateWrapper[User]().
		SetTyped(UserTypedFields.Name, "Alice").
		EqTyped(UserTypedFields.ID, int64(7)),
)
if err != nil {
	return err
}
_ = rows

Service 层可以直接对齐 MyBatis-Plus 常用业务写法:

userService, err := NewUserService(session)
if err != nil {
	return err
}

users, err := userService.
	ChainQuery().
	Eq(UserFields.Status, "ACTIVE").
	OrderByDesc(UserFields.ID).
	List(ctx)
if err != nil {
	return err
}
_ = users

Db 提供无实体生成代码时的显式 Session 快捷入口:

dbKit, err := orm.NewDb(session)
if err != nil {
	return err
}
result, err := dbKit.Exec(ctx, "system.user.UserMapper.UpdateName", orm.NamedArgs{
	"id":   int64(7),
	"name": "Alice",
})
if err != nil {
	return err
}
_ = result

自定义通用 SQL 可以通过 SQLInjector 显式注入到 Registry:

err := orm.RegisterInjectedStatements(
	registry,
	"system.user.UserExtraMapper",
	userEntityMeta,
	orm.LogicDeleteByIDInjector{},
	orm.WithInjectDialect(orm.NewPostgresDialect()),
)
if err != nil {
	return err
}

枚举字段可实现 EnumValuer 暴露入库值:

type UserStatus string

func (s UserStatus) EnumValue() any {
	return string(s)
}

枚举值转换需要读取调用方上下文时,可以实现 EnumValuerContextSQLSession 会在编译参数时透传当前 context.Context

通用 SQLSession 可以按需启用 MP 风格插件:

session, err := orm.NewSQLSession(
	registry,
	db,
	orm.NewPostgresDialect(),
	orm.WithInterceptors(
		orm.NewEntitySemanticInterceptor(registry),
		orm.NewDynamicTableInterceptor(map[string]string{"sys_user": "sys_user_2026"}),
		orm.NewTenantInterceptor("tenant_id", tenantID),
		orm.NewDataPermissionInterceptor(permissionProvider),
		orm.NewPaginationInterceptor(),
		orm.NewIllegalSQLInterceptor(),
		orm.NewBlockAttackInterceptor(),
	),
)
if err != nil {
	return err
}

ctx = orm.WithPageRequest(ctx, orm.NewPageRequest(1, 20))

只读链路可以单独启用写保护:

readSession, err := orm.NewSQLSession(
	registry,
	db,
	orm.NewPostgresDialect(),
	orm.WithInterceptors(orm.NewReadOnlyInterceptor()),
)
if err != nil {
	return err
}
_ = readSession

SQLSession 可通过独立配置对象统一设置运行期行为:

config := orm.DefaultConfiguration().
	WithLocalCache(true).
	WithSecondLevelCache(true).
	WithMapUnderscoreToCamelCase(true)
config.Dialect = orm.NewPostgresDialect()
config.LocalCacheScope = orm.LocalCacheScopeSession
config.DefaultExecutorType = orm.ExecutorTypeReuse
config.GlobalConfig.DbConfig.IDType = orm.IDTypeAssignID
config.GlobalConfig.DbConfig.TablePrefix = "sys_"
config.GlobalConfig.DbConfig.Schema = "tenant_01"
config.GlobalConfig.DbConfig.LogicDeleteValue = int64(1)
config.GlobalConfig.DbConfig.LogicNotDeleteValue = int64(0)
config.GlobalConfig.DbConfig.InsertStrategy = orm.FieldStrategyNotEmpty
config.GlobalConfig.DbConfig.UpdateStrategy = orm.FieldStrategyNotEmpty
config.GlobalConfig.MetaObjectHandler = auditFillHandler{}

session, err := orm.NewSQLSession(registry, db, nil, orm.WithConfiguration(config))
if err != nil {
	return err
}

也可以使用 MyBatis 命名风格的 Go 化配置模型构建运行期配置:

cacheEnabled := false
mybatisConfig := orm.MyBatisConfig{
	Settings: orm.MyBatisSettings{
		CacheEnabled:             &cacheEnabled,
		MapUnderscoreToCamelCase: true,
		DefaultExecutorType:      orm.ExecutorTypeReuse,
		DatabaseID:               "mysql8",
	},
	Environment: orm.MyBatisEnvironment{
		ID:     "prod",
		DbType: orm.DbTypeMySQL,
	},
	TypeAliases: []orm.TypeAlias{{Alias: "User", TypeName: "system.User"}},
	Mappers:     []orm.MapperRef{{Resource: "mapper/user_mapper.xml", Namespace: "system.user.UserMapper"}},
}

config, err := mybatisConfig.BuildConfiguration()
if err != nil {
	return err
}
session, err := orm.NewSQLSession(registry, db, nil, orm.WithConfiguration(config))
if err != nil {
	return err
}

自动填充处理器面向实体元数据工作,StrictInsertFill / StrictUpdateFill 会尊重字段 fill 策略:

type auditFillHandler struct{}

func (auditFillHandler) InsertFill(ctx context.Context, meta *orm.MetaObject) error {
	if err := meta.StrictInsertFill("CreatedBy", currentUserID(ctx)); err != nil {
		return err
	}
	return meta.StrictInsertFill("UpdatedBy", currentUserID(ctx))
}

func (auditFillHandler) UpdateFill(ctx context.Context, meta *orm.MetaObject) error {
	return meta.StrictUpdateFill("UpdatedBy", currentUserID(ctx))
}

大结果集可以使用游标逐条消费:

err = orm.QueryEach[User](ctx, session, "system.user.UserMapper.ListAll", nil, func(ctx context.Context, user User) error {
	return exportUser(ctx, user)
})
if err != nil {
	return err
}

生成 Mapper 也可以直接声明流式查询签名:

ListCursor(ctx context.Context, status string) (*orm.Cursor[User], error)
ListEach(ctx context.Context, status string, handler orm.ResultHandler[User]) error

注解 Mapper 可以使用 MyBatis 风格 <script>,复杂 SQL 也可以通过显式注册的 Provider 运行期生成:

//goark-orm:select(sql="<script>select id, name from sys_user <where><if test=\"status != nil and status != ''\">status = #{status}</if></where></script>")
List(ctx context.Context, status string) ([]User, error)

//goark-orm:select(provider="UserSQL.ListByStatus")
ListByProvider(ctx context.Context, status string) ([]User, error)
err := registry.RegisterSQLProvider("UserSQL.ListByStatus", func(ctx context.Context, statement orm.StatementMeta, args orm.NamedArgs) (orm.SQLSource, error) {
	return orm.SQLSource{SQL: "select id, name from sys_user where status = #{status}"}, nil
})
if err != nil {
	return err
}

${} 只允许显式安全 token,适合动态表名、列名或排序字段:

table, err := orm.NewRawIdentifier("tenant_01.sys_user")
if err != nil {
	return err
}
orderName, err := orm.NewRawOrderItem("name", false)
if err != nil {
	return err
}
orderID, err := orm.NewRawOrderItem("id", true)
if err != nil {
	return err
}

compiled, err := orm.CompileSQL(
	"select * from ${table} order by ${orderBy} limit #{limit}",
	orm.NamedArgs{
		"table":   table,
		"orderBy": orm.NewRawOrderBy(orderName, orderID),
		"limit":   20,
	},
	orm.NewPostgresDialect(),
)
if err != nil {
	return err
}
_ = compiled

MyBatis 风格事务可以通过 SQLSessionFactory 使用:

factory, err := orm.NewSQLSessionFactory(registry, db, orm.NewPostgresDialect())
if err != nil {
	return err
}

err = factory.InTx(ctx, nil, func(ctx context.Context, session orm.Session) error {
	userMapper := NewUserMapper(session)
	_, err := userMapper.ListByStatus(ctx, "ACTIVE")
	return err
})
if err != nil {
	return err
}

多数据源路由保持在独立适配层,不制造跨库事务假象。读写分离可以组合已有 Session:

routing, err := orm.NewRoutingSession(
	map[orm.DataSourceKey]orm.Session{
		"primary": primarySession,
		"replica": replicaSession,
	},
	orm.ReadWriteDataSourceResolver("replica", "primary"),
	orm.WithRoutingDefaultDataSource("primary"),
)
if err != nil {
	return err
}

ctx = orm.WithDataSource(ctx, "primary")
userMapper := NewUserMapper(routing)
_ = userMapper

批处理可以独立使用,也可以放入事务回调:

err = factory.InTx(ctx, nil, func(ctx context.Context, session orm.Session) error {
	batch, err := orm.NewBatchSession(session)
	if err != nil {
		return err
	}
	userMapper := NewUserMapper(batch)
	if _, err := userMapper.UpdateStatus(ctx, int64(7), "LOCKED"); err != nil {
		return err
	}
	_, err = batch.Flush(ctx)
	return err
})

XML Mapper 可以声明 namespace 二级缓存:

<mapper namespace="system.user.UserMapper">
  <cache eviction="LRU" size="1024" flushInterval="60000" blocking="true"/>
  <select id="FindByID" useCache="true" flushCache="false">
    select id, name from sys_user where id = #{id}
  </select>
</mapper>

多个 Mapper 可以通过 cache-ref 共享同一个 namespace 缓存:

<cache-ref namespace="system.user.UserMapper"/>

生成 Mapper 可以声明分页签名:

ListPage(ctx context.Context, status string, page orm.PageRequest) (orm.Page[User], error)

XML 嵌套查询可以使用显式 Lazy 字段:

type Order struct {
	ID    int64
	User  orm.Lazy[User]
	Items orm.LazySlice[OrderItem]
}

user, err := order.User.Load(ctx)
items, err := order.Items.Load(ctx)

Mapper 公共接口可以通过 Go 接口嵌入复用:

type UserQueryMapper interface {
	FindByID(ctx context.Context, id int64) (*User, error)
}

//goark-orm:mapper(namespace="system.user.UserMapper", xml="mapper/user_mapper.xml")
type UserMapper interface {
	UserQueryMapper
}

实体字段可通过 tag 开启通用 Mapper 语义:

Version   int64     `goark-orm:"column='version';version=true"`
Deleted   bool      `goark-orm:"column='deleted';soft-delete=true"`
CreatedAt time.Time `goark-orm:"column='created_at';created-at=true"`
UpdatedAt time.Time `goark-orm:"column='updated_at';updated-at=true"`
Remark    string    `goark-orm:"column='remark';select=false;insert-strategy='not-empty';update-strategy='not-empty'"`

字段策略取值支持 alwaysnot-nullnot-emptynot-zeronever。字段级策略优先于 DbConfig 全局策略;未声明时保持 V1 旧行为,通用 INSERT/UPDATE 默认包含零值字段。实体条件构造默认使用 Go 化 not-zero 策略,避免基础类型零值误参与 WHERE。

实体条件查询会读取字段级 conditionwhere-strategy

users, err := userService.ListByEntity(ctx, &User{Name: "%Alice%"})
if err != nil {
	return err
}
_ = users

Goark 主 CLI 不包含 ORM 子命令,也不依赖 goark.dev/orm。ORM 代码生成统一使用本仓库自带的独立 goark-orm 命令。

错误分类

运行期错误遵循 Go 原生包装语义。业务代码按分类处理时使用 errors.Is(err, orm.ErrBinding),需要定位信息时使用 errors.As 提取 *orm.BindingError*orm.MappingError*orm.ExecutorError 等结构体。

if errors.Is(err, orm.ErrTooManyResults) {
	return err
}

var mappingErr *orm.MappingError
if errors.As(err, &mappingErr) {
	_ = mappingErr.Statement
	_ = mappingErr.Column
	_ = mappingErr.Field
}

工程约定

  • Go 版本跟随 Goark 生态主线,当前模块声明为 go 1.25
  • 代码、脚本、配置和文档统一使用 UTF-8 与 LF。
  • Go 代码注释使用标准简体中文,只解释非显而易见的设计意图、边界和失败语义。
  • 公共 API 优先显式接口、小结构体和可组合选项,不使用 Java 风格运行时扫描或重代理模型。
  • 功能实现必须包含边界条件、错误处理、上下文取消和并发安全复核。

许可证

本项目使用 Apache License 2.0。

Documentation

Overview

Package orm 提供独立的 MyBatis/MyBatis-Plus 风格 Go ORM 运行时。

包内包含实体元数据、Configuration、GlobalConfig/DbConfig、结构化错误层级、Statement 编译、SQL Provider、参数路径绑定、MetaObjectHandler 自动填充、ResultMap constructor/association/collection 嵌套映射和 discriminator 分派、SQLSession、执行器/Handler SPI、REUSE 预编译语句复用、事务 Session、BatchSession、游标流式查询、显式 Lazy 延迟加载、一级缓存、Mapper namespace 二级缓存、条件构造器、分页模型、主键策略、Service 层和拦截器 SPI。 生成器输出的 Mapper 只依赖 Session 接口,因此自动提交 Session、事务 Session、BatchSession 和流式查询签名可以共用同一套生成代码。

Index

Constants

View Source
const (
	// ModulePath 是 goark-orm 的稳定 Go module 路径。
	ModulePath = "goark.dev/orm"

	// APIVersion 表示当前承诺兼容的公共 API 主版本。
	APIVersion = "v1"
)
View Source
const (
	// InterceptorNameAll 表示忽略全部可命名拦截器。
	InterceptorNameAll = "all"
	// InterceptorNameSQLObserver 表示 SQL 模板观察拦截器。
	InterceptorNameSQLObserver = "sql-observer"
	// InterceptorNameBlockAttack 表示全表更新/删除保护拦截器。
	InterceptorNameBlockAttack = "block-attack"
	// InterceptorNameDataPermission 表示数据权限条件拦截器。
	InterceptorNameDataPermission = "data-permission"
	// InterceptorNameTenant 表示租户条件拦截器。
	InterceptorNameTenant = "tenant"
	// InterceptorNameDynamicTable 表示动态表名拦截器。
	InterceptorNameDynamicTable = "dynamic-table"
	// InterceptorNamePagination 表示分页拦截器。
	InterceptorNamePagination = "pagination"
	// InterceptorNameEntitySemantic 表示实体语义拦截器。
	InterceptorNameEntitySemantic = "entity-semantic"
	// InterceptorNameSQLGuard 表示通用 SQL 治理规则拦截器。
	InterceptorNameSQLGuard = "sql-guard"
	// InterceptorNameIllegalSQL 表示非法 SQL 治理拦截器。
	InterceptorNameIllegalSQL = "illegal-sql"
	// InterceptorNameReadOnly 表示只读治理拦截器。
	InterceptorNameReadOnly = "read-only"
)
View Source
const (
	// DefaultBatchSize 是批量写入默认 flush 大小,对齐 MyBatis-Plus 常用默认值。
	DefaultBatchSize = 1000
)

Variables

View Source
var (
	// ErrORM 是 goark-orm 所有结构化错误的根分类。
	ErrORM = errors.New("goark-orm: orm error")
	// ErrConfiguration 表示运行期配置、选项或框架装配错误。
	ErrConfiguration = errors.New("goark-orm: configuration error")
	// ErrRegistry 表示元数据注册和查找错误。
	ErrRegistry = errors.New("goark-orm: registry error")
	// ErrStatementNotFound 表示 Mapper Statement 或 Provider 未注册。
	ErrStatementNotFound = errors.New("goark-orm: statement not found")
	// ErrBinding 表示 SQL 参数解析、绑定或占位符编译错误。
	ErrBinding = errors.New("goark-orm: binding error")
	// ErrMapping 表示结果集扫描、字段赋值或 TypeHandler 结果转换错误。
	ErrMapping = errors.New("goark-orm: mapping error")
	// ErrExecutor 表示数据库执行、预编译语句或行集生命周期错误。
	ErrExecutor = errors.New("goark-orm: executor error")
	// ErrTooManyResults 表示 QueryOne 返回了超过一行结果。
	ErrTooManyResults = errors.New("goark-orm: too many results")
)
View Source
var ErrTransactionCompleted = errors.New("goark-orm: transaction already completed")

ErrTransactionCompleted 表示事务已经提交或回滚。

Functions

func BetweenTypedValues

func BetweenTypedValues[T any, V any, W typedConditionTarget[T, W]](w W, field TypedField[T, V], left V, right V) W

BetweenTypedValues 用泛型函数保留字段值类型约束并添加 BETWEEN 条件。

func BetweenTypedValuesIf

func BetweenTypedValuesIf[T any, V any, W typedConditionTarget[T, W]](condition bool, w W, field TypedField[T, V], left V, right V) W

BetweenTypedValuesIf 在 condition 为 true 时添加类型安全的 BETWEEN 条件。

func EqTypedValue

func EqTypedValue[T any, V any, W typedConditionTarget[T, W]](w W, field TypedField[T, V], value V) W

EqTypedValue 用泛型函数为 QueryWrapper 和 UpdateWrapper 保留字段值类型约束。

func EqTypedValueIf

func EqTypedValueIf[T any, V any, W typedConditionTarget[T, W]](condition bool, w W, field TypedField[T, V], value V) W

EqTypedValueIf 在 condition 为 true 时添加类型安全的等值条件。

func GeTypedValue

func GeTypedValue[T any, V any, W typedConditionTarget[T, W]](w W, field TypedField[T, V], value V) W

GeTypedValue 用泛型函数保留字段值类型约束并添加大于等于条件。

func GeTypedValueIf

func GeTypedValueIf[T any, V any, W typedConditionTarget[T, W]](condition bool, w W, field TypedField[T, V], value V) W

GeTypedValueIf 在 condition 为 true 时添加类型安全的大于等于条件。

func GtTypedValue

func GtTypedValue[T any, V any, W typedConditionTarget[T, W]](w W, field TypedField[T, V], value V) W

GtTypedValue 用泛型函数保留字段值类型约束并添加大于条件。

func GtTypedValueIf

func GtTypedValueIf[T any, V any, W typedConditionTarget[T, W]](condition bool, w W, field TypedField[T, V], value V) W

GtTypedValueIf 在 condition 为 true 时添加类型安全的大于条件。

func InTypedValues

func InTypedValues[T any, V any, W typedConditionTarget[T, W]](w W, field TypedField[T, V], values ...V) W

InTypedValues 用泛型函数保留字段值类型约束并添加 IN 条件。

func InTypedValuesIf

func InTypedValuesIf[T any, V any, W typedConditionTarget[T, W]](condition bool, w W, field TypedField[T, V], values ...V) W

InTypedValuesIf 在 condition 为 true 时添加类型安全的 IN 条件。

func LeTypedValue

func LeTypedValue[T any, V any, W typedConditionTarget[T, W]](w W, field TypedField[T, V], value V) W

LeTypedValue 用泛型函数保留字段值类型约束并添加小于等于条件。

func LeTypedValueIf

func LeTypedValueIf[T any, V any, W typedConditionTarget[T, W]](condition bool, w W, field TypedField[T, V], value V) W

LeTypedValueIf 在 condition 为 true 时添加类型安全的小于等于条件。

func LikeLeftTypedValue

func LikeLeftTypedValue[T any, V any, W typedConditionTarget[T, W]](w W, field TypedField[T, V], value V) W

LikeLeftTypedValue 用泛型函数保留字段值类型约束并添加左侧模糊匹配条件。

func LikeLeftTypedValueIf

func LikeLeftTypedValueIf[T any, V any, W typedConditionTarget[T, W]](condition bool, w W, field TypedField[T, V], value V) W

LikeLeftTypedValueIf 在 condition 为 true 时添加类型安全的左侧模糊匹配条件。

func LikeRightTypedValue

func LikeRightTypedValue[T any, V any, W typedConditionTarget[T, W]](w W, field TypedField[T, V], value V) W

LikeRightTypedValue 用泛型函数保留字段值类型约束并添加右侧模糊匹配条件。

func LikeRightTypedValueIf

func LikeRightTypedValueIf[T any, V any, W typedConditionTarget[T, W]](condition bool, w W, field TypedField[T, V], value V) W

LikeRightTypedValueIf 在 condition 为 true 时添加类型安全的右侧模糊匹配条件。

func LikeTypedValue

func LikeTypedValue[T any, V any, W typedConditionTarget[T, W]](w W, field TypedField[T, V], value V) W

LikeTypedValue 用泛型函数保留字段值类型约束并添加 LIKE 条件。

func LikeTypedValueIf

func LikeTypedValueIf[T any, V any, W typedConditionTarget[T, W]](condition bool, w W, field TypedField[T, V], value V) W

LikeTypedValueIf 在 condition 为 true 时添加类型安全的 LIKE 条件。

func LtTypedValue

func LtTypedValue[T any, V any, W typedConditionTarget[T, W]](w W, field TypedField[T, V], value V) W

LtTypedValue 用泛型函数保留字段值类型约束并添加小于条件。

func LtTypedValueIf

func LtTypedValueIf[T any, V any, W typedConditionTarget[T, W]](condition bool, w W, field TypedField[T, V], value V) W

LtTypedValueIf 在 condition 为 true 时添加类型安全的小于条件。

func NeTypedValue

func NeTypedValue[T any, V any, W typedConditionTarget[T, W]](w W, field TypedField[T, V], value V) W

NeTypedValue 用泛型函数保留字段值类型约束并添加不等条件。

func NeTypedValueIf

func NeTypedValueIf[T any, V any, W typedConditionTarget[T, W]](condition bool, w W, field TypedField[T, V], value V) W

NeTypedValueIf 在 condition 为 true 时添加类型安全的不等条件。

func NotBetweenTypedValues

func NotBetweenTypedValues[T any, V any, W typedConditionTarget[T, W]](w W, field TypedField[T, V], left V, right V) W

NotBetweenTypedValues 用泛型函数保留字段值类型约束并添加 NOT BETWEEN 条件。

func NotBetweenTypedValuesIf

func NotBetweenTypedValuesIf[T any, V any, W typedConditionTarget[T, W]](condition bool, w W, field TypedField[T, V], left V, right V) W

NotBetweenTypedValuesIf 在 condition 为 true 时添加类型安全的 NOT BETWEEN 条件。

func NotInTypedValues

func NotInTypedValues[T any, V any, W typedConditionTarget[T, W]](w W, field TypedField[T, V], values ...V) W

NotInTypedValues 用泛型函数保留字段值类型约束并添加 NOT IN 条件。

func NotInTypedValuesIf

func NotInTypedValuesIf[T any, V any, W typedConditionTarget[T, W]](condition bool, w W, field TypedField[T, V], values ...V) W

NotInTypedValuesIf 在 condition 为 true 时添加类型安全的 NOT IN 条件。

func NotLikeTypedValue

func NotLikeTypedValue[T any, V any, W typedConditionTarget[T, W]](w W, field TypedField[T, V], value V) W

NotLikeTypedValue 用泛型函数保留字段值类型约束并添加 NOT LIKE 条件。

func NotLikeTypedValueIf

func NotLikeTypedValueIf[T any, V any, W typedConditionTarget[T, W]](condition bool, w W, field TypedField[T, V], value V) W

NotLikeTypedValueIf 在 condition 为 true 时添加类型安全的 NOT LIKE 条件。

func QueryEach

func QueryEach[T any](ctx context.Context, session Session, statement string, args NamedArgs, handler ResultHandler[T]) error

QueryEach 逐条扫描并回调处理查询结果。

func RegisterInjectedStatements

func RegisterInjectedStatements(registry *Registry, namespace string, entity EntityMeta, injector SQLInjector, options ...InjectOption) error

RegisterInjectedStatements 将注入器生成的通用 Statement 注册到 Registry。

func StatementInterceptorIgnored

func StatementInterceptorIgnored(statement StatementMeta, name string) bool

StatementInterceptorIgnored 判断语句是否声明跳过指定拦截器。

func WithDataSource

func WithDataSource(ctx context.Context, key DataSourceKey) context.Context

WithDataSource 在 context 中声明本次 ORM 调用使用的数据源。

func WithPageRequest

func WithPageRequest(ctx context.Context, page PageRequest) context.Context

WithPageRequest 将分页请求挂到 context,供分页拦截器读取。

Types

type BaseMapper

type BaseMapper[T any, ID any] struct {
	// contains filtered or unexported fields
}

BaseMapper 提供 MyBatis-Plus 风格的实体通用 CRUD。

func NewBaseMapper

func NewBaseMapper[T any, ID any](session StatementSession, entity EntityMeta, options ...BaseMapperOption) (*BaseMapper[T, ID], error)

NewBaseMapper 创建实体通用 Mapper。

func (*BaseMapper[T, ID]) Count

func (m *BaseMapper[T, ID]) Count(ctx context.Context, wrapper *QueryWrapper[T]) (int64, error)

Count 按条件统计记录数。

func (*BaseMapper[T, ID]) Delete

func (m *BaseMapper[T, ID]) Delete(ctx context.Context, wrapper *QueryWrapper[T]) (int64, error)

Delete 按条件删除记录,空条件会被拒绝。

func (*BaseMapper[T, ID]) DeleteBatchIDs

func (m *BaseMapper[T, ID]) DeleteBatchIDs(ctx context.Context, ids []ID) (int64, error)

DeleteBatchIDs 按主键集合删除记录。

func (*BaseMapper[T, ID]) DeleteByEntity

func (m *BaseMapper[T, ID]) DeleteByEntity(ctx context.Context, entity *T) (int64, error)

DeleteByEntity 按实体非零字段删除记录,空条件仍由 Delete 保持 fail-fast。

func (*BaseMapper[T, ID]) DeleteByID

func (m *BaseMapper[T, ID]) DeleteByID(ctx context.Context, id ID) (int64, error)

DeleteByID 按主键删除记录。

func (*BaseMapper[T, ID]) DeleteByMap

func (m *BaseMapper[T, ID]) DeleteByMap(ctx context.Context, columnMap map[string]any) (int64, error)

DeleteByMap 按列名 map 等值删除记录,空 map 会被拒绝。

func (*BaseMapper[T, ID]) EntityQueryWrapper

func (m *BaseMapper[T, ID]) EntityQueryWrapper(entity *T) (*QueryWrapper[T], error)

EntityQueryWrapper 按实体字段值构造查询条件,字段 whereStrategy 决定是否参与 WHERE。

func (*BaseMapper[T, ID]) Insert

func (m *BaseMapper[T, ID]) Insert(ctx context.Context, entity *T) (Result, error)

Insert 插入实体,返回写入结果。

func (*BaseMapper[T, ID]) InsertBatch

func (m *BaseMapper[T, ID]) InsertBatch(ctx context.Context, entities []T) (int64, error)

InsertBatch 按默认批量大小插入实体。

func (*BaseMapper[T, ID]) InsertBatchSize

func (m *BaseMapper[T, ID]) InsertBatchSize(ctx context.Context, entities []T, batchSize int) (int64, error)

InsertBatchSize 按指定批量大小插入实体。底层 Session 支持批处理时会分批 flush。

func (*BaseMapper[T, ID]) SaveOrUpdate

func (m *BaseMapper[T, ID]) SaveOrUpdate(ctx context.Context, entity *T) (Result, error)

SaveOrUpdate 根据主键零值判断插入或按主键更新。

func (*BaseMapper[T, ID]) SaveOrUpdateBatch

func (m *BaseMapper[T, ID]) SaveOrUpdateBatch(ctx context.Context, entities []T) (int64, error)

SaveOrUpdateBatch 按默认批量大小保存或更新实体。

func (*BaseMapper[T, ID]) SaveOrUpdateBatchSize

func (m *BaseMapper[T, ID]) SaveOrUpdateBatchSize(ctx context.Context, entities []T, batchSize int) (int64, error)

SaveOrUpdateBatchSize 保存或更新实体。该方法保留逐条语义,确保更新 0 行时再插入。

func (*BaseMapper[T, ID]) SelectBatchIDs

func (m *BaseMapper[T, ID]) SelectBatchIDs(ctx context.Context, ids []ID) ([]T, error)

SelectBatchIDs 按主键集合查询记录。

func (*BaseMapper[T, ID]) SelectByID

func (m *BaseMapper[T, ID]) SelectByID(ctx context.Context, id ID) (*T, error)

SelectByID 按主键查询单条记录。

func (*BaseMapper[T, ID]) SelectByMap

func (m *BaseMapper[T, ID]) SelectByMap(ctx context.Context, columnMap map[string]any) ([]T, error)

SelectByMap 按列名 map 等值查询记录。

func (*BaseMapper[T, ID]) SelectCount

func (m *BaseMapper[T, ID]) SelectCount(ctx context.Context, wrapper *QueryWrapper[T]) (int64, error)

SelectCount 是 Count 的 MyBatis-Plus 命名别名。

func (*BaseMapper[T, ID]) SelectCountByEntity

func (m *BaseMapper[T, ID]) SelectCountByEntity(ctx context.Context, entity *T) (int64, error)

SelectCountByEntity 按实体非零字段统计记录数。

func (*BaseMapper[T, ID]) SelectList

func (m *BaseMapper[T, ID]) SelectList(ctx context.Context, wrapper *QueryWrapper[T]) ([]T, error)

SelectList 按条件查询记录列表。

func (*BaseMapper[T, ID]) SelectListByEntity

func (m *BaseMapper[T, ID]) SelectListByEntity(ctx context.Context, entity *T) ([]T, error)

SelectListByEntity 按实体非零字段查询列表。

func (*BaseMapper[T, ID]) SelectMaps

func (m *BaseMapper[T, ID]) SelectMaps(ctx context.Context, wrapper *QueryWrapper[T]) ([]map[string]any, error)

SelectMaps 按条件查询 map 结果列表。

func (*BaseMapper[T, ID]) SelectMapsPage

func (m *BaseMapper[T, ID]) SelectMapsPage(ctx context.Context, page PageRequest, wrapper *QueryWrapper[T]) (Page[map[string]any], error)

SelectMapsPage 按条件执行 map 结果分页查询。

func (*BaseMapper[T, ID]) SelectObjs

func (m *BaseMapper[T, ID]) SelectObjs(ctx context.Context, wrapper *QueryWrapper[T]) ([]any, error)

SelectObjs 按条件查询首列结果列表,默认选择实体主键列。

func (*BaseMapper[T, ID]) SelectOne

func (m *BaseMapper[T, ID]) SelectOne(ctx context.Context, wrapper *QueryWrapper[T]) (*T, error)

SelectOne 按条件查询单条记录。

func (*BaseMapper[T, ID]) SelectPage

func (m *BaseMapper[T, ID]) SelectPage(ctx context.Context, page PageRequest, wrapper *QueryWrapper[T]) (Page[T], error)

SelectPage 按条件执行分页查询。

func (*BaseMapper[T, ID]) Update

func (m *BaseMapper[T, ID]) Update(ctx context.Context, entity *T, wrapper *QueryWrapper[T]) (int64, error)

Update 按条件更新实体非主键字段,空条件会被拒绝。

func (*BaseMapper[T, ID]) UpdateBatchByID

func (m *BaseMapper[T, ID]) UpdateBatchByID(ctx context.Context, entities []T) (int64, error)

UpdateBatchByID 按默认批量大小根据主键更新实体。

func (*BaseMapper[T, ID]) UpdateBatchByIDSize

func (m *BaseMapper[T, ID]) UpdateBatchByIDSize(ctx context.Context, entities []T, batchSize int) (int64, error)

UpdateBatchByIDSize 按指定批量大小根据主键更新实体。底层 Session 支持批处理时会分批 flush。

func (*BaseMapper[T, ID]) UpdateByID

func (m *BaseMapper[T, ID]) UpdateByID(ctx context.Context, entity *T) (int64, error)

UpdateByID 按主键更新实体非主键字段。

func (*BaseMapper[T, ID]) UpdateWithWrapper

func (m *BaseMapper[T, ID]) UpdateWithWrapper(ctx context.Context, wrapper *UpdateWrapper[T]) (int64, error)

UpdateWithWrapper 按 UpdateWrapper 的 SET 和 WHERE 执行局部更新。

type BaseMapperOption

type BaseMapperOption func(*baseMapperOptions)

BaseMapperOption 配置 BaseMapper。

func WithBaseMapperClock

func WithBaseMapperClock(clock func() time.Time) BaseMapperOption

WithBaseMapperClock 指定自动时间字段使用的时钟。

func WithBaseMapperDialect

func WithBaseMapperDialect(dialect Dialect) BaseMapperOption

WithBaseMapperDialect 指定 BaseMapper 生成 SQL 使用的数据库方言。

func WithBaseMapperGlobalConfig

func WithBaseMapperGlobalConfig(global GlobalConfig) BaseMapperOption

WithBaseMapperGlobalConfig 指定 BaseMapper 使用的全局配置。

func WithBaseMapperIdentifierGenerator

func WithBaseMapperIdentifierGenerator(generator IdentifierGenerator) BaseMapperOption

WithBaseMapperIdentifierGenerator 指定 BaseMapper 插入前主键生成器。

func WithBaseMapperMetaObjectHandler

func WithBaseMapperMetaObjectHandler(handler MetaObjectHandler) BaseMapperOption

WithBaseMapperMetaObjectHandler 指定 BaseMapper 自动填充处理器。

type BatchError

type BatchError struct {
	Index         int
	Statement     string
	StatementMeta StatementMeta
	Err           error
}

BatchError 描述批处理在指定下标语句上的执行失败。

func (*BatchError) Error

func (e *BatchError) Error() string

func (*BatchError) Unwrap

func (e *BatchError) Unwrap() error

Unwrap 返回底层执行错误。

type BatchResult

type BatchResult struct {
	Statement     string
	StatementMeta StatementMeta
	Args          NamedArgs
	Result        Result
}

BatchResult 表示批处理中单条语句的执行结果。

type BatchSession

type BatchSession struct {
	// contains filtered or unexported fields
}

BatchSession 提供 MyBatis BatchExecutor 风格的批处理 Session。

func NewBatchSession

func NewBatchSession(session Session) (*BatchSession, error)

NewBatchSession 创建批处理 Session。

func (*BatchSession) Call

func (s *BatchSession) Call(ctx context.Context, statement string, args NamedArgs, resultSets ...any) (CallResult, error)

Call 会先刷新批处理队列,再转发存储过程调用。

func (*BatchSession) CallStatement

func (s *BatchSession) CallStatement(ctx context.Context, statement StatementMeta, args NamedArgs, resultSets ...any) (CallResult, error)

CallStatement 会先刷新批处理队列,再转发 StatementMeta 调用。

func (*BatchSession) Clear

func (s *BatchSession) Clear()

Clear 丢弃所有尚未 flush 的批处理语句。

func (*BatchSession) Close

func (s *BatchSession) Close() error

Close 丢弃待执行语句并关闭底层 Session。

func (*BatchSession) Commit

func (s *BatchSession) Commit() error

Commit 使用后台上下文刷新批处理并提交底层 Session。

func (*BatchSession) CommitContext

func (s *BatchSession) CommitContext(ctx context.Context) error

CommitContext 刷新批处理并提交底层 Session。

func (*BatchSession) Dialect

func (s *BatchSession) Dialect() Dialect

Dialect 返回底层 Session 的数据库方言。

func (*BatchSession) Exec

func (s *BatchSession) Exec(ctx context.Context, statement string, args NamedArgs) (Result, error)

Exec 将命名 Statement 加入批处理队列。

func (*BatchSession) ExecStatement

func (s *BatchSession) ExecStatement(ctx context.Context, statement StatementMeta, args NamedArgs) (Result, error)

ExecStatement 将 StatementMeta 加入批处理队列。

func (*BatchSession) Flush

func (s *BatchSession) Flush(ctx context.Context) ([]BatchResult, error)

Flush 按入队顺序执行所有待处理写语句。

func (*BatchSession) Len

func (s *BatchSession) Len() int

Len 返回当前待执行语句数量。

func (*BatchSession) Query

func (s *BatchSession) Query(ctx context.Context, statement string, args NamedArgs, dest any) error

Query 会先刷新待执行写语句,再执行查询。

func (*BatchSession) QueryCursor

func (s *BatchSession) QueryCursor(ctx context.Context, statement string, args NamedArgs) (*RowCursor, error)

func (*BatchSession) QueryOne

func (s *BatchSession) QueryOne(ctx context.Context, statement string, args NamedArgs, dest any) error

QueryOne 会先刷新待执行写语句,再执行单行查询。

func (*BatchSession) QueryOneStatement

func (s *BatchSession) QueryOneStatement(ctx context.Context, statement StatementMeta, args NamedArgs, dest any) error

QueryOneStatement 会先刷新待执行写语句,再执行单行查询语句元数据。

func (*BatchSession) QueryPage

func (s *BatchSession) QueryPage(ctx context.Context, statement string, args NamedArgs, page PageRequest, dest any) (PageQueryResult, error)

QueryPage 会先刷新待执行写语句,再执行分页查询。

func (*BatchSession) QueryStatement

func (s *BatchSession) QueryStatement(ctx context.Context, statement StatementMeta, args NamedArgs, dest any) error

QueryStatement 会先刷新待执行写语句,再执行查询语句元数据。

func (*BatchSession) Rollback

func (s *BatchSession) Rollback() error

Rollback 丢弃待执行语句并回滚底层 Session。

type BindingError

type BindingError struct {
	Statement string
	Operation string
	Parameter string
	Column    string
	Field     string
	Message   string
	Err       error
}

BindingError 携带参数绑定和 SQL 编译阶段的定位信息。

func (*BindingError) Error

func (e *BindingError) Error() string

func (*BindingError) Is

func (e *BindingError) Is(target error) bool

func (*BindingError) Unwrap

func (e *BindingError) Unwrap() error

type BlockingCache

type BlockingCache struct {
	// contains filtered or unexported fields
}

BlockingCache 使用每个 key 一个加载权来合并并发缓存 miss。

func NewBlockingCache

func NewBlockingCache(delegate Cache) *BlockingCache

NewBlockingCache 创建缓存 miss 合并装饰器。

func (*BlockingCache) Clear

func (c *BlockingCache) Clear(ctx context.Context) error

Clear 清空缓存并释放全部等待者。

func (*BlockingCache) Get

func (c *BlockingCache) Get(ctx context.Context, key string) (any, bool, error)

Get 读取缓存;同一 key 已有加载者时等待其 Put、Remove、Clear 或 ReleaseMiss。

func (*BlockingCache) Put

func (c *BlockingCache) Put(ctx context.Context, key string, value any) error

Put 写入缓存并释放同 key 的等待者。

func (*BlockingCache) ReleaseMiss

func (c *BlockingCache) ReleaseMiss(ctx context.Context, key string) error

ReleaseMiss 释放一次未写入缓存的 miss 加载权。

func (*BlockingCache) Remove

func (c *BlockingCache) Remove(ctx context.Context, key string) error

Remove 删除缓存并释放同 key 的等待者。

func (*BlockingCache) Stats

func (c *BlockingCache) Stats() CacheStats

Stats 返回底层缓存的统计快照。

type Cache

type Cache interface {
	Get(ctx context.Context, key string) (any, bool, error)
	Put(ctx context.Context, key string, value any) error
	Remove(ctx context.Context, key string) error
	Clear(ctx context.Context) error
}

Cache 定义 Mapper namespace 级二级缓存 SPI。

type CacheMeta

type CacheMeta struct {
	Enabled             bool
	RefNamespace        string
	Eviction            string
	Size                int
	FlushIntervalMillis int64
	ReadOnly            bool
	Blocking            bool
}

CacheMeta 描述 Mapper namespace 级二级缓存配置。

type CacheMissReleaser

type CacheMissReleaser interface {
	ReleaseMiss(ctx context.Context, key string) error
}

CacheMissReleaser 描述可显式释放缓存 miss 加载权的可选能力。

type CacheStats

type CacheStats struct {
	ID          string
	MaxEntries  int
	Len         int
	Hits        uint64
	Misses      uint64
	Puts        uint64
	Removes     uint64
	Clears      uint64
	Evictions   uint64
	Expirations uint64
}

CacheStats 描述缓存运行期统计快照。

type CacheStatsProvider

type CacheStatsProvider interface {
	Stats() CacheStats
}

CacheStatsProvider 描述可导出缓存统计快照的可选能力。

type CallResult

type CallResult struct {
	RowsAffected int64
}

CallResult 表示存储过程调用结果。

func Call

func Call(ctx context.Context, session Session, statement string, args NamedArgs, resultSets ...any) (CallResult, error)

Call 执行生成 Mapper 使用的存储过程调用。

type CallSession

type CallSession interface {
	Call(ctx context.Context, statement string, args NamedArgs, resultSets ...any) (CallResult, error)
}

CallSession 描述支持按 Statement 名称调用存储过程的 Session。

type ColumnMeta

type ColumnMeta struct {
	FieldName      string
	FieldType      string
	ColumnName     string
	KeyColumn      string
	PrimaryKey     bool
	AutoIncrement  bool
	IDType         IDType
	Nullable       *bool
	Size           *int
	NumericScale   *int
	DBType         string
	DefaultValue   string
	TypeHandler    string
	Condition      string
	SelectDisabled bool
	InsertStrategy FieldStrategy
	UpdateStrategy FieldStrategy
	WhereStrategy  FieldStrategy
	Version        bool
	SoftDelete     bool
	CreatedAt      bool
	UpdatedAt      bool
	Fill           FieldFill
}

ColumnMeta 描述实体字段与数据库列的静态映射。

type CompiledSQL

type CompiledSQL struct {
	SQL  string
	Args []any
}

CompiledSQL 表示已经完成占位符改写和参数排序的 SQL。

func CompileSQL

func CompileSQL(query string, args NamedArgs, dialect Dialect) (CompiledSQL, error)

CompileSQL 将 #{name} 改写为数据库方言占位符,并按出现顺序绑定参数。

func CompileSQLContext

func CompileSQLContext(ctx context.Context, query string, args NamedArgs, dialect Dialect) (CompiledSQL, error)

CompileSQLContext 将 #{name} 改写为数据库方言占位符,并使用调用方上下文完成参数转换。

type Configuration

type Configuration struct {
	Dialect                  Dialect
	DatabaseID               string
	GlobalConfig             GlobalConfig
	LocalCacheEnabled        *bool
	LocalCacheScope          LocalCacheScope
	CacheEnabled             *bool
	MapUnderscoreToCamelCase bool
	UseGeneratedKeys         bool
	LazyLoadingEnabled       bool
	DefaultExecutorType      ExecutorType
	DefaultStatementTimeout  time.Duration
	DefaultFetchSize         int
	MetaObjectHandler        MetaObjectHandler
}

Configuration 描述 MyBatis 风格的 ORM 运行期配置。

func DefaultConfiguration

func DefaultConfiguration() Configuration

DefaultConfiguration 返回独立 ORM 的默认运行期配置。

func (Configuration) WithGlobalConfig

func (c Configuration) WithGlobalConfig(global GlobalConfig) Configuration

WithGlobalConfig 返回设置 MyBatis-Plus 风格全局配置后的配置副本。

func (Configuration) WithLocalCache

func (c Configuration) WithLocalCache(enabled bool) Configuration

WithLocalCache 返回显式设置一级缓存开关后的配置副本。

func (Configuration) WithMapUnderscoreToCamelCase

func (c Configuration) WithMapUnderscoreToCamelCase(enabled bool) Configuration

WithMapUnderscoreToCamelCase 返回设置下划线转驼峰自动映射后的配置副本。

func (Configuration) WithSecondLevelCache

func (c Configuration) WithSecondLevelCache(enabled bool) Configuration

WithSecondLevelCache 返回显式设置二级缓存总开关后的配置副本。

type ConfigurationError

type ConfigurationError struct {
	Option  string
	Message string
	Err     error
}

ConfigurationError 携带配置项名称和底层原因。

func (*ConfigurationError) Error

func (e *ConfigurationError) Error() string

func (*ConfigurationError) Is

func (e *ConfigurationError) Is(target error) bool

func (*ConfigurationError) Unwrap

func (e *ConfigurationError) Unwrap() error

type Cursor

type Cursor[T any] struct {
	// contains filtered or unexported fields
}

Cursor 是类型安全的查询游标。

func QueryCursor

func QueryCursor[T any](ctx context.Context, session Session, statement string, args NamedArgs) (*Cursor[T], error)

QueryCursor 打开类型安全游标。游标查询不写入一级缓存和二级缓存。

func (*Cursor[T]) Close

func (c *Cursor[T]) Close() error

Close 关闭游标。

func (*Cursor[T]) Err

func (c *Cursor[T]) Err() error

Err 返回底层行集的迭代错误。

func (*Cursor[T]) Next

func (c *Cursor[T]) Next(ctx context.Context) (T, bool, error)

Next 扫描下一条记录;ok 为 false 表示游标已经耗尽。

type CursorQuerySession

type CursorQuerySession interface {
	QueryCursor(ctx context.Context, statement string, args NamedArgs) (*RowCursor, error)
}

CursorQuerySession 描述支持游标查询的 Session。

type DataPermissionProvider

type DataPermissionProvider func(ctx context.Context, statement StatementMeta) (SQLCondition, error)

DataPermissionProvider 根据当前语句生成数据权限条件。

type DataSourceKey

type DataSourceKey string

DataSourceKey 表示一个逻辑数据源名称。

const (
	// DefaultDataSourceKey 表示默认逻辑数据源。
	DefaultDataSourceKey DataSourceKey = "default"
)

func DataSourceFromContext

func DataSourceFromContext(ctx context.Context) (DataSourceKey, bool)

DataSourceFromContext 从 context 读取数据源声明。

type DataSourceResolver

type DataSourceResolver func(ctx context.Context, operation RoutingOperation) (DataSourceKey, error)

DataSourceResolver 根据 ORM 操作选择逻辑数据源。

func ReadWriteDataSourceResolver

func ReadWriteDataSourceResolver(read DataSourceKey, write DataSourceKey) DataSourceResolver

ReadWriteDataSourceResolver 按读写操作拆分数据源。

func StatementDataSourceResolver

func StatementDataSourceResolver(routes map[string]DataSourceKey, fallback DataSourceResolver) DataSourceResolver

StatementDataSourceResolver 按 Statement 全名优先路由,未命中时回退到 fallback。

func StaticDataSourceResolver

func StaticDataSourceResolver(key DataSourceKey) DataSourceResolver

StaticDataSourceResolver 始终返回固定数据源。

type Db

type Db struct {
	// contains filtered or unexported fields
}

Db 是 MyBatis-Plus Db Kit 的 Go 化门面,不持有全局会话。

func NewDb

func NewDb(session Session) (Db, error)

NewDb 创建显式绑定 Session 的快捷操作门面。

func (Db) Exec

func (db Db) Exec(ctx context.Context, statement string, args NamedArgs) (Result, error)

Exec 执行写语句。

func (Db) GetOne

func (db Db) GetOne(ctx context.Context, statement string, args NamedArgs, dest any) error

GetOne 查询单行记录。

func (Db) List

func (db Db) List(ctx context.Context, statement string, args NamedArgs, dest any) error

List 查询多行记录。

type DbConfig

type DbConfig struct {
	IDType              IDType
	TablePrefix         string
	Schema              string
	LogicDeleteField    string
	LogicDeleteValue    any
	LogicNotDeleteValue any
	InsertStrategy      FieldStrategy
	UpdateStrategy      FieldStrategy
	WhereStrategy       FieldStrategy
}

DbConfig 描述数据库命名、主键和逻辑删除默认策略。

func DefaultDbConfig

func DefaultDbConfig() DbConfig

DefaultDbConfig 返回数据库层默认配置。

type DbType

type DbType string

DbType 对齐 MyBatis-Plus 的数据库类型枚举,并保持 Go 字符串常量形式。

const (
	DbTypeQuestion  DbType = "question"
	DbTypePostgres  DbType = "postgres"
	DbTypeMySQL     DbType = "mysql"
	DbTypeMariaDB   DbType = "mariadb"
	DbTypeSQLite    DbType = "sqlite"
	DbTypeSQLServer DbType = "sqlserver"
	DbTypeOracle    DbType = "oracle"
)

func ParseDbType

func ParseDbType(value string) (DbType, error)

ParseDbType 解析常见数据库类型别名。

type DefaultIdentifierGenerator

type DefaultIdentifierGenerator struct {
	// contains filtered or unexported fields
}

DefaultIdentifierGenerator 是无外部依赖的默认主键生成器。

func NewDefaultIdentifierGenerator

func NewDefaultIdentifierGenerator() *DefaultIdentifierGenerator

NewDefaultIdentifierGenerator 创建默认主键生成器。

func (*DefaultIdentifierGenerator) NextID

func (g *DefaultIdentifierGenerator) NextID(ctx context.Context, entity EntityMeta, column ColumnMeta) (any, error)

NextID 生成 Snowflake 风格 64 位整数主键。

func (*DefaultIdentifierGenerator) NextUUID

func (g *DefaultIdentifierGenerator) NextUUID(ctx context.Context, entity EntityMeta, column ColumnMeta) (string, error)

NextUUID 生成 RFC 4122 Version 4 UUID。

type Dialect

type Dialect interface {
	Name() string
	Placeholder(index int) string
	QuoteIdent(identifier string) string
}

Dialect 封装数据库方言差异。

func NewDialect

func NewDialect(dbType DbType) (Dialect, error)

NewDialect 根据数据库类型创建方言实例。

func NewMariaDBDialect

func NewMariaDBDialect() Dialect

NewMariaDBDialect 创建 MariaDB 方言。

func NewMySQLDialect

func NewMySQLDialect() Dialect

NewMySQLDialect 创建 MySQL 方言。

func NewOracleDialect

func NewOracleDialect() Dialect

NewOracleDialect 创建 Oracle 方言。

func NewPostgresDialect

func NewPostgresDialect() Dialect

NewPostgresDialect 创建 PostgreSQL 方言。

func NewQuestionDialect

func NewQuestionDialect() Dialect

NewQuestionDialect 创建使用问号占位符的通用方言。

func NewSQLServerDialect

func NewSQLServerDialect() Dialect

NewSQLServerDialect 创建 SQL Server 方言。

func NewSQLiteDialect

func NewSQLiteDialect() Dialect

NewSQLiteDialect 创建 SQLite 方言。

type DialectCapabilities

type DialectCapabilities struct {
	DBType                     DbType
	Placeholder                DialectPlaceholderStyle
	IdentifierQuote            DialectIdentifierQuoteStyle
	LimitOffset                bool
	LimitOffsetRequiresOrderBy bool
	GeneratedKey               DialectGeneratedKeyStyle
	Upsert                     DialectUpsertStyle
	RowLock                    DialectRowLockStyle
	JSON                       DialectJSONStyle
	BatchInsert                bool
	Savepoint                  bool
	SkipLocked                 bool
	NoWait                     bool
}

DialectCapabilities 描述数据库方言的可用能力,不绑定具体 driver。

func DialectCapabilitiesOf

func DialectCapabilitiesOf(dialect Dialect) DialectCapabilities

DialectCapabilitiesOf 返回方言能力;未知自定义方言只保留名称。

func NewDialectCapabilities

func NewDialectCapabilities(dbType DbType) (DialectCapabilities, error)

NewDialectCapabilities 根据数据库类型返回内置方言能力。

func (DialectCapabilities) SupportsGeneratedKey

func (c DialectCapabilities) SupportsGeneratedKey() bool

SupportsGeneratedKey 返回方言是否声明了主键回读能力。

func (DialectCapabilities) SupportsJSON

func (c DialectCapabilities) SupportsJSON() bool

SupportsJSON 返回方言是否声明了 JSON 能力。

func (DialectCapabilities) SupportsRowLock

func (c DialectCapabilities) SupportsRowLock() bool

SupportsRowLock 返回方言是否声明了行锁能力。

func (DialectCapabilities) SupportsUpsert

func (c DialectCapabilities) SupportsUpsert() bool

SupportsUpsert 返回方言是否声明了原生 UPSERT 能力。

type DialectCapabilitiesProvider

type DialectCapabilitiesProvider interface {
	DialectCapabilities() DialectCapabilities
}

DialectCapabilitiesProvider 由支持能力查询的方言可选实现。

type DialectGeneratedKeyStyle

type DialectGeneratedKeyStyle string

DialectGeneratedKeyStyle 描述主键回读能力。

const (
	// DialectGeneratedKeyNone 表示方言没有声明统一主键回读能力。
	DialectGeneratedKeyNone DialectGeneratedKeyStyle = ""
	// DialectGeneratedKeyLastInsertID 表示依赖 database/sql Result.LastInsertId。
	DialectGeneratedKeyLastInsertID DialectGeneratedKeyStyle = "last_insert_id"
	// DialectGeneratedKeyReturning 表示支持 INSERT ... RETURNING。
	DialectGeneratedKeyReturning DialectGeneratedKeyStyle = "returning"
	// DialectGeneratedKeyOutput 表示 SQL Server OUTPUT inserted.<column>。
	DialectGeneratedKeyOutput DialectGeneratedKeyStyle = "output"
	// DialectGeneratedKeyReturningInto 表示 Oracle RETURNING ... INTO。
	DialectGeneratedKeyReturningInto DialectGeneratedKeyStyle = "returning_into"
)

type DialectIdentifierQuoteStyle

type DialectIdentifierQuoteStyle string

DialectIdentifierQuoteStyle 描述标识符引用风格。

const (
	// DialectIdentifierQuoteBacktick 表示反引号标识符。
	DialectIdentifierQuoteBacktick DialectIdentifierQuoteStyle = "backtick"
	// DialectIdentifierQuoteDouble 表示双引号标识符。
	DialectIdentifierQuoteDouble DialectIdentifierQuoteStyle = "double_quote"
	// DialectIdentifierQuoteBracket 表示 SQL Server 方括号标识符。
	DialectIdentifierQuoteBracket DialectIdentifierQuoteStyle = "bracket"
)

type DialectJSONStyle

type DialectJSONStyle string

DialectJSONStyle 描述 JSON 列支持级别。

const (
	// DialectJSONNone 表示方言没有声明 JSON 能力。
	DialectJSONNone DialectJSONStyle = ""
	// DialectJSONNative 表示数据库内建 JSON 类型或函数。
	DialectJSONNative DialectJSONStyle = "native"
	// DialectJSONExtension 表示 JSON 能力依赖数据库扩展或构建选项。
	DialectJSONExtension DialectJSONStyle = "extension"
)

type DialectPlaceholderStyle

type DialectPlaceholderStyle string

DialectPlaceholderStyle 描述方言占位符风格。

const (
	// DialectPlaceholderQuestion 表示 `?` 占位符。
	DialectPlaceholderQuestion DialectPlaceholderStyle = "question"
	// DialectPlaceholderDollarNumber 表示 PostgreSQL `$1` 风格占位符。
	DialectPlaceholderDollarNumber DialectPlaceholderStyle = "dollar_number"
	// DialectPlaceholderAtPNumber 表示 SQL Server `@p1` 风格占位符。
	DialectPlaceholderAtPNumber DialectPlaceholderStyle = "at_p_number"
	// DialectPlaceholderColonNumber 表示 Oracle `:1` 风格占位符。
	DialectPlaceholderColonNumber DialectPlaceholderStyle = "colon_number"
)

type DialectRowLockStyle

type DialectRowLockStyle string

DialectRowLockStyle 描述行锁语义。

const (
	// DialectRowLockNone 表示方言没有声明统一行锁语义。
	DialectRowLockNone DialectRowLockStyle = ""
	// DialectRowLockForUpdate 表示 SELECT ... FOR UPDATE。
	DialectRowLockForUpdate DialectRowLockStyle = "for_update"
	// DialectRowLockHints 表示 SQL Server WITH (...) 锁提示。
	DialectRowLockHints DialectRowLockStyle = "lock_hints"
)

type DialectUpsertStyle

type DialectUpsertStyle string

DialectUpsertStyle 描述方言原生 UPSERT 语义。

const (
	// DialectUpsertNone 表示方言没有声明统一 UPSERT 语义。
	DialectUpsertNone DialectUpsertStyle = ""
	// DialectUpsertOnConflict 表示 ON CONFLICT 语义。
	DialectUpsertOnConflict DialectUpsertStyle = "on_conflict"
	// DialectUpsertOnDuplicateKey 表示 ON DUPLICATE KEY UPDATE 语义。
	DialectUpsertOnDuplicateKey DialectUpsertStyle = "on_duplicate_key"
	// DialectUpsertMerge 表示 MERGE 语义。
	DialectUpsertMerge DialectUpsertStyle = "merge"
)

type DynamicSQLNode

type DynamicSQLNode struct {
	Kind            DynamicSQLNodeKind
	Text            string
	Test            string
	Prefix          string
	Suffix          string
	PrefixOverrides string
	SuffixOverrides string
	Collection      string
	Item            string
	Index           string
	Name            string
	Value           string
	Open            string
	Close           string
	Separator       string
	RefID           string
	Children        []DynamicSQLNode
}

DynamicSQLNode 描述 XML 动态 SQL 的静态节点树。

type DynamicSQLNodeKind

type DynamicSQLNodeKind string

DynamicSQLNodeKind 表示动态 SQL 节点类型。

const (
	// DynamicSQLNodeText 表示普通 SQL 文本。
	DynamicSQLNodeText DynamicSQLNodeKind = "text"
	// DynamicSQLNodeIf 表示条件 SQL 节点。
	DynamicSQLNodeIf DynamicSQLNodeKind = "if"
	// DynamicSQLNodeWhere 表示 WHERE 包装节点。
	DynamicSQLNodeWhere DynamicSQLNodeKind = "where"
	// DynamicSQLNodeSet 表示 SET 包装节点。
	DynamicSQLNodeSet DynamicSQLNodeKind = "set"
	// DynamicSQLNodeTrim 表示通用前后缀修剪节点。
	DynamicSQLNodeTrim DynamicSQLNodeKind = "trim"
	// DynamicSQLNodeForeach 表示集合展开节点。
	DynamicSQLNodeForeach DynamicSQLNodeKind = "foreach"
	// DynamicSQLNodeChoose 表示分支选择节点。
	DynamicSQLNodeChoose DynamicSQLNodeKind = "choose"
	// DynamicSQLNodeWhen 表示 choose 的条件分支。
	DynamicSQLNodeWhen DynamicSQLNodeKind = "when"
	// DynamicSQLNodeOtherwise 表示 choose 的默认分支。
	DynamicSQLNodeOtherwise DynamicSQLNodeKind = "otherwise"
	// DynamicSQLNodeInclude 表示 XML sql 片段引用,生成期应展开。
	DynamicSQLNodeInclude DynamicSQLNodeKind = "include"
	// DynamicSQLNodeBind 表示 XML bind 变量绑定节点。
	DynamicSQLNodeBind DynamicSQLNodeKind = "bind"
)

type EntityMeta

type EntityMeta struct {
	TypeName string
	Table    string
	Columns  []ColumnMeta
}

EntityMeta 描述一个实体类型的 ORM 映射。

type EntitySemanticInterceptorOption

type EntitySemanticInterceptorOption func(*entitySemanticInterceptor)

EntitySemanticInterceptorOption 配置实体语义拦截器。

func WithEntitySemanticClock

func WithEntitySemanticClock(clock func() time.Time) EntitySemanticInterceptorOption

WithEntitySemanticClock 配置自动填充时间使用的时钟。

type EnumValuer

type EnumValuer interface {
	EnumValue() any
}

EnumValuer 对齐 MyBatis-Plus IEnum/@EnumValue 的 Go 化枚举值接口。

type EnumValuerContext

type EnumValuerContext interface {
	EnumValueContext(ctx context.Context) (any, error)
}

EnumValuerContext 支持需要上下文的枚举值转换。

type ExecutorError

type ExecutorError struct {
	Statement string
	Operation string
	SQL       string
	Message   string
	Err       error
}

ExecutorError 携带数据库执行阶段的操作、SQL 和底层原因。

func (*ExecutorError) Error

func (e *ExecutorError) Error() string

func (*ExecutorError) Is

func (e *ExecutorError) Is(target error) bool

func (*ExecutorError) Unwrap

func (e *ExecutorError) Unwrap() error

type ExecutorType

type ExecutorType string

ExecutorType 描述默认执行器类型。

const (
	// ExecutorTypeSimple 表示普通即时执行器。
	ExecutorTypeSimple ExecutorType = "SIMPLE"
	// ExecutorTypeReuse 表示可复用预编译语句执行器。
	ExecutorTypeReuse ExecutorType = "REUSE"
	// ExecutorTypeBatch 表示批量执行器。
	ExecutorTypeBatch ExecutorType = "BATCH"
)

func ParseExecutorType

func ParseExecutorType(value string) (ExecutorType, error)

ParseExecutorType 解析 MyBatis defaultExecutorType 配置值。

type Field

type Field[T any] struct {
	Column string
}

Field 描述实体字段对应的数据库列。

func NewField

func NewField[T any](column string) Field[T]

NewField 创建实体字段描述。通常由生成器生成字段常量,业务代码不需要手写列名。

type FieldFill

type FieldFill string

FieldFill 描述 MyBatis-Plus 风格字段自动填充时机。

const (
	// FieldFillDefault 表示字段不参与严格自动填充。
	FieldFillDefault FieldFill = ""
	// FieldFillInsert 表示字段仅在 INSERT 时参与自动填充。
	FieldFillInsert FieldFill = "INSERT"
	// FieldFillUpdate 表示字段仅在 UPDATE 时参与自动填充。
	FieldFillUpdate FieldFill = "UPDATE"
	// FieldFillInsertUpdate 表示字段在 INSERT 和 UPDATE 时都参与自动填充。
	FieldFillInsertUpdate FieldFill = "INSERT_UPDATE"
)

func ParseFieldFill

func ParseFieldFill(value string) (FieldFill, error)

ParseFieldFill 解析字段填充策略,兼容大小写、短横线和下划线。

type FieldStrategy

type FieldStrategy string

FieldStrategy 描述字段参与 INSERT、UPDATE、WHERE 片段的策略。

const (
	// FieldStrategyDefault 表示沿用调用方或全局默认策略。
	FieldStrategyDefault FieldStrategy = ""
	// FieldStrategyAlways 表示字段始终参与 SQL。
	FieldStrategyAlways FieldStrategy = "ALWAYS"
	// FieldStrategyNotNull 表示字段值非 nil 时参与 SQL。
	FieldStrategyNotNull FieldStrategy = "NOT_NULL"
	// FieldStrategyNotEmpty 表示字段值非 nil 且非空字符串、切片、数组或 map 时参与 SQL。
	FieldStrategyNotEmpty FieldStrategy = "NOT_EMPTY"
	// FieldStrategyNotZero 表示字段值非 nil 且非 Go 零值时参与 SQL。
	FieldStrategyNotZero FieldStrategy = "NOT_ZERO"
	// FieldStrategyNever 表示字段永不参与对应 SQL。
	FieldStrategyNever FieldStrategy = "NEVER"
)

func ParseFieldStrategy

func ParseFieldStrategy(value string) (FieldStrategy, error)

ParseFieldStrategy 解析 MyBatis-Plus 风格字段策略。

type GlobalConfig

type GlobalConfig struct {
	DbConfig            DbConfig
	IdentifierGenerator IdentifierGenerator
	MetaObjectHandler   MetaObjectHandler
}

GlobalConfig 描述 MyBatis-Plus 风格全局配置。

func DefaultGlobalConfig

func DefaultGlobalConfig() GlobalConfig

DefaultGlobalConfig 返回独立 ORM 的全局默认配置。

type IDType

type IDType string

IDType 表示 MyBatis-Plus 风格主键生成策略。

const (
	// IDTypeNone 表示未指定主键策略。
	IDTypeNone IDType = ""
	// IDTypeAuto 表示数据库自增或数据库端生成主键。
	IDTypeAuto IDType = "AUTO"
	// IDTypeInput 表示调用方显式传入主键。
	IDTypeInput IDType = "INPUT"
	// IDTypeAssignID 表示 ORM 在插入前分配整数主键。
	IDTypeAssignID IDType = "ASSIGN_ID"
	// IDTypeAssignUUID 表示 ORM 在插入前分配 UUID 字符串主键。
	IDTypeAssignUUID IDType = "ASSIGN_UUID"
)

func ParseIDType

func ParseIDType(value string) (IDType, error)

ParseIDType 解析主键策略,兼容下划线和短横线写法。

type IdentifierGenerator

type IdentifierGenerator interface {
	NextID(ctx context.Context, entity EntityMeta, column ColumnMeta) (any, error)
	NextUUID(ctx context.Context, entity EntityMeta, column ColumnMeta) (string, error)
}

IdentifierGenerator 为 ASSIGN_ID 和 ASSIGN_UUID 提供插入前主键。

type IllegalSQLOption

type IllegalSQLOption func(*illegalSQLConfig)

IllegalSQLOption 配置非法 SQL 治理拦截器。

func WithIllegalSQLDenyMultipleStatements

func WithIllegalSQLDenyMultipleStatements(enabled bool) IllegalSQLOption

WithIllegalSQLDenyMultipleStatements 配置是否拒绝多语句 SQL 模板。

func WithIllegalSQLDenySelectWildcard

func WithIllegalSQLDenySelectWildcard(enabled bool) IllegalSQLOption

WithIllegalSQLDenySelectWildcard 配置是否拒绝顶层 SELECT *。

func WithIllegalSQLDenyWriteWithoutWhere

func WithIllegalSQLDenyWriteWithoutWhere(enabled bool) IllegalSQLOption

WithIllegalSQLDenyWriteWithoutWhere 配置是否拒绝无 WHERE 的 UPDATE/DELETE。

type InjectOption

type InjectOption func(*injectOptions)

InjectOption 配置 SQL 注入行为。

func WithInjectDialect

func WithInjectDialect(dialect Dialect) InjectOption

WithInjectDialect 指定注入器使用的数据库方言。

func WithInjectGlobalConfig

func WithInjectGlobalConfig(global GlobalConfig) InjectOption

WithInjectGlobalConfig 指定注入器使用的全局配置。

type Lazy

type Lazy[T any] struct {
	// contains filtered or unexported fields
}

Lazy 表示显式延迟加载的单值关联。

func NewLazy

func NewLazy[T any](loader func(context.Context) (T, error)) Lazy[T]

NewLazy 创建单值延迟加载器。

func (*Lazy[T]) Load

func (l *Lazy[T]) Load(ctx context.Context) (T, error)

Load 返回延迟加载值;首次成功后会缓存结果。

func (*Lazy[T]) Loaded

func (l *Lazy[T]) Loaded() bool

Loaded 返回是否已经成功加载。

func (*Lazy[T]) Reset

func (l *Lazy[T]) Reset(loader func(context.Context) (T, error))

Reset 替换延迟加载器并清空已加载值。

func (*Lazy[T]) Value

func (l *Lazy[T]) Value() (value T, ok bool)

Value 返回已加载值;未加载时 ok 为 false。

type LazySlice

type LazySlice[T any] struct {
	// contains filtered or unexported fields
}

LazySlice 表示显式延迟加载的集合关联。

func NewLazySlice

func NewLazySlice[T any](loader func(context.Context) ([]T, error)) LazySlice[T]

NewLazySlice 创建集合延迟加载器。

func (*LazySlice[T]) Load

func (l *LazySlice[T]) Load(ctx context.Context) ([]T, error)

Load 返回延迟加载集合;首次成功后会缓存结果。

func (*LazySlice[T]) Loaded

func (l *LazySlice[T]) Loaded() bool

Loaded 返回集合是否已经成功加载。

func (*LazySlice[T]) Reset

func (l *LazySlice[T]) Reset(loader func(context.Context) ([]T, error))

Reset 替换集合延迟加载器并清空已加载值。

func (*LazySlice[T]) Value

func (l *LazySlice[T]) Value() (value []T, ok bool)

Value 返回已加载集合;未加载时 ok 为 false。

type LocalCacheScope

type LocalCacheScope string

LocalCacheScope 描述一级缓存作用域。

const (
	// LocalCacheScopeSession 表示一级缓存跨同一 Session 的多次语句复用。
	LocalCacheScopeSession LocalCacheScope = "SESSION"
	// LocalCacheScopeStatement 表示一级缓存只服务单次语句执行。
	LocalCacheScopeStatement LocalCacheScope = "STATEMENT"
)

func ParseLocalCacheScope

func ParseLocalCacheScope(value string) (LocalCacheScope, error)

ParseLocalCacheScope 解析 MyBatis localCacheScope 配置值。

type LogicDeleteByIDInjector

type LogicDeleteByIDInjector struct{}

LogicDeleteByIDInjector 生成按主键逻辑删除语句。

func (LogicDeleteByIDInjector) Inspect

func (LogicDeleteByIDInjector) Inspect(entity EntityMeta, dialect Dialect, global GlobalConfig) ([]StatementMeta, error)

Inspect 生成 LogicDeleteByID Statement。

type ManagedSession

type ManagedSession interface {
	Session
	Commit() error
	Rollback() error
	Close() error
}

ManagedSession 描述具备 MyBatis 风格生命周期的 Session。

type MapperMeta

type MapperMeta struct {
	TypeName     string
	Namespace    string
	XML          string
	Cache        CacheMeta
	ResultMaps   []ResultMapMeta
	Statements   []StatementMeta
	ImplTypeName string
}

MapperMeta 描述一个 Mapper 接口及其语句集合。

type MapperRef

type MapperRef struct {
	Resource  string
	Namespace string
}

MapperRef 描述 Mapper 声明引用。Resource 供生成器使用,Namespace 供运行期校验。

type MappingError

type MappingError struct {
	Statement string
	ResultMap string
	Column    string
	Field     string
	Message   string
	Err       error
}

MappingError 携带结果映射阶段的 Statement、列名、字段名和 resultMap 信息。

func (*MappingError) Error

func (e *MappingError) Error() string

func (*MappingError) Is

func (e *MappingError) Is(target error) bool

func (*MappingError) Unwrap

func (e *MappingError) Unwrap() error

type MemoryCache

type MemoryCache struct {
	// contains filtered or unexported fields
}

MemoryCache 是并发安全的有界 LRU 二级缓存。

func NewMemoryCache

func NewMemoryCache(id string, options ...MemoryCacheOption) *MemoryCache

NewMemoryCache 创建默认内存二级缓存。

func (*MemoryCache) Clear

func (c *MemoryCache) Clear(ctx context.Context) error

Clear 清空全部缓存条目。

func (*MemoryCache) Get

func (c *MemoryCache) Get(ctx context.Context, key string) (any, bool, error)

Get 读取缓存条目。

func (*MemoryCache) Put

func (c *MemoryCache) Put(ctx context.Context, key string, value any) error

Put 写入缓存条目。

func (*MemoryCache) Remove

func (c *MemoryCache) Remove(ctx context.Context, key string) error

Remove 删除单个缓存条目。

func (*MemoryCache) Stats

func (c *MemoryCache) Stats() CacheStats

Stats 返回默认内存缓存的运行期统计快照。

type MemoryCacheOption

type MemoryCacheOption func(*MemoryCache)

MemoryCacheOption 配置默认内存二级缓存。

func WithMemoryCacheMaxEntries

func WithMemoryCacheMaxEntries(maxEntries int) MemoryCacheOption

WithMemoryCacheMaxEntries 设置最大缓存条数,0 表示不缓存任何条目。

func WithMemoryCacheTTL

func WithMemoryCacheTTL(ttl time.Duration) MemoryCacheOption

WithMemoryCacheTTL 设置缓存条目的存活时间。

type MetaObject

type MetaObject struct {
	// contains filtered or unexported fields
}

MetaObject 暴露实体字段和 SQL 命名参数的统一填充视图。

func NewMetaObject

func NewMetaObject(entity EntityMeta, target any) (*MetaObject, error)

NewMetaObject 基于实体指针创建可直接填充的元对象。

func (*MetaObject) Args

func (m *MetaObject) Args() NamedArgs

Args 返回当前命名参数快照。

func (*MetaObject) Entity

func (m *MetaObject) Entity() EntityMeta

Entity 返回当前填充目标的实体元数据快照。

func (*MetaObject) FieldValue

func (m *MetaObject) FieldValue(name string) (any, bool, error)

FieldValue 读取字段当前值,优先读取实体指针,其次读取命名参数。

func (*MetaObject) HasField

func (m *MetaObject) HasField(name string) bool

HasField 判断实体元数据中是否存在指定字段或列。

func (*MetaObject) SetField

func (m *MetaObject) SetField(name string, value any) error

SetField 覆盖写入指定字段,并同步命名参数中的字段名和 lower-camel 别名。

func (*MetaObject) SetFieldIfZero

func (m *MetaObject) SetFieldIfZero(name string, value any) error

SetFieldIfZero 仅在当前字段为零值时写入指定字段。

func (*MetaObject) StrictInsertFill

func (m *MetaObject) StrictInsertFill(name string, value any) error

StrictInsertFill 在字段允许 INSERT 填充且当前为零值时写入。

func (*MetaObject) StrictUpdateFill

func (m *MetaObject) StrictUpdateFill(name string, value any) error

StrictUpdateFill 在字段允许 UPDATE 填充时覆盖写入。

type MetaObjectHandler

type MetaObjectHandler interface {
	InsertFill(ctx context.Context, meta *MetaObject) error
	UpdateFill(ctx context.Context, meta *MetaObject) error
}

MetaObjectHandler 按 INSERT/UPDATE 时机填充实体字段或命名参数。

type MetaObjectHandlerFuncs

type MetaObjectHandlerFuncs struct {
	Insert func(ctx context.Context, meta *MetaObject) error
	Update func(ctx context.Context, meta *MetaObject) error
}

MetaObjectHandlerFuncs 使用函数组合构造 MetaObjectHandler。

func (MetaObjectHandlerFuncs) InsertFill

func (h MetaObjectHandlerFuncs) InsertFill(ctx context.Context, meta *MetaObject) error

InsertFill 执行 INSERT 填充函数。

func (MetaObjectHandlerFuncs) UpdateFill

func (h MetaObjectHandlerFuncs) UpdateFill(ctx context.Context, meta *MetaObject) error

UpdateFill 执行 UPDATE 填充函数。

type MyBatisConfig

type MyBatisConfig struct {
	Settings    MyBatisSettings
	Environment MyBatisEnvironment
	TypeAliases []TypeAlias
	Mappers     []MapperRef
	Global      GlobalConfig
}

MyBatisConfig 是 MyBatis 配置文件的 Go 化声明模型。

func DefaultMyBatisConfig

func DefaultMyBatisConfig() MyBatisConfig

DefaultMyBatisConfig 返回可直接构建运行期配置的默认声明模型。

func (MyBatisConfig) BuildConfiguration

func (c MyBatisConfig) BuildConfiguration() (Configuration, error)

BuildConfiguration 将声明模型转换为运行期 Configuration。

func (MyBatisConfig) TypeAliasMap

func (c MyBatisConfig) TypeAliasMap() (map[string]string, error)

TypeAliasMap 返回规范化后的别名映射,并拒绝重复别名。

func (MyBatisConfig) Validate

func (c MyBatisConfig) Validate() error

Validate 校验声明模型中的稳定契约,不触发任何文件系统扫描。

type MyBatisEnvironment

type MyBatisEnvironment struct {
	ID         string
	DbType     DbType
	Dialect    Dialect
	DatabaseID string
}

MyBatisEnvironment 描述数据库环境配置。Dialect 显式指定时优先于 DbType。

type MyBatisSettings

type MyBatisSettings struct {
	CacheEnabled             *bool
	LocalCacheEnabled        *bool
	LocalCacheScope          LocalCacheScope
	MapUnderscoreToCamelCase bool
	UseGeneratedKeys         bool
	LazyLoadingEnabled       bool
	DefaultExecutorType      ExecutorType
	DefaultStatementTimeout  time.Duration
	DefaultFetchSize         int
	DatabaseID               string
}

MyBatisSettings 描述 MyBatis settings 的 Go 化配置子集。

type NamedArgs

type NamedArgs map[string]any

NamedArgs 保存已经按名称绑定的 SQL 参数。

type Page

type Page[T any] struct {
	Records []T
	Total   int64
	Size    int64
	Current int64
	Pages   int64
}

Page 描述分页查询结果。

func QueryPage

func QueryPage[T any](ctx context.Context, session Session, statement string, args NamedArgs, page PageRequest) (Page[T], error)

QueryPage 执行生成 Mapper 使用的分页查询。

type PageQueryResult

type PageQueryResult struct {
	Total   int64
	Size    int64
	Current int64
	Pages   int64
}

PageQueryResult 描述分页查询除记录外的统计信息。

type PageQuerySession

type PageQuerySession interface {
	QueryPage(ctx context.Context, statement string, args NamedArgs, page PageRequest, dest any) (PageQueryResult, error)
}

PageQuerySession 描述支持直接分页查询的 Session。

type PageRequest

type PageRequest struct {
	Current     int64
	Size        int64
	SearchCount bool
	MaxLimit    int64
}

PageRequest 描述分页查询输入。

func NewPageRequest

func NewPageRequest(current int64, size int64) PageRequest

NewPageRequest 创建分页请求,页码从 1 开始。

func PageRequestFromContext

func PageRequestFromContext(ctx context.Context) (PageRequest, bool)

PageRequestFromContext 从 context 读取分页请求。

type ParameterHandler

type ParameterHandler interface {
	Bind(ctx context.Context, statement StatementMeta, args NamedArgs) (NamedArgs, error)
}

ParameterHandler 负责根据参数类型和 TypeHandler 绑定数据库参数。

type ParameterHandlerMiddleware

type ParameterHandlerMiddleware interface {
	WrapParameterHandler(next ParameterHandler) ParameterHandler
}

ParameterHandlerMiddleware 包装参数处理器,用于扩展实体参数绑定和 TypeHandler 入库转换层。

type ParameterHandlerMiddlewareFunc

type ParameterHandlerMiddlewareFunc func(next ParameterHandler) ParameterHandler

ParameterHandlerMiddlewareFunc 将函数适配为 ParameterHandlerMiddleware。

func (ParameterHandlerMiddlewareFunc) WrapParameterHandler

WrapParameterHandler 执行函数式参数处理器包装。

type ParameterMeta

type ParameterMeta struct {
	Name        string
	Mode        ParameterMode
	JDBCType    string
	TypeHandler string
}

ParameterMeta 描述可调用语句中的单个参数。

type ParameterMode

type ParameterMode string

ParameterMode 表示可调用语句参数方向。

const (
	// ParameterModeIn 表示普通输入参数。
	ParameterModeIn ParameterMode = "IN"
	// ParameterModeOut 表示仅输出参数。
	ParameterModeOut ParameterMode = "OUT"
	// ParameterModeInOut 表示既输入又输出的参数。
	ParameterModeInOut ParameterMode = "INOUT"
)

func NormalizeParameterMode

func NormalizeParameterMode(mode ParameterMode) ParameterMode

NormalizeParameterMode 返回参数方向的安全默认值。

func ParseParameterMode

func ParseParameterMode(value string) (ParameterMode, error)

ParseParameterMode 解析可调用语句参数方向。

type QueryChain

type QueryChain[T any, ID any] struct {
	// contains filtered or unexported fields
}

QueryChain 提供 MyBatis-Plus QueryChainWrapper 风格的查询链。

func (*QueryChain[T, ID]) Count

func (c *QueryChain[T, ID]) Count(ctx context.Context) (int64, error)

Count 执行链式计数查询。

func (*QueryChain[T, ID]) Eq

func (c *QueryChain[T, ID]) Eq(field Field[T], value any) *QueryChain[T, ID]

Eq 添加等值条件。

func (*QueryChain[T, ID]) First

func (c *QueryChain[T, ID]) First(ctx context.Context) (*T, error)

First 执行链式单条查询,多行时返回第一行。

func (*QueryChain[T, ID]) Like

func (c *QueryChain[T, ID]) Like(field Field[T], value any) *QueryChain[T, ID]

Like 添加 LIKE 条件。

func (*QueryChain[T, ID]) List

func (c *QueryChain[T, ID]) List(ctx context.Context) ([]T, error)

List 执行链式列表查询。

func (*QueryChain[T, ID]) Map

func (c *QueryChain[T, ID]) Map(ctx context.Context) (map[string]any, error)

Map 执行链式单条 map 查询。

func (*QueryChain[T, ID]) Maps

func (c *QueryChain[T, ID]) Maps(ctx context.Context) ([]map[string]any, error)

Maps 执行链式 map 列表查询。

func (*QueryChain[T, ID]) Obj

func (c *QueryChain[T, ID]) Obj(ctx context.Context) (any, error)

Obj 执行链式首列单值查询。

func (*QueryChain[T, ID]) Objs

func (c *QueryChain[T, ID]) Objs(ctx context.Context) ([]any, error)

Objs 执行链式首列列表查询。

func (*QueryChain[T, ID]) One

func (c *QueryChain[T, ID]) One(ctx context.Context) (*T, error)

One 执行链式单条查询。

func (*QueryChain[T, ID]) OrderByAsc

func (c *QueryChain[T, ID]) OrderByAsc(field Field[T]) *QueryChain[T, ID]

OrderByAsc 添加升序排序。

func (*QueryChain[T, ID]) OrderByDesc

func (c *QueryChain[T, ID]) OrderByDesc(field Field[T]) *QueryChain[T, ID]

OrderByDesc 添加降序排序。

func (*QueryChain[T, ID]) Page

func (c *QueryChain[T, ID]) Page(ctx context.Context, page PageRequest) (Page[T], error)

Page 执行链式分页查询。

func (*QueryChain[T, ID]) Where

func (c *QueryChain[T, ID]) Where(apply func(*QueryWrapper[T])) *QueryChain[T, ID]

Where 使用底层 QueryWrapper 添加复杂条件。

func (*QueryChain[T, ID]) Wrapper

func (c *QueryChain[T, ID]) Wrapper() *QueryWrapper[T]

Wrapper 返回底层查询 Wrapper。

type QueryWrapper

type QueryWrapper[T any] struct {
	// contains filtered or unexported fields
}

QueryWrapper 是 MyBatis-Plus Wrapper 的 Go 化条件构造器。

func NewQueryWrapper

func NewQueryWrapper[T any]() *QueryWrapper[T]

NewQueryWrapper 创建空查询条件构造器。

func (*QueryWrapper[T]) AllEq

func (w *QueryWrapper[T]) AllEq(values map[Field[T]]any) *QueryWrapper[T]

AllEq 按 map 批量添加等值条件。

func (*QueryWrapper[T]) And

func (w *QueryWrapper[T]) And(apply func(*QueryWrapper[T])) *QueryWrapper[T]

And 添加 AND 连接的嵌套条件组。

func (*QueryWrapper[T]) Apply

func (w *QueryWrapper[T]) Apply(sqlText string, args NamedArgs) *QueryWrapper[T]

Apply 添加自定义条件片段,SQL 仅允许 #{name} 参数占位符。

func (*QueryWrapper[T]) Between

func (w *QueryWrapper[T]) Between(field Field[T], left any, right any) *QueryWrapper[T]

Between 添加 BETWEEN 条件。

func (*QueryWrapper[T]) BetweenTyped

func (w *QueryWrapper[T]) BetweenTyped(field TypedFieldRef[T], left any, right any) *QueryWrapper[T]

BetweenTyped 添加类型化字段引用的 BETWEEN 条件。

func (*QueryWrapper[T]) Empty

func (w *QueryWrapper[T]) Empty() bool

Empty 返回是否没有任何过滤条件。

func (*QueryWrapper[T]) Eq

func (w *QueryWrapper[T]) Eq(field Field[T], value any) *QueryWrapper[T]

Eq 添加等值条件。

func (*QueryWrapper[T]) EqIf

func (w *QueryWrapper[T]) EqIf(condition bool, field Field[T], value any) *QueryWrapper[T]

EqIf 在 condition 为 true 时添加等值条件。

func (*QueryWrapper[T]) EqTyped

func (w *QueryWrapper[T]) EqTyped(field TypedFieldRef[T], value any) *QueryWrapper[T]

EqTyped 添加类型化字段引用的等值条件。

func (*QueryWrapper[T]) Exists

func (w *QueryWrapper[T]) Exists(sqlText string, args NamedArgs) *QueryWrapper[T]

Exists 添加 EXISTS 子查询条件,SQL 仅允许 #{name} 参数占位符。

func (*QueryWrapper[T]) Ge

func (w *QueryWrapper[T]) Ge(field Field[T], value any) *QueryWrapper[T]

Ge 添加大于等于条件。

func (*QueryWrapper[T]) GeTyped

func (w *QueryWrapper[T]) GeTyped(field TypedFieldRef[T], value any) *QueryWrapper[T]

GeTyped 添加类型化字段引用的大于等于条件。

func (*QueryWrapper[T]) GroupBy

func (w *QueryWrapper[T]) GroupBy(fields ...Field[T]) *QueryWrapper[T]

GroupBy 添加 GROUP BY 字段。

func (*QueryWrapper[T]) GroupByTyped

func (w *QueryWrapper[T]) GroupByTyped(fields ...TypedFieldRef[T]) *QueryWrapper[T]

GroupByTyped 添加类型化字段引用的 GROUP BY 字段。

func (*QueryWrapper[T]) Gt

func (w *QueryWrapper[T]) Gt(field Field[T], value any) *QueryWrapper[T]

Gt 添加大于条件。

func (*QueryWrapper[T]) GtTyped

func (w *QueryWrapper[T]) GtTyped(field TypedFieldRef[T], value any) *QueryWrapper[T]

GtTyped 添加类型化字段引用的大于条件。

func (*QueryWrapper[T]) Having

func (w *QueryWrapper[T]) Having(sqlText string, args NamedArgs) *QueryWrapper[T]

Having 添加 HAVING 条件片段,SQL 仅允许 #{name} 参数占位符。

func (*QueryWrapper[T]) In

func (w *QueryWrapper[T]) In(field Field[T], values any) *QueryWrapper[T]

In 添加 IN 条件。空集合会渲染为 1 = 0,避免意外全量命中。

func (*QueryWrapper[T]) InTyped

func (w *QueryWrapper[T]) InTyped(field TypedFieldRef[T], values any) *QueryWrapper[T]

InTyped 添加类型化字段引用的 IN 条件。

func (*QueryWrapper[T]) IsNotNull

func (w *QueryWrapper[T]) IsNotNull(field Field[T]) *QueryWrapper[T]

IsNotNull 添加 IS NOT NULL 条件。

func (*QueryWrapper[T]) IsNotNullTyped

func (w *QueryWrapper[T]) IsNotNullTyped(field TypedFieldRef[T]) *QueryWrapper[T]

IsNotNullTyped 添加类型化字段引用的 IS NOT NULL 条件。

func (*QueryWrapper[T]) IsNull

func (w *QueryWrapper[T]) IsNull(field Field[T]) *QueryWrapper[T]

IsNull 添加 IS NULL 条件。

func (*QueryWrapper[T]) IsNullTyped

func (w *QueryWrapper[T]) IsNullTyped(field TypedFieldRef[T]) *QueryWrapper[T]

IsNullTyped 添加类型化字段引用的 IS NULL 条件。

func (*QueryWrapper[T]) Last

func (w *QueryWrapper[T]) Last(sqlText string) *QueryWrapper[T]

Last 添加 SQL 尾部片段,例如 FOR UPDATE。尾部不支持参数绑定。

func (*QueryWrapper[T]) Le

func (w *QueryWrapper[T]) Le(field Field[T], value any) *QueryWrapper[T]

Le 添加小于等于条件。

func (*QueryWrapper[T]) LeTyped

func (w *QueryWrapper[T]) LeTyped(field TypedFieldRef[T], value any) *QueryWrapper[T]

LeTyped 添加类型化字段引用的小于等于条件。

func (*QueryWrapper[T]) Like

func (w *QueryWrapper[T]) Like(field Field[T], value any) *QueryWrapper[T]

Like 添加 LIKE 条件,通配符由调用方显式传入。

func (*QueryWrapper[T]) LikeLeft

func (w *QueryWrapper[T]) LikeLeft(field Field[T], value any) *QueryWrapper[T]

LikeLeft 添加左侧模糊匹配条件。

func (*QueryWrapper[T]) LikeLeftTyped

func (w *QueryWrapper[T]) LikeLeftTyped(field TypedFieldRef[T], value any) *QueryWrapper[T]

LikeLeftTyped 添加类型化字段引用的左侧模糊匹配条件。

func (*QueryWrapper[T]) LikeRight

func (w *QueryWrapper[T]) LikeRight(field Field[T], value any) *QueryWrapper[T]

LikeRight 添加右侧模糊匹配条件。

func (*QueryWrapper[T]) LikeRightTyped

func (w *QueryWrapper[T]) LikeRightTyped(field TypedFieldRef[T], value any) *QueryWrapper[T]

LikeRightTyped 添加类型化字段引用的右侧模糊匹配条件。

func (*QueryWrapper[T]) LikeTyped

func (w *QueryWrapper[T]) LikeTyped(field TypedFieldRef[T], value any) *QueryWrapper[T]

LikeTyped 添加类型化字段引用的 LIKE 条件。

func (*QueryWrapper[T]) Lt

func (w *QueryWrapper[T]) Lt(field Field[T], value any) *QueryWrapper[T]

Lt 添加小于条件。

func (*QueryWrapper[T]) LtTyped

func (w *QueryWrapper[T]) LtTyped(field TypedFieldRef[T], value any) *QueryWrapper[T]

LtTyped 添加类型化字段引用的小于条件。

func (*QueryWrapper[T]) Ne

func (w *QueryWrapper[T]) Ne(field Field[T], value any) *QueryWrapper[T]

Ne 添加不等条件。

func (*QueryWrapper[T]) NeTyped

func (w *QueryWrapper[T]) NeTyped(field TypedFieldRef[T], value any) *QueryWrapper[T]

NeTyped 添加类型化字段引用的不等条件。

func (*QueryWrapper[T]) Nested

func (w *QueryWrapper[T]) Nested(apply func(*QueryWrapper[T])) *QueryWrapper[T]

Nested 添加默认 AND 连接的嵌套条件组。

func (*QueryWrapper[T]) NotBetween

func (w *QueryWrapper[T]) NotBetween(field Field[T], left any, right any) *QueryWrapper[T]

NotBetween 添加 NOT BETWEEN 条件。

func (*QueryWrapper[T]) NotBetweenTyped

func (w *QueryWrapper[T]) NotBetweenTyped(field TypedFieldRef[T], left any, right any) *QueryWrapper[T]

NotBetweenTyped 添加类型化字段引用的 NOT BETWEEN 条件。

func (*QueryWrapper[T]) NotExists

func (w *QueryWrapper[T]) NotExists(sqlText string, args NamedArgs) *QueryWrapper[T]

NotExists 添加 NOT EXISTS 子查询条件,SQL 仅允许 #{name} 参数占位符。

func (*QueryWrapper[T]) NotIn

func (w *QueryWrapper[T]) NotIn(field Field[T], values any) *QueryWrapper[T]

NotIn 添加 NOT IN 条件。空集合会渲染为 1 = 0,避免写操作意外放大。

func (*QueryWrapper[T]) NotInTyped

func (w *QueryWrapper[T]) NotInTyped(field TypedFieldRef[T], values any) *QueryWrapper[T]

NotInTyped 添加类型化字段引用的 NOT IN 条件。

func (*QueryWrapper[T]) NotLike

func (w *QueryWrapper[T]) NotLike(field Field[T], value any) *QueryWrapper[T]

NotLike 添加 NOT LIKE 条件。

func (*QueryWrapper[T]) NotLikeTyped

func (w *QueryWrapper[T]) NotLikeTyped(field TypedFieldRef[T], value any) *QueryWrapper[T]

NotLikeTyped 添加类型化字段引用的 NOT LIKE 条件。

func (*QueryWrapper[T]) Or

func (w *QueryWrapper[T]) Or(apply func(*QueryWrapper[T])) *QueryWrapper[T]

Or 添加 OR 连接的嵌套条件组。

func (*QueryWrapper[T]) OrderBy

func (w *QueryWrapper[T]) OrderBy(condition bool, asc bool, fields ...Field[T]) *QueryWrapper[T]

OrderBy 按条件和方向添加排序。

func (*QueryWrapper[T]) OrderByAsc

func (w *QueryWrapper[T]) OrderByAsc(field Field[T]) *QueryWrapper[T]

OrderByAsc 添加升序排序。

func (*QueryWrapper[T]) OrderByAscTyped

func (w *QueryWrapper[T]) OrderByAscTyped(field TypedFieldRef[T]) *QueryWrapper[T]

OrderByAscTyped 添加类型化字段引用的升序排序。

func (*QueryWrapper[T]) OrderByDesc

func (w *QueryWrapper[T]) OrderByDesc(field Field[T]) *QueryWrapper[T]

OrderByDesc 添加降序排序。

func (*QueryWrapper[T]) OrderByDescTyped

func (w *QueryWrapper[T]) OrderByDescTyped(field TypedFieldRef[T]) *QueryWrapper[T]

OrderByDescTyped 添加类型化字段引用的降序排序。

func (*QueryWrapper[T]) OrderByTyped

func (w *QueryWrapper[T]) OrderByTyped(condition bool, asc bool, fields ...TypedFieldRef[T]) *QueryWrapper[T]

OrderByTyped 按条件和方向添加类型化字段排序。

func (*QueryWrapper[T]) Select

func (w *QueryWrapper[T]) Select(fields ...Field[T]) *QueryWrapper[T]

Select 指定查询投影字段。

func (*QueryWrapper[T]) SelectTyped

func (w *QueryWrapper[T]) SelectTyped(fields ...TypedFieldRef[T]) *QueryWrapper[T]

SelectTyped 指定类型化字段查询投影。

func (*QueryWrapper[T]) When

func (w *QueryWrapper[T]) When(condition bool, apply func(*QueryWrapper[T])) *QueryWrapper[T]

When 在 condition 为 true 时应用构造逻辑。

type RawIdentifier

type RawIdentifier struct {
	// contains filtered or unexported fields
}

RawIdentifier 表示表名、列名或 schema.table 形式的标识符。

func NewRawIdentifier

func NewRawIdentifier(name string) (RawIdentifier, error)

NewRawIdentifier 创建受控 SQL 标识符 token。

type RawOrderBy

type RawOrderBy struct {
	// contains filtered or unexported fields
}

RawOrderBy 表示 ORDER BY 子句后的受控字段列表。

func NewRawOrderBy

func NewRawOrderBy(items ...RawOrderItem) RawOrderBy

NewRawOrderBy 创建受控 ORDER BY token。

type RawOrderItem

type RawOrderItem struct {
	Column RawIdentifier
	Desc   bool
}

RawOrderItem 表示 ORDER BY 中的一个受控字段。

func NewRawOrderItem

func NewRawOrderItem(column string, desc bool) (RawOrderItem, error)

NewRawOrderItem 创建受控排序字段。

type RawSQLToken

type RawSQLToken interface {
	// contains filtered or unexported methods
}

RawSQLToken 表示允许进入 ${} 的受控 SQL 片段。

接口包含非导出方法,外部包只能通过本包构造器创建安全 token。

type Registry

type Registry struct {
	// contains filtered or unexported fields
}

Registry 保存编译期生成的 ORM 元数据。

func NewRegistry

func NewRegistry() *Registry

NewRegistry 创建空的 ORM 元数据注册表。

func (*Registry) Cache

func (r *Registry) Cache(namespace string) (Cache, string, bool)

Cache 按 mapper namespace 读取二级缓存,自动解析 cache-ref。

func (*Registry) Entities

func (r *Registry) Entities() []EntityMeta

Entities 返回所有实体元数据副本。

func (*Registry) Entity

func (r *Registry) Entity(typeName string) (EntityMeta, bool)

Entity 按实体类型名读取元数据。

func (*Registry) Mapper

func (r *Registry) Mapper(namespace string) (MapperMeta, bool)

Mapper 按 namespace 读取 Mapper 元数据。

func (*Registry) Mappers

func (r *Registry) Mappers() []MapperMeta

Mappers 返回所有 Mapper 元数据副本。

func (*Registry) RegisterCache

func (r *Registry) RegisterCache(namespace string, cache Cache) error

RegisterCache 注册或替换指定 namespace 的二级缓存实现。

func (*Registry) RegisterEntity

func (r *Registry) RegisterEntity(meta EntityMeta) error

RegisterEntity 注册实体元数据。

func (*Registry) RegisterMapper

func (r *Registry) RegisterMapper(meta MapperMeta) error

RegisterMapper 注册 Mapper 元数据,并同步注册内部 Statement。

func (*Registry) RegisterRowScanner

func (r *Registry) RegisterRowScanner(typeName string, scanner RowScanner) error

RegisterRowScanner 注册或替换指定实体类型的生成式行扫描器。

func (*Registry) RegisterSQLProvider

func (r *Registry) RegisterSQLProvider(name string, provider SQLProvider) error

RegisterSQLProvider 注册或替换全局 SQL Provider。

func (*Registry) RegisterTypeHandler

func (r *Registry) RegisterTypeHandler(name string, handler TypeHandler) error

RegisterTypeHandler 注册或替换全局 TypeHandler。

func (*Registry) RegisterTypeHandlers

func (r *Registry) RegisterTypeHandlers(handlers map[string]TypeHandler) error

RegisterTypeHandlers 批量注册或替换全局 TypeHandler。

func (*Registry) RowScanner

func (r *Registry) RowScanner(typeName string) (RowScanner, bool)

RowScanner 按实体类型名读取生成式行扫描器。

func (*Registry) SQLProvider

func (r *Registry) SQLProvider(name string) (SQLProvider, bool)

SQLProvider 按名称读取全局 SQL Provider。

func (*Registry) Statement

func (r *Registry) Statement(fullName string) (StatementMeta, bool)

Statement 按完整 Statement 名称读取语句元数据。

func (*Registry) TypeHandler

func (r *Registry) TypeHandler(name string) (TypeHandler, bool)

TypeHandler 按名称读取全局 TypeHandler。

func (*Registry) TypeHandlers

func (r *Registry) TypeHandlers() map[string]TypeHandler

TypeHandlers 返回全局 TypeHandler 快照。

type RegistryError

type RegistryError struct {
	Resource string
	Name     string
	Message  string
	Err      error
}

RegistryError 携带元数据资源类型、名称和底层原因。

func (*RegistryError) Error

func (e *RegistryError) Error() string

func (*RegistryError) Is

func (e *RegistryError) Is(target error) bool

func (*RegistryError) Unwrap

func (e *RegistryError) Unwrap() error

type RenderedSQL

type RenderedSQL struct {
	SQL  string
	Args NamedArgs
}

RenderedSQL 表示动态 SQL 渲染后的 SQL 和参数。

func RenderDynamicSQL

func RenderDynamicSQL(nodes []DynamicSQLNode, args NamedArgs) (RenderedSQL, error)

RenderDynamicSQL 将动态 SQL 节点树渲染为可继续参数编译的 SQL。

type Result

type Result struct {
	RowsAffected int64
	LastInsertID int64
}

Result 表示写操作结果。

type ResultArgMeta

type ResultArgMeta struct {
	Name        string
	Property    string
	Column      string
	ID          bool
	TypeHandler string
}

ResultArgMeta 描述 constructor 中的 arg 或 idArg。

type ResultAssociationMeta

type ResultAssociationMeta struct {
	Property       string
	TypeName       string
	Column         string
	ColumnPrefix   string
	NotNullColumns []string
	Select         string
	FetchType      string
	Fields         []ResultFieldMeta
	Associations   []ResultAssociationMeta
	Collections    []ResultCollectionMeta
}

ResultAssociationMeta 描述 resultMap 中的嵌套对象映射。

type ResultCollectionMeta

type ResultCollectionMeta struct {
	Property       string
	TypeName       string
	Column         string
	ColumnPrefix   string
	NotNullColumns []string
	Select         string
	FetchType      string
	Fields         []ResultFieldMeta
	Associations   []ResultAssociationMeta
	Collections    []ResultCollectionMeta
}

ResultCollectionMeta 描述 resultMap 中的嵌套集合映射。

type ResultConstructorMeta

type ResultConstructorMeta struct {
	Args []ResultArgMeta
}

ResultConstructorMeta 描述 resultMap 的构造参数映射。

type ResultDiscriminatorCaseMeta

type ResultDiscriminatorCaseMeta struct {
	Value        string
	ResultMap    string
	ResultType   string
	Fields       []ResultFieldMeta
	Associations []ResultAssociationMeta
	Collections  []ResultCollectionMeta
}

ResultDiscriminatorCaseMeta 描述 discriminator 的单个 case。

type ResultDiscriminatorMeta

type ResultDiscriminatorMeta struct {
	Column      string
	TypeName    string
	TypeHandler string
	Cases       []ResultDiscriminatorCaseMeta
}

ResultDiscriminatorMeta 描述 MyBatis resultMap discriminator。

type ResultFieldMeta

type ResultFieldMeta struct {
	Property    string
	Column      string
	ID          bool
	TypeHandler string
}

ResultFieldMeta 描述 XML resultMap 中的一项结果映射。

type ResultHandler

type ResultHandler[T any] func(context.Context, T) error

ResultHandler 逐条消费查询结果。

type ResultMapMeta

type ResultMapMeta struct {
	ID            string
	TypeName      string
	Extends       string
	AutoMapping   *bool
	Constructor   ResultConstructorMeta
	Fields        []ResultFieldMeta
	Associations  []ResultAssociationMeta
	Collections   []ResultCollectionMeta
	Discriminator ResultDiscriminatorMeta
}

ResultMapMeta 描述 XML resultMap。

type ResultSetHandler

type ResultSetHandler interface {
	ScanRows(ctx context.Context, rows Rows, statement StatementMeta, dest any) error
	ScanOne(ctx context.Context, rows Rows, statement StatementMeta, dest any) error
}

ResultSetHandler 负责把 database/sql 行集扫描到调用方目标对象。

type ResultSetHandlerMiddleware

type ResultSetHandlerMiddleware interface {
	WrapResultSetHandler(next ResultSetHandler) ResultSetHandler
}

ResultSetHandlerMiddleware 包装结果集处理器,用于扩展行扫描和结果映射层。

type ResultSetHandlerMiddlewareFunc

type ResultSetHandlerMiddlewareFunc func(next ResultSetHandler) ResultSetHandler

ResultSetHandlerMiddlewareFunc 将函数适配为 ResultSetHandlerMiddleware。

func (ResultSetHandlerMiddlewareFunc) WrapResultSetHandler

WrapResultSetHandler 执行函数式结果集处理器包装。

type ResultSetMeta

type ResultSetMeta struct {
	Name       string
	ResultMap  string
	ResultType string
}

ResultSetMeta 描述存储过程返回的一个结果集。

type ResultSetRows

type ResultSetRows interface {
	Rows
	NextResultSet() bool
}

ResultSetRows 描述支持多结果集前进的行集。

type ResultSetType

type ResultSetType string

ResultSetType 描述 Statement 期望的结果集游标类型。

const (
	// ResultSetTypeForwardOnly 表示只向前读取的结果集。
	ResultSetTypeForwardOnly ResultSetType = "FORWARD_ONLY"
	// ResultSetTypeScrollInsensitive 表示可滚动且不感知底层数据变化的结果集。
	ResultSetTypeScrollInsensitive ResultSetType = "SCROLL_INSENSITIVE"
	// ResultSetTypeScrollSensitive 表示可滚动且感知底层数据变化的结果集。
	ResultSetTypeScrollSensitive ResultSetType = "SCROLL_SENSITIVE"
)

func ParseResultSetType

func ParseResultSetType(value string) (ResultSetType, error)

ParseResultSetType 解析 MyBatis resultSetType 配置值。

type RoutingOperation

type RoutingOperation struct {
	Kind      RoutingOperationKind
	Statement string
	Command   StatementCommand
	Args      NamedArgs
	Page      PageRequest
}

RoutingOperation 描述一次待路由的 ORM 操作。

type RoutingOperationKind

type RoutingOperationKind string

RoutingOperationKind 表示路由时的 ORM 操作类型。

const (
	// RoutingOperationQuery 表示多行查询。
	RoutingOperationQuery RoutingOperationKind = "query"
	// RoutingOperationQueryOne 表示单行查询。
	RoutingOperationQueryOne RoutingOperationKind = "query-one"
	// RoutingOperationExec 表示写语句执行。
	RoutingOperationExec RoutingOperationKind = "exec"
	// RoutingOperationCall 表示存储过程调用。
	RoutingOperationCall RoutingOperationKind = "call"
	// RoutingOperationPage 表示分页查询。
	RoutingOperationPage RoutingOperationKind = "page"
)

type RoutingSession

type RoutingSession struct {
	// contains filtered or unexported fields
}

RoutingSession 按 context 和路由规则把 ORM 操作转发到具体 Session。

func NewRoutingSession

func NewRoutingSession(sessions map[DataSourceKey]Session, resolver DataSourceResolver, options ...RoutingSessionOption) (*RoutingSession, error)

NewRoutingSession 创建多数据源路由 Session。

func (*RoutingSession) Call

func (s *RoutingSession) Call(ctx context.Context, statement string, args NamedArgs, resultSets ...any) (CallResult, error)

Call 路由并执行存储过程调用。

func (*RoutingSession) Close

func (s *RoutingSession) Close() error

Close 关闭所有实现 Close 方法的委托 Session。

func (*RoutingSession) Exec

func (s *RoutingSession) Exec(ctx context.Context, statement string, args NamedArgs) (Result, error)

Exec 路由并执行写语句。

func (*RoutingSession) Query

func (s *RoutingSession) Query(ctx context.Context, statement string, args NamedArgs, dest any) error

Query 路由并执行多行查询。

func (*RoutingSession) QueryOne

func (s *RoutingSession) QueryOne(ctx context.Context, statement string, args NamedArgs, dest any) error

QueryOne 路由并执行单行查询。

func (*RoutingSession) QueryPage

func (s *RoutingSession) QueryPage(ctx context.Context, statement string, args NamedArgs, page PageRequest, dest any) (PageQueryResult, error)

QueryPage 路由并执行分页查询。

type RoutingSessionFactory

type RoutingSessionFactory struct {
	// contains filtered or unexported fields
}

RoutingSessionFactory 创建多数据源路由 Session。

func NewRoutingSessionFactory

func NewRoutingSessionFactory(openers map[DataSourceKey]SessionOpenFunc, resolver DataSourceResolver, options ...RoutingSessionOption) (*RoutingSessionFactory, error)

NewRoutingSessionFactory 创建多数据源路由 SessionFactory。

func (*RoutingSessionFactory) OpenSession

func (f *RoutingSessionFactory) OpenSession() (*RoutingSession, error)

OpenSession 打开所有委托 Session,并返回路由 Session。

type RoutingSessionOption

type RoutingSessionOption func(*RoutingSession) error

RoutingSessionOption 配置多数据源路由 Session。

func WithRoutingDefaultDataSource

func WithRoutingDefaultDataSource(key DataSourceKey) RoutingSessionOption

WithRoutingDefaultDataSource 配置默认数据源。

func WithRoutingRegistry

func WithRoutingRegistry(registry *Registry) RoutingSessionOption

WithRoutingRegistry 配置用于读取 StatementCommand 的 Registry。

type RowCursor

type RowCursor struct {
	// contains filtered or unexported fields
}

RowCursor 暴露非泛型行游标,供框架扩展和自定义扫描使用。

func (*RowCursor) Close

func (c *RowCursor) Close() error

Close 关闭游标持有的行集。

func (*RowCursor) Err

func (c *RowCursor) Err() error

Err 返回底层行集的迭代错误。

func (*RowCursor) Next

func (c *RowCursor) Next() bool

Next 前进到下一行。

func (*RowCursor) Scan

func (c *RowCursor) Scan(ctx context.Context, dest any) error

Scan 扫描当前行到 dest。

type RowScanner

type RowScanner interface {
	ScanRow(ctx context.Context, columns []string, row RowScannerRow, dest any) error
}

RowScanner 描述由生成器输出的实体行扫描器。

type RowScannerFunc

type RowScannerFunc func(ctx context.Context, columns []string, row RowScannerRow, dest any) error

RowScannerFunc 将函数适配为 RowScanner。

func (RowScannerFunc) ScanRow

func (f RowScannerFunc) ScanRow(ctx context.Context, columns []string, row RowScannerRow, dest any) error

ScanRow 执行函数式行扫描器。

type RowScannerRow

type RowScannerRow interface {
	Scan(dest ...any) error
}

RowScannerRow 是生成式行扫描器需要的最小行读取契约。

type Rows

type Rows interface {
	Columns() ([]string, error)
	Next() bool
	Scan(dest ...any) error
	Err() error
	Close() error
}

Rows 是 *sql.Rows 的最小扫描接口,便于测试和自定义执行器复用扫描器。

type SQLCondition

type SQLCondition struct {
	SQL  string
	Args NamedArgs
}

SQLCondition 描述可注入到 WHERE 子句的 SQL 条件。

type SQLExecutor

type SQLExecutor interface {
	QueryContext(ctx context.Context, query string, args ...any) (*sql.Rows, error)
	ExecContext(ctx context.Context, query string, args ...any) (sql.Result, error)
}

SQLExecutor 是 *sql.DB 和 *sql.Tx 共同满足的最小执行接口。

type SQLFetchSizeApplier

type SQLFetchSizeApplier interface {
	ApplyFetchSize(ctx context.Context, query string, fetchSize int) error
}

SQLFetchSizeApplier 是支持查询级 fetch size 的可选执行器能力。

type SQLGuardRule

type SQLGuardRule interface {
	CheckSQL(ctx context.Context, statement StatementMeta, sql string) error
}

SQLGuardRule 表示一条可组合的 SQL 治理规则。

type SQLGuardRuleFunc

type SQLGuardRuleFunc func(ctx context.Context, statement StatementMeta, sql string) error

SQLGuardRuleFunc 将函数适配为 SQLGuardRule。

func (SQLGuardRuleFunc) CheckSQL

func (f SQLGuardRuleFunc) CheckSQL(ctx context.Context, statement StatementMeta, sql string) error

CheckSQL 执行函数式 SQL 治理规则。

type SQLInjector

type SQLInjector interface {
	Inspect(entity EntityMeta, dialect Dialect, global GlobalConfig) ([]StatementMeta, error)
}

SQLInjector 对齐 MyBatis-Plus SQL Injector,用于为实体生成通用方法语句。

type SQLInjectorFunc

type SQLInjectorFunc func(entity EntityMeta, dialect Dialect, global GlobalConfig) ([]StatementMeta, error)

SQLInjectorFunc 允许用函数声明轻量注入器。

func (SQLInjectorFunc) Inspect

func (f SQLInjectorFunc) Inspect(entity EntityMeta, dialect Dialect, global GlobalConfig) ([]StatementMeta, error)

Inspect 执行函数式 SQL 注入器。

type SQLObservation

type SQLObservation struct {
	Statement StatementMeta
	SQL       string
	Args      NamedArgs
	Dialect   Dialect
}

SQLObservation 描述一次 SQL 模板观察事件。

type SQLPreparer

type SQLPreparer interface {
	PrepareContext(ctx context.Context, query string) (*sql.Stmt, error)
}

SQLPreparer 是支持预编译语句的可选执行器能力。

type SQLProvider

type SQLProvider func(ctx context.Context, statement StatementMeta, args NamedArgs) (SQLSource, error)

SQLProvider 按 Statement 和入参在运行期生成 SQL。

type SQLSession

type SQLSession struct {
	// contains filtered or unexported fields
}

SQLSession 基于 database/sql 执行已经注册的 Statement。

func NewSQLSession

func NewSQLSession(registry *Registry, executor SQLExecutor, dialect Dialect, options ...SQLSessionOption) (*SQLSession, error)

NewSQLSession 创建可独立使用的 database/sql ORM Session。

func (*SQLSession) Call

func (s *SQLSession) Call(ctx context.Context, statement string, args NamedArgs, resultSets ...any) (CallResult, error)

Call 执行存储过程或可调用语句。

func (*SQLSession) CallStatement

func (s *SQLSession) CallStatement(ctx context.Context, meta StatementMeta, args NamedArgs, resultSets ...any) (CallResult, error)

CallStatement 基于 StatementMeta 执行存储过程或可调用语句。

func (*SQLSession) Close

func (s *SQLSession) Close() error

Close 关闭自动提交 Session。底层连接由 database/sql 管理。

func (*SQLSession) Commit

func (s *SQLSession) Commit() error

Commit 对自动提交 Session 不执行任何操作。

func (*SQLSession) Configuration

func (s *SQLSession) Configuration() Configuration

Configuration 返回当前 Session 使用的配置快照。

func (*SQLSession) Dialect

func (s *SQLSession) Dialect() Dialect

Dialect 返回当前 Session 使用的数据库方言。

func (*SQLSession) Exec

func (s *SQLSession) Exec(ctx context.Context, statement string, args NamedArgs) (Result, error)

Exec 执行 insert、update、delete 语句。

func (*SQLSession) ExecStatement

func (s *SQLSession) ExecStatement(ctx context.Context, meta StatementMeta, args NamedArgs) (Result, error)

ExecStatement 执行写入语句元数据。

func (*SQLSession) GlobalConfig

func (s *SQLSession) GlobalConfig() GlobalConfig

GlobalConfig 返回当前 Session 使用的全局配置快照。

func (*SQLSession) IdentifierGenerator

func (s *SQLSession) IdentifierGenerator() IdentifierGenerator

IdentifierGenerator 返回当前 Session 使用的主键生成器。

func (*SQLSession) MetaObjectHandler

func (s *SQLSession) MetaObjectHandler() MetaObjectHandler

MetaObjectHandler 返回当前 Session 使用的自动填充处理器。

func (*SQLSession) Query

func (s *SQLSession) Query(ctx context.Context, statement string, args NamedArgs, dest any) error

Query 执行查询语句并扫描多行结果。

func (*SQLSession) QueryCursor

func (s *SQLSession) QueryCursor(ctx context.Context, statement string, args NamedArgs) (*RowCursor, error)

QueryCursor 执行查询并返回非泛型行游标。

func (*SQLSession) QueryCursorStatement

func (s *SQLSession) QueryCursorStatement(ctx context.Context, meta StatementMeta, args NamedArgs) (*RowCursor, error)

QueryCursorStatement 基于 StatementMeta 打开非泛型行游标。

func (*SQLSession) QueryOne

func (s *SQLSession) QueryOne(ctx context.Context, statement string, args NamedArgs, dest any) error

QueryOne 执行查询语句并要求最多返回一行。

func (*SQLSession) QueryOneStatement

func (s *SQLSession) QueryOneStatement(ctx context.Context, meta StatementMeta, args NamedArgs, dest any) error

QueryOneStatement 执行查询语句元数据并要求最多返回一行。

func (*SQLSession) QueryPage

func (s *SQLSession) QueryPage(ctx context.Context, statement string, args NamedArgs, page PageRequest, dest any) (PageQueryResult, error)

QueryPage 执行分页查询并把记录扫描到 dest。

func (*SQLSession) QueryPageStatement

func (s *SQLSession) QueryPageStatement(ctx context.Context, meta StatementMeta, args NamedArgs, page PageRequest, dest any) (PageQueryResult, error)

QueryPageStatement 基于 StatementMeta 执行分页查询。

func (*SQLSession) QueryStatement

func (s *SQLSession) QueryStatement(ctx context.Context, meta StatementMeta, args NamedArgs, dest any) error

QueryStatement 执行查询语句元数据并扫描多行结果。

func (*SQLSession) Rollback

func (s *SQLSession) Rollback() error

Rollback 对自动提交 Session 不执行任何操作。

type SQLSessionFactory

type SQLSessionFactory struct {
	// contains filtered or unexported fields
}

SQLSessionFactory 创建普通 Session 和事务 Session。

func NewSQLSessionFactory

func NewSQLSessionFactory(registry *Registry, db *sql.DB, dialect Dialect, options ...SQLSessionOption) (*SQLSessionFactory, error)

NewSQLSessionFactory 创建基于 database/sql 的 SessionFactory。

func (*SQLSessionFactory) BeginBatchTx

func (f *SQLSessionFactory) BeginBatchTx(ctx context.Context, opts *sql.TxOptions) (*BatchSession, error)

BeginBatchTx 打开手动事务批处理 Session。

func (*SQLSessionFactory) BeginTx

func (f *SQLSessionFactory) BeginTx(ctx context.Context, opts *sql.TxOptions) (*TxSession, error)

BeginTx 打开手动事务 Session。

func (*SQLSessionFactory) InTx

InTx 在事务中执行回调,回调返回错误时自动回滚。

func (*SQLSessionFactory) OpenBatchSession

func (f *SQLSessionFactory) OpenBatchSession() (*BatchSession, error)

OpenBatchSession 打开自动提交批处理 Session。

func (*SQLSessionFactory) OpenConfiguredSession

func (f *SQLSessionFactory) OpenConfiguredSession() (Session, error)

OpenConfiguredSession 按运行期 Configuration 打开 Session。

当 DefaultExecutorType 为 BATCH 时返回 BatchSession;其他执行器类型返回普通 SQLSession。 该方法保留 OpenSession 的既有返回类型,避免破坏 V1 公共契约。

func (*SQLSessionFactory) OpenSession

func (f *SQLSessionFactory) OpenSession() (*SQLSession, error)

OpenSession 打开自动提交 Session。

func (*SQLSessionFactory) SetTransactionFactory

func (f *SQLSessionFactory) SetTransactionFactory(factory TransactionFactory) error

SetTransactionFactory 替换事务工厂,供外部集成层适配自定义事务来源。

type SQLSessionOption

type SQLSessionOption func(*SQLSession) error

SQLSessionOption 配置 SQLSession。

func WithConfiguration

func WithConfiguration(config Configuration) SQLSessionOption

WithConfiguration 应用独立 ORM 配置。

func WithIdentifierGenerator

func WithIdentifierGenerator(generator IdentifierGenerator) SQLSessionOption

WithIdentifierGenerator 替换 Session 级主键生成器。

func WithInterceptors

func WithInterceptors(interceptors ...StatementInterceptor) SQLSessionOption

WithInterceptors 为 SQLSession 注册 Statement 拦截器。

func WithLocalCache

func WithLocalCache(enabled bool) SQLSessionOption

WithLocalCache 配置 Session 级一级缓存。

func WithMetaObjectHandler

func WithMetaObjectHandler(handler MetaObjectHandler) SQLSessionOption

WithMetaObjectHandler 配置 Session 级自动填充处理器。

func WithParameterHandler

func WithParameterHandler(handler ParameterHandler) SQLSessionOption

WithParameterHandler 替换参数绑定处理器。

func WithParameterHandlerMiddleware

func WithParameterHandlerMiddleware(middleware ...ParameterHandlerMiddleware) SQLSessionOption

WithParameterHandlerMiddleware 按声明顺序包装 ParameterHandler。

func WithResultSetHandler

func WithResultSetHandler(handler ResultSetHandler) SQLSessionOption

WithResultSetHandler 替换结果集扫描处理器。

func WithResultSetHandlerMiddleware

func WithResultSetHandlerMiddleware(middleware ...ResultSetHandlerMiddleware) SQLSessionOption

WithResultSetHandlerMiddleware 按声明顺序包装 ResultSetHandler。

func WithStatementExecutor

func WithStatementExecutor(executor StatementExecutor) SQLSessionOption

WithStatementExecutor 替换 Session 级 Statement 执行器。

func WithStatementExecutorMiddleware

func WithStatementExecutorMiddleware(middleware ...StatementExecutorMiddleware) SQLSessionOption

WithStatementExecutorMiddleware 按声明顺序包装 StatementExecutor。

func WithStatementHandler

func WithStatementHandler(handler StatementHandler) SQLSessionOption

WithStatementHandler 替换 Statement 编译处理器。

func WithStatementHandlerMiddleware

func WithStatementHandlerMiddleware(middleware ...StatementHandlerMiddleware) SQLSessionOption

WithStatementHandlerMiddleware 按声明顺序包装 StatementHandler。

func WithTypeHandler

func WithTypeHandler(name string, handler TypeHandler) SQLSessionOption

WithTypeHandler 注册运行时 TypeHandler。

func WithTypeHandlers

func WithTypeHandlers(handlers map[string]TypeHandler) SQLSessionOption

WithTypeHandlers 批量注册 Session 级 TypeHandler。

type SQLSource

type SQLSource struct {
	SQL        string
	DynamicSQL []DynamicSQLNode
}

SQLSource 表示 Provider 在运行期返回的 SQL 来源。

type SQLStatementOptionsApplier

type SQLStatementOptionsApplier interface {
	ApplyStatementOptions(ctx context.Context, query string, options StatementOptions) error
}

SQLStatementOptionsApplier 是支持完整语句级执行选项的可选执行器能力。

type SQLTransactionFactory

type SQLTransactionFactory struct{}

SQLTransactionFactory 基于 database/sql 创建事务。

func NewSQLTransactionFactory

func NewSQLTransactionFactory() SQLTransactionFactory

NewSQLTransactionFactory 创建默认 database/sql 事务工厂。

func (SQLTransactionFactory) Begin

Begin 开启 database/sql 事务。

type SelectKeyMeta

type SelectKeyMeta struct {
	Enabled     bool
	KeyProperty string
	ResultType  string
	Order       SelectKeyOrder
	SQL         string
	DynamicSQL  []DynamicSQLNode
}

SelectKeyMeta 描述 MyBatis 风格 selectKey 主键生成语句。

type SelectKeyOrder

type SelectKeyOrder string

SelectKeyOrder 表示 selectKey 的执行时机。

const (
	// SelectKeyOrderBefore 表示先生成主键再执行主写入语句。
	SelectKeyOrderBefore SelectKeyOrder = "BEFORE"
	// SelectKeyOrderAfter 表示主写入语句执行后再查询生成主键。
	SelectKeyOrderAfter SelectKeyOrder = "AFTER"
)

type Service

type Service[T any, ID any] struct {
	// contains filtered or unexported fields
}

Service 提供 MyBatis-Plus IService 风格的实体服务层。

func NewService

func NewService[T any, ID any](mapper *BaseMapper[T, ID]) (*Service[T, ID], error)

NewService 基于 BaseMapper 创建服务层实例。

func (*Service[T, ID]) BaseMapper

func (s *Service[T, ID]) BaseMapper() *BaseMapper[T, ID]

BaseMapper 返回底层通用 Mapper。

func (*Service[T, ID]) ChainQuery

func (s *Service[T, ID]) ChainQuery() *QueryChain[T, ID]

ChainQuery 创建链式查询。

func (*Service[T, ID]) ChainUpdate

func (s *Service[T, ID]) ChainUpdate() *UpdateChain[T, ID]

ChainUpdate 创建链式更新。

func (*Service[T, ID]) Count

func (s *Service[T, ID]) Count(ctx context.Context, wrapper *QueryWrapper[T]) (int64, error)

Count 按条件统计记录数。

func (*Service[T, ID]) CountByEntity

func (s *Service[T, ID]) CountByEntity(ctx context.Context, entity *T) (int64, error)

CountByEntity 按实体非零字段统计记录数。

func (*Service[T, ID]) GetByID

func (s *Service[T, ID]) GetByID(ctx context.Context, id ID) (*T, error)

GetByID 按主键查询实体。

func (*Service[T, ID]) GetMap

func (s *Service[T, ID]) GetMap(ctx context.Context, wrapper *QueryWrapper[T]) (map[string]any, error)

GetMap 按条件查询单条 map 结果。

func (*Service[T, ID]) GetMapOrFirst

func (s *Service[T, ID]) GetMapOrFirst(ctx context.Context, wrapper *QueryWrapper[T]) (map[string]any, error)

GetMapOrFirst 按条件查询 map 结果,多行时返回第一行。

func (*Service[T, ID]) GetObj

func (s *Service[T, ID]) GetObj(ctx context.Context, wrapper *QueryWrapper[T]) (any, error)

GetObj 按条件查询首列单个值。

func (*Service[T, ID]) GetObjOrFirst

func (s *Service[T, ID]) GetObjOrFirst(ctx context.Context, wrapper *QueryWrapper[T]) (any, error)

GetObjOrFirst 按条件查询首列值,多行时返回第一行。

func (*Service[T, ID]) GetOne

func (s *Service[T, ID]) GetOne(ctx context.Context, wrapper *QueryWrapper[T]) (*T, error)

GetOne 按条件查询单条实体。

func (*Service[T, ID]) GetOneOrFirst

func (s *Service[T, ID]) GetOneOrFirst(ctx context.Context, wrapper *QueryWrapper[T]) (*T, error)

GetOneOrFirst 按条件查询单条实体,多行时返回第一行。

func (*Service[T, ID]) List

func (s *Service[T, ID]) List(ctx context.Context, wrapper *QueryWrapper[T]) ([]T, error)

List 按条件查询实体列表。wrapper 为 nil 时查询全部记录。

func (*Service[T, ID]) ListByEntity

func (s *Service[T, ID]) ListByEntity(ctx context.Context, entity *T) ([]T, error)

ListByEntity 按实体非零字段查询实体列表。

func (*Service[T, ID]) ListByIDs

func (s *Service[T, ID]) ListByIDs(ctx context.Context, ids []ID) ([]T, error)

ListByIDs 按主键集合查询实体列表。

func (*Service[T, ID]) ListByMap

func (s *Service[T, ID]) ListByMap(ctx context.Context, columnMap map[string]any) ([]T, error)

ListByMap 按列名 map 等值查询实体列表。

func (*Service[T, ID]) ListMaps

func (s *Service[T, ID]) ListMaps(ctx context.Context, wrapper *QueryWrapper[T]) ([]map[string]any, error)

ListMaps 按条件查询 map 列表。

func (*Service[T, ID]) ListObjs

func (s *Service[T, ID]) ListObjs(ctx context.Context, wrapper *QueryWrapper[T]) ([]any, error)

ListObjs 按条件查询首列列表。

func (*Service[T, ID]) Page

func (s *Service[T, ID]) Page(ctx context.Context, page PageRequest, wrapper *QueryWrapper[T]) (Page[T], error)

Page 按条件分页查询实体列表。

func (*Service[T, ID]) PageMaps

func (s *Service[T, ID]) PageMaps(ctx context.Context, page PageRequest, wrapper *QueryWrapper[T]) (Page[map[string]any], error)

PageMaps 按条件分页查询 map 结果。

func (*Service[T, ID]) Remove

func (s *Service[T, ID]) Remove(ctx context.Context, wrapper *QueryWrapper[T]) (int64, error)

Remove 按条件删除实体。

func (*Service[T, ID]) RemoveBatchByIDs

func (s *Service[T, ID]) RemoveBatchByIDs(ctx context.Context, ids []ID) (int64, error)

RemoveBatchByIDs 是 RemoveByIDs 的 MyBatis-Plus 命名别名。

func (*Service[T, ID]) RemoveByEntity

func (s *Service[T, ID]) RemoveByEntity(ctx context.Context, entity *T) (int64, error)

RemoveByEntity 按实体非零字段删除实体。

func (*Service[T, ID]) RemoveByID

func (s *Service[T, ID]) RemoveByID(ctx context.Context, id ID) (bool, error)

RemoveByID 按主键删除实体。

func (*Service[T, ID]) RemoveByIDs

func (s *Service[T, ID]) RemoveByIDs(ctx context.Context, ids []ID) (int64, error)

RemoveByIDs 按主键集合删除实体。

func (*Service[T, ID]) RemoveByMap

func (s *Service[T, ID]) RemoveByMap(ctx context.Context, columnMap map[string]any) (int64, error)

RemoveByMap 按列名 map 等值删除实体。

func (*Service[T, ID]) Save

func (s *Service[T, ID]) Save(ctx context.Context, entity *T) (bool, error)

Save 插入实体。

func (*Service[T, ID]) SaveBatch

func (s *Service[T, ID]) SaveBatch(ctx context.Context, entities []T) (int64, error)

SaveBatch 按顺序批量插入实体。

func (*Service[T, ID]) SaveBatchSize

func (s *Service[T, ID]) SaveBatchSize(ctx context.Context, entities []T, batchSize int) (int64, error)

SaveBatchSize 按指定批量大小插入实体。

func (*Service[T, ID]) SaveOrUpdate

func (s *Service[T, ID]) SaveOrUpdate(ctx context.Context, entity *T) (bool, error)

SaveOrUpdate 根据主键零值选择插入或更新。

func (*Service[T, ID]) SaveOrUpdateBatch

func (s *Service[T, ID]) SaveOrUpdateBatch(ctx context.Context, entities []T) (int64, error)

SaveOrUpdateBatch 按顺序批量保存或更新实体。

func (*Service[T, ID]) SaveOrUpdateBatchSize

func (s *Service[T, ID]) SaveOrUpdateBatchSize(ctx context.Context, entities []T, batchSize int) (int64, error)

SaveOrUpdateBatchSize 按指定批量大小保存或更新实体。

func (*Service[T, ID]) Update

func (s *Service[T, ID]) Update(ctx context.Context, entity *T, wrapper *QueryWrapper[T]) (int64, error)

Update 按实体和条件更新记录。

func (*Service[T, ID]) UpdateBatchByID

func (s *Service[T, ID]) UpdateBatchByID(ctx context.Context, entities []T) (int64, error)

UpdateBatchByID 按默认批量大小根据主键更新实体。

func (*Service[T, ID]) UpdateBatchByIDSize

func (s *Service[T, ID]) UpdateBatchByIDSize(ctx context.Context, entities []T, batchSize int) (int64, error)

UpdateBatchByIDSize 按指定批量大小根据主键更新实体。

func (*Service[T, ID]) UpdateByID

func (s *Service[T, ID]) UpdateByID(ctx context.Context, entity *T) (bool, error)

UpdateByID 按主键更新实体。

func (*Service[T, ID]) UpdateWithWrapper

func (s *Service[T, ID]) UpdateWithWrapper(ctx context.Context, wrapper *UpdateWrapper[T]) (int64, error)

UpdateWithWrapper 按 UpdateWrapper 更新记录。

type Session

type Session interface {
	Query(ctx context.Context, statement string, args NamedArgs, dest any) error
	QueryOne(ctx context.Context, statement string, args NamedArgs, dest any) error
	Exec(ctx context.Context, statement string, args NamedArgs) (Result, error)
}

Session 是生成 Mapper 代码依赖的最小执行边界。

type SessionOpenFunc

type SessionOpenFunc func() (Session, error)

SessionOpenFunc 打开一个 ORM Session。

func (SessionOpenFunc) OpenSession

func (f SessionOpenFunc) OpenSession() (Session, error)

OpenSession 执行函数式 Session 打开器。

type StatementCachePolicy

type StatementCachePolicy string

StatementCachePolicy 描述 Statement 级缓存策略。

const (
	// StatementCacheDefault 表示使用 MyBatis 风格默认缓存策略。
	StatementCacheDefault StatementCachePolicy = ""
	// StatementCacheEnabled 表示显式启用缓存行为。
	StatementCacheEnabled StatementCachePolicy = "enabled"
	// StatementCacheDisabled 表示显式禁用缓存行为。
	StatementCacheDisabled StatementCachePolicy = "disabled"
)

type StatementCallSession

type StatementCallSession interface {
	CallStatement(ctx context.Context, statement StatementMeta, args NamedArgs, resultSets ...any) (CallResult, error)
}

StatementCallSession 描述支持直接执行 StatementMeta 调用的 Session。

type StatementCommand

type StatementCommand string

StatementCommand 表示 SQL 语句命令类型。

const (
	// StatementCommandSelect 表示查询语句。
	StatementCommandSelect StatementCommand = "select"
	// StatementCommandInsert 表示插入语句。
	StatementCommandInsert StatementCommand = "insert"
	// StatementCommandUpdate 表示更新语句。
	StatementCommandUpdate StatementCommand = "update"
	// StatementCommandDelete 表示删除语句。
	StatementCommandDelete StatementCommand = "delete"
	// StatementCommandCall 表示存储过程或可调用语句。
	StatementCommandCall StatementCommand = "call"
)

type StatementExecutor

type StatementExecutor interface {
	Query(ctx context.Context, session *SQLSession, meta StatementMeta, args NamedArgs, dest any) error
	QueryOne(ctx context.Context, session *SQLSession, meta StatementMeta, args NamedArgs, dest any) error
	Exec(ctx context.Context, session *SQLSession, meta StatementMeta, args NamedArgs) (Result, error)
}

StatementExecutor 承担 Mapper Statement 的最终执行调度。

type StatementExecutorMiddleware

type StatementExecutorMiddleware interface {
	WrapStatementExecutor(next StatementExecutor) StatementExecutor
}

StatementExecutorMiddleware 包装最终执行器,用于扩展 Query、QueryOne 和 Exec 层。

type StatementExecutorMiddlewareFunc

type StatementExecutorMiddlewareFunc func(next StatementExecutor) StatementExecutor

StatementExecutorMiddlewareFunc 将函数适配为 StatementExecutorMiddleware。

func (StatementExecutorMiddlewareFunc) WrapStatementExecutor

WrapStatementExecutor 执行函数式执行器包装。

type StatementHandler

type StatementHandler interface {
	Prepare(ctx context.Context, meta StatementMeta, args NamedArgs) (*StatementRuntime, error)
	Compile(ctx context.Context, runtime *StatementRuntime) (CompiledSQL, error)
	CompileText(ctx context.Context, meta StatementMeta, dialect Dialect, sqlText string, args NamedArgs) (CompiledSQL, error)
}

StatementHandler 负责动态 SQL、拦截器和方言占位符编译。

type StatementHandlerMiddleware

type StatementHandlerMiddleware interface {
	WrapStatementHandler(next StatementHandler) StatementHandler
}

StatementHandlerMiddleware 包装语句处理器,用于扩展动态 SQL、拦截器和占位符编译层。

type StatementHandlerMiddlewareFunc

type StatementHandlerMiddlewareFunc func(next StatementHandler) StatementHandler

StatementHandlerMiddlewareFunc 将函数适配为 StatementHandlerMiddleware。

func (StatementHandlerMiddlewareFunc) WrapStatementHandler

WrapStatementHandler 执行函数式语句处理器包装。

type StatementInterceptor

type StatementInterceptor interface {
	Intercept(ctx context.Context, invocation *StatementInvocation) error
}

StatementInterceptor 拦截并改写一次 Statement 执行。

func NewBlockAttackInterceptor

func NewBlockAttackInterceptor() StatementInterceptor

NewBlockAttackInterceptor 创建全表更新/删除拦截器。

func NewDataPermissionInterceptor

func NewDataPermissionInterceptor(provider DataPermissionProvider) StatementInterceptor

NewDataPermissionInterceptor 创建数据权限条件注入拦截器。

func NewDynamicTableInterceptor

func NewDynamicTableInterceptor(tables map[string]string) StatementInterceptor

NewDynamicTableInterceptor 创建动态表名拦截器。

func NewEntitySemanticInterceptor

func NewEntitySemanticInterceptor(registry *Registry, options ...EntitySemanticInterceptorOption) StatementInterceptor

NewEntitySemanticInterceptor 创建实体语义拦截器。

func NewIllegalSQLInterceptor

func NewIllegalSQLInterceptor(options ...IllegalSQLOption) StatementInterceptor

NewIllegalSQLInterceptor 创建非法 SQL 治理拦截器。

func NewPaginationInterceptor

func NewPaginationInterceptor() StatementInterceptor

NewPaginationInterceptor 创建分页拦截器。

func NewReadOnlyInterceptor

func NewReadOnlyInterceptor() StatementInterceptor

NewReadOnlyInterceptor 创建只读治理拦截器。

func NewSQLGuardInterceptor

func NewSQLGuardInterceptor(rules ...SQLGuardRule) StatementInterceptor

NewSQLGuardInterceptor 创建通用 SQL 治理拦截器。

func NewSQLObserverInterceptor

func NewSQLObserverInterceptor(observe func(context.Context, SQLObservation) error) StatementInterceptor

NewSQLObserverInterceptor 创建 SQL 模板观察拦截器。

func NewTenantInterceptor

func NewTenantInterceptor(column string, value any) StatementInterceptor

NewTenantInterceptor 创建多租户条件注入拦截器。

type StatementInterceptorFunc

type StatementInterceptorFunc func(ctx context.Context, invocation *StatementInvocation) error

StatementInterceptorFunc 将函数适配为 StatementInterceptor。

func (StatementInterceptorFunc) Intercept

func (f StatementInterceptorFunc) Intercept(ctx context.Context, invocation *StatementInvocation) error

Intercept 执行函数式拦截器。

type StatementInvocation

type StatementInvocation struct {
	// contains filtered or unexported fields
}

StatementInvocation 维护拦截器链的执行游标。

func (*StatementInvocation) Proceed

func (i *StatementInvocation) Proceed(ctx context.Context) error

Proceed 执行链上的下一个拦截器。

func (*StatementInvocation) Statement

func (i *StatementInvocation) Statement() *StatementRuntime

Statement 返回当前可变 SQL 模板。

type StatementMeta

type StatementMeta struct {
	ID                 string
	Namespace          string
	FullName           string
	Command            StatementCommand
	StatementType      StatementType
	Source             StatementSource
	SQL                string
	Provider           string
	ResultMap          string
	ResultType         string
	ParameterType      string
	DatabaseID         string
	UseGeneratedKeys   bool
	KeyProperty        string
	Options            StatementOptions
	SelectKey          SelectKeyMeta
	UseCache           StatementCachePolicy
	FlushCache         StatementCachePolicy
	Parameters         []string
	ParameterModes     []ParameterMeta
	ResultSets         []ResultSetMeta
	DynamicSQL         []DynamicSQLNode
	InterceptorIgnores []string
}

StatementMeta 描述已经编译好的 Mapper 语句元数据。

type StatementNotFoundError

type StatementNotFoundError struct {
	Statement string
	Message   string
	Err       error
}

StatementNotFoundError 表示指定 Statement 或 SQL Provider 没有注册。

func (*StatementNotFoundError) Error

func (e *StatementNotFoundError) Error() string

func (*StatementNotFoundError) Is

func (e *StatementNotFoundError) Is(target error) bool

func (*StatementNotFoundError) Unwrap

func (e *StatementNotFoundError) Unwrap() error

type StatementOptions

type StatementOptions struct {
	Timeout       time.Duration
	FetchSize     int
	ResultSetType ResultSetType
	ResultOrdered bool
	KeyColumn     string
}

StatementOptions 描述 MyBatis 风格的语句级执行选项。

type StatementRuntime

type StatementRuntime struct {
	Meta          StatementMeta
	SQL           string
	Args          NamedArgs
	Dialect       Dialect
	Configuration Configuration
}

StatementRuntime 描述一次执行中的可变 SQL 模板。

type StatementSession

type StatementSession interface {
	QueryStatement(ctx context.Context, statement StatementMeta, args NamedArgs, dest any) error
	QueryOneStatement(ctx context.Context, statement StatementMeta, args NamedArgs, dest any) error
	ExecStatement(ctx context.Context, statement StatementMeta, args NamedArgs) (Result, error)
}

StatementSession 执行已经构造好的 StatementMeta。

type StatementSource

type StatementSource string

StatementSource 表示 SQL 语句来源。

const (
	// StatementSourceXML 表示语句来源于 Mapper XML。
	StatementSourceXML StatementSource = "xml"
	// StatementSourceAnnotation 表示语句来源于方法注解。
	StatementSourceAnnotation StatementSource = "annotation"
	// StatementSourceBase 表示语句来源于通用 BaseMapper。
	StatementSourceBase StatementSource = "base"
)

type StatementType

type StatementType string

StatementType 表示 Statement 的底层执行形态。

const (
	// StatementTypePrepared 表示普通预编译 SQL 语句。
	StatementTypePrepared StatementType = "PREPARED"
	// StatementTypeCallable 表示数据库存储过程或 callable statement。
	StatementTypeCallable StatementType = "CALLABLE"
)

type TooManyResultsError

type TooManyResultsError struct {
	Statement string
	Expected  int
	Actual    int
	Message   string
	Err       error
}

TooManyResultsError 表示单行查询返回了超过一行结果。

func (*TooManyResultsError) Error

func (e *TooManyResultsError) Error() string

func (*TooManyResultsError) Is

func (e *TooManyResultsError) Is(target error) bool

func (*TooManyResultsError) Unwrap

func (e *TooManyResultsError) Unwrap() error

type Transaction

type Transaction interface {
	Executor() SQLExecutor
	Commit() error
	Rollback() error
}

Transaction 描述 ORM 自身独立事务抽象。

type TransactionFactory

type TransactionFactory interface {
	Begin(ctx context.Context, source TransactionSource, opts *sql.TxOptions) (Transaction, error)
}

TransactionFactory 创建事务实例。

type TransactionSource

type TransactionSource interface {
	BeginTx(ctx context.Context, opts *sql.TxOptions) (*sql.Tx, error)
}

TransactionSource 是可以开启 database/sql 事务的最小边界。

type TxSession

type TxSession struct {
	// contains filtered or unexported fields
}

TxSession 是绑定单个事务的 Session。

func (*TxSession) Call

func (s *TxSession) Call(ctx context.Context, statement string, args NamedArgs, resultSets ...any) (CallResult, error)

Call 执行事务内存储过程调用。

func (*TxSession) CallStatement

func (s *TxSession) CallStatement(ctx context.Context, statement StatementMeta, args NamedArgs, resultSets ...any) (CallResult, error)

CallStatement 执行事务内 StatementMeta 存储过程调用。

func (*TxSession) Close

func (s *TxSession) Close() error

Close 在事务未完成时回滚,避免连接被长时间占用。

func (*TxSession) Commit

func (s *TxSession) Commit() error

Commit 提交事务。

func (*TxSession) Dialect

func (s *TxSession) Dialect() Dialect

Dialect 返回当前事务 Session 使用的数据库方言。

func (*TxSession) Exec

func (s *TxSession) Exec(ctx context.Context, statement string, args NamedArgs) (Result, error)

Exec 执行事务内写入语句。

func (*TxSession) ExecStatement

func (s *TxSession) ExecStatement(ctx context.Context, statement StatementMeta, args NamedArgs) (Result, error)

ExecStatement 执行事务内写入语句元数据。

func (*TxSession) Query

func (s *TxSession) Query(ctx context.Context, statement string, args NamedArgs, dest any) error

Query 执行事务内查询并扫描多行结果。

func (*TxSession) QueryCursor

func (s *TxSession) QueryCursor(ctx context.Context, statement string, args NamedArgs) (*RowCursor, error)

func (*TxSession) QueryOne

func (s *TxSession) QueryOne(ctx context.Context, statement string, args NamedArgs, dest any) error

QueryOne 执行事务内查询并要求最多返回一行。

func (*TxSession) QueryOneStatement

func (s *TxSession) QueryOneStatement(ctx context.Context, statement StatementMeta, args NamedArgs, dest any) error

QueryOneStatement 执行事务内查询语句元数据并要求最多返回一行。

func (*TxSession) QueryPage

func (s *TxSession) QueryPage(ctx context.Context, statement string, args NamedArgs, page PageRequest, dest any) (PageQueryResult, error)

QueryPage 执行事务内分页查询。

func (*TxSession) QueryStatement

func (s *TxSession) QueryStatement(ctx context.Context, statement StatementMeta, args NamedArgs, dest any) error

QueryStatement 执行事务内查询语句元数据并扫描多行结果。

func (*TxSession) Rollback

func (s *TxSession) Rollback() error

Rollback 回滚事务。

type TypeAlias

type TypeAlias struct {
	Alias    string
	TypeName string
}

TypeAlias 描述 Go 类型别名。运行时不扫描包,别名由生成器或业务显式注册。

type TypeHandler

type TypeHandler interface {
	ToDB(ctx context.Context, value any) (any, error)
	FromDB(ctx context.Context, value any, target any) error
}

TypeHandler 负责 Go 值与数据库值之间的双向转换。

func NewBoolTypeHandler

func NewBoolTypeHandler() TypeHandler

NewBoolTypeHandler 创建布尔字段转换器。

func NewBytesTypeHandler

func NewBytesTypeHandler() TypeHandler

NewBytesTypeHandler 创建字节切片字段转换器。

func NewDecimalTypeHandler

func NewDecimalTypeHandler() TypeHandler

NewDecimalTypeHandler 创建无外部依赖的 Decimal 字段转换器。

func NewJSONTypeHandler

func NewJSONTypeHandler() TypeHandler

NewJSONTypeHandler 创建 JSON 字段转换器。

func NewStringTypeHandler

func NewStringTypeHandler() TypeHandler

NewStringTypeHandler 创建字符串字段转换器。

func NewTimeTypeHandler

func NewTimeTypeHandler() TypeHandler

NewTimeTypeHandler 创建时间字段转换器。

func NewTypeHandler

func NewTypeHandler(toDB func(context.Context, any) (any, error), fromDB func(context.Context, any, any) error) TypeHandler

NewTypeHandler 使用函数创建 TypeHandler,nil 函数会采用保守默认行为。

type TypeHandlerAdapter

type TypeHandlerAdapter struct {
	ToDBFunc   func(context.Context, any) (any, error)
	FromDBFunc func(context.Context, any, any) error
}

TypeHandlerAdapter 用函数适配自定义 TypeHandler。

func (TypeHandlerAdapter) FromDB

func (h TypeHandlerAdapter) FromDB(ctx context.Context, value any, target any) error

FromDB 执行出库转换。

func (TypeHandlerAdapter) ToDB

func (h TypeHandlerAdapter) ToDB(ctx context.Context, value any) (any, error)

ToDB 执行入库转换。

type TypedField

type TypedField[T any, V any] struct {
	Column string
}

TypedField 描述带 Go 值类型的实体字段。

func NewTypedField

func NewTypedField[T any, V any](column string) TypedField[T, V]

NewTypedField 创建带值类型约束的实体字段描述。

func (TypedField[T, V]) Field

func (f TypedField[T, V]) Field() Field[T]

Field 返回不携带值类型的字段描述。

type TypedFieldRef

type TypedFieldRef[T any] interface {
	Field() Field[T]
}

TypedFieldRef 是可转换为普通字段的类型化字段引用。

type UpdateChain

type UpdateChain[T any, ID any] struct {
	// contains filtered or unexported fields
}

UpdateChain 提供 MyBatis-Plus UpdateChainWrapper 风格的更新链。

func (*UpdateChain[T, ID]) Eq

func (c *UpdateChain[T, ID]) Eq(field Field[T], value any) *UpdateChain[T, ID]

Eq 添加等值条件。

func (*UpdateChain[T, ID]) Set

func (c *UpdateChain[T, ID]) Set(field Field[T], value any) *UpdateChain[T, ID]

Set 添加字段赋值。

func (*UpdateChain[T, ID]) SetDecrBy

func (c *UpdateChain[T, ID]) SetDecrBy(field Field[T], value any) *UpdateChain[T, ID]

SetDecrBy 添加字段自减赋值。

func (*UpdateChain[T, ID]) SetIncrBy

func (c *UpdateChain[T, ID]) SetIncrBy(field Field[T], value any) *UpdateChain[T, ID]

SetIncrBy 添加字段自增赋值。

func (*UpdateChain[T, ID]) Update

func (c *UpdateChain[T, ID]) Update(ctx context.Context) (int64, error)

Update 执行链式更新。

func (*UpdateChain[T, ID]) Where

func (c *UpdateChain[T, ID]) Where(apply func(*UpdateWrapper[T])) *UpdateChain[T, ID]

Where 使用底层 UpdateWrapper 添加复杂条件。

func (*UpdateChain[T, ID]) Wrapper

func (c *UpdateChain[T, ID]) Wrapper() *UpdateWrapper[T]

Wrapper 返回底层更新 Wrapper。

type UpdateWrapper

type UpdateWrapper[T any] struct {
	// contains filtered or unexported fields
}

UpdateWrapper 是 MyBatis-Plus UpdateWrapper 的 Go 化更新构造器。

func NewUpdateWrapper

func NewUpdateWrapper[T any]() *UpdateWrapper[T]

NewUpdateWrapper 创建空更新构造器。

func SetDecrByTypedValue

func SetDecrByTypedValue[T any, V any](w *UpdateWrapper[T], field TypedField[T, V], value V) *UpdateWrapper[T]

SetDecrByTypedValue 用泛型函数保留字段值类型约束并添加字段自减 SET 片段。

func SetDecrByTypedValueIf

func SetDecrByTypedValueIf[T any, V any](condition bool, w *UpdateWrapper[T], field TypedField[T, V], value V) *UpdateWrapper[T]

SetDecrByTypedValueIf 在 condition 为 true 时添加类型安全的字段自减 SET 片段。

func SetIncrByTypedValue

func SetIncrByTypedValue[T any, V any](w *UpdateWrapper[T], field TypedField[T, V], value V) *UpdateWrapper[T]

SetIncrByTypedValue 用泛型函数保留字段值类型约束并添加字段自增 SET 片段。

func SetIncrByTypedValueIf

func SetIncrByTypedValueIf[T any, V any](condition bool, w *UpdateWrapper[T], field TypedField[T, V], value V) *UpdateWrapper[T]

SetIncrByTypedValueIf 在 condition 为 true 时添加类型安全的字段自增 SET 片段。

func SetTypedValue

func SetTypedValue[T any, V any](w *UpdateWrapper[T], field TypedField[T, V], value V) *UpdateWrapper[T]

SetTypedValue 用泛型函数保留字段值类型约束。

func SetTypedValueIf

func SetTypedValueIf[T any, V any](condition bool, w *UpdateWrapper[T], field TypedField[T, V], value V) *UpdateWrapper[T]

SetTypedValueIf 在 condition 为 true 时添加类型安全的字段赋值。

func (*UpdateWrapper[T]) And

func (w *UpdateWrapper[T]) And(apply func(*UpdateWrapper[T])) *UpdateWrapper[T]

And 添加 AND 连接的嵌套条件组。

func (*UpdateWrapper[T]) Apply

func (w *UpdateWrapper[T]) Apply(sqlText string, args NamedArgs) *UpdateWrapper[T]

Apply 添加自定义条件片段,SQL 仅允许 #{name} 参数占位符。

func (*UpdateWrapper[T]) Between

func (w *UpdateWrapper[T]) Between(field Field[T], left any, right any) *UpdateWrapper[T]

Between 添加 BETWEEN 条件。

func (*UpdateWrapper[T]) BetweenTyped

func (w *UpdateWrapper[T]) BetweenTyped(field TypedFieldRef[T], left any, right any) *UpdateWrapper[T]

BetweenTyped 添加类型化字段引用的 BETWEEN 条件。

func (*UpdateWrapper[T]) Empty

func (w *UpdateWrapper[T]) Empty() bool

Empty 返回是否没有任何过滤条件。

func (*UpdateWrapper[T]) Eq

func (w *UpdateWrapper[T]) Eq(field Field[T], value any) *UpdateWrapper[T]

Eq 添加等值条件。

func (*UpdateWrapper[T]) EqIf

func (w *UpdateWrapper[T]) EqIf(condition bool, field Field[T], value any) *UpdateWrapper[T]

EqIf 在 condition 为 true 时添加等值条件。

func (*UpdateWrapper[T]) EqTyped

func (w *UpdateWrapper[T]) EqTyped(field TypedFieldRef[T], value any) *UpdateWrapper[T]

EqTyped 添加类型化字段引用的等值条件。

func (*UpdateWrapper[T]) Exists

func (w *UpdateWrapper[T]) Exists(sqlText string, args NamedArgs) *UpdateWrapper[T]

Exists 添加 EXISTS 子查询条件,SQL 仅允许 #{name} 参数占位符。

func (*UpdateWrapper[T]) Ge

func (w *UpdateWrapper[T]) Ge(field Field[T], value any) *UpdateWrapper[T]

Ge 添加大于等于条件。

func (*UpdateWrapper[T]) GeTyped

func (w *UpdateWrapper[T]) GeTyped(field TypedFieldRef[T], value any) *UpdateWrapper[T]

GeTyped 添加类型化字段引用的大于等于条件。

func (*UpdateWrapper[T]) Gt

func (w *UpdateWrapper[T]) Gt(field Field[T], value any) *UpdateWrapper[T]

Gt 添加大于条件。

func (*UpdateWrapper[T]) GtTyped

func (w *UpdateWrapper[T]) GtTyped(field TypedFieldRef[T], value any) *UpdateWrapper[T]

GtTyped 添加类型化字段引用的大于条件。

func (*UpdateWrapper[T]) In

func (w *UpdateWrapper[T]) In(field Field[T], values any) *UpdateWrapper[T]

In 添加 IN 条件。空集合会渲染为 1 = 0,避免意外全量命中。

func (*UpdateWrapper[T]) InTyped

func (w *UpdateWrapper[T]) InTyped(field TypedFieldRef[T], values any) *UpdateWrapper[T]

InTyped 添加类型化字段引用的 IN 条件。

func (*UpdateWrapper[T]) IsNotNull

func (w *UpdateWrapper[T]) IsNotNull(field Field[T]) *UpdateWrapper[T]

IsNotNull 添加 IS NOT NULL 条件。

func (*UpdateWrapper[T]) IsNotNullTyped

func (w *UpdateWrapper[T]) IsNotNullTyped(field TypedFieldRef[T]) *UpdateWrapper[T]

IsNotNullTyped 添加类型化字段引用的 IS NOT NULL 条件。

func (*UpdateWrapper[T]) IsNull

func (w *UpdateWrapper[T]) IsNull(field Field[T]) *UpdateWrapper[T]

IsNull 添加 IS NULL 条件。

func (*UpdateWrapper[T]) IsNullTyped

func (w *UpdateWrapper[T]) IsNullTyped(field TypedFieldRef[T]) *UpdateWrapper[T]

IsNullTyped 添加类型化字段引用的 IS NULL 条件。

func (*UpdateWrapper[T]) Last

func (w *UpdateWrapper[T]) Last(sqlText string) *UpdateWrapper[T]

Last 添加 SQL 尾部片段,例如 RETURNING id。尾部不支持参数绑定。

func (*UpdateWrapper[T]) Le

func (w *UpdateWrapper[T]) Le(field Field[T], value any) *UpdateWrapper[T]

Le 添加小于等于条件。

func (*UpdateWrapper[T]) LeTyped

func (w *UpdateWrapper[T]) LeTyped(field TypedFieldRef[T], value any) *UpdateWrapper[T]

LeTyped 添加类型化字段引用的小于等于条件。

func (*UpdateWrapper[T]) Like

func (w *UpdateWrapper[T]) Like(field Field[T], value any) *UpdateWrapper[T]

Like 添加 LIKE 条件,通配符由调用方显式传入。

func (*UpdateWrapper[T]) LikeLeft

func (w *UpdateWrapper[T]) LikeLeft(field Field[T], value any) *UpdateWrapper[T]

LikeLeft 添加左侧模糊匹配条件。

func (*UpdateWrapper[T]) LikeLeftTyped

func (w *UpdateWrapper[T]) LikeLeftTyped(field TypedFieldRef[T], value any) *UpdateWrapper[T]

LikeLeftTyped 添加类型化字段引用的左侧模糊匹配条件。

func (*UpdateWrapper[T]) LikeRight

func (w *UpdateWrapper[T]) LikeRight(field Field[T], value any) *UpdateWrapper[T]

LikeRight 添加右侧模糊匹配条件。

func (*UpdateWrapper[T]) LikeRightTyped

func (w *UpdateWrapper[T]) LikeRightTyped(field TypedFieldRef[T], value any) *UpdateWrapper[T]

LikeRightTyped 添加类型化字段引用的右侧模糊匹配条件。

func (*UpdateWrapper[T]) LikeTyped

func (w *UpdateWrapper[T]) LikeTyped(field TypedFieldRef[T], value any) *UpdateWrapper[T]

LikeTyped 添加类型化字段引用的 LIKE 条件。

func (*UpdateWrapper[T]) Lt

func (w *UpdateWrapper[T]) Lt(field Field[T], value any) *UpdateWrapper[T]

Lt 添加小于条件。

func (*UpdateWrapper[T]) LtTyped

func (w *UpdateWrapper[T]) LtTyped(field TypedFieldRef[T], value any) *UpdateWrapper[T]

LtTyped 添加类型化字段引用的小于条件。

func (*UpdateWrapper[T]) Ne

func (w *UpdateWrapper[T]) Ne(field Field[T], value any) *UpdateWrapper[T]

Ne 添加不等条件。

func (*UpdateWrapper[T]) NeTyped

func (w *UpdateWrapper[T]) NeTyped(field TypedFieldRef[T], value any) *UpdateWrapper[T]

NeTyped 添加类型化字段引用的不等条件。

func (*UpdateWrapper[T]) Nested

func (w *UpdateWrapper[T]) Nested(apply func(*UpdateWrapper[T])) *UpdateWrapper[T]

Nested 添加默认 AND 连接的嵌套条件组。

func (*UpdateWrapper[T]) NotBetween

func (w *UpdateWrapper[T]) NotBetween(field Field[T], left any, right any) *UpdateWrapper[T]

NotBetween 添加 NOT BETWEEN 条件。

func (*UpdateWrapper[T]) NotBetweenTyped

func (w *UpdateWrapper[T]) NotBetweenTyped(field TypedFieldRef[T], left any, right any) *UpdateWrapper[T]

NotBetweenTyped 添加类型化字段引用的 NOT BETWEEN 条件。

func (*UpdateWrapper[T]) NotExists

func (w *UpdateWrapper[T]) NotExists(sqlText string, args NamedArgs) *UpdateWrapper[T]

NotExists 添加 NOT EXISTS 子查询条件,SQL 仅允许 #{name} 参数占位符。

func (*UpdateWrapper[T]) NotIn

func (w *UpdateWrapper[T]) NotIn(field Field[T], values any) *UpdateWrapper[T]

NotIn 添加 NOT IN 条件。空集合会渲染为 1 = 0,避免写操作意外放大。

func (*UpdateWrapper[T]) NotInTyped

func (w *UpdateWrapper[T]) NotInTyped(field TypedFieldRef[T], values any) *UpdateWrapper[T]

NotInTyped 添加类型化字段引用的 NOT IN 条件。

func (*UpdateWrapper[T]) NotLike

func (w *UpdateWrapper[T]) NotLike(field Field[T], value any) *UpdateWrapper[T]

NotLike 添加 NOT LIKE 条件。

func (*UpdateWrapper[T]) NotLikeTyped

func (w *UpdateWrapper[T]) NotLikeTyped(field TypedFieldRef[T], value any) *UpdateWrapper[T]

NotLikeTyped 添加类型化字段引用的 NOT LIKE 条件。

func (*UpdateWrapper[T]) Or

func (w *UpdateWrapper[T]) Or(apply func(*UpdateWrapper[T])) *UpdateWrapper[T]

Or 添加 OR 连接的嵌套条件组。

func (*UpdateWrapper[T]) Set

func (w *UpdateWrapper[T]) Set(field Field[T], value any) *UpdateWrapper[T]

Set 添加字段赋值。

func (*UpdateWrapper[T]) SetDecrBy

func (w *UpdateWrapper[T]) SetDecrBy(field Field[T], value any) *UpdateWrapper[T]

SetDecrBy 添加字段自减 SET 片段。

func (*UpdateWrapper[T]) SetDecrByTyped

func (w *UpdateWrapper[T]) SetDecrByTyped(field TypedFieldRef[T], value any) *UpdateWrapper[T]

SetDecrByTyped 添加类型化字段引用的字段自减 SET 片段。

func (*UpdateWrapper[T]) SetEmpty

func (w *UpdateWrapper[T]) SetEmpty() bool

SetEmpty 返回是否没有任何更新字段。

func (*UpdateWrapper[T]) SetIf

func (w *UpdateWrapper[T]) SetIf(condition bool, field Field[T], value any) *UpdateWrapper[T]

SetIf 在 condition 为 true 时添加字段赋值。

func (*UpdateWrapper[T]) SetIncrBy

func (w *UpdateWrapper[T]) SetIncrBy(field Field[T], value any) *UpdateWrapper[T]

SetIncrBy 添加字段自增 SET 片段。

func (*UpdateWrapper[T]) SetIncrByTyped

func (w *UpdateWrapper[T]) SetIncrByTyped(field TypedFieldRef[T], value any) *UpdateWrapper[T]

SetIncrByTyped 添加类型化字段引用的字段自增 SET 片段。

func (*UpdateWrapper[T]) SetSQL

func (w *UpdateWrapper[T]) SetSQL(sqlText string, args NamedArgs) *UpdateWrapper[T]

SetSQL 添加安全的原生 SET 片段,SQL 仅允许 #{name} 参数占位符。

func (*UpdateWrapper[T]) SetTyped

func (w *UpdateWrapper[T]) SetTyped(field TypedFieldRef[T], value any) *UpdateWrapper[T]

SetTyped 添加类型化字段引用的字段赋值。

func (*UpdateWrapper[T]) SetTypedIf

func (w *UpdateWrapper[T]) SetTypedIf(condition bool, field TypedFieldRef[T], value any) *UpdateWrapper[T]

SetTypedIf 在 condition 为 true 时添加类型化字段引用的字段赋值。

func (*UpdateWrapper[T]) When

func (w *UpdateWrapper[T]) When(condition bool, apply func(*UpdateWrapper[T])) *UpdateWrapper[T]

When 在 condition 为 true 时应用构造逻辑。

Directories

Path Synopsis
cmd
goark-orm command
examples
internal
jsoncodec
Package jsoncodec 集中封装 ORM 内部 JSON 编解码能力。
Package jsoncodec 集中封装 ORM 内部 JSON 编解码能力。
Package ormtest 提供真实数据库兼容性测试辅助工具。
Package ormtest 提供真实数据库兼容性测试辅助工具。

Jump to

Keyboard shortcuts

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