The day PostgreSQL saved my butt from Django and TSearch2

LingQ recently integrated TSearch2 a full text engine for PostgreSQL. TSearch2 improves the search accuracy and speed it up. LingQ is built with Django, and we ran into a major issue regarding Django and TSearch2 integration: the test command which runs unit tests was broken.

When unit tests are run; Django creates an empty database. Thus the operations performed during the tests don't overwrite the data on the working database. TSearch2 needs to be installed on the newly created database; it needs to install a new SQL type: tsvector and some other stuffs. Without it the table creation failed.

Unfortunately Django does not provide any means of running SQL code immediately after the database creation.

The solution: Template Databases

PostgresSQL provide a mechanism called Template Databases. The database creation works by copying an existing database: template1. Installing TSearch2 on the database template1 solves the problem:

sudo -u postgres psql template1 < /path/to/tsearch2.sql

Everything runs smoothly now. Thanks to PostgreSQL we did not have to throw away all our unit tests to use TSearch2!