gom

package module
v4.1.2-ai Latest Latest
Warning

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

Go to latest
Published: Dec 31, 2024 License: Apache-2.0 Imports: 15 Imported by: 2

README

GOM - Go ORM and Model Generator

GOM 是一个强大的 Go 语言 ORM 框架和模型生成器,支持 PostgreSQL 和 MySQL 数据库。

特性

  • 支持 PostgreSQL 和 MySQL 数据库
  • 自动生成 Go 结构体模型
  • 支持自定义表名和字段映射
  • 支持多种数据类型(包括 Decimal、UUID、IP 等)
  • 自动处理创建时间和更新时间
  • 支持自定义标签风格
  • 支持表名前缀和后缀处理
  • 生成完整的 CRUD 方法
  • 支持事务处理
  • 内置模型注册机制

安装

go get -u github.com/kmlixh/gom/v4

快速开始

1. 使用代码生成器
# 安装代码生成器
go install github.com/kmlixh/gom/v4/gomen/cmd/gomen@latest

# PostgreSQL 示例
gomen -type postgres \
      -url "postgres://user:password@localhost:5432/dbname?sslmode=disable" \
      -pattern "public.user*" \
      -out "./models"

# MySQL 示例
gomen -type mysql \
      -url "user:password@tcp(localhost:3306)/dbname" \
      -prefix "t_" \
      -out "./models"
2. 使用生成的模型
package main

import (
    "log"
    "github.com/kmlixh/gom/v4"
    "your/project/models"
)

func main() {
    // 连接数据库
    db, err := gom.Open("postgres", "postgres://user:password@localhost:5432/dbname?sslmode=disable", true)
    if err != nil {
        log.Fatal(err)
    }
    defer db.Close()

    // 创建记录
    user := &models.User{
        Username: "john",
        Email:    "john@example.com",
    }
    if err := db.Chain().Create(user); err != nil {
        log.Fatal(err)
    }

    // 查询记录
    var users []*models.User
    if err := db.Chain().Where("age", ">", 18).Find(&users); err != nil {
        log.Fatal(err)
    }

    // 更新记录
    if err := db.Chain().Where("id", "=", 1).Update(map[string]interface{}{
        "status": "active",
    }); err != nil {
        log.Fatal(err)
    }

    // 删除记录
    if err := db.Chain().Where("id", "=", 1).Delete(); err != nil {
        log.Fatal(err)
    }
}

代码生成器选项

选项:
  -type string
        数据库类型 (mysql/postgres)
  -url string
        数据库连接URL
  -out string
        输出目录 (默认 "models")
  -package string
        包名 (默认 "models")
  -pattern string
        表名匹配模式 (PostgreSQL 可用 schema.table* 格式)
  -tag string
        标签风格 (gom/db) (默认 "gom")
  -prefix string
        表名前缀(生成时会去掉)
  -suffix string
        表名后缀(生成时会去掉)
  -db
        生成db标签
  -debug
        开启调试模式

数据类型映射

数据库类型 Go 类型 说明
INT/INTEGER int 32位整数
BIGINT int64 64位整数
SMALLINT int16 16位整数
TINYINT int8 8位整数
DECIMAL/NUMERIC decimal.Decimal 精确小数
FLOAT float32 32位浮点数
DOUBLE float64 64位浮点数
BOOLEAN/BOOL bool 布尔值
VARCHAR/TEXT string 字符串
TIME/TIMESTAMP time.Time 时间类型
JSON json.RawMessage JSON数据
UUID uuid.UUID UUID类型
INET net.IP IP地址

标签说明

生成的结构体字段包含以下标签:

  • gom:"column_name": 字段映射
  • gom:"column_name,@": 主键
  • gom:"column_name,auto": 自增
  • gom:"column_name,notnull": 非空
  • json:"column_name": JSON标签
  • db:"column_name": 数据库标签(可选)

贡献

欢迎提交 Issue 和 Pull Request!

许可证

MIT License

统计方法

GOM 提供了以下统计方法:

// 计算记录总数
count, err := db.Chain().Table("users").Count()

// 计算字段平均值
avgAge, err := db.Chain().Table("users").Eq("active", true).Avg("age")

// 计算字段总和
sumAge, err := db.Chain().Table("users").Eq("role", "admin").Sum("age")

