ilibs / gosql Goto Github PK
View Code? Open in Web Editor NEW🐥The very simple ORM library for Golang
License: MIT License
🐥The very simple ORM library for Golang
License: MIT License
资询个问题:
mysql 表字字段是大写, 比如 COL_NAME
结构定义为
type def struct{
ColName string `db:"col_name"`
}
这样查询是空的,大小写不匹配, 有没有类似这样 `db:"col_name";lowercase:true`用法?
你好,这种查询能支持分表吗?
rows := make([]*models.TopicInfo, 0)
_ = gosql.Model(&rows).Where("uid=? ", uid).OrderBy("id DESC").Limit(20).All()
result, err := b.db.Exec(b.updateString(m), b.args...)
err:
Query: UPDATE user
SET updated_at
=? WHERE (id in (?));
Args: []interface {}{1617872905, []int64{413}}
Error: sql: converting argument $2 type: unsupported type []int64, a slice of int64
我使用gosql+echo做接口,配置了标题内的两个关键字,但在返回结果中没有起任何作用,想请问这两个关键字的作用是什么,谢谢!
查询只能映射到结构体吗 ,能映射到map吗
是这样的,我现在线上有一个需求是,默认的情况下,不显示sql语句,但是比如线上出了问题,我需要在不重启服务的情况下修改我本地的配置文件,监听配置文件变化改变你的showsql为true,监听本地配置文件变化,并获取新的配置文件我用的viper 这个配置库,所以能不能对外提供一个主动设置showsql的方法?
package main
import (
"fmt"
_ "github.com/go-sql-driver/mysql" //mysql driver
"github.com/ilibs/gosql/v2"
"os"
)
func main() {
configs := make(map[string]*gosql.Config)
configs["default"] = &gosql.Config{
Enable: true,
Driver: "mysql",
Dsn: "root:321@@tcp(127.0.0.1:3306)/soulma?charset=utf8mb4&parseTime=True&loc=Asia%2FShanghai",
ShowSql: true,
}
configs["db2"] = &gosql.Config{
Enable: true,
Driver: "mysql",
Dsn: "root:123@@tcp(127.0.0.1:3306)/soulmb?charset=utf8mb4&parseTime=True&loc=Asia%2FShanghai",
ShowSql: true,
}
//connection database
if err := gosql.Connect(configs); err != nil {
fmt.Println(err.Error())
os.Exit(0)
}
type UserList struct {
UID int `db:"Pid"`
}
user := UserList{}
rows := gosql.Use("db2").QueryRowx("SELECT * FROM user_list WHERE pid = 1333;")
gosql.Begin()
// `木有gosql.Commit这函数`
gosql.Begin()
gosql.Use("db2").Commit() // `这里有Commit函数`
fmt.Println(rows.Err(),user)
}
有时候跑着跑着, 查询数据库就卡死了,必须重启服务才可以
不知道是否是MySQL自动断开连接导致的
当主键维uint64时候, 原本代码在反射情况下会直接崩掉, 因为v.SetInt里面没有对Uint类型的支持, 需要修改为如下代码才行
在util.go下 107行开始
// fillPrimaryKey is created fill primary key
func fillPrimaryKey(v reflect.Value, value int64) {
v = reflect.Indirect(v)
if v.IsValid() {
switch v.Kind() {
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
v.SetInt(value)
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
v.SetUint(uint64(value))
}
}
}
注意到你新增加的钩子函数,为什么没有BeforeFind呀
在config.go
里面
MaxLifetime int
yml:"max_lefttime" toml:"max_lefttime" json:"max_lefttime"
这个英文你写错成lefttime
了, 应该是lifetime
错误信息:
Query: SELECT * FROM "pwdinfo" WHERE (password=?);
Args: []interface {}{"123"}
Error: pq: 操作符不存在: character varying =?
Time: 1.02744s
源码:
pwd:=c.QueryParam("pwd") pwdinfo:= &models.Pwdinfo{} err:= gosql.Model(pwdinfo).Where("password=?",pwd).Get() if err!=nil{ log.Println(err.Error()) }
有个需求是,创建时间和成功时间,在创建的时候成功时间是可以为空的,设置表的模型为
由于我的时间类型是为字符串,所以我设置了 sql.NullString
SuccessTime sql.NullString db:"success_time" json:"success_time"
// 成功时间
但是在插入的时候,你的sql语句出现了 多个字段 应该是解析的时候出了问题
success_time
,success_time.String
,success_time.Valid
你好,用你这个gosql 有时候回出现db 错误 错误是: invalid connection 好像是连接池的某个链接被关闭了
找到原因了:
在使用go-sql-driver过程中,有时候我发现会报invalid connection的错误,这个错误产生的原因设置了空闲连接不为0时,客户端拿到连接有可能是已经被服务端关闭了,此时就会发生invalid connection,网上有些解决方案是把空闲连接数设置0,不知道设置为0跟设置为50之类的性能有什么大的区别吗?跪求大神解答!
当然这是因为服务端主动关闭了连接,因为服务端对连接的保持超时时间到了也关闭的,所以可以设置客户端连接超时时间小于服务端DB.SetConnMaxLifetime(time.Second)
https://www.studygolang.com/topics/5576
你能不能框架 修复一下这个问题 默认配置一下
sess.SetMaxOpenConns(conf.MaxOpenConns)
sess.SetMaxIdleConns(conf.MaxIdleConns)
sess.SetConnMaxLifetime(conf.MaxLifetime)
type Config struct {
Enable bool json:"enable"
Driver string json:"driver"
Dsn string json:"dsn"
MaxOpenConns int toml:"max_open_conns" json:"max_open_conns"
MaxIdleConns int toml:"max_idle_conns" json:"max_idle_conns"
MaxLifetime int toml:"max_lifetime" json:"max_lifetime"
ShowSql bool toml:"show_sql" json:"show_sql"
}
hi gosql.exec 不支持字段内容为空吗?
currTime := time.Now().Format("2006-01-02 15:04:05")
_, err := gosql.Exec("update man_Task set tsk_state = %d, tsk_lasttime = '%s', tsk_nexttime = '%s' where tsk_Taskid= %d",
TASKRUNING_STATE, currTime, "", 12)
szSql := fmt.Sprintf("update man_Task set tsk_state = %d, tsk_lasttime = '%s', tsk_nexttime = '%s' where tsk_Taskid= %d",
TASKRUNING_STATE, currTime, “”, 12)
_, err := gosql.Exec(szSql)
这里可以正常执行
Originally posted by @dawei101 in #28 (comment)
where里面的in操作只支持[]int类型, 目前不支持[]string类型, 希望能支持[]string类型, 或者增加一个方法如下:
在使用IN(?)时候调用
result := make([]ThreadStatus, 0)
_ = gosql.Select(&result,"show global status")
have a case like that
before insert into table A ,i need select count(x) as sum from tableA .
if sum < Y ,then insert .
so i want to have a table lock before count
模型能不能提供一个设置表名的方法,支持一下分表?
在进行模型查询时,能不能提供一个方法改变model内的tablename,用于分表操作?
如gosql.Use(db).Model(&Users{}}).Table("user_100").Get() 这样?
I think this library looks great, but unfortunately I can't use it because it has to much forced output.
I can't find any way to suppress the "[db] connect:default" to stderr, and I need it to be silent so I can handle logging my own way.
I would appreciate if if you didn't assuming I want logging to stderr and returned messages in a way that I could handle them the way I want instead.
gosql怎么支持读写分离呢,我注意到db链接是可以配置多个的,如何切换呢?
有没有文档或是完整的demo
比如
select * from user where id = #{id}
或者
select * from user where id = :id
这种命名参数的方式么?
``
configs["default"] = &gosql.Config{
Enable: true,
Driver: "postgres",
Dsn: "...",
ShowSql: true,
}
err = gosql.Connect(configs)
_, err = gosql.Table("users").Create(map[string]interface{}{
"username": username,
"status": 1,
})
the log
Query: INSERT INTO users
(,status
,username
) VALUES(?,?);
Args: []interface {}{ 1, "test12345"}
Error: pq: syntax error at or near "`"
Time: 0.00698s
``
在使用多库操作时,我使用下面操作管理端数据库,操作更新时,出现错误,无法找到对应的库名进行操作
model := &models.Report{}
data := make(map[string]interface{}, 0)
data["create_time"] = "2018-09-18 12:00:00"
gosql.Use("admin").Table(model.TableName()).Where("from_uid=? AND to_uid=? ", 1, 2).Update(data)
如果实现 update table set num=num+1 where id=1 功能?
我今天用了,字段里面有created_at还有updated_at
在win下调试,然后插入进去的是UTC时间,比正常时间少8小时,这个怎么调整?
gosql.Exec("insert into users(name,email,created_at,updated_at) value(?,?,?,?)","test","[email protected]",time.Now(),time.Now())
通过这个语句 会创建出两条数据, 一条是空数据,一条是完整的
我写了一个db反射的工具,已经适应gosql了,可以用上哈, 能支持postrges和mysql读取
github.com/athanxx/dbtag
已经适应gosql的IModel结构, 支持xorm,gorm和任何的tag生成
还能自动生成脚本,方便下次使用
// Logger represents a logging collector. You can pass a logging collector to
// gosql.SetLogger(myCollector) to make it collect QueryStatus messages
// after executing a query.
type Logger interface {
Printf(format string, v ...interface{})
}
Maybe we shoud change this interface to:
type Logger interface {
Printf(ctx context.Context, format string, v ...interface{})
}
I need to get DB.database member for set db config properties:
db.SetMaxOpenConns(10)
db.SetMaxIdleConns(4)
Can not do this now, add a Func to return internal member DB.database please.
I love this library so much, it's simple yet powerful.
It could even be better if it support "in query" in where method.
for example:
users := make([]*User, 0)
gosql.Model(&user).Where("id in (?)", []int{1, 2, 3}).All()
postgresDialect count add every query times
it's should be set to 1
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.