Where communities thrive


  • Join over 1.5M+ people
  • Join over 100K+ communities
  • Free without limits
  • Create your own community
People
Repo info
Activity
  • 03:31
    shalakakad labeled #5898
  • 03:31
    shalakakad assigned #5898
  • 03:31
    shalakakad opened #5898
  • Dec 02 09:02
    github-actions[bot] labeled #5897
  • Dec 02 09:02
    github-actions[bot] commented #5897
  • Dec 02 08:59
    zhangdaogui edited #5897
  • Dec 02 08:59
    zhangdaogui edited #5897
  • Dec 02 08:57
    zhangdaogui edited #5897
  • Dec 02 08:55
    github-actions[bot] labeled #5897
  • Dec 02 08:55
    zhangdaogui assigned #5897
  • Dec 02 08:55
    zhangdaogui opened #5897
  • Dec 02 06:07
    choudhary-Sanchit-sherawat labeled #612
  • Dec 02 06:07
    choudhary-Sanchit-sherawat assigned #612
  • Dec 02 06:07
    choudhary-Sanchit-sherawat opened #612
  • Dec 02 05:39
    zwjzxh520 commented #5879
  • Dec 02 01:21
    hktalent closed #5669
  • Dec 01 23:15
    zchenyu commented #5689
  • Dec 01 22:53
    williamdenton commented on ab5f80a
  • Dec 01 21:25
    cgetzen commented #4414
  • Dec 01 20:54
    revenkroz commented #5764
IoCodes
@IoCodes
will try it out,
shouldn't it default on the zero date if it is null ?

sql.NullTime

fixed it

will have to change the logic

IoCodes
@IoCodes

thank you for the great help

@ChristianRansom

but I believe the Find should have generated an error, if time.time does not accept null and we are forcing it somehow
gameloader
@game-loader
hello everyone, i want to know if the struct primary key has value then the First() function would automated use it primarykey value to get a sql query , right?
This is a example
image.png
Then i use where() before First() and set "q_id = 41" but it wouldn't cover the First() using the struct's q_id
like this
image.png
gameloader
@game-loader
this is different to what doc say
image.png
Oussama Sethoum
@osethoum:matrix.org
[m]
Hi, is there a way to drop columns automatically from the table that are not included in the struct fields during migration?
Christian Ransom
@ChristianRansom
@game-loader The example in the doc probably has the &user.id set to its zero value so that it is ignored.
JBHolmes
@jonbr
func (project *Project) DeleteProject(db *gorm.DB) *error.ErrorResp {
    if err := db.Delete(&project).Error; err != nil {
        return error.New(error.WithDetails(err))
    }
    dump.P(db)
    if db.RowsAffected < 1 {
        errResponse := error.New(error.WithDetails(fmt.Sprintf("Can't delete project with id: %s it does not exists!", strconv.FormatUint(uint64(project.ID), 10))))
        return errResponse
    }

    return nil
}
I'm trying to soft delete a record and recognize that it was in fact marked as deleted, the RowsAffeced does not seem to working on soft delete, how do I achieve this?
Christian Ransom
@ChristianRansom
@jonbr What does dump.P(db) do? You're not always able to safely reuse the gorm.DB. https://gorm.io/docs/method_chaining.html#New-Session-Method
1 reply
Christian Ransom
@ChristianRansom
@jonbr I'd also try storing the result of db.Delete(&project) and getting the RowsAffected from that - https://gorm.io/docs/update.html#Updated-Records-Count
programmergogogogo
@programmergogogogo
In GORM, if I set SkipDefaultTransaction: true and a failure occurs during the registration of a vast data set, does it roll back correctly? Documentation: https://gorm.io/docs/transactions.html#Disable-Default-Transaction
Nicholas Guriev
@mymedia2
Hi there! Does the .Scopes() feature support OR conditions?
Can I combine it with the .Or() method?
I have this short sample. But I think GORM puts closing parenthesis in a wrong position.
https://gist.github.com/mymedia2/9e809d210c68ab5107f0bce3d28587b8
Is there a way around this?
Roman
@Roemer

Hello all
Greenhorn here with gorm.
I struggle to get a an entity where a field is not null and also ordered by that field.
The entitiy looks like:

type MyEntity struct {
    gorm.Model
    ReleasedAt            sql.NullTime
}

Now I want to search the the entity with the highest ReleasedAt and also where ReleasedAt is not null.
I would prefer to use the field of the struct for type safety and not the string released_at.
I am playing around with something like db.Not(&promoteVersionEntity{ReleaseCandidateAt: sql.NullTime{}}).Order(&promoteVersionEntity{}.ReleaseCandidateAt) but I don't know how to define the Order part and if the Not part works like this for null values.