这些统计方法都支持:

  • 与条件查询方法配合使用
  • 处理 NULL 值和空结果集
  • 支持复杂条件组合

分页查询

GOM 提供了便捷的分页查询方法:

// 使用模型的分页查询
pageInfo, err := db.Chain().
    Table("users").
    Eq("active", true).
    OrderBy("created_at").
    Page(1, 10).  // 第1页,每页10条
    PageInfo(&User{})

// 不使用模型的分页查询(返回原始数据)
rawPageInfo, err := db.Chain().
    Table("users").
    Fields("id", "username").
    Page(2, 5).   // 第2页,每页5条
    PageInfo(nil)

PageInfo 结构包含以下信息:

  • PageNum: 当前页码
  • PageSize: 每页大小
  • Total: 总记录数
  • Pages: 总页数
  • HasPrev: 是否有上一页
  • HasNext: 是否有下一页
  • List: 当前页数据
  • IsFirstPage: 是否是第一页
  • IsLastPage: 是否是最后页

版本历史

v4.1.0-ai (2024-12-31 10:15 UTC+8)

新特性:

  • 增强 SaveUpdateDelete 方法
    • 支持不定长参数,可同时处理多个对象
    • 自动事务支持,确保多对象操作的原子性
    • 智能事务管理:单对象操作不使用事务,多对象自动使用事务
    • 详细的错误信息,包含失败对象的序号
    • 自动回滚机制,任何操作失败时回滚整个事务
    • 影响行数检查,确保操作成功执行

使用示例:

// 保存多个对象(自动使用事务)
user1 := &User{Name: "user1", Age: 20}
user2 := &User{Name: "user2", Age: 25}
result, err := db.Chain().
    Table("users").
    Save(user1, user2)

// 更新多个不同类型的对象(自动使用事务)
type UserRole struct {
    Role string `gom:"role"`
}
type UserStatus struct {
    Active bool `gom:"active"`
}
role := &UserRole{Role: "admin"}
status := &UserStatus{Active: true}
result, err = db.Chain().
    Table("users").
    Eq("id", 1).
    Update(role, status)

// 删除多个对象(自动使用事务)
result, err = db.Chain().
    Table("users").
    Delete(user1, user2)
v4.0.9-ai (2024-01-02 22:00 UTC+8)

新特性:

  • 增强 Update 方法
    • 支持传入不定长结构体参数
    • 支持不同类型的结构体更新
    • 每个结构体独立执行更新
    • 自动解析非空字段
    • 自动排除主键字段

使用示例:

// 使用完整结构体更新
updateUser := &User{
    Username: "new_name",
    Email:    "new@example.com",
}
result1, err := db.Chain().
    Table("users").
    Eq("id", 1).
    Update(updateUser)

// 使用不同类型的结构体更新
type UserRole struct {
    Role string `gom:"role"`
}
type UserStatus struct {
    Active    bool      `gom:"active"`
    UpdatedAt time.Time `gom:"updated_at"`
}

// 分别更新角色和状态
updateRole := &UserRole{Role: "admin"}
updateStatus := &UserStatus{
    Active:    true,
    UpdatedAt: time.Now(),
}
result2, err := db.Chain().
    Table("users").
    Eq("id", 1).
    Update(updateRole, updateStatus)
v4.0.8-ai (2024-01-02 21:50 UTC+8)

新特性:

  • 添加 GetTableName 方法
    • 支持从结构体获取表名
    • 支持自定义表名接口
    • 自动处理命名转换(驼峰转蛇形)
    • 严格的类型检查
    • 返回错误信息

更新:

  • 更新 MySQL 驱动到 v1.8.1
  • 移除 lib/pq 依赖,使用 pgx 作为 PostgreSQL 驱动
  • 优化代码生成器的数据库连接
v4.0.6-ai (2024-01-02 21:35 UTC+8)

新特性:

  • 添加分页查询方法
    • PageInfo(model): 支持模型和原始数据的分页查询
    • 提供完整的分页信息(总数、页数、导航等)
  • 支持与现有查询方法完美集成
  • 支持自动处理默认值和边界情况
v4.0.5-ai (2024-01-02 21:27 UTC+8)

新特性:

  • 添加统计相关方法
    • Count(): 计算记录总数
    • Sum(field): 计算字段总和
    • Avg(field): 计算字段平均值
  • 所有统计方法支持条件过滤
  • 优化了 NULL 值和空结果集的处理

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Chain

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

