How to modify SQLite3 schemas

Sunday, 31 January 2016
Écrit par
Grégory Soutadé

SQLite3 is a wonderful library allowing to have a tiny SQL database in a simple file rather than a big (but more powerful) SQL server. I use it a lot for my projects to be "self contained".

Unfortunately, SQLite3 has some limitations. One of them is the unavailability to modify columns constraints or to delete them.

By upgrading from Django 1.5 to Django 1.8, I found that I cannot add a new user to my database. The problem is that the constraint of the last_login column in the User schema (controlled by Django framework) has changed. Now it can be NULL, while the table was created with a non NULL constraint. I got this exception :

NOT NULL constraint failed: auth_user.last_login

I already faces this kind of situation. The solution is pretty simple and does not requires modifying code.

First of all, make a backup of your database.

To get round this problem, we will export database in SQL commands format, modify it with a simple text editor and import it again.

Assume that your database is named denote.db

$ cp denote.db denote.db.bak
$ sqlite3 denote.db
$ .output denote.sql
$ .dump
$ .exit
$ rm denote.db
$ emacs denote.sql
$ sqlite3 -init denote.sql denote.db
$ sudo apachectl restart

That's all !

For complex modifications, it can be long/boring, so I recommend to use tools like sed, perl or python scripts, regexp replace mode from emacs...

Auteur :

e-mail* :

Le commentaire :

* Seulement pour être notifié d'une réponse à cet article
* Only for email notification