Git Product home page Git Product logo

gorm's Introduction

GORM

The fantastic ORM library for Golang, aims to be developer friendly.

go report card test status MIT license Go.Dev reference

Overview

  • Full-Featured ORM
  • Associations (Has One, Has Many, Belongs To, Many To Many, Polymorphism, Single-table inheritance)
  • Hooks (Before/After Create/Save/Update/Delete/Find)
  • Eager loading with Preload, Joins
  • Transactions, Nested Transactions, Save Point, RollbackTo to Saved Point
  • Context, Prepared Statement Mode, DryRun Mode
  • Batch Insert, FindInBatches, Find To Map
  • SQL Builder, Upsert, Locking, Optimizer/Index/Comment Hints, NamedArg, Search/Update/Create with SQL Expr
  • Composite Primary Key
  • Auto Migrations
  • Logger
  • Extendable, flexible plugin API: Database Resolver (Multiple Databases, Read/Write Splitting) / Prometheus…
  • Every feature comes with tests
  • Developer Friendly

Getting Started

Contributing

You can help to deliver a better GORM, check out things you can do

Contributors

Thank you for contributing to the GORM framework!

License

© Jinzhu, 2013~time.Now

Released under the MIT License

gorm's People

Contributors

0x2d3c avatar a631807682 avatar ag9920 avatar black-06 avatar bom-d-van avatar daheige avatar demomanito avatar deoxxa avatar dependabot[bot] avatar destel avatar emirb avatar galeone avatar huacnlee avatar jaytaylor avatar jinzhu avatar jnfeinstein avatar kimiby avatar li-jin-gou avatar nkovacs avatar qqxhb avatar rbg avatar richardknop avatar rtfb avatar s-takehana avatar saeidee avatar tr1v3r avatar tstorch avatar xwjdsh avatar zaneli avatar zenovich avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

gorm's Issues

对Mysql的支持不够好

已知的一个问题是关于表名的引号, 生成的SQL语句如下

DROP TABLE 'user';

Mysql要求

DROP TABLE user;

其他INSERT等也有类似问题

postgres parameter ordering in select statements

in postgresql:

db.Table("my_table").Select("some, columns, count(distinct id) as dist").Group("some, columns").Order("dist desc").Limit(10).Rows()

results in:

SELECT some, columns, count(distinct columns) as dist FROM my_table ORDER BY dist desc LIMIT 10 GROUP BY some, columns

Should be:

SELECT ... FROM my_table GROUP BY ... ORDER BY ... LIMIT

Event the mysql documentation states:

In general, clauses used must be given in exactly the order shown in the syntax description.

so it might be best for cross languages to do something like:

func (s *Do) combinedSql() string {
        return s.whereSql() + s.groupSql() + s.havingSql() + s.orderSql() + s.limitSql() + s.offsetSql()
}

I'll put this in a pull request for you to review.

Add support of nullable timestamp :)

Hi Jinzu 👍

I believe you know, sql package has not sql.NullTime type. That's why evebody create something like

type NullTime struct {
    Time time.Time
    Valid bool  // Valid is true if Time is not NULL
}

// Scan implements the Scanner interface.
func (nt *NullTime) Scan(value interface{}) error {
    if value == nil {
        nt.Valid = false
        return nil
    }
    nt.Time, nt.Valid = value.(time.Time), true
    return nil
}

// Value implements the driver Valuer interface.
func (nt NullTime) Value() (driver.Value, error) {
    if !nt.Valid {
        return nil, nil
    }
    return nt.Time, nil
}

The exception raises in following case:

type User struct {
    Id     int64
    Name string
    VerifiedDate    NullTime
}
...
..
db.Save(&user) 

db.Save(&user) generates insert SQL into tables users and null_times
How to deal with this issue? Could you suggest something?
Thank you in advance
Regards,
Robert

Can Save() be executed in single transaction?

Example

type UserSetting {
Id int64
UserId int64
...
..
}