Chain represents the base chain structure

func (*Chain) Avg added in v4.1.3

func (c *Chain) Avg(field string) (float64, error)

Avg calculates the average of a specific field

func (*Chain) BatchValues

func (c *Chain) BatchValues(values []map[string]interface{}) *Chain

BatchValues sets batch insert values

func (*Chain) Begin

func (c *Chain) Begin() error

Begin starts a new transaction with optional isolation level

func (*Chain) Between added in v4.1.3

func (c *Chain) Between(field string, start, end interface{}) *Chain

Between adds a BETWEEN condition

func (*Chain) Commit

func (c *Chain) Commit() error

Commit commits the transaction

func (*Chain) Count added in v4.1.3

func (c *Chain) Count() (int64, error)

Count returns the count of records

func (*Chain) Count2 added in v4.1.3

func (c *Chain) Count2(field string) (int64, error)

Count2 returns the count of specified field

func (*Chain) CreateTable

func (c *Chain) CreateTable(model interface{}) error

CreateTable creates a table based on the model struct

func (*Chain) Delete

func (c *Chain) Delete(models ...interface{}) (sql.Result, error)

Delete executes a DELETE query

func (*Chain) Eq added in v4.1.3

func (c *Chain) Eq(field string, value interface{}) *Chain

Eq adds an equals condition

func (*Chain) Fields

func (c *Chain) Fields(fields ...string) *Chain

Fields sets the fields to select

func (*Chain) First

func (c *Chain) First(dest ...interface{}) *QueryResult

First returns the first result

func (*Chain) From

func (c *Chain) From(model interface{}) *Chain

From sets the table name and conditions from a struct or string

func (*Chain) Ge added in v4.1.3

func (c *Chain) Ge(field string, value interface{}) *Chain

Ge adds a greater than or equal condition

func (*Chain) Gt added in v4.1.3

func (c *Chain) Gt(field string, value interface{}) *Chain

Gt adds a greater than condition

func (*Chain) In added in v4.1.3

func (c *Chain) In(field string, value interface{}) *Chain

In adds an IN condition

func (*Chain) Into

func (c *Chain) Into(dest interface{}) error

Into scans the result into a struct or slice of structs

func (*Chain) IsInTransaction

func (c *Chain) IsInTransaction() bool

IsInTransaction returns whether the chain is currently in a transaction

func (*Chain) IsNotNull added in v4.1.3

func (c *Chain) IsNotNull(field string) *Chain

IsNotNull adds an IS NOT NULL condition

func (*Chain) IsNull added in v4.1.3

func (c *Chain) IsNull(field string) *Chain

IsNull adds an IS NULL condition

func (*Chain) Le added in v4.1.3

func (c *Chain) Le(field string, value interface{}) *Chain

Le adds a less than or equal condition

func (*Chain) Like added in v4.1.3

func (c *Chain) Like(field string, value interface{}) *Chain

Like adds a LIKE condition

func (*Chain) Limit

func (c *Chain) Limit(count int) *Chain

Limit sets the limit count

func (*Chain) List

func (c *Chain) List(dest ...interface{}) *QueryResult

List executes a SELECT query and returns all results

func (*Chain) Lt added in v4.1.3

func (c *Chain) Lt(field string, value interface{}) *Chain

Lt adds a less than condition

func (*Chain) Ne added in v4.1.3

func (c *Chain) Ne(field string, value interface{}) *Chain

Ne adds a not equals condition

func (*Chain) NewCondition added in v4.1.3

func (c *Chain) NewCondition() *define.Condition

NewCondition creates a new condition with AND join type

func (*Chain) NotBetween added in v4.1.3

func (c *Chain) NotBetween(field string, start, end interface{}) *Chain

NotBetween adds a NOT BETWEEN condition

func (*Chain) NotIn added in v4.1.3

func (c *Chain) NotIn(field string, value interface{}) *Chain

NotIn adds a NOT IN condition

func (*Chain) NotLike added in v4.1.3

func (c *Chain) NotLike(field string, value interface{}) *Chain

NotLike adds a NOT LIKE condition

func (*Chain) Offset

func (c *Chain) Offset(count int) *Chain

