Skip to content

last_insert_rowid() returns 1 after INSERT with RETURNING #5490

@LeMikaelF

Description

@LeMikaelF

Description

last_insert_rowid() is not updated when INSERT uses RETURNING. The value is clobbered by the ephemeral table's NewRowid instruction, which always assigns rowid 1. Inside RETURNING expressions last_insert_rowid() returns the correct value, but after the statement completes it reverts to the ephemeral table's rowid.

Reproducer

CREATE TABLE t1(a INTEGER PRIMARY KEY, b TEXT);

INSERT INTO t1 VALUES(10, 'a');
SELECT last_insert_rowid();
-- Turso: 10
-- SQLite: 10

-- Inside RETURNING: correct
INSERT INTO t1 VALUES(20, 'b') RETURNING last_insert_rowid();
-- Turso: 20
-- SQLite: 20

-- After RETURNING: wrong
SELECT last_insert_rowid();
-- Turso: 1
-- SQLite: 20

INSERT INTO t1 VALUES(50, 'c') RETURNING *;
SELECT last_insert_rowid();
-- Turso: 1
-- SQLite: 50

Per SQLite documentation: "An INSERT that fails due to a constraint violation is not a successful INSERT and does not change the value returned by this routine." Since INSERT with RETURNING succeeds, last_insert_rowid() should reflect the real table's rowid, not the ephemeral table's.

The ephemeral table used to buffer RETURNING rows uses NewRowid which sets last_insert_rowid to 1, clobbering the real value.


This issue brought to you by Mikaël and Claude Code.

Metadata

Metadata

Assignees

No one assigned

    Type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions