by

Where communities thrive


  • Join over 1.5M+ people
  • Join over 100K+ communities
  • Free without limits
  • Create your own community
People
Repo info
Activity
  • 09:17
    github-actions[bot] labeled #3257
  • 09:17
    github-actions[bot] commented #3257
  • 09:11
    github-actions[bot] labeled #3257
  • 09:11
    githubzhaoqian assigned #3257
  • 09:11
    githubzhaoqian opened #3257
  • 06:30
    iHDJ commented #3116
  • 04:52
    goakshit assigned #7
  • 04:52
    goakshit opened #7
  • 03:49
    thep0y edited #3256
  • 03:32
    thep0y edited #3256
  • 03:31
    github-actions[bot] labeled #3256
  • 03:31
    github-actions[bot] commented #3256
  • 03:29
    thep0y edited #3256
  • 03:24
    github-actions[bot] labeled #3256
  • 03:24
    thep0y assigned #3256
  • 03:24
    thep0y opened #3256
  • 00:28
    github-actions[bot] labeled #63
  • 00:28
    github-actions[bot] commented #63
  • Aug 11 21:54
    ferdigokdemir closed #3254
  • Aug 11 21:54
    ferdigokdemir commented #3254
ZZY2357
@ZZY2357
func createUser(name string, password string) {
    h := sha256.New()
    h.Write([]byte(password))
    passwordHash := hex.EncodeToString(h.Sum(nil))
    user := User{Name: name, PasswordHash: passwordHash}
    db.Create(&user)
}
panic: runtime error: invalid memory address or nil pointer dereference
[signal SIGSEGV: segmentation violation code=0x1 addr=0x40 pc=0x586d24]

goroutine 1 [running]:
github.com/jinzhu/gorm.(*DB).clone(0x1182080, 0x1182bc0)
    /home/zzy2357/Workspace/Go/pkg/mod/github.com/jinzhu/gorm@v1.9.14/main.go:848 +0x34
github.com/jinzhu/gorm.(*DB).NewScope(0x1182080, 0xad85a0, 0xc000096070, 0x1)
    /home/zzy2357/Workspace/Go/pkg/mod/github.com/jinzhu/gorm@v1.9.14/main.go:204 +0x2f
github.com/jinzhu/gorm.(*DB).Create(0x1182080, 0xad85a0, 0xc000096070, 0x40)
    /home/zzy2357/Workspace/Go/pkg/mod/github.com/jinzhu/gorm@v1.9.14/main.go:482 +0x43
main.createUser(0xbe50b6, 0x7, 0xbe1068, 0x1)
    /home/zzy2357/Workspace/Web/YoumingProject/server/db.go:23 +0x21f
main.main()
    /home/zzy2357/Workspace/Web/YoumingProject/server/main.go:21 +0xf7
I don't know why
That's strange
Steve Fan
@stevefan1999-personal
deep dark fantasy
Sujit Prasad Baniya
@itsursujit
How can I defer DB.DB().close in v2?
Also How can I set MaxActiveConnection or MaxIdleConnection for db in v2?
In v1, I could do something like this:
func SetupDB() (*gorm.DB, error) {
    LoadDBConfig()
    if DB != nil {
        return DB, nil
    }
    connectionString := DBConfig.DB_User + ":" + DBConfig.DB_Pass + "@tcp(" + DBConfig.DB_Host + ")/" + DBConfig.DB_Name + "?charset=utf8&parseTime=True&loc=Local" //nolint:wsl,lll
    var err error                                                                                                                                                   //nolint:wsl

    // Connect again with DB name.
    DB, err = gorm.Open(DBConfig.DB_Driver, connectionString)
    if err != nil {
        return nil, err
    }

    DB.DB().SetMaxOpenConns(100)
    DB.DB().SetMaxIdleConns(100)
    DB.DB().SetConnMaxLifetime(5 * time.Minute)
    return DB, nil //nolint:wsl
}
ZZY2357
@ZZY2357
func findPostByID(id string) (postFound Post, err error) {
    var post Post
    db.First(&post, "ID = ?", id)
    if post.Title != "" {
        return post, nil
    }
    return post, errors.New("Post not found")
}
It cannot set post.ID into id
ZZY2357
@ZZY2357
Is it the mistake of the type?
Or my mind?
ZZY2357
@ZZY2357
I also create another table users
yeluoqiuzhi
@yeluoqiuzhi
hello, is anyone here?
Thanks, Who can help me solve this? go-gorm/gorm#1236
yeluoqiuzhi
@yeluoqiuzhi
哈哈哈
yeluoqiuzhi
@yeluoqiuzhi
<script>console.log('hello')</script>
monsterpooka
@monsterpooka
I try to save a big.Int value into mysql, but it seem gorm ignore this. so what I need to do?
Alex Walker
@amlwwalker

