morm

package module
v0.6.4 Latest Latest
Warning

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

Go to latest
Published: Dec 20, 2025 License: Apache-2.0 Imports: 10 Imported by: 0

README

Morm

English Version

混合ORM(Mixed orm),配置数据源源即可轻松访问不同类型的数据库,目前支持mysqlmongodbsqlite,底层使用gormmongo-driver实现。

配置文件使用viper进行解析

zread

通过配置结构体初始化

除了使用配置文件初始化ORM外,还可以通过DBConfig结构体直接初始化ORM:

package main

import (
	"github.com/lfhy/morm"
	"github.com/lfhy/morm/conf"
)

func main() {
	// 通过结构体配置初始化
	dbConfig := &conf.DBConfig{
		Type: "sqlite",
		LogConfig: &conf.LogConfig{
			Log:      "./db.log",
			LogLevel: "4",
		},
		SQLiteConfig: &conf.SQLiteConfig{
			AutoCreateTable: true,
			FilePath:        "./test.db",
			ConnMaxLifetime: "1h",
			MaxIdleConns:    "10",
			MaxOpenConns:    "100",
		},
	}

	// 使用配置结构体初始化ORM
	orm := morm.InitWithDBConfig(dbConfig)
	
	// 后续使用ORM进行数据库操作...
}

配置文件参考

[db]
log = './db.log'    # 日志文件路径
loglevel = '4'  # 日志等级 
type = 'mysql' # 默认orm类型

[mongodb]
# mongodb连接的数据库
database = 'testorm'    
# 连接池大小
option_pool_size = '200'   
# mongodb代理连接方法
proxy = 'socks5://127.0.0.1:7890'  
# mongodb连接uri mongodb://[认证用户名]:[认证密码]@[连接地址]/[额外参数]
uri = 'mongodb://mgouser:mgopass@127.0.0.1:27027/?authSource=admin' 

[mysql]
# mysql连接数据库
database = 'testorm'
# 数据库编码
charset = 'utf8mb4'
# 连接最大生命时间
conn_max_lifetime = '1h'
# mysql连接主机
host = '127.0.0.1'
# mysql连接端口
port = '3306'
# 最大空闲连接数
max_idle_conns = '10'
# 最大连接数
max_open_conns = '100'
# mysql认证用户
user = 'orm'
# mysql认证密码
password = 'password'

[sqlite]
# sqlite数据库文件路径
file_path = './data.db'
# 连接最大生命时间
conn_max_lifetime = '1h'
# 最大空闲连接数
max_idle_conns = '10'
# 最大连接数
max_open_conns = '100'

配置文件读取使用了viper,所以支持多种配置文件格式,如jsonyamltomlini等,详情请参考viper文档。

也可以直接传入viper实例进行读取。

使用案例

package main

import (
	"fmt"

	"github.com/lfhy/morm"
)

// 数据库结构体
// 如果数据在mongo需要按mongo-driver进行标注
// 在其他gorm的(mysql,sqlite)按gorm进行标注
type DBSturct struct {
	ID   string `bson:"_id" gorm:"id"`
	Name string `bson:"name" gorm:"name"`
}

// 表名或集合名
func (DBSturct) TableName() string {
	return "dbtable"
}

func main() {
	// 初始化配置文件
	configPath := "/path/to/config.toml"
	err := morm.InitORMConfig(configPath)
	if err != nil {
		fmt.Printf("配置文件加载错误:%v\n", err)
		panic(err)
	}
	// 使用自定义日志:db.SetLogger
	// 数据库初始化
	// 也可以自己处理错误
	// orm, err := morm.InitWithError(configPath)
	// 也可以直接传入配置文件
	// orm := morm.Init(configPath)
	// 如果已经用viper解析了,那也可以使用对应的配置实例 morm.UseViperConfig(viperConfig)
	orm := morm.Init()

	// 创建查询
	var db DBSturct
	db.ID = "123"

	err = orm.Model(&db).Find().One(&db)
	if err != nil {
		fmt.Printf("查询失败:%v\n", err)
		return
	}
	fmt.Printf("查询结果:%+v\n", db)
}

TODO

  • 添加测试案例

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	ListOptionAll     = types.ListOptionAll
	ListOptionDefault = types.ListOptionDefault
)
View Source
var (
	OrderDirAsc  = types.OrderDirAsc
	OrderDirDesc = types.OrderDirDesc
	Asc          = types.OrderDirAsc
	Desc         = types.OrderDirDesc
)

Functions

func All added in v0.4.5

func All[T any](baseModel BaseModel, where ...any) ([]*T, error)

获取多个 Where 可以是函数,也可以是Model

func Create added in v0.4.5

func Create(baseModel BaseModel) error

创建

func Delete added in v0.4.5

func Delete(baseModel BaseModel, where any) error

删除 Where 可以是函数,也可以是Model

func GetConfig added in v0.3.1

func GetConfig() *viper.Viper

获取当前viper配置实例

func GetDBLoger added in v0.6.3

func GetDBLoger() logger.Interface

func InitDBLoger added in v0.0.4

func InitDBLoger() logger.Interface

func InitORMConfig added in v0.0.2

func InitORMConfig(configFilePath string) (err error)

初始化orm配置文件

func Insert added in v0.5.6

func Insert(baseModel BaseModel) (id string, err error)

创建并返回ID