Offset sets the offset count

func (*Chain) One

func (c *Chain) One(dest ...interface{}) *QueryResult

One returns exactly one result

func (*Chain) OrBetween added in v4.1.3

func (c *Chain) OrBetween(field string, start, end interface{}) *Chain

OrBetween adds an OR BETWEEN condition

func (*Chain) OrEq added in v4.1.3

func (c *Chain) OrEq(field string, value interface{}) *Chain

OrEq adds an OR equals condition

func (*Chain) OrGe added in v4.1.3

func (c *Chain) OrGe(field string, value interface{}) *Chain

OrGe adds an OR greater than or equal condition

func (*Chain) OrGt added in v4.1.3

func (c *Chain) OrGt(field string, value interface{}) *Chain

OrGt adds an OR greater than condition

func (*Chain) OrIn added in v4.1.3

func (c *Chain) OrIn(field string, value interface{}) *Chain

OrIn adds an OR IN condition

func (*Chain) OrIsNotNull added in v4.1.3

func (c *Chain) OrIsNotNull(field string) *Chain

OrIsNotNull adds an OR IS NOT NULL condition

func (*Chain) OrIsNull added in v4.1.3

func (c *Chain) OrIsNull(field string) *Chain

OrIsNull adds an OR IS NULL condition

func (*Chain) OrLe added in v4.1.3

func (c *Chain) OrLe(field string, value interface{}) *Chain

OrLe adds an OR less than or equal condition

func (*Chain) OrLike added in v4.1.3

func (c *Chain) OrLike(field string, value interface{}) *Chain

OrLike adds an OR LIKE condition

func (*Chain) OrLt added in v4.1.3

func (c *Chain) OrLt(field string, value interface{}) *Chain

OrLt adds an OR less than condition

func (*Chain) OrNe added in v4.1.3

func (c *Chain) OrNe(field string, value interface{}) *Chain

OrNe adds an OR not equals condition

func (*Chain) OrNotBetween added in v4.1.3

func (c *Chain) OrNotBetween(field string, start, end interface{}) *Chain

OrNotBetween adds an OR NOT BETWEEN condition

func (*Chain) OrNotIn added in v4.1.3

func (c *Chain) OrNotIn(field string, value interface{}) *Chain

OrNotIn adds an OR NOT IN condition

func (*Chain) OrNotLike added in v4.1.3

func (c *Chain) OrNotLike(field string, value interface{}) *Chain

OrNotLike adds an OR NOT LIKE condition

func (*Chain) OrWhereGroup added in v4.1.3

func (c *Chain) OrWhereGroup() *define.Condition

OrWhereGroup starts a new condition group with OR join type

func (*Chain) OrderBy

func (c *Chain) OrderBy(field string) *Chain

OrderBy adds an ascending order by clause

func (*Chain) OrderByDesc

func (c *Chain) OrderByDesc(field string) *Chain

OrderByDesc adds a descending order by clause

func (*Chain) Page

func (c *Chain) Page(pageNum, pageSize int) *Chain

Page sets the page number and page size for pagination

func (*Chain) PageInfo added in v4.1.3

func (c *Chain) PageInfo(model interface{}) (*PageInfo, error)

PageInfo executes a paginated query and returns pagination information

func (*Chain) RawExecute

func (c *Chain) RawExecute(sql string, args ...interface{}) (sql.Result, error)

RawExecute executes a raw SQL statement with args

func (*Chain) RawQuery

func (c *Chain) RawQuery(sqlStr string, args ...interface{}) *QueryResult

RawQuery executes a raw SQL query

func (*Chain) ReleaseSavepoint

func (c *Chain) ReleaseSavepoint(name string) error

ReleaseSavepoint releases the specified savepoint

func (*Chain) Rollback

func (c *Chain) Rollback() error

Rollback rolls back the transaction

func (*Chain) RollbackTo

func (c *Chain) RollbackTo(name string) error

RollbackTo rolls back to the specified savepoint

func (*Chain) Save

func (c *Chain) Save(models ...interface{}) (define.Result, error)

Save executes an INSERT or UPDATE query

func (*Chain) Savepoint

func (c *Chain) Savepoint(name string) error

Savepoint creates a savepoint with the given name

func (*Chain) Set

func (c *Chain) Set(field string, value interface{}) *Chain

Set sets update fields