Hi, I have created a relationship between a campaign and a []customers. I can create an entry in the psql db and attach customers when I db.Save() however how do I add relationships later when my frontend sends the ID of the campaign and the IDs of the customers.
I have tried:

func UpdateCustomersForCampaignByIds(cId uint, ids []uint) error {
    var c Campaign
    if err := db.Debug().Where("id=?", cId).Preload("Customers", "id IN (?)", ids).Update(&c).Error; err != nil {
        return err
    }
    return nil
}

however I get nothing entered into the foreign-key table when I call it with

customerIds := []uint{1}
database.UpdateCustomersForCampaignByIds(4, customerIds)

Thanks!

ChannelCook
@ChannelCook
Is there anybody tell me diffrent between gorm:"not null" and sql:"not null"?
vojta001
@vojta001

Could anyone just point me to the right direction or tell me it is not possible? I use simple preloads with

db.Preload("Countries").Find(&towns)

It works great. However, I would like to do the same using JOINs, instead of SELECT and then SELECT WHERE IN. Is it possible? I found out GORM isn't willing to load fields of the inner struct (Country in this case) without having it mentioned in the Preload, however it always makes a SELECT WHERE IN if you include it in the Preload, no matter what other columns have already been selected

Jeroen Bulters
@bulters
Hi!
I'm running into an error I cant figure out: Trying to append an item to a many2many relation via db.Model(&parent).Association("Remarks").Append(newRemark)
but it gives me a glorious invalid memory address or nil pointer dereference runtime error.
in this case the Remarks struct field is set to []MeetingRemark
and many2many tag is setup correctly (since the Preload works as expected)
Morteza Aghili
@MortezaAghili
Hi there!
Do you have any working Gin & Gorm example that has Many2Many? I'm stuck in implemented relations!
Best
qilx
@qilx
Which package should I use: github.com/jinzhu/gorm or gorm.io/gorm? It seems like firstone should be older v1 and second v2. But I can`t find dialects for second one. And also documentation for both v1 and v2 mentions first package.
rookie7799
@rookie7799
howdy, is it possible to print the final query before executing it ?
Tom Berger
@tab1293
yes, in gorm v2 use a logger with logger.Info log level http://v2.gorm.io/docs/logger.html
rookie7799
@rookie7799
right, that I see but is there a "standalone" func that I can call ?
Tom Berger
@tab1293
@qilx connecting with v2 is documented here: https://github.com/go-gorm/gorm/wiki/GORM-V2-Release-Note-Draft#usage and docs are here http://v2.gorm.io/docs/
rookie7799
@rookie7799
having hard time creating multiple compound indexes
type UserClassmate struct {
ID int64 gorm:"primary_key" json:"id"
EduID1 int64 json:"exp_id1" gorm:"index:edu1;index:edu1_user1;index:edu1_user2"
EduID2 int64 json:"exp_id2" gorm:"index:edu2;index:edu2_user1;index:edu2_user2"
UserID1 int64 json:"user_id1" gorm:"index:user_id1;index:edu1_user1;index:edu2_user1"
UserID2 int64 json:"user_id2" gorm:"index:user_id2;index:edu1_user2;index:edu2_user2"
but when running "create tables" i get
CREATE INDEX edu1_user2 ON user_classmate(edu_id1) [] 0
CREATE INDEX edu2_user2 ON user_classmate(edu_id2, user_id2) [] 0
CREATE INDEX edu2_user1 ON user_classmate(user_id1) [] 0
which makes no sense
qilx
@qilx
@tab1293 Thank you!
jjvsun
@jjvsun
How to use gorm second-level cache
ahuigo
@ahuigo
Is there any good way to make gorm support postgresql's array type?
{"message":"sql: converting argument $1 type: unsupported type []string, a slice of string"}
ahuigo
@ahuigo
Gorm supports custom any type of data. e.g. Array
struct Room{
    names pq.StringArray ` gorm:"type:text[]"`
}
Sujit Prasad Baniya
@itsursujit
Is there any example of connection pooling and settings for MaxOpenConnections and Idle Connection on Gorm v2?

I'm wondering how this piece of code:

sqlDB, err := DB.DB()
    sqlDB.SetMaxOpenConns(100)
    sqlDB.SetMaxIdleConns(100)
    sqlDB.SetConnMaxLifetime(5 * time.Minute)
return DB, nil

will ensure the MaxOpenConnections and IdleConnection on DB.DB() because the settings are defined for sqlDB which is a new variable

Sujit Prasad Baniya
@itsursujit

I tried to implement GormV2 with SetMaxOpenConns and SetMaxIdleConns using following code

var DB *gorm.DB

func SetupDB() (*gorm.DB, error) {
    //nolint:wsl,lll
    var err error //nolint:wsl
    LoadDBConfig()
    connectionString := ""
    if DB != nil {
        return DB, nil
    }
    switch DBConfig.DB_Driver {
    case "postgres":
        connectionString = fmt.Sprintf("host=%s port=%d user=%s dbname=%s password=%s", DBConfig.DB_Host, DBConfig.DB_Port, DBConfig.DB_User, DBConfig.DB_Name, DBConfig.DB_Pass)
        DB, err = gorm.Open(postgres.Open(connectionString), &gorm.Config{})

    default:
        connectionString = fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=utf8&parseTime=True&loc=Local", DBConfig.DB_User, DBConfig.DB_Pass, DBConfig.DB_Host, DBConfig.DB_Port, DBConfig.DB_Name)
        DB, err = gorm.Open(mysql.Open(connectionString), &gorm.Config{})
    }
    if err != nil {
        panic(err)
    }
    sqlDB, err := DB.DB()
    sqlDB.SetMaxOpenConns(100)
    sqlDB.SetMaxIdleConns(100)
    sqlDB.SetConnMaxLifetime(5 * time.Minute)
    return DB, nil //nolint:wsl
}

func GetUserByEmail(email string) (*User, error) {
    var user User
    if err := DB.Where(&User{Email: email}).First(&user).Error; err != nil {
        return nil, err
    }
    return &user, nil //nolint:wsl
}

Getting following error when trying to do a load test:

failed to connect to `host=localhost user=postgres database=casbin`: server error (FATAL: sorry, too many clients already (SQLSTATE 53300))

What am I missing in above code?

wengang.liu
@Nihility981
hello anyone here
not v2.0 how batch insert data
@jinzhu
and i need this data id
wengang.liu
@Nihility981
a century later
Joshua Hemmings
@jLemmings

What am I doing wrong while trying to preload data?
db.Debug().Preload("Disposal").Where("project_id = ?", c.Param("id")).Find(&projects)

My Project model:

// Project struct is used to store all relevant information
type Project struct {
    ProjectID uint   `gorm:"primary_key" json:"ProjectID"`
    Name      string `json:"Name"`
    Disposals []Disposal
    Supplies  []Supply
}

My Disposal model:

// Disposal struct is used to store all relevant information
type Disposal struct {
    DisposalID      uint       `gorm:"primary_key" json:"DisposalID"`
    Depository      Depository `gorm:"foreignkey:DepositoryRefer" json:"Depository"`
    DepositoryRefer uint
    Material        Material `gorm:"foreignkey:MaterialRefer" json:"Material"`
    MaterialRefer   uint
    Date            time.Time `json:"Date"`
    Measurement     float64   `json:"Measurement"`
    Project         Project   `gorm:"foreignkey:ProjectRefer;AssociationForeignKey:project_id" json:"Project"`
    ProjectRefer    uint
}

The foreign keys I've set:

db.Model(Disposal{}).AddForeignKey("depository_refer", "depositories(depository_id)", "RESTRICT", "RESTRICT")
        db.Model(Disposal{}).AddForeignKey("material_refer", "materials(material_id)", "RESTRICT", "RESTRICT")
        db.Model(Disposal{}).AddForeignKey("project_refer", "projects(project_id)", "RESTRICT", "RESTRICT")
Philip Hutchins
@phutchins

Are there known issues with using associations? I have had a lot of trouble getting GORM to create associations consistently.

Also, is there a standard or guide as to when we would need to create associations as pointers vs not? Does adding a json tag affect an association?