func List added in v0.4.5

func List[T BaseModel, ListFn func(m T) bool | func(m T) | func(m T) error](base T, ctx *ListOption, where any, listFn ListFn) int64

List 分页查询 Where 可以是函数,也可以是Model

func One added in v0.4.5

func One[T any](baseModel BaseModel, where ...any) (*T, error)

获取单个 Where 可以是函数,也可以是Model

func SetDBLoger added in v0.6.3

func SetDBLoger(l logger.Interface)

func Update added in v0.4.5

func Update(baseModel BaseModel, where any, update any) error

更新 Where 可以是函数,也可以是Model update 为Model对象

func Upsert added in v0.4.5

func Upsert(baseModel BaseModel, where any, update any) error

更新或插入 Where 可以是函数,也可以是Model update 为Model对象

func UseViperConfig added in v0.3.1

func UseViperConfig(config *viper.Viper)

设置viper配置

Types

type BaseModel added in v0.4.5

type BaseModel interface {
	M() Model
	TableName() string
}

type BoolORM

type BoolORM = types.BoolORM

为了避免识别错误设置Bool类型为int类型

const (
	BoolORMTrue  BoolORM = 1
	BoolORMFalse BoolORM = -1
	// 空字符串
	EmptyStr = "-"
)

type BulkWriteOperation added in v0.1.9

type BulkWriteOperation = types.BulkWriteOperation

type DBConfig added in v0.3.5

type DBConfig = conf.DBConfig

type ListOption added in v0.4.5

type ListOption = types.ListOption

type LogConfig added in v0.5.7

type LogConfig = conf.LogConfig

type LogLevel added in v0.4.8

type LogLevel = types.LogLevel
const (
	LogLevelSilent LogLevel = iota + 1
	LogLevelError
	LogLevelWarn
	LogLevelInfo
)

type Model added in v0.4.5

type Model = types.ORMModel

type MongoBulkWriteOperation added in v0.1.9

type MongoBulkWriteOperation = types.MongoBulkWriteOperation

type MongoDBConfig added in v0.3.5

type MongoDBConfig = conf.MongoDBConfig

type MySQLConfig added in v0.3.5

type MySQLConfig = conf.MySQLConfig

type ORM

type ORM = types.ORM

func Init added in v0.0.2

func Init(configPath ...string) ORM

初始化ORM连接(带错误panic)

func InitMongoDB added in v0.0.2

func InitMongoDB(configPath ...string) ORM

初始化MongoDB连接(带错误panic)

func InitMongoDBWithDBConfig added in v0.3.5

func InitMongoDBWithDBConfig(config *MongoDBConfig) ORM

func InitMongoDBWithDBConfigWithError added in v0.3.5

func InitMongoDBWithDBConfigWithError(config *MongoDBConfig) (ORM, error)

func InitMongoDBWithError added in v0.3.1

func InitMongoDBWithError(configPath ...string) (ORM, error)

初始化MongoDB连接(返回错误)

func InitMySQL added in v0.0.2

func InitMySQL(configPath ...string) ORM

初始化MySQL连接(带错误panic)

func InitMySQLWithDBConfig added in v0.3.5

func InitMySQLWithDBConfig(config *MySQLConfig) ORM

使用配置结构体初始化MySQL

func InitMySQLWithDBConfigWithError added in v0.3.5

func InitMySQLWithDBConfigWithError(config *MySQLConfig) (ORM, error)

使用配置结构体初始化MySQL

func InitMySQLWithError added in v0.3.1

func InitMySQLWithError(configPath ...string) (ORM, error)

初始化MySQL连接(返回错误)

func InitSQLite added in v0.1.0

func InitSQLite(configPath ...string) ORM

初始化SQLite连接(带错误panic)

func InitSQLiteWithDBConfig added in v0.3.5

func InitSQLiteWithDBConfig(config *SQLiteConfig) ORM

使用配置结构体初始化SQLite

func InitSQLiteWithDBConfigWithError added in v0.3.5

func InitSQLiteWithDBConfigWithError(config *SQLiteConfig) (ORM, error)

使用配置结构体初始化SQLite

func InitSQLiteWithError added in v0.3.1

func InitSQLiteWithError(configPath ...string) (ORM, error)

初始化SQLite连接(返回错误)

func InitWithDBConfig added in v0.3.5

func InitWithDBConfig(config *DBConfig) ORM

使用配置结构体初始化

func InitWithDBConfigWithError added in v0.3.5

func InitWithDBConfigWithError(config *DBConfig) (ORM, error)

使用配置结构体初始化

func InitWithError added in v0.3.1

func InitWithError(configPath ...string) (ORM, error)

初始化ORM连接(返回错误)

type ORMModel

type ORMModel = types.ORMModel

type ORMQuery added in v0.5.2

type ORMQuery = types.ORMQuery

type OrderDir added in v0.4.9

type OrderDir = types.OrderDir

type SQLiteConfig added in v0.3.5

type SQLiteConfig = conf.SQLiteConfig

type Session added in v0.3.7

type Session = types.Session

type Sort added in v0.4.9

type Sort = types.Sort

Directories

Path Synopsis
db
example
config command
curd command
curd-map command
cursor command
find command
fuzzy-search command
service command
sort command
sort-complexity command
sort-list command
transaction command
upsert command

Jump to

Keyboard shortcuts

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