gom

package module
v4.0.1-ai Latest Latest
Warning

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

Go to latest
Published: Dec 25, 2024 License: Apache-2.0 Imports: 11 Imported by: 3

README

GOM - Go ORM Made by Cursor

English | 中文

English

GOM is a lightweight and flexible ORM framework for Go, developed with guidance from Cursor - an AI-powered IDE. It provides an intuitive chain-style API for database operations and supports both MySQL and PostgreSQL.

Features
  • Chain-style API for fluent database operations
  • Support for MySQL and PostgreSQL
  • Automatic table creation from struct definitions
  • Custom table name and creation SQL through interfaces
  • Flexible query building with struct tags
  • Support for complex queries and relationships
  • Built-in pagination
  • Raw SQL execution capability
  • Debug mode for SQL logging
Installation
go get github.com/kmlixh/gom/v4
Quick Start
  1. Define your model:
type User struct {
    ID        int64     `gom:"id,@"`              // @ means auto-increment primary key
    Username  string    `gom:"username,unique,notnull"`
    Email     string    `gom:"email,unique,notnull"`
    Age       int       `gom:"age,notnull,default:18"`
    Active    bool      `gom:"active,notnull,default:true"`
    CreatedAt time.Time `gom:"created_at"`
    UpdatedAt time.Time `gom:"updated_at"`
}
  1. Connect to database:
db, err := gom.Open("postgres", "postgres://user:pass@localhost:5432/dbname?sslmode=disable", true)
if err != nil {
    log.Fatal(err)
}
defer db.Close()
  1. Create table:
err = db.Chain().CreateTable(&User{})
if err != nil {
    log.Fatal(err)
}
  1. Basic CRUD operations:
// Using struct
user := &User{
    Username: "john_doe",
    Email:    "john@example.com",
    Age:      30,
    Active:   true,
}
result, err := db.Chain().From(user).Save()

// Using table name directly
result, err := db.Chain().From("users").Where("age", ">", 25).List()

// Query
var users []User
queryResult, err := db.Chain().From(&User{}).Where("age", ">", 25).List()
err = queryResult.Into(&users)

// Update
_, err = db.Chain().From(&User{}).Set("age", 31).Where("id", "=", 1).Save()

// Delete
_, err = db.Chain().From(&User{}).Where("id", "=", 1).Delete()
Advanced Features
  1. Custom Table Model:
type CustomUser struct {
    ID       int64  `gom:"id,primaryAuto"`
    Username string `gom:"username,notnull"`
}

func (u *CustomUser) TableName() string {
    return "custom_users"
}

func (u *CustomUser) CreateSql() string {
    return `CREATE TABLE IF NOT EXISTS custom_users (...)`
}
  1. Complex Queries:
type UserQuery struct {
    MinAge   *int  `gom:"min_age"`
    MaxAge   *int  `gom:"max_age"`
    IsActive *bool `gom:"is_active"`
}

queryModel := &UserQuery{
    MinAge:   &minAge,
    IsActive: &isActive,
}
result, err := db.Chain().From(queryModel).List()
  1. Pagination:
result, err := db.Chain().From(&User{}).Page(1, 10).List()
  1. Raw SQL:
result, err := db.Chain().RawQuery("SELECT * FROM users WHERE age > $1", 25)
  1. Transaction Support:
// Method 1: Using Transaction callback (Recommended)
err := db.Chain().Transaction(func(chain *Chain) error {
    // Create user
    user := &User{
        Username: "john_doe",
        Email:    "john@example.com",
    }
    _, err := chain.From(user).Save()
    if err != nil {
        return err // Will automatically rollback
    }

    // Create profile
    profile := &UserProfile{
        UserID: user.ID,
        Bio:    "Software Engineer",
    }
    _, err = chain.From(profile).Save()
    if err != nil {
        return err // Will automatically rollback
    }

    return nil // Will automatically commit
})

// Method 2: Manual transaction control
chain := db.Chain()
err := chain.Begin()
if err != nil {
    log.Fatal(err)
}

// Perform operations within transaction
_, err = chain.From(user).Save()
if err != nil {
    chain.Rollback()
    return err
}

_, err = chain.From(profile).Save()
if err != nil {
    chain.Rollback()
    return err
}

// Commit the transaction
err = chain.Commit()
Contributing

This project was developed with guidance from Cursor, an AI-powered IDE. Contributions are welcome!

License

MIT License


中文

GOM 是一个轻量级且灵活的 Go ORM 框架,在 Cursor(一个 AI 驱动的 IDE)的指导下开发。它为数据库操作提供了直观的链式 API,并支持 MySQL 和 PostgreSQL。

