sqlite | id generator

他のデータは扱わず、ユーザーIDだけ管理するサービスは、sqliteのautoincrementを利用してID生成してみる。
sqlite使ったことが無いので、適当。。。

http://www.sqlite.org/sqlite.html

$ sqlite3 filename

これでデータベースできるみたい。

$ sqlite3 data/sqlite/def
SQLite version 3.3.6
Enter ".help" for instructions
sqlite> .databases
seq  name             file                                                      
---  ---------------  ----------------------------------------------------------
0    main             /home/opt/home/socialic.tarot/data/sqlite/def              

* create table

sqlite> create table users(
   ...> id integer primary key,
   ...> authid varchar(255) not null unique,
   ...> mail varchar(255) unique,
   ...> passhash varchar(32),
   ...> created_at datetime default current_timestamp,
   ...> updated_at datetime default current_timestamp );

on updateが使えないので、trigger作成
* trigger

sqlite> create trigger update_updated_at AFTER UPDATE ON users 
   ...> BEGIN
   ...> update users set updated_at=CURRENT_TIMESTAMP where id=old.id;
   ...> END;
sqlite> insert into users(id, authid) values(null,'test001');
sqlite> insert into users(id, authid) values(null,'test002');
sqlite> insert into users(id, authid) values(null,'test001');
SQL error: column authid is not unique
sqlite> update users set mail='mail' where id=1;
sqlite> select * from users;
1|test001|mail||2012-01-11 04:28:47|2012-01-11 04:29:37
2|test002|||2012-01-11 04:28:49|2012-01-11 04:28:49

・idは自動で増えました。
・uniqueもOK
・updated_atも更新されています!

OKで、後は簡単なスクリプトで、insertして、select id するだけです。

最後にinsertしたidを取得

sqlite> select * from users;
1|test001|mail||2012-01-11 04:28:47|2012-01-11 04:29:37
2|test002|||2012-01-11 04:28:49|2012-01-11 04:28:49
sqlite> select last_insert_rowid() ;
0
sqlite> insert into users( id, authid ) values(null,'test3');
sqlite> select last_insert_rowid() ;
3

同じコネクション内でinsertした値が対象となります。
ので、最初の select は 0 です。

This entry was posted on 水曜日, 1月 11th, 2012 at 1:32 PM and is filed under sqlite. You can follow any responses to this entry through the RSS 2.0 feed. Both comments and pings are currently closed.

Unityによるゲームを公開しております iOS/Android
https://itunes.apple.com/jp/app/lost-knight-3d-action/id900917032
https://play.google.com/store/apps/details?id=com.groundroad.runknight

各種開発支援・機能開発等小さいお仕事などもお請けしております。
unity開発支援, PHPシステム開発, javascript/html5 フロント開発, titanium mobileアプリ開発
お気軽にお問い合わせください
大崎・五反田近郊での対面でのお打ち合わせはいつでも可能です。