type User struct {
Id int64
Name string
Settings UserSetting
}

...
var
u User{Name: "Robert"} 
err := db.Save(&user)

command finished with error (problem was with table user_settings) but row was stayed in table users. Database has become unconsisted.

mysql insert placeholder support

do.go:162, 我加了一行输出sql代码

image

得到的sql为

INSERT INTO users (age,name,birthday) VALUES ($1,$2,$3) 

mysql需要

INSERT INTO users (age,name,birthday) VALUES (?, ?, ?) 

Find Vs FindAll

It would be nice if a FindAll method is supported.
Find would find 1 row (limit 1),
FindAll would find all rows.

Currently using Find for both single and multiple results makes for code that is less clear in purpose than it could be

RemoveIndex doesn't seem to work

This is a PostgreSQL db.
For this structure:

type User struct {
Id int64
Name string
}

this code:

db.Model(User{}).RemoveIndex("name") 

does not seem to remove the index.

Is it possible to define a callback for all structs?

In the docs this example is given:

func (u *User) BeforeUpdate() (err error) {
    if u.readonly() {
        err = errors.New("Read Only User!")
    }
    return
}

Is it possible to define a callback that runs on all models, e.g. I want to automatically set a created_by_user_id field on every table?

(Please excuse my ignorance, I started learning Go 3 days ago)

Postgres precision loss

When storing a number such as longitude or latitude (35.03554004971999), unmarshalling correctly retains precision, however the process of saving to the database loses it's precision to the 6th decimal.

To verify this, I manually inserted the value directly into Postgres and it was stored correctly. I've printed the value of the struct containing the float64 value, and again, it appears correctly.

This seems to potentially be a loss somewhere in saving to the database.

FirstOrCreate with embeded struct doesnt work

type Demo struct {
        Id   int64
    Data           float64 
    Notes         []Note
}

type Note struct {
    Name        string
        DemoId     int64
    Description string
}

The following code works fine if used with