2 replies
JBHolmes
@jonbr
I'm trying to permanently delete a record in association table, the association table only holds two records user_id and project_id this takes place inside a for loop, I've trying two methods
Session(&gorm.Session{AllowGlobalUpdate: true}) and Unscoped() but both don't work, the former method, throws no error, but does not delete the record, the latter throws error WHERE conditions required
// UserProjects join table for linking projects to users.
type UserProjects struct {
    UserID          uint
    ProjectID       uint
}

func updateUserProjects(db *gorm.DB, userID uint, projects []Project) error {
    for _, project := range projects {
        userProject := UserProjects{
            UserID:     userID,
            ProjectID:  project.ID,
        }
        dump.P(userProject)

        result := db.Debug().Create(userProject)
        if result.Error != nil {
            // record already exists in db, will be removed instead of being inserted.
            if result.Error.(*mysql.MySQLError).Number == 1062 {
                //if result := db.Debug().Session(&gorm.Session{AllowGlobalUpdate: true}).Delete(&userProject); result.Error != nil {
                if result := db.Debug().Unscoped().Delete(&userProject); result.Error != nil {
                    dump.P(result.Error)
                }
                fmt.Println("project was not inserted, but instead removed!")
                continue
            }
            fmt.Println("sql create error return")
        }
        fmt.Println("project attached to user")
    }

    return nil
}
1 reply
programmergogogogo
@programmergogogogo
In GORM, if I set SkipDefaultTransaction: true and a failure occurs during the registration of a vast data set, does it roll back correctly? Documentation: https://gorm.io/docs/transactions.html#Disable-Default-Transaction
4 replies
Rutvik Vatsa
@vatsa.rutvik:matrix.org
[m]
hey can someone tell me what datatype is db pointing to and what is gorm.DB exactly var db *gorm.DB
1 reply
jwatsonlegalserver
@jwatsonlegalserver
Good afternoon. I am still quite new to Go. My primary experience since 1998 is in PHP and Java. This seems somewhat basic, or that it should be, yet I cannot get this to work and unable to find a clear explanation in any search so far.
2 replies
jwatsonlegalserver
@jwatsonlegalserver

Good afternoon. I am still quite new to Go. My primary experience since 1998 is in PHP and Java. This seems somewhat basic, or that it should be, yet I cannot get this to work and unable to find a clear explanation in any search so far. The issue is that the table is getting created with only the gorm.Model pieces; not the single column I've added to the model. The full code is

package main

import (
"fmt"
"gorm.io/driver/sqlite"
"gorm.io/gorm"
)

type migration_queue struct {
gorm.Model
jsondata string json:"jsondata"
}

/
This shows how to process a json record set.
Need to receive an array of records that conform to the defined record structure.
/
func main() {
//var jdata = "[{Username: \"jwatson\", Password: \"123456\"},{Username: \"jdoh\", Password: \"3h587gb\"},]"

fmt.Printf("Attempting connection to SQLite database, migrate.db... ")
db, err := gorm.Open(sqlite.Open("migrate.db"), &gorm.Config{})
if err != nil {
    panic("failed to connect database")
}
fmt.Println("[ok]")

//var d string
var queue_row []migration_queue
var rowcount int64

//rows, err := db.Raw("select * from migration_queues").Rows()
db.Model(&queue_row).Count(&rowcount)
//defer rows.Close()
if err != nil {
    panic(fmt.Sprintf("Failed to SELECT FROM migration_queues, got error %v", err))
}

println("interate migration_queues table")
fmt.Printf("%d rows returned\n", rowcount)
fmt.Println(queue_row)

db.Migrator().DropTable(&migration_queue{})
//db.Migrator().CreateTable(&migration_queue{})
if err := db.Debug().AutoMigrate(&migration_queue{}); err != nil {
    panic(fmt.Sprintf("Failed to auto migrate, but got error %v", err))
}
db.Migrator().CreateTable(&migration_queue{})
//db.(migration_queue{})


lsdata := migration_queue{
    jsondata: "{Username: \"jwatson\", Password: \"123456\"}",
}
fmt.Println(lsdata)

rowsInserted := db.Create(&lsdata).RowsAffected
fmt.Println(rowsInserted)

}

I get no error when running, but the resulting table contains only
echo "select * from migration_queues"|sqlite3 migrate.db -header
id|created_at|updated_at|deleted_at
1|2022-11-14 13:13:39.812452-06:00|2022-11-14 13:13:39.812452-06:00|

The jsondata string field is not there. Can anyone help clarify what it is I am missing?

6 replies
jwatsonlegalserver
@jwatsonlegalserver
Is there a better place to post questions than here in Gitter?
Fernando B
@TheFern2
Hi, can anyone please tell me what I am doing wrong, PostTag fields should be foreign keys, but they are not in the database. They are also a compound Pk.
type BaseRow struct {
    ID     uint `xml:"Id,attr"`
    Offset int
    Length int
}

type RowQuestion struct {
    BaseRow
    AnswerId uint   `xml:"AcceptedAnswerId,attr"`
    Title    string `xml:"Title,attr" gorm:"type:varchar(150)"`
}

