~lifeless/python-oops-tools/prune

« back to all changes in this revision

Viewing changes to src/oopstools/oops/migrations/0001_add_custom_group_concat_sql.py

  • Committer: Robert Collins
  • Date: 2011-10-13 20:18:51 UTC
  • Revision ID: robertc@robertcollins.net-20111013201851-ym8jmdhoeol3p83s
Export of cruft-deleted tree.

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
# Copyright 2005-2011 Canonical Ltd.  All rights reserved.
 
2
#
 
3
# This program is free software: you can redistribute it and/or modify
 
4
# it under the terms of the GNU Affero General Public License as published by
 
5
# the Free Software Foundation, either version 3 of the License, or
 
6
# (at your option) any later version.
 
7
#
 
8
# This program is distributed in the hope that it will be useful,
 
9
# but WITHOUT ANY WARRANTY; without even the implied warranty of
 
10
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 
11
# GNU Affero General Public License for more details.
 
12
#
 
13
# You should have received a copy of the GNU Affero General Public License
 
14
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
 
15
 
 
16
# encoding: utf-8
 
17
from south.db import db
 
18
from south.v2 import SchemaMigration
 
19
 
 
20
class Migration(SchemaMigration):
 
21
 
 
22
    def forwards(self, orm):
 
23
        # Note that Postgres does not support GROUP_CONCAT directly and needs
 
24
        # to emulate it.
 
25
        # Stuart suggests:
 
26
        # <stub> http://www.postgresql.org/docs/current/static/xaggr.html has
 
27
        # the array_accum aggregate function, which can be combined with
 
28
        # array_to_string at
 
29
        # http://www.postgresql.org/docs/8.4/static/functions-array.html to do
 
30
        # something similar.
 
31
        # <stub> ie. array_to_string(array_accum(foo),',') should be
 
32
        # equivalent to group_concat(foo)
 
33
        #
 
34
        # Since this custom SQL is run by automatically when running
 
35
        # migrations, we first need to drop the AGGREGATE and the FUNCTION 
 
36
        # before trying to CREATE a new one.
 
37
        db.execute("DROP AGGREGATE IF EXISTS GROUP_CONCAT(text);")
 
38
        db.execute("DROP FUNCTION IF EXISTS comma_array_to_string(text[]);")
 
39
        db.execute("CREATE FUNCTION comma_array_to_string(text[]) RETURNS text AS $$ SELECT array_to_string($1,','); $$ LANGUAGE SQL;")
 
40
        db.execute("""CREATE AGGREGATE GROUP_CONCAT(text)
 
41
            (
 
42
                sfunc = array_append,
 
43
                stype = text[],
 
44
                finalfunc = comma_array_to_string,
 
45
                initcond = '{}'
 
46
            );""")
 
47
 
 
48
    def backwards(self, orm):
 
49
        pass