data := Demo{Data: 0.55,Notes: []Note{{Name: "asdads", Description: "asdasd"}}
db.Save(&data)

However the following:

var new Demo
data := Demo{Data: 0.55,Notes: []Note{{Name: "asdads", Description: "asdasd"}}
db.Where(Demo{Data: 0.33}).Assign(data).FirstOrCreate(&new)

produces
panic: runtime error: comparing uncomparable type []main.Note

Im a Go newbie so no clue where to start debuging, or maybe the error is somewhere with me, but even the basic example in the docs with the User and Email produces the same problem.

Go version is latest stable 1.2.

Create foreign key constraint between references

Starting with your example;

type User struct {
        Id                int64     // Id: Primary key
       ................
        Emails            []Email       // Embedded structs
        BillingAddress    Address       // Embedded struct
        BillingAddressId  sql.NullInt64 // Embedded struct's foreign key
        ShippingAddress   Address       // Embedded struct
        ShippingAddressId int64         // Embedded struct's foreign key
        IgnoreMe          int64 `sql:"-"`
}

you are not creating foreign key constraints between two tables(User-Address), this is useful for data integrity.

mysql建表失败

type Address struct {
Id int64
Address1 string sql:"not null;unique"
Address2 string sql:"type:varchar(100);unique"
Post sql.NullString sql:not null

}
db.LogMode(true)
db.CreateTable(Address{})

在mysql下执行后没有建表成功,程序也不报错
删除掉Address1的注解 sql:"not null;unique" 后可以建表成功,但是程序不打印sql日志

Postgres fields not quoted

Column names that are reserved words in Postgres don't get quoted properly, so Postgresql throws a syntax error.

    db, _ := gorm.Open("postgres", "user=gorm dbname=gorm sslmode=disable")
    type Foo struct {
        When time.Time
    }
    f := Foo{}
    err = db.Save(&f).Error
    if err != nil {
        panic(err)
    }

Output:

panic: pq: syntax error at or near "when"

Postgres query log:

ERROR:  syntax error at or near "when" at character 19
STATEMENT:  INSERT INTO foos (when) VALUES ($1) RETURNING "id"

License

Hello, can you include a LICENSE file to describe what license you are sharing your code under?

Non conventional foreign keys

I need to be able to map unconventional foreign keys

The docs give this example:

type Email struct {
    Id         int64
    UserId     int64   // Foreign key for User
    Email      string  `sql:"type:varchar(100);"` // Set this field's type
    Subscribed bool
}

What happens if UserId becomes something like CreatedByUserId but the primary key of User remains Id? How do I map the two together?

Count(&count) retrives right result but raises an error

Hi !

var
    count int64
    err := db.Model(User{}).Where("mobile = ?", mobile).Count(&count).Error
       fmt.Printf("Error: %v\n", err)

prints:

SQL is not valid, count(*)

and count has right value. I passed go test and results are the same. PostgreSQL 8.4.2, compiled by Visual C++ build 1400, 32-bit

No eager loading support?

It seems that eager loading is not supported?

eg. If a User has many Emails:

// Get the first record
db.First(&user)
//// SELECT * FROM users ORDER BY id LIMIT 1;

This does not get their emails.
How do I populate the entire struct?

The docs show that to then get the emails the following is needed:

// Find user's emails with guessed foreign key
db.Model(&user).Related(&emails)
//// SELECT * FROM emails WHERE user_id = 111;

So if I wanted to get a User and all their Emails, would I need to do something like the following?

db.First(&user)
db.Model(&user).Related(&user.Emails)
// Repeat for Addresses and all other relations

Iteration doesn't support parsing raw data into struct?

I may be missing something, but the docs aren't really clear on this. They mention the Rows() function can be used to iterate over table but since this returns *sql.Row, I'm not sure how to scan this into the struct for this row. The great thing about gorm is that it handles parsing the sql data into a struct, but this seems to be missing for iteration.

The example shows this, which really isn't great given how easy all of the other functions are to use.

rows.Scan(&name, &age, &email)

Setting *sql.DB without using Open

I've design my function to accept *sql.DB as the parameter. This way it's general enough if in the feature we want to use basic driver or switch between ORM.

The way I do this right now is something like this.

func Users(source *sql.DB) (users []User) {
    db := initGorm(source)
    db.Table("user").Find(&users)
}

func initGorm(source *sql.DB) *gorm.DB {
    result := gorm.SetDB("mysql", db)
    return &result
}

// on gorm/main.go
func SetDB(driver string, dbSource *sql.DB) (db DB) {
   db.db = dbSource
   db.dialect = dialect.New(driver)
   db.tagIdentifier = "sql"
   db.parent = &db
   return
}

Is this the right way to do this ? or gorm already have functionality that support this ?

Panic on db.CreateTable(Something{}) when using CreatedAt and UpdatedAt fields.

The code: https://gist.github.com/ainar-g/7323528

If I use &User{} instead of User{}, or remove CreatedAt and UpdatedAt fields, it works as it should. But otherwise, it causes this:

panic: reflect: reflect.Value.Set using unaddressable value

goroutine 1 [running]:
reflect.flag.mustBeAssignable(0x192)
    /usr/lib/go/src/pkg/reflect/value.go:268 +0x151
reflect.Value.Set(0x81d0c80, 0x1846a478, 0x192, 0x81d0c80, 0x1846dfe0, ...)
    /usr/lib/go/src/pkg/reflect/value.go:1373 +0x29
github.com/jinzhu/gorm.(*Model).fields(0x184a06a0, 0x81d8788, 0x6, 0x18484480, 0x3, ...)
    /home/ainar/go/src/github.com/jinzhu/gorm/model.go:120 +0xc2b
github.com/jinzhu/gorm.(*Do).createTable(0x184740b0, 0x81c4a20)
    /home/ainar/go/src/github.com/jinzhu/gorm/do.go:689 +0x64
github.com/jinzhu/gorm.(*Chain).CreateTable(0x1846e140, 0x81c4a20, 0x1846a460, 0x1846e000)
    /home/ainar/go/src/github.com/jinzhu/gorm/chain.go:237 +0x45
github.com/jinzhu/gorm.(*DB).CreateTable(0x1846d150, 0x81c4a20, 0x1846a460, 0x0)
    /home/ainar/go/src/github.com/jinzhu/gorm/main.go:106 +0x7c
main.main()
    /home/ainar/playground/go/db.go:36 +0x1a1

goroutine 2 [syscall]:
exit status 2

Customization on column name

I understand that gorm choose convention over configuration. I really like that. But sometimes the column name are something that is given and could not be changed. For instance I'm currently dealing with legacy app. The old app is still running, but we needed to add more functionality on top of that.

It would be very useful to follow the convention by default, but user can still set the column name for a field. Maybe using tags on the filed ?

Configuring Gorm to roll back automatically after each Revel test

Is it possible to configure Gorm to roll back automatically after each Revel test?
http://robfig.github.io/revel/manual/testing.html

For instance I have a method to promote a User from "admin" to "superadmin" and I have a func like below (untested code):

// app/models/user.go
import "db" // Contains the db setup
func (user *User) Promote (role string) {
         user.Role = role
         db.save(user)
}

And then I have a test:

func (t *AppTest) TestUserPromoteWorks() {
         // Create and save user with role "admin"
         t.AssertEqual("admin", user.Role)

         // Update the user's role to super-admin and save
         t.AssertEqual("superadmin", user.Role)
}

I don't want this user to exist in my test db after the test, so I would like to automatically roll back any changes to the database.

DATETIME fields in MySQL converted to string instead of time.Time

I'm using MySQL 5.6.10, and the DATETIME fields are throwing this error when following the same format from your example:

type User struct {
    Id          int64
    CreatedAt   time.Time
}

The error thrown is:

sql: Scan error on column index 2: unsupported driver -> Scan pair: []uint8 -> *time.Time

This is complaining that the field is actually a string. Using string as the type sends the string equivalent of the datetime

2013-07-25 22:48:23

I can workaround this by just casting it to a time.Time myself but you may want to fix this issue. The driver I'm using the is typical one https://github.com/go-sql-driver/mysql.

I've made sure the field is indeed of type DATETIME in my database.

Let me know if you need any other information.

Option to disable updating of nested data?

Currently if you insert/update an object with nested data, gorm sends sql update for nested data each time too.
For example, if you have Article with Author, every time you update Article additional sql update for Author will be sent.

Would be nice to have option to disable it.

very cool~, it's just want I want. " developer friendly", yes , you did it!

我一直想Go里面ORM如何能够自定义table_name(提供灵活性与旧系统对接), struct本身似乎无法保存这些信息.

gorp的做法是

t1 := dbmap.AddTableWithName(Invoice{}, "invoice_test").SetKeys(true, "Id")
t2 := dbmap.AddTableWithName(Person{}, "person_test").SetKeys(true, "Id")
t3 := dbmap.AddTableWithName(Product{}, "product_test").SetKeys(true, "Id")

urgly, beedb的做法好像是

orm.SetTable("userinfo").SetPK("uid").Where(2).Update(t)

urgly too. 你有没有好主意?

按照rails风格的类名与表名的转化在实际工作中不够灵活, 特别是国内各种拼音加单词混合的节奏....

Error while retiring DATETIME field value from MySQL DB table

my model structure looks like bellow

type Status struct {
    Id          int64
    AuthorId int64
    Description string `sql:"size:255"`
    PublishDate   time.Time
}

When I create a new record & save

myStatus:= Status{
        AuthorId :  business1.Id,
        Description: "I got stuck here",
        PublishDate   :   time.Date(2013, time.January, 22, 23, 59, 59, 0, time.UTC),
    }
DB.save(&myStatus)

it successfully save the record in MySQL database like bellow

+----+-----------+------------------+---------------------+
| id | author_id | description      | publish_date        |
+----+-----------+------------------+---------------------+
|  1 |         1 | I got stuck here | 2013-01-22 23:59:59 |
+----+-----------+------------------+---------------------+

when I try to retrieve the record from MySQL database, like bellow

 var allStatus []Status
 DB.Find(&allStatus)

I gives me following error

sql: Scan error on column index 3: unsupported driver -> Scan pair: []uint8 -> *time.Time

Required callback after fetching rows

I need to use diffrent date-time format for database and application. I have following struc for model

type SomeTable struct {
Id int64
SomeString string sql:"size:255"
SomeDate time.Time
}

I'm converting the the date format before saving by

func (o *SomeTable ) BeforeSave() (err error) {
o.SomeDate = o.SomeDate.Format(SQL_DATE_FORMAT)
return
}

but the problem is when I'm facing in when fetching data from data base. I am looking for an AfterGet method to transform the data (similar to PostGet in gorp). Can you suggest any other workaround?

NULL deleted_at fields

Is it possible to leave deleted_at fields as NULL when inserting new records? For purposes of a standardized serialization response this seems to make the most sense.

Searching with nil values broken

Hi,

I discovered a potential security issue with gorm.
In the following code:

DB.Where(models.User{Email: email}).First(&user)

if email is nil, the condition seems to be just ignored, instead of where email is null or something similar. In result, the first user is returned!
If email is coming from params, the developer has to always check for nil values, it's a bit verbose and prone to errors.

Thanks

Docs are not clear if Gorm uses transactions by default.

The docs do not make it clear if Gorm uses transactions by default, such as with this example given (no sign of begin transaction and commit):

user := User{
        Name:            "jinzhu",
        BillingAddress:  Address{Address1: "Billing Address - Address 1"},
        ShippingAddress: Address{Address1: "Shipping Address - Address 1"},
        Emails:          []Email{{Email: "[email protected]"}, {Email: "jinzhu-2@[email protected]"}},
}

db.Save(&user)
//// INSERT INTO "addresses" (address1) VALUES ("Billing Address - Address 1");
//// INSERT INTO "addresses" (address1) VALUES ("Shipping Address - Address 1");
//// INSERT INTO "users" (name,billing_address_id,shipping_address_id) VALUES ("jinzhu", 1, 2);
//// INSERT INTO "emails" (user_id,email) VALUES (111, "[email protected]");
//// INSERT INTO "emails" (user_id,email) VALUES (111, "[email protected]");

However the section on callbacks indicates that saves and deletes are run in transactions by default

// As you know, the save/delete operations are running in a transaction
// This is means all your changes will be rollbacked if get any errors
// If you want your changes in callbacks be run in the same transaction
// You have to pass the transaction as argument to the function
func (u *User) AfterCreate(tx *gorm.DB) (err error) {
    tx.Model(u).Update("role", "admin")
    return
}

Does Gorm use transactions for all saves and deletes by default? If so, perhaps the docs could indicate that right at the top?

support postgres varchar(N)/Char(N) for primary keys

Hi :)
Again me.
If the table has varchar(N) as a primary key I get
panic("unsupported sql adaptor, please submit an issue in github")

Would it be possible to add support of varchar for PKs?
Thank you in advance

func getPrimaryKeySqlType(adaptor string, column interface{}, size int) {
...
case "postgres":
        switch column.(type) {
        case int, int8, int16, int32, uint, uint8, uint16, uint32:
            return "serial"
        case int64, uint64:
            return "bigserial"
        }
    }
}

