Where communities thrive


  • Join over 1.5M+ people
  • Join over 100K+ communities
  • Free without limits
  • Create your own community
People
Repo info
Activity
  • 20:18
    github-actions[bot] closed #3986
  • 18:16
    anshuljhawar edited #3992
  • 18:16
    anshuljhawar edited #3992
  • 18:15
    anshuljhawar edited #3992
  • 18:14
    anshuljhawar labeled #3992
  • 18:14
    anshuljhawar assigned #3992
  • 18:14
    anshuljhawar opened #3992
  • 18:00
    anshuljhawar closed #375
  • 17:06
    anshuljhawar edited #375
  • 17:06
    anshuljhawar edited #375
  • 17:05
    anshuljhawar edited #375
  • 17:04
    anshuljhawar opened #375
  • 13:00
    github-actions[bot] closed #3984
  • 08:47
    thep0y assigned #3991
  • 08:47
    thep0y labeled #3991
  • 08:47
    thep0y opened #3991
  • 08:34
    lhzcm commented #15
  • 08:31
    itgelo commented #3952
  • 08:29
    lhzcm edited #15
  • 08:29
    lhzcm edited #15
Mr. NorthWatch
@mr-northwatch
i'm pretty sure the first/main example is showing SQLite
if you don't already have a schema (or are creating your db from-scratch), you can just create structs like this:
type Name struct {
    gorm.Model // creates fields for created/modified dates and id
    ExampleField string
    ExampleField int
    // and so on...
}

db.AutoMigrate(&Name{})
I usually make a deadicated model.go file where I put all my structs and I will create a func StartDB() {} with all the migration commands for each model and caching commands, then I trigger that on startup to generate everything
you can also set a global var in that model.go file like DB, DBError := gorm.Open(...), then as part of your startdb function you can check for an error to make sure that everything loaded in properly and stop the app with a console msg or similar if db load fails
the gorm docs are not very well indexed for whatever reason, and even the search tool isn't great so I would suggest just keeping them open in a new tab as you develop
nirefx
@nirefx
Thank you @mr-northwatch ! I will take a look
Noam
@noamshalev

Hi All :)
For a new app that I'm developing, I need to read and approve the SQL commands before committing them to the database.
For example, for
Create(&User{name:"John"})
I need to have the gorm-transalated SQL command : INSERT INTO users (name) VALUES ("John"); before the transaction is committed.

Is it possible to do it with gorm? how can I extract the about-to-be-executed SQL commands?

Thanks!

Kostya Ostrovsky
@kostyay
Hey all
I've created a gorm plugin for OpenTelemetry, very handy if you use that for tracing.
https://github.com/kostyay/gorm-opentelemetry
Madhu Kanoor
@mkanoor
Hello When doing an INSERT INTO a table the order of RETURNING columns is not consistent looking at https://github.com/go-gorm/gorm/blob/79864af9ffee6e12051f6bbdfaab31df77f3bc61/callbacks/create.go#L109 its not clear how it figures the order of columns. In the returning columns it has the Primary Key column and a relationship column (id and service_credenttial_type_id) , and it keeps toggling the order and makes it difficult to write tests e.g.
"service_credentials" ("created_at","updated_at","archived_at","source_ref","source_created_at","last_seen_at","name","type_name","description","tenant_id","source_id") VALUES ('2021-01-01 14:46:01.031','2021-01-01 14:46:01.031',NULL,'4','2020-01-08 10:22:59.423',NULL,'demo','','desc',99,1) RETURNING "id",”service_credential_type_id"

Versus
INSERT INTO "service_credentials" ("created_at","updated_at","archived_at","source_ref","source_created_at","last_seen_at","name","type_name","description","tenant_id","source_id") VALUES ('2021-01-01 14:47:25.842','2021-01-01 14:47:25.842',NULL,'4','2020-01-08 10:22:59.423',NULL,'demo','','desc',99,1) RETURNING "service_credential_type_id",”id"
Madhu Kanoor
@mkanoor
Since maps in Go don’t retain the order when this code iterates thru the column names here https://github.com/go-gorm/gorm/blob/f6550419088d21a98cf5f3c8dc3bfc30e46e1cb1/schema/schema.go#L194 it will pick up columns in random order. Should Gorm order these column names for consistent tests
Martin Claesson
@pentacore

Hey!

I'm running in to an issue when trying to migrate my customized Many2Many table, i keep getting a "invalid memory address or nil pointer dereference", which ive traced down to a relationship on the join table.

