Commit | Line | Data |
---|---|---|
652c5d02 EMS |
1 | # encoding: utf-8 |
2 | ||
a10aee41 | 3 | from django import db |
13328043 | 4 | from django.db.models import signals |
652c5d02 EMS |
5 | |
6 | import auf.django.references.models | |
7 | ||
13328043 | 8 | |
652c5d02 | 9 | def post_syncdb(sender, **kwargs): |
a10aee41 EMS |
10 | """Création des vues vers datamaster.""" |
11 | ||
12 | # On ne crée des vues que si on est sur une BD MySQL. | |
13 | # L'attribut db.connection.vendor n'est présent qu'à partir de Django | |
14 | # 1.3 | |
13328043 EMS |
15 | if (hasattr(db.connection, 'vendor') |
16 | and db.connection.vendor != 'mysql') or \ | |
a10aee41 EMS |
17 | 'mysql' not in db.backend.__name__: |
18 | return | |
19 | ||
20 | cursor = db.connection.cursor() | |
21 | ||
22 | # Vérifions qu'on a une BD qui s'appelle 'datamaster' | |
23 | if not cursor.execute("SHOW DATABASES LIKE 'datamaster'"): | |
24 | return | |
25 | ||
26 | # Déterminons la liste de tables de référence dans datamaster | |
27 | cursor.execute("SHOW TABLES IN datamaster LIKE 'ref\\_%%'") | |
28 | datamaster_tables = set(row[0] for row in cursor) | |
29 | ||
30 | # Déterminons la liste de tables que nous avons déjà et | |
31 | # enlevons-les des tables de datamaster | |
32 | cursor.execute("SHOW FULL TABLES WHERE Table_type != 'VIEW'") | |
33 | my_tables = set(row[0] for row in cursor) | |
34 | datamaster_tables.difference_update(my_tables) | |
35 | ||
36 | # On peut maintenant créer les vues | |
37 | cursor = db.connection.cursor() | |
13328043 | 38 | schema = db.connection.settings_dict['NAME'] |
a10aee41 | 39 | for table in datamaster_tables: |
97462e05 | 40 | print u"Création d'une vue vers datamaster.%s" % table |
a10aee41 | 41 | cursor.execute( |
13328043 EMS |
42 | 'CREATE OR REPLACE VIEW `%s` AS SELECT * FROM datamaster.`%s`' % |
43 | (table, table) | |
a10aee41 | 44 | ) |
652c5d02 | 45 | |
13328043 EMS |
46 | # Vérifions s'il y a des foreign keys vers cette vue. |
47 | cursor.execute( | |
48 | ''' | |
49 | SELECT TABLE_NAME, CONSTRAINT_NAME | |
50 | FROM information_schema.REFERENTIAL_CONSTRAINTS | |
51 | WHERE CONSTRAINT_SCHEMA = %s AND REFERENCED_TABLE_NAME = %s | |
52 | ''', | |
53 | (schema, table) | |
54 | ) | |
55 | for row in cursor: | |
56 | db.connection.cursor().execute( | |
57 | 'ALTER TABLE %s DROP FOREIGN KEY %s' % row | |
58 | ) | |
59 | ||
60 | ||
652c5d02 | 61 | signals.post_syncdb.connect(post_syncdb, sender=auf.django.references.models) |