Support for custom primitive types?

I tried the following:

type Role string

const (
    Customer   Role = "CUSTOMER"
    Instructor Role = "INSTRUCTOR"
    Admin      Role = "ADMIN"
    SuperAdmin Role = "SUPERADMIN"
)

type User struct {
    Id             int64
    Email        string    
    Role          Role //Falls over if not string    
}

I kept getting the error below:

goroutine 38 [runnable]:
github.com/jinzhu/gorm.(*safeMap).Set(0xc210043ef0, 0x8598e0, 0x2, 0xc210000a08, 0x2)
    /home/lee/Code/gocode/src/github.com/jinzhu/gorm/utils.go:17
created by github.com/jinzhu/gorm.toSnake
    /home/lee/Code/gocode/src/github.com/jinzhu/gorm/utils.go:50 +0x219

Is it not possible to support custom primitives, and if not, is it possible to give a more detailed error message, it was difficult to try and work out what was wrong from that error message.

Does Related(&row) support sql.NullInt64?

Hi Jinzhu !
thank you for gorm. It's great. I started to use it recently.

I've faced one problem.

type Deposit struct {
    Id                  int64
    PaidDt              time.Time
    StateId             int32
    StateDt             time.Time
    Details             sql.NullString
    Amount              float64
}
type Withdraw struct {
...
}