特性
  • 链式 API,流畅的数据库操作
  • 支持 MySQL 和 PostgreSQL
  • 从结构体定义自动创建表
  • 通过接口自定义表名和创建 SQL
  • 使用结构体标签灵活构建查询
  • 支持复杂查询和关系
  • 内置分页功能
  • 原生 SQL 执行能力
  • 调试模式下的 SQL 日志
安装
go get github.com/kmlixh/gom/v4
快速开始
  1. 定义模型:
type User struct {
    ID        int64     `gom:"id,@"`              // @ 表示自增主键
    Username  string    `gom:"username,unique,notnull"`
    Email     string    `gom:"email,unique,notnull"`
    Age       int       `gom:"age,notnull,default:18"`
    Active    bool      `gom:"active,notnull,default:true"`
    CreatedAt time.Time `gom:"created_at"`
    UpdatedAt time.Time `gom:"updated_at"`
}
  1. 连接数据库:
db, err := gom.Open("postgres", "postgres://user:pass@localhost:5432/dbname?sslmode=disable", true)
if err != nil {
    log.Fatal(err)
}
defer db.Close()
  1. 创建表:
err = db.Chain().CreateTable(&User{})
if err != nil {
    log.Fatal(err)
}
  1. 基本的 CRUD 操作:
// 使用结构体
user := &User{
    Username: "john_doe",
    Email:    "john@example.com",
    Age:      30,
    Active:   true,
}
result, err := db.Chain().From(user).Save()

// 直接使用表名
result, err := db.Chain().From("users").Where("age", ">", 25).List()

// 查询
var users []User
queryResult, err := db.Chain().From(&User{}).Where("age", ">", 25).List()
err = queryResult.Into(&users)

// 更新
_, err = db.Chain().From(&User{}).Set("age", 31).Where("id", "=", 1).Save()

// 删除
_, err = db.Chain().From(&User{}).Where("id", "=", 1).Delete()
高级特性
  1. 自定义表模型:
type CustomUser struct {
    ID       int64  `gom:"id,primaryAuto"`
    Username string `gom:"username,notnull"`
}

func (u *CustomUser) TableName() string {
    return "custom_users"
}

func (u *CustomUser) CreateSql() string {
    return `CREATE TABLE IF NOT EXISTS custom_users (...)`
}
  1. 复杂查询:
type UserQuery struct {
    MinAge   *int  `gom:"min_age"`
    MaxAge   *int  `gom:"max_age"`
    IsActive *bool `gom:"is_active"`
}

queryModel := &UserQuery{
    MinAge:   &minAge,
    IsActive: &isActive,
}
result, err := db.Chain().From(queryModel).List()
  1. 分页:
result, err := db.Chain().From(&User{}).Page(1, 10).List()
  1. 原生 SQL:
result, err := db.Chain().RawQuery("SELECT * FROM users WHERE age > $1", 25)
  1. 事务支持:
// Method 1: Using Transaction callback (Recommended)
err := db.Chain().Transaction(func(chain *Chain) error {
    // Create user
    user := &User{
        Username: "john_doe",
        Email:    "john@example.com",
    }
    _, err := chain.From(user).Save()
    if err != nil {
        return err // Will automatically rollback
    }

    // Create profile
    profile := &UserProfile{
        UserID: user.ID,
        Bio:    "Software Engineer",
    }
    _, err = chain.From(profile).Save()
    if err != nil {
        return err // Will automatically rollback
    }

    return nil // Will automatically commit
})

// Method 2: Manual transaction control
chain := db.Chain()
err := chain.Begin()
if err != nil {
    log.Fatal(err)
}

// Perform operations within transaction
_, err = chain.From(user).Save()
if err != nil {
    chain.Rollback()
    return err
}

_, err = chain.From(profile).Save()
if err != nil {
    chain.Rollback()
    return err
}

// Commit the transaction
err = chain.Commit()
贡献

本项目在 Cursor(一个 AI 驱动的 IDE)的指导下开发。欢迎贡献!

许可证

Apache License 2.0

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, error)

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, error)

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, error)

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, error)

One returns exactly one result

func (*Chain) OrderBy

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

OrderBy sets the order by expression

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, error)

RawQuery executes a raw SQL query with args

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

type QueryResult

type QueryResult struct {
	Data    []map[string]interface{} `json:"data"`
	Columns []string                 `json:"columns"`
}

QueryResult represents a query result

func (*QueryResult) Empty

func (qr *QueryResult) Empty() bool

Empty returns true if the result is empty

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
mysql command
postgres command
factory

Jump to

Keyboard shortcuts

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