|
1 import os |
|
2 from django.conf import settings |
|
3 from django.core.management import call_command |
|
4 from django.db import connection |
|
5 |
|
6 def spatialite_init_file(): |
|
7 # SPATIALITE_SQL may be placed in settings to tell |
|
8 # GeoDjango to use a specific user-supplied file. |
|
9 return getattr(settings, 'SPATIALITE_SQL', 'init_spatialite-2.3.sql') |
|
10 |
|
11 def create_test_spatial_db(verbosity=1, autoclobber=False, interactive=False): |
|
12 "Creates a spatial database based on the settings." |
|
13 |
|
14 # Making sure we're using PostgreSQL and psycopg2 |
|
15 if settings.DATABASE_ENGINE != 'sqlite3': |
|
16 raise Exception('SpatiaLite database creation only supported on sqlite3 platform.') |
|
17 |
|
18 # Getting the test database name using the SQLite backend's |
|
19 # `_create_test_db`. Unless `TEST_DATABASE_NAME` is defined, |
|
20 # it returns ":memory:". |
|
21 db_name = connection.creation._create_test_db(verbosity, autoclobber) |
|
22 |
|
23 # Closing out the current connection to the database set in |
|
24 # originally in the settings. This makes it so `initialize_spatialite` |
|
25 # function will be run on the connection for the _test_ database instead. |
|
26 connection.close() |
|
27 |
|
28 # Point to the new database |
|
29 settings.DATABASE_NAME = db_name |
|
30 connection.settings_dict["DATABASE_NAME"] = db_name |
|
31 can_rollback = connection.creation._rollback_works() |
|
32 settings.DATABASE_SUPPORTS_TRANSACTIONS = can_rollback |
|
33 connection.settings_dict["DATABASE_SUPPORTS_TRANSACTIONS"] = can_rollback |
|
34 |
|
35 # Finally, loading up the SpatiaLite SQL file. |
|
36 load_spatialite_sql(db_name, verbosity=verbosity) |
|
37 |
|
38 if verbosity >= 1: |
|
39 print 'Creation of spatial database %s successful.' % db_name |
|
40 |
|
41 # Syncing the database |
|
42 call_command('syncdb', verbosity=verbosity, interactive=interactive) |
|
43 |
|
44 def load_spatialite_sql(db_name, verbosity=1): |
|
45 """ |
|
46 This routine loads up the SpatiaLite SQL file. |
|
47 """ |
|
48 # Getting the location of the SpatiaLite SQL file, and confirming |
|
49 # it exists. |
|
50 spatialite_sql = spatialite_init_file() |
|
51 if not os.path.isfile(spatialite_sql): |
|
52 raise Exception('Could not find the SpatiaLite initialization SQL file: %s' % spatialite_sql) |
|
53 |
|
54 # Opening up the SpatiaLite SQL initialization file and executing |
|
55 # as a script. |
|
56 sql_fh = open(spatialite_sql, 'r') |
|
57 try: |
|
58 cur = connection.cursor() |
|
59 cur.executescript(sql_fh.read()) |
|
60 finally: |
|
61 sql_fh.close() |