type Usage struct {
...
}


type Transaction struct {
    Id                  int64
    TypeId              string
    StateId             int32
    CreatedDt               time.Time
    CompletedDt         olib.NullTime
    DebitAccountId          sql.NullInt64
    DebitAmount         float64
    CreditAccountId         sql.NullInt64
    CreditAmount            float64
    // only one of 3 following columns has value (that's all are nullable)
    DepositId               sql.NullInt64   // works if change to int64
    WithdrawId          sql.NullInt64
    UsageId             sql.NullInt64

        Deposit                 Deposit
    Withdraw                Withdraw
    Usage               Usage
}

func f (
           t := Transaction {}
       db.First(&t)
           db.Model(&t).Related(&t.Deposit)
)

Related() does not work return value if t.DepositID is sql.NullInt64 and it works fine if change DepositId to int64

PostgreSQL uuid primary key

Hi,
will you be adding support to allow PostgreSQL's UUID data type to be used as primary keys? Instead of just int64.
If I had to do this myself which files and methods would I need to alter?

Tests fail, timezone weirdness ensues

I stumbled onto a strange timezone bug while running tests. It could very well be my install of Go. I'm running 1.2rc5 on darwin_amd64. I'll see what I can dig up tomorrow, but I figured I'd write down my notes.

I expanded the test to add some debugging info.

