gom

package module
v4.0.3-ai Latest Latest
Warning

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

Go to latest
Published: Dec 26, 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

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) 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) Commit

func (c *Chain) Commit() error

Commit commits the transaction

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() (sql.Result, error)

Delete executes a DELETE query

func (*Chain) Fields

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

Fields sets the fields to select

func (*Chain) First

func (c *Chain) First() *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) 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) Last

func (c *Chain) Last() *QueryResult

Last returns the last result

func (*Chain) Limit

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

Limit sets the limit count

func (*Chain) List

func (c *Chain) List() *QueryResult

List executes a SELECT query and returns all results

func (*Chain) Offset

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

Offset sets the offset count

func (*Chain) One

func (c *Chain) One() *QueryResult

One returns exactly one result

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) 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() (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) 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() (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 string, value interface{}) *Chain

Where adds a where condition

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) GetTables

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

GetTables 获取符合模式的所有表

type GenerateOptions

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

GenerateOptions 代码生成选项

type OrderBy

type OrderBy struct {
	Field string
	Type  OrderType
}

OrderBy represents an order by clause

type OrderType

type OrderType int

OrderType represents the type of ordering

const (
	OrderAsc  OrderType = iota // Ascending order
	OrderDesc                  // Descending order
)

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