func (*Chain) SetIsolationLevel

func (c *Chain) SetIsolationLevel(level sql.IsolationLevel) *Chain

SetIsolationLevel sets the isolation level for the next transaction

func (*Chain) Sum added in v4.1.3

func (c *Chain) Sum(field string) (float64, error)

Sum calculates the sum of a specific field

func (*Chain) Table

func (c *Chain) Table(table string) *Chain

Table sets the table name for the chain

func (*Chain) Transaction

func (c *Chain) Transaction(fn func(*Chain) error) error

Transaction executes a function within a transaction

func (*Chain) Update

func (c *Chain) Update(models ...interface{}) (sql.Result, error)

Update executes an UPDATE query

func (*Chain) Values

func (c *Chain) Values(fields map[string]interface{}) *Chain

Values sets insert fields

func (*Chain) Where

func (c *Chain) Where(field string, op define.OpType, value interface{}) *Chain

Where adds a where condition with custom operator

func (*Chain) Where2 added in v4.1.3

func (c *Chain) Where2(cond *define.Condition) *Chain

Where2 adds a condition directly

func (*Chain) WhereGroup added in v4.1.3

func (c *Chain) WhereGroup() *define.Condition

WhereGroup starts a new condition group with AND join type

type DB

type DB struct {
	DB        *sql.DB
	Factory   define.SQLFactory
	RoutineID int64
}

DB represents the database connection

func MustOpen

func MustOpen(driverName, dsn string) *DB

MustOpen creates a new DB connection and panics on error

func Open

func Open(driverName, dsn string, debug bool) (*DB, error)

Open creates a new DB connection with debug option

func (*DB) Chain

func (db *DB) Chain() *Chain

Chain starts a new chain

func (*DB) Close

func (db *DB) Close() error

Close closes the database connection

func (*DB) GenerateStruct

func (db *DB) GenerateStruct(tableName, outputDir, packageName string) error

GenerateStruct 生成单个表的结构体代码

func (*DB) GenerateStructs

func (db *DB) GenerateStructs(opts GenerateOptions) error

GenerateStructs 批量生成表的结构体代码

func (*DB) GetTableInfo

func (db *DB) GetTableInfo(tableName string) (*define.TableInfo, error)

GetTableInfo 获取表信息

func (*DB) GetTableName added in v4.1.3

func (db *DB) GetTableName(model interface{}) (string, error)

GetTableName 获取结构体对应的表名

func (*DB) GetTables

func (db *DB) GetTables(pattern string) ([]string, error)

GetTables 获取符合模式的所有表

type GenerateOptions

type GenerateOptions struct {
	OutputDir   string // 输出目录
	PackageName string // 包名
	Pattern     string // 表名匹配模式
}

GenerateOptions 代码生成选项

type PageInfo added in v4.1.3

type PageInfo struct {
	PageNum     int         `json:"pageNum"`     // 当前页码
	PageSize    int         `json:"pageSize"`    // 每页大小
	Total       int64       `json:"total"`       // 总记录数
	Pages       int         `json:"pages"`       // 总页数
	HasPrev     bool        `json:"hasPrev"`     // 是否有上一页
	HasNext     bool        `json:"hasNext"`     // 是否有下一页
	List        interface{} `json:"list"`        // 当前页数据
	IsFirstPage bool        `json:"isFirstPage"` // 是否是第一页
	IsLastPage  bool        `json:"isLastPage"`  // 是否是最后页
}

PageInfo represents pagination information

type QueryResult

type QueryResult struct {
	Data    []map[string]interface{} `json:"data"`
	Columns []string                 `json:"columns"`
	// contains filtered or unexported fields
}

QueryResult represents a query result

func (*QueryResult) Empty

func (qr *QueryResult) Empty() bool

Empty returns true if the result is empty

func (*QueryResult) Error

func (qr *QueryResult) Error() error

Error returns the error if any

func (*QueryResult) First

func (qr *QueryResult) First() *QueryResult

First returns the first result or error if no results

func (*QueryResult) Into

func (qr *QueryResult) Into(dest interface{}) error

Into scans the result into a slice of structs

func (*QueryResult) Size

func (qr *QueryResult) Size() int

Size returns the number of rows in the result

Directories

Path Synopsis
factory

Jump to

Keyboard shortcuts

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