func TestFindOrCreate(t *testing.T) {
        ...
        var tmp User
        db.Where(&User{Name: "find or create"}).Find(&tmp)
        t.Logf("tmp=%v", tmp)

        q := db.Where(&User{Name: "find or create"}).Assign(User{Age: 44}).FirstOrCreate(&user6)
        if user6.Name != "find or create" || user6.Id == 0 || user6.Age != 44 {
                t.Errorf("user should be found and updated with assigned attrs")
        }
        if q.Error != nil {
                t.Errorf("Error: %v", q.Error)
        }
        ...
}

Output:

-- FAIL: TestFindOrCreate (0.01 seconds)
    gorm_test.go:1071: tmp={13 -0001-12-31 18:09:24 -0409 -0409 33 find or create 2013-11-23 22:48:56.622898 -0600 -0600 2013-11-23 22:48:56.6229 -0600 -0600 -0001-12-31 18:09:24 -0409 -0409 [] {0    0001-01-01 00:00:00 +0000 UTC 0001-01-01 00:00:00 +0000 UTC 0001-01-01 00:00:00 +0000 UTC} {0 false} {0    0001-01-01 00:00:00 +0000 UTC 0001-01-01 00:00:00 +0000 UTC 0001-01-01 00:00:00 +0000 UTC} 0 {0  {0 false} 0001-01-01 00:00:00 +0000 UTC 0001-01-01 00:00:00 +0000 UTC 0001-01-01 00:00:00 +0000 UTC} [] 0}
    gorm_test.go:1078: Error: pq: invalid input syntax for type timestamp with time zone: "-0001-12-31T18:09:24-04:09"
    gorm_test.go:1083: user should be found and updated with assigned attrs
FAIL

When I turn on query logging in GORM, I see this:

