python 2.7 - SQLite starting rowid of 0 -
i'm trying set sqlite table rowid starts 0 instead of default 1. end goal able run first insert statement , have insert rowid 0. explicitly setting rowid 0 first insert not option.
i've tried few things related autoincrement not having luck getting work cleanly. successful way i've found insert row rowid of -1 , delete later. works it's messy , i'd find cleaner way of doing it. working in python 2.7 built-in sqlite3 library.
the bottom-line question:
is there cleaner way start rowid 0 other manually inserting -1 value , removing later?
some side information:
i found similar question here , played autoincrement settings: set start value autoincrement in sqlite
the sqlite_sequence table doesn't seem work negative numbers. used following test it:
import sqlite3 con = sqlite3.connection('db.db') cur = con.cursor() cur.execute("create table test(id integer primary key autoincrement, val text)") cur.execute("insert sqlite_sequence (name,seq) values (?,?)", ('test',-1)) cur.execute("insert test (val) values (?)", ('testval',)) #becomes rowid 1 cur.execute("insert test (val) values (?)", ('testval',)) #becomes rowid 2 cur.execute("insert test (val) values (?)", ('testval',)) #becomes rowid 3 cur.execute("select rowid, id, val test") print cur.fetchall()
with -1 inserted sqlite_sequence should set next rowid 0, it's using 1 instead. if sqlite_sequence initialized positive number rowids expected.
import sqlite3 con = sqlite3.connection('db.db') cur = con.cursor() cur.execute("create table test(id integer primary key autoincrement, val text)") cur.execute("insert sqlite_sequence (name,seq) values (?,?)", ('test',10)) cur.execute("insert test (val) values (?)", ('testval',)) #becomes rowid 11 cur.execute("insert test (val) values (?)", ('testval',)) #becomes rowid 12 cur.execute("insert test (val) values (?)", ('testval',)) #becomes rowid 13 cur.execute("select rowid, id, val test") print cur.fetchall()
does auto-increment not support negative numbers this? couldn't find mention of in sqlite documentation.
the documentation says that, autoincrement,
the rowid chosen new row @ least 1 larger largest rowid has ever before existed in same table.
so algorithm looks not @ value in sqlite_sequence
table, @ last row in table, , uses larger of these 2 values.
when table empty, largest actual rowid instead assumed zero. done first inserted rowid becomes 1
.
therefore, way generate rowid less 1 have row in table.
Comments
Post a Comment