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

LastInsertId method returns 0? #13

Open
vendion opened this issue Apr 13, 2012 · 6 comments
Open

LastInsertId method returns 0? #13

vendion opened this issue Apr 13, 2012 · 6 comments

Comments

@vendion
Copy link

vendion commented Apr 13, 2012

I don't know if this driver implements the LastInsertId method of the Result type of the database/sql package or not but when I tried to use it I got back a 0 but in Postgres I could see the last ID was 98.

The way that I tried it out is as follows:

result, err := db.Exec("insert into commands (command,slot) values ($1,$2)", incoming.Command, incoming.Slot)
if err != nil {
    l.Printf("Error inserting into the commands table: %v\n", err)
    return
}

id, _ := result.LastInsertId()
fmt.Println(id) //Prints 0
@lxn
Copy link
Owner

lxn commented Apr 13, 2012

This indeed isn't supported. The main obstacle is to get at the name of the primary key sequence.

@betamos
Copy link

betamos commented Apr 30, 2012

Subscribing, very useful

@temoto
Copy link
Contributor

temoto commented Jan 22, 2013

If you use not ancient PostgreSQL, you can do insert into <table> ... returning <id-column> and read it like normal select statement, e.g. Scan().

@lxn
Copy link
Owner

lxn commented Jan 22, 2013

Yes, returning is nice, but to implement LastInsertId, how would we know the exact name of the id column without guessing?

@temoto
Copy link
Contributor

temoto commented Jan 22, 2013

I guess there is no way without fetching table structure. And even then you can't do anything for table like id1 serial, id2 serial, primary key (id1, id2).

Basically, LastInsertId interface is not as generic as SQL standard. That's why i'm suggesting him to use other way to get inserted ids.

@brianoh
Copy link

brianoh commented Oct 14, 2013

I'm using "SELECT LASTVAL()" which appears to work OK, and alternatively a query using eg. " RETURNING iKey" appears to work OK.

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

5 participants