jmoiron / modl

golang database modelling library
MIT License
479 stars 48 forks source link

Quick question: How to insert an row that has a primary key that will be created in the database ? #12

Open joaojeronimo opened 10 years ago

joaojeronimo commented 10 years ago

I'm using PostgreSQL and in my table I have the primary key like

CREATE TABLE IF NOT EXISTS users (
  id UUID NOT NULL PRIMARY KEY DEFAULT UUID_GENERATE_V4(),
  name VARCHAR(320) NOT NULL
);
CREATE INDEX ON users (email);

Which means that INSERT INTO users (name) VALUES ("Bob"); will work, and postgresql will generate a UUID in the id column.

I'm trying to do the same with modl, but as the field id is empty in my struct, apparently modl is filling with an empty string ("") and pg complains that's not a valid uuid type.

type User struct {
    Id             string    `db:"id" json:"id,omitempty"`
    Name           string    `db:"name" json:"name,omitempty"`
}

dbmap := modl.NewDbMap()
dbmap.AddTable(User{}, "users")

user := &User{}
user.Name = "Bob"
err := dbmap.Insert(&user)
if err != nil {
    panic(err)
}

I this panic PANIC: pq: invalid input syntax for uuid: ""

How can I achieve this ? I tried using db:"-" in the Id field, and that worked for the insert, but that makes it harder to use the same struct after.

vkryukov commented 9 years ago

You haven't set the key in dbmap. Since DbMap.AddTable returns a *TableMap, you can chain AddTable call with SetKeys, like this:

dbmap.AddTable(User{}, "users").SetKeys(true, "id")

That should solve your problem.