xaver23
xaver23

Reputation: 1321

Is there a last_insert_id method for Sequel?

After an insert, I need to know the ID from the row, how can I do that?

Upvotes: 3

Views: 1930

Answers (2)

Greg Campbell
Greg Campbell

Reputation: 15302

According to the Dataset#insert documentation, the return value for insert() is usually the primary key of the inserted row, but it depends which adapter you're using.

Upvotes: 2

knut
knut

Reputation: 27865

I tried the same with SQL-Server and a uniqueidentifier, but without success. The uniqueidentifier is not returned.

Extract from my Definition:

CREATE TABLE [dbo].[MyTable](
     [ID] [uniqueidentifier] NOT NULL,
     [Data] [nvarchar](255) NULL
)
ALTER TABLE [dbo].[MyTable] ADD  DEFAULT (newid()) FOR [ID]

When I insert with Sequel:

DB[:MyTable].insert( :Data => 'data' )

the dataset is added with a uniqueidentifier, but the return code if Dataset#insert is nil.

With

DB[:MyTable].insert(:ID => Sequel.function(:newid),  :Data => 'data' )

you get the same result.

I tried

key = Sequel.function(:ID)
DB[:MyTable].insert(:ID => key,  :Data => 'data' )

but 'key' is only the function call, not the value. With Sequel.function(:ID).f you get an "Invalid column name ID'."-error

But if you use a Model, the you get the uniqueidentifier:

class MyTable < Sequel::Model(:MyTable); end 
entry = MyTable.create(:Data => 'data')
$uniqueidentifier = entry[:ID]

Upvotes: 1

Related Questions