type RowAnswer struct {
    BaseRow
    RowQuestionID int `xml:"ParentId,attr"`
}

type Tag struct {
    ID   uint
    Name string `gorm:"type:varchar(35);unique"`
}

type PostTag struct {
    RowQuestionID uint `gorm:"primaryKey"`
    TagID         uint `gorm:"primaryKey"`
}
Fernando B
@TheFern2
Just trying to do eav, btw
Fernando B
@TheFern2
nvm was able to solve with many2many
Fernando B
@TheFern2
okay I can't seem to find the answer for this anywhere, if I want to rename tables db.Table("my_table").AutoMigrate(&Post{}) the join table gets created but not the posts table, what's the best way to handle this?
iwarapter
@iwarapter
has anyone been able to set a variable for a transaction within a plugin?
NGUYEN TIEN LONG
@long-nguyen
Hi, does anyone know if AutoMigrate support handling race condition ? I have multiple instance of golang project connect to single Postgres DB and automigrate might be run at the same time. How to avoid it?
2 replies
ls-2018
@ls-2018
go-gorm/gen#709
Hi, can anyone please merge this pr?
gameloader
@game-loader
how to scan the results to map[string]interfaces{}{} , I use take() function and it say it can only receive slice or struct
NitroCao
@NitroCao
Hi all. I'm using many2many association, there is a strange thing that the insertion of the join table happens before the parent table, so it fails because of the failure of the foreign key constraint. Does anyone know how to correct the insertion sequence?
Nicolás Camilo
@nicolasecamilo_gitlab

Hello! Let say I have a table User and a table Contact, and there's a relation User.ContactID -> Contact.ContactID. When I insert or fetch the user everything works fine. If I update fields in User, everything works as expected, but when I try to update something in this User contact (just one field, using PATCH), everything else get deleted.
There's no way to update specific fields of the joined table? I'm doing something like this:
r.db.GetDB().Preload("Contact").Updates(&User) <- this User contains only a modified phone inside contact and name inside User

Original body

{"first_name": "John", "last_name": "Doe", "contact": {"phone": "555-555", "cellphone":"555-551"}}

Expected after update

{"first_name": "John", "last_name": "Doe", "contact": {"phone": "555-553", "cellphone":"555-551"}}

Actual result after update

{"first_name": "John", "last_name": "Doe", "contact": {"phone": "555-553", "cellphone":null}}
Nicolás Camilo
@nicolasecamilo_gitlab
I found something weird about what I commented above: it creates a whole new Contact row and updates the User
Even tried with r.db.GetDB().Session(&gorm.Session{FullSaveAssociations: true}).Updates(&User) with the same result
Tine Šubic
@tinesubic

Hey all, I'm doing some testing with AutoMigrate. When running once, it creates a table, but on re-run, I get the following error: ALTER TABLE "test" ALTER COLUMN "mycol" TYPE integer USING "mycol"::integer
Struct:

type TestStruct struct {
     Mycol int32
}

The column is originally created as bigint from this struct, so not sure why it's trying to alter it.
Any ideas?

Hermann Rösch
@gutyoh

Hello! I have a question, why does the Find() method does not return an error in contrast to Find(), Last() and Take()?

I suppose it is maybe because Find(), Last() and Take() are restricted to returning only one record via the LIMIT 1 clause and that's why only those three return ErrRecordNotFound error?

Hermann Rösch
@gutyoh
Nevermind, I was able to find the answer myself in the docs: https://pkg.go.dev/github.com/jinzhu/gorm#pkg-variables
// ErrRecordNotFound returns a "record not found error". 
// Occurs only when attempting to query the database with a struct; 
// querying with a slice won't return this error
ErrRecordNotFound = errors.New("record not found")
Franco Nicolás Castagna
@fncastagna
Hi! I'm getting an error while creating the Go Structs based on an existing MYSQL DB using GenTool:
image.png
rs2152
@rs2152
type Test struct {
     Id        int       `json:"id"`
     CreatedAt time.Time `json:"createdAt"`
     UpdatedAt time.Time `json:"updatedAt"`
     StartTime  time.Time `json:"startTime"`

 }

database : postgres
StartTime column type time without timezone
I'm facing issue while fetching the data, below error is occured,

sql: Scan error on column index 9, name "start_time": unsupported Scan, storing driver.Value type string into type time.Time; sql: Scan error on column index 9, name "start_time": unsupported Scan, storing driver.Value type string into type time.Time

Sonam Wangchu
@swangchu
Recommend me a video on many to many in GORM. I am not able to understand the doc.
Erik Kvale
@erikkvale
Hello, I am trying to determine how best to set a variable for AWS Aurora when configuring GORM that would be valid for the entire session, basically running this SET = aurora_replica_read_consistency="SESSION". Looked at plugins, but that seems to run for every query. Any advice from the GORM side of things on how best to set that variable?
programmergogogogo
@programmergogogogo
Does AutoMigration() also give the NOT NULL attribute on the database?
1 reply