modl icon indicating copy to clipboard operation
modl copied to clipboard

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

Open joaojeronimo opened this issue 11 years ago • 1 comments

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.

joaojeronimo avatar Mar 04 '14 13:03 joaojeronimo

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.

vkryukov avatar Oct 07 '14 07:10 vkryukov