The only issue is.. that this is not a relation that i've added myself, It seems to be a fully nilled out relation to itself, so when trying to get the rel.Field.TagSettings["CONSTRAINT"] in relationship.go:475 it panics.

The join table:

type EventAttendee struct {
    EventID     uint64           `gorm:"index:unique_attendee,unique"`
    CharacterID uint64           `gorm:"index:unique_attendee,unique"`
    Role        string
    CreatedAt     time.Time      `gorm:"default:now()"`
    UpdatedAt     time.Time      `gorm:"default:now()"`
    DeletedAt     gorm.DeletedAt `gorm:"index" json:"-"`
}
image.png
Omar Hossam
@moar55
hey
I am having an issue with using the belongs to association
test01
@yeshaohuayeshaohua
自定义日志怎么这么不方便。。。
appcypher
@appcypher

Hey fellas,
I'm working with Gormv2 and Postgres. I cannot get the following code to work because I suspect Gorm isn't escaping table names properly for Postgres.

db.Exec(
    "DELETE FROM ? WHERE id IN (SELECT seed_id FROM seeds WHERE table_name = ?)",
    tableName,
    tableName,
)

If I change the code to the following, it works.

db.Exec(
    "DELETE FROM \"users\" WHERE id IN (SELECT seed_id FROM seeds WHERE table_name = ?)",
    tableName,
)

or

db.Exec(
    "DELETE FROM users WHERE id IN (SELECT seed_id FROM seeds WHERE table_name = ?)",
    tableName,
)
Mostafa Yaghobi
@moyamos

Hey there,
I am trying to add a record with a map as follow:

var newRow map[string]interface{}
tx.Create(newRow)

How can I get the id of the inserted record or the other field that does not exist in the newRow map in the case that I am not using a struct?

I have tried to do as follow:

addedRow := map[string]interface{}{}
tx.Create(newRow).Order("id DESC").Find(&addedRow).Limit(1)

However, I consider, it is not an optimized approach!

Thanks

Mr. NorthWatch
@mr-northwatch
you aren't really doing that in a logical way
you're probably better off doing manual SQL commands for anything that isn't doing to be done with a struct
Mostafa Yaghobi
@moyamos

you aren't really doing that in a logical way

Is working with GORM without structs recommend for a data provider layer of an application? Actually, there are a lot of tables, which have to be modeled with structs then. And, a dynamic table and struct selection is another consideration.

2bu4
@2bu4
image.png
why left join
guoguowd
@guoguowd
image.png
i set timeout in dsn with timeout=2s when gorm.open , but , it has no response after 2s, and still connecting
Alan D. Cabrera
@maguro
How do I map a struct with a map[string]string field? I can map that field to another table and use a hook to copy it to a private list field before saving. But how can I reassemble it back into a map after a find?
1 reply
Hồ Vũ
@qwerty22121998
Hi guys, is there any way to check what field in model has changed and it's old and new value ? I could use tx.Statement.Changed() but it doesn't return the values. I'm currently select that data from db in BeforeUpdate hook and compare to current model.
smartluckeyboy
@smartluckeyboy

type User struct {
//gorm.Model
ID string json:"id" gorm:"primary_key"
LastLogin time.Time json:"last_login"
UserCount uint json:"user_count"
Roles []Role gorm:"many2many:user_roles;"
}

//Role are exported
type Role struct {
//gorm.Model
ID uint json:"id" gorm:"primary_key"
Name string json:"name"
}

when pesisting the user records into mysql db then getting error like below.
//save user and rolesrecords into database

db.Save(&user)

