morm

package module
v0.0.4 Latest Latest
Warning

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

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

README

Morm

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

配置文件使用viper进行解析

配置文件参考

[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'

使用案例

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.Init()
	if err != nil {
		fmt.Printf("数据库初始化失败:%v\n", err)
		panic(err)
	}

	// 创建查询
	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

  • 支持sqlite
  • 添加测试案例

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Init added in v0.0.2

func Init() *orm.ORM

func InitDBLoger added in v0.0.4

func InitDBLoger() logger.Interface

func InitMongoDB added in v0.0.2

func InitMongoDB() *orm.ORM

func InitMySQL added in v0.0.2

func InitMySQL() *orm.ORM

func InitORMConfig added in v0.0.2

func InitORMConfig(configFilePath string) (err error)

初始化orm配置文件

Types

This section is empty.

Directories

Path Synopsis
db
example
find command

Jump to

Keyboard shortcuts

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