go-gorm / playground Goto Github PK
View Code? Open in Web Editor NEWGORM Playground (Please Create PR for this project to report issues)
License: MIT License
GORM Playground (Please Create PR for this project to report issues)
License: MIT License
I didn't write such business in the code:
ALTER TABLE 'mes mat main' MODIFY COLUMN 'mat code' varchar(50) NOT NULL COMMENT 'material code'
It seems to be executing automatically, resulting in locking the table
And the fields are of uniqueIndex or index unique type
I am trying to submit an issue, but for some reason it doesn't run the code:
Run GORM_DIALECT=sqlite ./test.sh
git clone --depth 1 -b
error: switch `b' requires a value
##[error]Process completed with exit code 129.
Hi, I want to search a value inside a jsonb that stored in PostgreSQL
Here the jsonb example inside the PostgreSQL:
[
{
"INFO": {
"DESCRIPTION": "lorem ipsum",
"BUYERS": [
{
"ID": 1,
"NAME": "John Doe"
},
{
"ID": 2,
"NAME": "Jane Doe"
}
]
}
},
{
"INFO": {
"DESCRIPTION": "lorem ipsum",
"BUYERS": [
{
"ID": 1,
"NAME": "John Doe"
},
{
"ID": 2,
"NAME": "Michael"
}
]
}
},
]
From the JSONB that stored in the PostgreSQL I want search the product by the buyers name if any of them are match.
So the PostgreSQL query that worked would be:
SELECT * FROM products WHERE info -> 'buyers' @> '[{"name": "Jane Doe"}]'
I have tried with GORM by using named arguments but it doesn't work:
result = db.Where("info-> 'buyers' @> '[{\"name\": @name}]'", map[string]interface{}{"name": request.body.name}).Find(&products)
Where I got error and the SQL query output like below:
SELECT * FROM "product" WHERE info-> 'buyers' @> '[{"name": @name}]'
ERROR: invalid input syntax for type json (SQLSTATE 22P02)
What I want is the product result that has buyer's name 'Jane Doe' based on the given search name, like this:
[
{
"INFO": {
"DESCRIPTION": "lorem ipsum",
"BUYERS": [
{
"ID": 1,
"NAME": "John Doe"
},
{
"ID": 2,
"NAME": "Jane Doe"
}
]
}
}
]
原来使用正常,版本为
gorm.io/gorm v1.23.8
gorm.io/driver/postgres v1.3.9
升级后
gorm.io/gorm v1.25.8
gorm.io/driver/postgres v1.5.7
问题一:无法通过map添加数据
error:LastInsertId is not supported by this driver,无法插入数据
以下为测试代码
package gorm
import (
"fmt"
"gorm.io/driver/postgres"
"gorm.io/gorm"
"testing"
)
func TestRun(t *testing.T) {
var source = `host=127.0.0.1 user=postgres password=postgres dbname=ztf_host port=5432 sslmode=disable`
//tdb, err := NewGorm(&models.DbConfig{
// DbType: models.DbType(1),
// Source: source,
//})
tdb, err := gorm.Open(postgres.Open(source), &gorm.Config{})
if err != nil {
return
}
var c int64
//dba := tdb.Table("test").Debug().Where(fmt.Sprintf(`%s =?`, "a"), "111")
//dba.Count(&c)
var newData = map[string]any{
"a": "222",
"id": "1",
}
err = tdb.Table("test").Debug().Create(&newData).Error
fmt.Println(err)
fmt.Println(c)
}
问题二:gorm如果有求数量操作的话,生成的更新语句错误
此时生成的sql为 update test set a='222' from test where a='111'
package gorm
import (
"fmt"
"gorm.io/driver/postgres"
"gorm.io/gorm"
"testing"
)
func TestRun(t *testing.T) {
var source = `host=127.0.0.1 user=postgres password=postgres dbname=ztf_host port=5432 sslmode=disable`
//tdb, err := NewGorm(&models.DbConfig{
// DbType: models.DbType(1),
// Source: source,
//})
tdb, err := gorm.Open(postgres.Open(source), &gorm.Config{})
if err != nil {
return
}
var c int64
dba := tdb.Table("test").Debug().Where(fmt.Sprintf(`%s =?`, "a"), "111")
dba.Count(&c)
var newData = map[string]any{
"a": "222",
}
err =dba.Updates(&newData).Error
fmt.Println(err)
fmt.Println(c)
}
./test.sh
git clone --depth 1 -b master https://github.com/go-gorm/gorm.git
Cloning into 'gorm'...
remote: Enumerating objects: 179, done.
remote: Counting objects: 100% (179/179), done.
remote: Compressing objects: 100% (173/173), done.
remote: Total 179 (delta 11), reused 61 (delta 4), pack-reused 0
Receiving objects: 100% (179/179), 226.27 KiB | 2.73 MiB/s, done.
Resolving deltas: 100% (11/11), done.
go: downloading gorm.io/driver/postgres v1.5.2
go: downloading gorm.io/driver/sqlite v1.5.3
go: downloading gorm.io/driver/mysql v1.5.1
go: downloading gorm.io/driver/sqlserver v1.5.1
go: downloading github.com/jackc/pgx/v5 v5.4.3
go: downloading github.com/go-sql-driver/mysql v1.7.1
go: downloading github.com/microsoft/go-mssqldb v1.5.0
go: downloading github.com/jackc/pgx v3.6.2+incompatible
go: downloading github.com/jackc/pgservicefile v0.0.0-20221227161230-091c0ba34f0a
go: downloading golang.org/x/crypto v0.12.0
go: downloading golang.org/x/text v0.12.0
go: downloading github.com/jackc/pgpassfile v1.0.0
go: downloading github.com/microsoft/go-mssqldb v1.6.0
go: downloading github.com/golang-sql/sqlexp v0.1.0
go: downloading github.com/golang-sql/civil v0.0.0-20220223132316-b832511892a9
go: downloading golang.org/x/crypto v0.14.0
go: downloading golang.org/x/text v0.13.0
go: upgraded github.com/microsoft/go-mssqldb v1.5.0 => v1.6.0
go: upgraded golang.org/x/crypto v0.12.0 => v0.14.0
go: upgraded golang.org/x/text v0.12.0 => v0.13.0
go: upgraded gorm.io/driver/sqlite v1.5.3 => v1.5.4
Creating network "playground_default" with the default driver
Creating playground_mysql_1 ... done
Creating playground_postgres_1 ... done
Creating playground_mssql_1 ... done
starting...
testing sqlite...
2023/10/08 15:46:37 testing sqlite3...
2023/10/08 15:46:37 /home/qcazelles/Desktop/playground/db.go:97 table "companies" has more than one primary key
[0.023ms] [rows:0] CREATE TABLE `companies` (`id` integer PRIMARY KEY AUTOINCREMENT,`name` text,PRIMARY KEY (`id`))
2023/10/08 15:46:37 Failed to auto migrate, but got error table "companies" has more than one primary key
FAIL gorm.io/playground 0.038s
I wanted to use the playground to submit the same issue for Gorm usage with sqlite itself ...
go version go1.20.2 linux/amd64
Gorm is in version 1.25.4
gorm.io/driver/sqlite in v1.5.4
Minimal reproducer
main.go
package main
import (
"fmt"
"gorm.io/driver/sqlite"
"gorm.io/gorm"
)
type TestStruct struct {
gorm.Model
field string
}
func main() {
db, err := gorm.Open(sqlite.Open("test.db"), &gorm.Config{})
if err != nil {
panic("failed to connect database")
}
// Migrate the schema
err = db.AutoMigrate(&TestStruct{})
if err != nil {
fmt.Println(err)
}
}
2023/10/08 15:40:03 /home/qcazelles/Desktop/minimal_reproducer/main.go:21 table "test_structs" has more than one primary key
[0.016ms] [rows:0] CREATE TABLE `test_structs` (`id` integer PRIMARY KEY AUTOINCREMENT,`created_at` datetime,`updated_at` datetime,`deleted_at` datetime,PRIMARY KEY (`id`))
table "test_structs" has more than one primary key
This last code works fine with mysql driver.
Thank you
1.请关注如下参数设置的连接池最大连接数目,该参数无效, 我设置的连接池最大连接数为30, 实际做并发测试的时候,mysql 显示客户端数量为本次测试并发值(128)+已有连接. 但是基于 database/sql 原生方式操作,结果为: 30++已有连接.
2.请作者检查一下代码,看看是我写的有问题,还是存在bug. 请求帮忙解决此问题.
3.我在追踪代码,但是源代码写的有点绕,暂时没有找到问题点, 请作者协助排查一下。
gormDb, err := gorm.Open(mysql.Open("Dsn"), &gorm.Config{
})
if err != nil {
//gorm 数据库驱动初始化失败
return nil, err
}
var resolverConf dbresolver.Config
// 如果开启了读写分离,配置读数据库(resource、read、replicas)
resolverConf = dbresolver.Config{
Sources: []gorm.Dialector{mysql.Open("WriteDsn")},
Replicas: []gorm.Dialector{mysql.Open("ReadDsn")},
Policy: dbresolver.RandomPolicy{},
}
err = gormDb.Use(dbresolver.Register(resolverConf, "").SetConnMaxIdleTime(time.Minute).
SetConnMaxLifetime(10* time.Second).
SetMaxIdleConns(10).
SetMaxOpenConns(30)) // 这里设置的连接池最大连接为30
if err != nil {
return nil, err
}
// 并发性能测试,同时测试连接池
var wg sync.WaitGroup
// 并发最大连接数设置为 128 进行本次测试, 问题如下:
// 如果使用 database/sql 原生操作,在数据库使用 show processlist 命令查看,程序执行期间的连接为 30+已有连接
// 使用 gorm 测试,连接池的上限根本无效,数据库的连接就是 128+已有连接
var conNum = make(chan uint16, 128)
wg.Add(1000)
time1 := time.Now()
for i := 1; i <= 1000; i++ {
conNum <- 1
go func() {
defer func() {
<-conNum
wg.Done()
}()
var received []tb_code_lists
gormDb.Table("tb_code_list").Select("code", "name", "company_name", "province", "city", "remark", "status", "created_at", "updated_at").Where("id<=?", 3500).Find(&received)
//fmt.Printf("本次读取的数据条数:%d\n",len(received))
}()
}
wg.Wait()
fmt.Printf("耗时(ms):%d\n", time.Now().Sub(time1).Milliseconds())
I get this error when trying to start docker:
Server. Server is not found or not accessible. Check if instance name is correct and if SQL Server is configured to allow remote connections. For more information see SQL Server Books Online..
mssql_1 | Error: MSSQL SERVER took more than thirty seconds to start up.
mssql_1 | tail: inotify cannot be used, reverting to polling: Function not implemented
I'm on OS X 12.4 with Apple's M1.
This is blocking me from reporting this bug on the main repo 🤦♂️
In the existing models of this repo the user foreign key (manager_id) gets created by the has-many Team relation.
When that is no longer present no foreign key is created for the self-referential has-one relation corresponding to the Manager member.
This is a test case which shows this bug with a separate model:
type Task struct {
gorm.Model
Content string `gorm:"not null; default:Empty Task" json:"content"`
ParentTaskID *uint `gorm:"not null" json:"parent_task_id"`
ParentTask *Task `gorm:"foreignKey:ParentTaskID" json:"-"`
}
When this is AutoMigrated, parent_task_id isn't marked as a foreign key.
1.20.7版本可以正常运行
1.21.3版本插入数据库不正常
type User struct {
gorm.Model
CreditCards []CreditCard
}
type CreditCard struct {
gorm.Model
Number string
UserID uint
Other []Other
}
type Other struct {
gorm.Model
Number string
CreditCardID uint
}
V1.20.7版本通过Create(&u) ,以上三表可以一次插入数据
V1.21.3版本,只能插入User表和CreditCard
go mod 更改才能避免
replace gorm.io/gorm v1.21.3 => gorm.io/gorm v1.20.7
replace gorm.io/driver/mysql v1.0.5 => gorm.io/driver/mysql v1.0.1
gorm v2组查询时,使用.Table与不使用生成的sql不一样
This parameter is used to query the gorm v2 group. Table is not the same as sql generated without using it
`
db, _ := gorm.Open(sqlite.Open("gorm.db"), &gorm.Config{})
pizzas := struct {
}{}
db.Table("microloan.account_base").Where(
db.Where("pizza = ?", "pepperoni").Where(db.Where("size = ?", "small").Or("size = ?", "medium")),
).Or(
db.Where("pizza = ?", "hawaiian").Where("size = ?", "xlarge"),
).Find(&pizzas)
db = db.Table("microloan.account_base")
db.Where(
db.Where("pizza = ?", "pepperoni").Where(db.Where("size = ?", "small").Or("size = ?", "medium")),
).Or(
db.Where("pizza = ?", "hawaiian").Where("size = ?", "xlarge"),
).Find(&pizzas)
`
this not use
2023/08/08 15:06:09
[0.122ms] [rows:0] SELECT * FROM microloan.account_base WHERE (pizza = "pepperoni" AND (size = "small" OR size = "medium")) OR (pizza = "hawaiian" AND size = "xlarge")
this used
2023/08/08 15:06:09
[0.025ms] [rows:0] SELECT * FROM microloan.account_base WHERE ((pizza = "pepperoni" AND size = "small" OR size = "medium") AND pizza = "hawaiian" AND size = "xlarge")
I need to specify 'database.table' using 'table()', but I want the result of the first.
Or is there another way to specify a database?
On a 2023 Macbook Pro M2:
./test.sh fails because of line 19:
go install github.com/microsoft/go-sqlcmd/cmd/sqlcmd@latest || true
fails with the error: package github.com/microsoft/go-sqlcmd/cmd/sqlcmd is not a main package
I cannot use gorm Playground because cannot use github client in company.
code:
// ShowGormInheritBug show bug caused by DB.Omit()
func ShowGormInheritBug() {
//init DB function
getDB := func() *gormv2.DB {
dbName := "my_test"
dsn := fmt.Sprintf("root:@tcp(127.0.0.1:3306)/%s?charset=utf8mb4&parseTime=True&loc=Local", dbName)
db, _ := gormv2.Open(mysql.Open(dsn))
return db.Omit("something") //omit "something" field //this bug won't appear if do not use Omit()
}
//some struct slice
var tmp, anotherTmp []struct {
ID int
Val string
}
IDList := []string{"1", "2", "3"} //used in where in clause
db := getDB()
//step 1. do some query work, not with Debug()
db.Table("test").
Select("val").
Where("id in ?", IDList).
Find(&tmp)
//step2. do another query work, it will inherit the "Select", "Where" methods before, and cannot work
db.Debug().Table("test2").
Joins("JOIN test3 ON test3.val=test2.val").
Find(&anotherTmp)
//output:
//Error 1052: Column 'val' in field list is ambiguous
//SELECT `val` FROM `test2` JOIN test3 ON test3.val=test2.val WHERE id in ('1','2','3')
}
When use DB.Omit(),the Find() by same DB will inherit the conditional statement before.
如果执行了DB.Omit(),使用同一个DB对象,前面第一次查询时设置的select\where条件,在后面的第二次查询时,这些条件还会出现(其他条件:1、如果前面第一次使用了.Debug()不会出现 2、db设置时使用.Session(&gorm.Session{NewDB: true}也不会出现)
I found a API in gorm.Session(SkipHooks: true)
, I used it to do save|update|query|delete
, and callbacks were still be called, may be the API I used is not right, can you tell me how?
Which API I should use to prevent from callbacks been invoked when do save|update|query|delete
?
在软删除的时候,如何把deletedBy同时更新为deletedAt的时间戳。
`
type BaseModel struct {
gorm.Model
CreatedBy uint `gorm:"column:CreatedBy;type:bigint(20) UNSIGNED;not null;default:0;"`
UpdatedBy uint `gorm:"column:UpdatedBy;type:bigint(20) UNSIGNED;not null;default:0;"`
DeletedBy soft_delete.DeletedAt `gorm:"softDelete:flag,DeletedAtField:DeletedAt;column:DeletedBy;type:bigint(20) UNSIGNED;not null;default:0;"`
}
`
执行软删除的理想sql:
UPDATE users SET DeletedBy = 1658095638, DeletedAt = '2022-07-18 06:07:18' WHERE ID = 1;
Ran into a similar issue and reproduced it in the playground, see #690
Should this work or no?
If this should work, then I guess this is a bug?
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.