error:
Error 1366: Incorrect integer value: 'ń' for column 'user_id' at row 1 ←[0m

Please let me know the solution for the same.

yiranzai
@yiranzai_gitlab

The Demo
https://gorm.io/docs/advanced_query.html#Group-Conditions

db.Where(
  db.Where("pizza = ?", "pepperoni").Where(db.Where("size = ?", "small").Or("size = ?", "medium")),
).Or(
  db.Where("pizza = ?", "hawaiian").Where("size = ?", "xlarge"),
).Find(&Pizza{}).Statement

// SELECT * FROM `pizzas` WHERE (pizza = "pepperoni" AND (size = "small" OR size = "medium")) OR (pizza = "hawaiian" AND size = "xlarge")

But my code

var result []map[string]interface{}
    db = db.Table("test")
    db.Where(
        db.Where("pizza = ?", "pepperoni").Where(db.Where("size = ?", "small").Or("size = ?", "medium")),
    ).Or(
        db.Where("pizza = ?", "hawaiian").Where("size = ?", "xlarge"),
    ).Find(&result)

I got sql

SELECT * FROM `test` WHERE pizza = 'pepperoni' AND size = 'small' OR size = 'medium' AND (pizza = 'pepperoni' AND size = 'small' OR size = 'medium') AND (pizza = 'pepperoni' AND size = 'small' OR size = 'medium' AND (pizza = 'pepperoni' AND size = 'small' OR size = 'medium')) AND pizza = 'hawaiian' AND size = 'xlarge' OR (pizza = 'pepperoni' AND size = 'small' OR size = 'medium' AND (pizza = 'pepperoni' AND size = 'small' OR size = 'medium') AND (pizza = 'pepperoni' AND size = 'small' OR size = 'medium' AND (pizza = 'pepperoni' AND size = 'small' OR size = 'medium')) AND pizza = 'hawaiian' AND size = 'xlarge')
The condition is repeated twice
Keon Ye
@keonjeo
@yiranzai_gitlab it's a very complicated sql. lol
yiranzai
@yiranzai_gitlab
Version v1.20.8
Yes, very complicated, in fact I have a dozen SQL conditions. SQL that repeats a condition occurs only when "grouping conditions" and "or conditions"
yiranzai
@yiranzai_gitlab
The key to the problem is getInstance(). Whendb.clone > 0, the next call will generate a new DB
yiranzai
@yiranzai_gitlab
db.clone > 0 in Demo,So, The Demo is OK.
My code. db.Table("test”) generate a new DB and new DB db.clone = 0. When db.clone = 0, the next call will change himself.
clayton
@Y1nPengfei
tx.Set("query_option", "FOR UPDATE") is no effective
evan.kim
@zacscoding
Hello guys :)
Is there any way to check db connections's dsn when switching from db resolver in gorm v2?
I just want to debug connection's dsn whenever write or read :)
I tried to add callbacks or hooks but given db arg's connection pool is master not replica :(
Somers B Matthews
@somersbmatthews
it looks like the database name is not being set, but I'm not sure
Daniel
@DanielDanteDosSantosViana
Hello guys, I have a situation when try consult with field nil in database , but create a query with value NULL and not IS NULL in condition where ( brand is null string). Where(&paymentSchema, map[string]interface{}{ "modality": paymentScheme.Modality().Value(), "brand": brand, }) , How find with string nil ?
smartluckeyboy
@smartluckeyboy

Hello Guys..
Please do the needful for help.I'm using two table User and roles with many2many relationship ,once saving the records into DB then getting issue as mentioned .
type User struct {
//gorm.Model
ID string json:"id" gorm:"primary_key"
LastLogin time.Time json:"last_login"
UserCount uint json:"user_count"
Roles []Role gorm:"many2many:user_roles;"
}

//Role are exported
type Role struct {
//gorm.Model
ID uint json:"id" gorm:"primary_key"
Name string json:"name"
}

when pesisting the user records into mysql db then getting error like below.
//save user and rolesrecords into database
var roles []Role
db.Model(Role{}).Where("Name = ?", "ROLE_ADMIN").Take(&roles)
newUser:=&User{Password:EncodePassword(user.Password),CreatedTimeStamp:time.Now(),UpdateTimeStamp:time.Now(),LastLogin:time.Now(),Roles:roles}
db.Save(&user)

error:
Error 1366: Incorrect integer value: 'ń' for column 'user_id' at row 1 ←[0m

               Please suggest what is the issue ?
Keon Ye
@keonjeo
image.png
image.png
anyone comes across this kind of the problem like me? I use preload("Relations"), But it return me "unsupported relations", and it's a very small probability event. Anyone can give me any guidance here? Thanks so much
bruce.liu
@bruceliuxuejian
go get gorm.io/driver/mysql has errors now!
tiagomelo
@tiagomelo
Hi! I'm having some issues when trying to connect to CloudSQL. Does anyone have any working example? I'm trying to use "github.com/GoogleCloudPlatform/cloudsql-proxy/proxy/dialers/mysql" as well, but I'm not sure how to correctly use it with Gorm.
thanks in advance!
Tanmay Joshi
@tanmay-joshi
Do we need to use AddForiegnKey in Gorm V2.0?
deanroker123
@deanroker123
Hi, I had a weird panic in my app I wonder if anyone could help. its not in my code, looking at the gorm code it seems to be a tx is nil when it runs a call back.
I am at a loss as to what caused it or how to fix it.
popomen
@popomen
test