sql601.851usINSERT INTO users (birthday,age,deleted_at,password_hash,name,created_at,updated_at,billing_address_id,shipping_address_id) VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9) RETURNING "id"[0001-01-01 00:00:00 +0000 UTC 33 0001-01-01 00:00:00 +0000 UTC [] find or create 2013-11-23 22:57:58.690353832 -0600 CST 2013-11-23 22:57:58.690355235 -0600 CST {0 false} 0]
...
sql253.948usUPDATE users SET birthday = $1, age = $2, name = $3, created_at = $4, updated_at = $5, deleted_at = $6, shipping_address_id = $7, password_hash = $8, billing_address_id = $9 WHERE (deleted_at IS NULL OR deleted_at <= '0001-01-02') AND (id = $10) AND ((name = $11))[-0001-12-31 18:09:24 -0409 -0409 44 find or create 2013-11-23 22:57:58.690354 -0600 -0600 2013-11-23 22:57:58.698527043 -0600 CST -0001-12-31 18:09:24 -0409 -0409 0 [] {0 false} 13 find or create]
...
sql246.245usUPDATE users SET age = $1, updated_at = $2, deleted_at = $3, password_hash = $4, birthday = $5, name = $6, created_at = $7, billing_address_id = $8, shipping_address_id = $9 WHERE (deleted_at IS NULL OR deleted_at <= '0001-01-02') AND (id = $10) AND ((name = $11))[44 2013-11-23 22:38:37.686012577 -0600 CST -0001-12-31 18:09:24 -0409 -0409 [] -0001-12-31 18:09:24 -0409 -0409 find or create 2013-11-23 22:38:37.679395 -0600 -0600 {0 false} 0 13 find or create]

This is what I see in postgres after the test fails:

gorm=# select * from users where name='find or create';
-[ RECORD 1 ]-------+--------------------------------
id                  | 13
birthday            | 0001-12-31 18:09:24-05:50:36 BC
age                 | 33
name                | find or create
created_at          | 2013-11-23 22:45:33.268583-06
updated_at          | 2013-11-23 22:45:33.268584-06
deleted_at          | 0001-12-31 18:09:24-05:50:36 BC
billing_address_id  |
shipping_address_id | 0
password_hash       | \x

Quite a few deleted_at dates have a strange timezone like this (all but one). I'll see what I can dig up tomorrow, but I'm going to crash for tonight.

I think I might also look at checking for query errors in tests. I think this is happening on the products table as well.

add another kind of Count() function

Hi!

There is code from readme

db.Where("name = ?", "jinzhu").Or("name = ?", "jinzhu 2").Find(&users).Count(&count)
//// SELECT * from USERS WHERE name = 'jinzhu' OR name = 'jinzhu 2'; (users)
//// SELECT count(*) FROM users WHERE name = 'jinzhu' OR name = 'jinzhu 2'; (count)

could you add another CountSomething()

db.Where("name = ?", "jinzhu").Or("name = ?", "jinzhu 2").Find(&users).CountSomething(&countfetchedrows) 

what will return amount of fetched rows without executing additinal SQL SELECT count(*)

Problem with simple Join table

I'm trying to use a simple join table in my project, the records returned have the correct attributes, but the Ids are off-by-one.

Here is a simplified version that shows the bug. One would expect the returned emails to have Ids 1 & 2, but they are 2 & 3, the Name fields are correct though.

For some reason, the SQL logging doesn't work using .Debug() in this simple example, but it does in the real project. I've copy pasted the logged SQL into the sqlite3 console, and the correct records are returned from the query.

https://gist.github.com/duskhacker/8541704

eager DB reverse tools

对于已经存在的数据库, 编写所有model是件费力费时的工作, 如果能够批量生成struct定义会带来极大方便, 例如

gorm dump  mysql://root:123@databasename 

Go毕竟是一门新语言, 从头开始构建一个生产系统的机会不多, 在旧系统周边用起来的机会比较多, 保持对外界的灵活性能增加生命力.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.