Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
joaojeronimo opened this issue Mar 4, 2014 · 1 comment

Comments

@joaojeronimo
Copy link

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
Copy link
Contributor

vkryukov commented Oct 7, 2014

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants