summaryrefslogtreecommitdiff
path: root/chimere/scripts/upgrade.py
blob: f260a07092494e7c776d58b581b8fea8835dcefe (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
#!/usr/bin/python
# -*- coding: utf-8 -*-

import sys
sys.path.append('.')

from django.core.management import setup_environ
import settings

setup_environ(settings)

from django.db import connection, transaction

cursor = connection.cursor()

from main.models import Area, Route
from django.contrib.gis.geos import LineString

# early versions before 0.1: urn field doesn't exist for area

import htmlentitydefs, re

def slugfy(text, separator):
    ret = u""
    text = text.strip()
    for c in text.lower():
        try:
           ret += htmlentitydefs.codepoint2name[ord(c)][0]
        except:
            ret += c
    ret = re.sub("\W", " ", ret)
    ret = re.sub(" +", separator, ret)
    return ret.strip()

QUERY_CHECK_TABLE = """SELECT c.relname FROM pg_class c
WHERE c.relname = '%s';"""

query = """SELECT a.attname AS field FROM pg_class c, pg_attribute a
    WHERE c.relname = 'main_area' AND a.attnum > 0 AND a.attrelid = c.oid
          AND a.attname='urn';"""
cursor.execute(query)
transaction.commit_unless_managed()

row = cursor.fetchone()
if not row:
    query_update = "ALTER TABLE main_area ADD COLUMN urn VARCHAR(50) \
UNIQUE"
    cursor.execute(query_update)
    transaction.commit_unless_managed()
    areas = Area.objects.all()
    print " * urn field created in table main_area"
    for area in areas:
        urn = slugfy(area.name, "-")
        area.urn = urn
        area.save()
        print " * area %s urn is now: %s" % (area.name, area.urn)

    query = "ALTER TABLE main_area ALTER COLUMN urn SET not null;"
    cursor.execute(query)
    transaction.commit_unless_managed()
    print " * urn field has now the constraint NOT NULL"

from django.contrib.auth.models import Permission, ContentType

# check if permission have been correctly set for each areas
areas = Area.objects.all()
for area in areas:
    content_type = ContentType.objects.get(app_label="main",
            model="area")
    mnemo = 'change_area_' + area.urn
    perm = Permission.objects.filter(codename=mnemo)
    if not perm:
        lbl = "Can change " + area.name
        perm = Permission(name=lbl, content_type_id=content_type.id,
                          codename=mnemo)
        perm.save()
        print ' * permission "' + lbl + '" has been created'
        print " WARNING: don't forget to update administrator's rights with \
this new permission"

# early versions before 0.1: subcategory_areas table doesn't exist
# version 1.0 subcategory_areas renamed to main_subcategory_areas

query = QUERY_CHECK_TABLE % 'main_subcategory_areas'
cursor.execute(query)
transaction.commit_unless_managed()

row = cursor.fetchone()
if not row:
    query = QUERY_CHECK_TABLE % 'subcategory_areas'
    cursor.execute(query)
    transaction.commit_unless_managed()

    row = cursor.fetchone()
    if row:
        query_rename = """ALTER TABLE subcategory_areas RENAME TO main_subcategory_areas;"""
        cursor.execute(query_rename)
        transaction.commit_unless_managed()
        print " * subcategory_areas renamed to main_subcategory_areas"
    else:
        query_create = """
CREATE TABLE "main_subcategory_areas" (
    "id" serial NOT NULL PRIMARY KEY,
    "subcategory_id" integer NOT NULL REFERENCES "main_subcategory" ("id")
                                                  DEFERRABLE INITIALLY DEFERRED,
    "area_id" integer NOT NULL REFERENCES "main_area" ("id")
                                                  DEFERRABLE INITIALLY DEFERRED,
    UNIQUE ("subcategory_id", "area_id"));
"""
        cursor.execute(query_create)
        transaction.commit_unless_managed()
        print " * main_subcategory_areas created"

# early versions before 0.1: main_tinyurl table doesn't exist

query = QUERY_CHECK_TABLE % 'main_tinyurl'
cursor.execute(query)
transaction.commit_unless_managed()

row = cursor.fetchone()
if not row:
    query_create = """
CREATE TABLE "main_tinyurl" (
    "id" serial NOT NULL PRIMARY KEY,
    "parameters" varchar(500) NOT NULL);
"""
    cursor.execute(query_create)
    transaction.commit_unless_managed()
    print " * main_tinyurl created"


# early versions before 0.1: save area with wrong SRID
# only errors with default SRID is managed adapt the script for your SRID

from osgeo import osr

srs = osr.SpatialReference()
srs.ImportFromEPSG(4326) # WGS84
ll = srs.CloneGeogCS()
srs.ImportFromEPSG(settings.EPSG_PROJECTION)
proj = osr.CoordinateTransformation(srs, ll)

changed = False
areas = Area.objects.all()
for area in areas:
    # only one test: assume each point as been save with the same SRID...
    if area.upper_left_corner.srid == 4326 and area.upper_left_corner.x > 90 \
                                           or area.upper_left_corner.x < -90:
        changed = True
        pt = proj.TransformPoint(area.upper_left_corner.y,
                                 area.upper_left_corner.x)
        area.upper_left_corner.x = pt[0]
        area.upper_left_corner.y = pt[1]
        pt = proj.TransformPoint(area.lower_right_corner.y,
                                 area.lower_right_corner.x)
        area.lower_right_corner.x = pt[0]
        area.lower_right_corner.y = pt[1]
        area.save()
if changed:
    print " * projections of areas corrected"

# early versions before 0.1: save route with wrong SRID
# only errors with default SRID is managed adapt the script for your SRID

changed = False
routes = Route.objects.all()
for route in routes:
    # only one test: assume each point as been save with the same SRID...
    if route.route and route.route.srid == 4326 and \
       route.route[0][0] > 90 or route.route[0][0] < -90:
        changed = True
        new_route = []
        for pt in route.route:
            pt = proj.TransformPoint(pt[0], pt[1])
            new_route.append((pt[0], pt[1]))
        route.route = LineString(new_route)
        route.save()
if changed:
    print " * projections of routes corrected"