Django

Code

Ticket #87: management.py

File management.py, 25.4 kB (added by Jason Huggins, 3 years ago)
Line 
1 # Django management-related functions, including "CREATE TABLE" generation and
2 # development-server initialization.
3
4 import django
5 import os, re, sys
6
7 MODULE_TEMPLATE = '''    {%% if perms.%(app)s.%(addperm)s or perms.%(app)s.%(changeperm)s %%}
8     <tr>
9         <th>{%% if perms.%(app)s.%(changeperm)s %%}<a href="%(app)s/%(mod)s/">{%% endif %%}%(name)s{%% if perms.%(app)s.%(changeperm)s %%}</a>{%% endif %%}</th>
10         <td class="x50">{%% if perms.%(app)s.%(addperm)s %%}<a href="%(app)s/%(mod)s/add/" class="addlink">{%% endif %%}Add{%% if perms.%(app)s.%(addperm)s %%}</a>{%% endif %%}</td>
11         <td class="x75">{%% if perms.%(app)s.%(changeperm)s %%}<a href="%(app)s/%(mod)s/" class="changelink">{%% endif %%}Change{%% if perms.%(app)s.%(changeperm)s %%}</a>{%% endif %%}</td>
12     </tr>
13     {%% endif %%}'''
14
15 APP_ARGS = '[app app ...]'
16
17 # Use django.__path__[0] because we don't know which directory django into
18 # which has been installed.
19 PROJECT_TEMPLATE_DIR = os.path.join(django.__path__[0], 'conf/%s_template')
20 ADMIN_TEMPLATE_DIR = os.path.join(django.__path__[0], 'conf/admin_templates')
21
22 def _get_packages_insert(app_label):
23     return "INSERT INTO packages (label, name) VALUES ('%s', '%s')" % (app_label, app_label)
24
25 def _get_permission_codename(action, opts):
26     return '%s_%s' % (action, opts.object_name.lower())
27
28 def _get_all_permissions(opts):
29     "Returns (codename, name) for all permissions in the given opts."
30     perms = []
31     if opts.admin:
32         for action in ('add', 'change', 'delete'):
33             perms.append((_get_permission_codename(action, opts), 'Can %s %s' % (action, opts.verbose_name)))
34     return perms + list(opts.permissions)
35
36 def _get_permission_insert(name, codename, opts):
37     return "INSERT INTO auth_permissions (name, package, codename) VALUES ('%s', '%s', '%s')" % \
38         (name.replace("'", "''"), opts.app_label, codename)
39
40 def _get_contenttype_insert(opts):
41     return "INSERT INTO content_types (name, package, python_module_name) VALUES ('%s', '%s', '%s')" % \
42         (opts.verbose_name, opts.app_label, opts.module_name)
43
44 def _is_valid_dir_name(s):
45     return bool(re.search(r'^\w+$', s))
46
47 def get_sql_create(mod):
48     "Returns a list of the CREATE TABLE SQL statements for the given module."
49     from django.core import db, meta
50     final_output = []
51     for klass in mod._MODELS:
52         opts = klass._meta
53         table_output = []
54         for f in opts.fields:
55             if isinstance(f, meta.ForeignKey):
56                 rel_field = f.rel.get_related_field()
57                 # If the foreign key points to an AutoField, the foreign key
58                 # should be an IntegerField, not an AutoField. Otherwise, the
59                 # foreign key should be the same type of field as the field
60                 # to which it points.
61                 if rel_field.__class__.__name__ == 'AutoField':
62                     data_type = 'IntegerField'
63                 else:
64                     data_type = rel_field.__class__.__name__
65             else:
66                 rel_field = f
67                 data_type = f.__class__.__name__
68             col_type = db.DATA_TYPES[data_type]
69             if col_type is not None:
70                 field_output = [f.name, col_type % rel_field.__dict__]
71                 field_output.append('%sNULL' % (not f.null and 'NOT ' or ''))
72                 if f.unique:
73                     field_output.append('UNIQUE')
74                 if f.primary_key:
75                     field_output.append('PRIMARY KEY')
76                 if f.rel:
77                     field_output.append('REFERENCES %s (%s)' % \
78                         (f.rel.to.db_table, f.rel.to.get_field(f.rel.field_name).name))
79                 table_output.append(' '.join(field_output))
80         if opts.order_with_respect_to:
81             table_output.append('_order %s NULL' % db.DATA_TYPES['IntegerField'])
82         for field_constraints in opts.unique_together:
83             table_output.append('UNIQUE (%s)' % ", ".join(field_constraints))
84
85         full_statement = ['CREATE TABLE %s (' % opts.db_table]
86         for i, line in enumerate(table_output): # Combine and add commas.
87             full_statement.append('    %s%s' % (line, i < len(table_output)-1 and ',' or ''))
88         full_statement.append(')')
89         final_output.append('\n'.join(full_statement))
90        
91         if (db.DATABASE_ENGINE == 'oracle') & (opts.has_auto_field):
92             # To simulate auto-incrementing primary keys in Oracle
93                        
94             sequence_statement = 'CREATE SEQUENCE %s_sq\n' % opts.db_table
95             final_output.append(sequence_statement)
96            
97             trigger_statement = "" + \
98                 "CREATE OR REPLACE trigger %s_tr\n"    % opts.db_table + \
99                 "  before insert on %s\n"           % opts.db_table + \
100                 "    for each row\n"  + \
101                 "      begin\n" + \
102                 "        select %s_sq.NEXTVAL into :new.id from DUAL;\n" % opts.db_table + \
103                 "      end;\n"
104             final_output.append(trigger_statement)
105                                
106
107    
108     for klass in mod._MODELS:
109         opts = klass._meta
110         for f in opts.many_to_many:
111             table_output = ['CREATE TABLE %s (' % f.get_m2m_db_table(opts)]
112             table_output.append('    id %s NOT NULL PRIMARY KEY,' % db.DATA_TYPES['AutoField'])
113             table_output.append('    %s_id %s NOT NULL REFERENCES %s (%s),' % \
114                 (opts.object_name.lower(), db.DATA_TYPES['IntegerField'], opts.db_table, opts.pk.name))
115             table_output.append('    %s_id %s NOT NULL REFERENCES %s (%s),' % \
116                 (f.rel.to.object_name.lower(), db.DATA_TYPES['IntegerField'], f.rel.to.db_table, f.rel.to.pk.name))
117             table_output.append('    UNIQUE (%s_id, %s_id)' % (opts.object_name.lower(), f.rel.to.object_name.lower()))
118             table_output.append(')')
119             final_output.append('\n'.join(table_output))
120            
121             if (db.DATABASE_ENGINE == 'oracle') & (opts.has_auto_field):
122                 sequence_statement = 'CREATE SEQUENCE %s_sq\n' % f.get_m2m_db_table(opts)
123                 final_output.append(sequence_statement)   
124                                
125                 trigger_statement = "" + \
126                     "CREATE OR REPLACE trigger %s_tr\n"    % f.get_m2m_db_table(opts) + \
127                     "  before insert on %s\n"           % f.get_m2m_db_table(opts) + \
128                     "    for each row\n"  + \
129                     "      begin\n" + \
130                     "        select %s_sq.NEXTVAL into :new.id from DUAL;\n" % f.get_m2m_db_table(opts) + \
131                     "      end;\n"
132                 final_output.append(trigger_statement)               
133            
134     return final_output
135 get_sql_create.help_doc = "Prints the CREATE TABLE SQL statements for the given app(s)."
136 get_sql_create.args = APP_ARGS
137
138 def get_sql_delete(mod):
139     "Returns a list of the DROP TABLE SQL statements for the given module."
140     from django.core import db
141     try:
142         cursor = db.db.cursor()
143     except:
144         cursor = None
145     output = []
146     for klass in mod._MODELS:
147         try:
148             if cursor is not None:
149                 # Check whether the table exists.
150                 cursor.execute("SELECT COUNT(1) FROM %s" % klass._meta.db_table)
151         except:
152             # The table doesn't exist, so it doesn't need to be dropped.
153             db.db.rollback()
154         else:
155             output.append("DROP TABLE %s;" % klass._meta.db_table)
156             if db.DATABASE_ENGINE == 'oracle':
157                 output.append("DROP SEQUENCE %s_sq" % klass._meta.db_table)
158            
159     for klass in mod._MODELS:
160         opts = klass._meta
161         for f in opts.many_to_many:
162             try:
163                 if cursor is not None:
164                     cursor.execute("SELECT COUNT(1) FROM %s" % f.get_m2m_db_table(opts))
165             except:
166                 db.db.rollback()
167             else:
168                 output.append("DROP TABLE %s;" % f.get_m2m_db_table(opts))
169                 if db.DATABASE_ENGINE == 'oracle':
170                     output.append("DROP SEQUENCE %s_sq" % f.get_m2m_db_table(opts))
171     app_label = mod._MODELS[0]._meta.app_label
172
173     # Delete from packages, auth_permissions, content_types.
174     output.append("DELETE FROM packages WHERE label = '%s';" % app_label)
175     output.append("DELETE FROM auth_permissions WHERE package = '%s';" % app_label)
176     output.append("DELETE FROM content_types WHERE package = '%s';" % app_label)
177
178     # Delete from the admin log.
179     if cursor is not None:
180         cursor.execute("SELECT id FROM content_types WHERE package = %s", [app_label])
181         for row in cursor.fetchall():
182             output.append("DELETE FROM auth_admin_log WHERE content_type_id = %s;" % row[0])
183
184     return output[::-1] # Reverse it, to deal with table dependencies.
185 get_sql_delete.help_doc = "Prints the DROP TABLE SQL statements for the given app(s)."
186 get_sql_delete.args = APP_ARGS
187
188 def get_sql_reset(mod):
189     "Returns a list of the DROP TABLE SQL, then the CREATE TABLE SQL, for the given module."
190     return get_sql_delete(mod) + get_sql_all(mod)
191 get_sql_reset.help_doc = "Prints the DROP TABLE SQL, then the CREATE TABLE SQL, for the given app(s)."
192 get_sql_reset.args = APP_ARGS
193
194 def get_sql_initial_data(mod):
195     "Returns a list of the initial INSERT SQL statements for the given module."
196     output = []
197     app_label = mod._MODELS[0]._meta.app_label
198     output.append(_get_packages_insert(app_label))
199     app_dir = os.path.normpath(os.path.join(os.path.dirname(mod.__file__), '../sql'))
200     for klass in mod._MODELS:
201         opts = klass._meta
202         # Add custom SQL, if it's available.
203         sql_file_name = os.path.join(app_dir, opts.module_name + '.sql')
204         if os.path.exists(sql_file_name):
205             fp = open(sql_file_name, 'r')
206             output.append(fp.read())
207             fp.close()
208         # Content types.
209         output.append(_get_contenttype_insert(opts))
210         # Permissions.
211         for codename, name in _get_all_permissions(opts):
212             output.append(_get_permission_insert(name, codename, opts))
213     return output
214 get_sql_initial_data.help_doc = "Prints the initial INSERT SQL statements for the given app(s)."
215 get_sql_initial_data.args = APP_ARGS
216
217 def get_sql_sequence_reset(mod):
218     "Returns a list of the SQL statements to reset PostgreSQL sequences for the given module."
219     from django.core import db, meta
220     output = []
221     for klass in mod._MODELS:
222         for f in klass._meta.fields:
223             if isinstance(f, meta.AutoField):
224                 if db.DATABASE_ENGINE == 'postgresql':
225                     output.append("SELECT setval('%s_%s_seq', (SELECT max(%s) FROM %s));" % (klass._meta.db_table, f.name, f.name, klass._meta.db_table))
226                 else:
227                     raise "Not implemented yet for %s!" % (db.DATABASE_ENGINE)
228     return output
229 get_sql_sequence_reset.help_doc = "Prints the SQL statements for resetting PostgreSQL sequences for the given app(s)."
230 get_sql_sequence_reset.args = APP_ARGS
231
232 def get_sql_indexes(mod):
233     "Returns a list of the CREATE INDEX SQL statements for the given module."
234     output = []
235     for klass in mod._MODELS:
236         for f in klass._meta.fields:
237             if f.db_index:
238                 unique = f.unique and "UNIQUE " or ""
239                 output.append("CREATE %sINDEX %s_%s ON %s (%s);" % \
240                     (unique, klass._meta.db_table, f.name, klass._meta.db_table, f.name))
241     return output
242 get_sql_indexes.help_doc = "Prints the CREATE INDEX SQL statements for the given app(s)."
243 get_sql_indexes.args = APP_ARGS
244
245 def get_sql_all(mod):
246     "Returns a list of CREATE TABLE SQL and initial-data insert for the given module."
247     return get_sql_create(mod) + get_sql_initial_data(mod)
248 get_sql_all.help_doc = "Prints the CREATE TABLE and initial-data SQL statements for the given app(s)."
249 get_sql_all.args = APP_ARGS
250
251 def database_check(mod):
252     "Checks that everything is properly installed in the database for the given module."
253     from django.core import db
254     cursor = db.db.cursor()
255     app_label = mod._MODELS[0]._meta.app_label
256
257     # Check that the package exists in the database.
258     cursor.execute("SELECT 1 FROM packages WHERE label = %s", [app_label])
259     if cursor.rowcount < 1:
260 #         sys.stderr.write("The '%s' package isn't installed.\n" % app_label)
261         print _get_packages_insert(app_label)
262
263     # Check that the permissions and content types are in the database.
264     perms_seen = {}
265     contenttypes_seen = {}
266     for klass in mod._MODELS:
267         opts = klass._meta
268         perms = _get_all_permissions(opts)
269         perms_seen.update(dict(perms))
270         contenttypes_seen[opts.module_name] = 1
271         for codename, name in perms:
272             cursor.execute("SELECT 1 FROM auth_permissions WHERE package = %s AND codename = %s", (app_label, codename))
273             if cursor.rowcount < 1:
274 #                 sys.stderr.write("The '%s.%s' permission doesn't exist.\n" % (app_label, codename))
275                 print _get_permission_insert(name, codename, opts)
276         cursor.execute("SELECT 1 FROM content_types WHERE package = %s AND python_module_name = %s", (app_label, opts.module_name))
277         if cursor.rowcount < 1:
278 #             sys.stderr.write("The '%s.%s' content type doesn't exist.\n" % (app_label, opts.module_name))
279             print _get_contenttype_insert(opts)
280
281     # Check that there aren't any *extra* permissions in the DB that the model
282     # doesn't know about.
283     cursor.execute("SELECT codename FROM auth_permissions WHERE package = %s", (app_label,))
284     for row in cursor.fetchall():
285         try:
286             perms_seen[row[0]]
287         except KeyError:
288 #             sys.stderr.write("A permission called '%s.%s' was found in the database but not in the model.\n" % (app_label, row[0]))
289             print "DELETE FROM auth_permissions WHERE package='%s' AND codename = '%s';" % (app_label, row[0])
290
291     # Check that there aren't any *extra* content types in the DB that the
292     # model doesn't know about.
293     cursor.execute("SELECT python_module_name FROM content_types WHERE package = %s", (app_label,))
294     for row in cursor.fetchall():
295         try:
296             contenttypes_seen[row[0]]
297         except KeyError:
298 #             sys.stderr.write("A content type called '%s.%s' was found in the database but not in the model.\n" % (app_label, row[0]))
299             print "DELETE FROM content_types WHERE package='%s' AND python_module_name = '%s';" % (app_label, row[0])
300 database_check.help_doc = "Checks that everything is installed in the database for the given app(s) and prints SQL statements if needed."
301 database_check.args = APP_ARGS
302
303 def get_admin_index(mod):
304     "Returns admin-index template snippet (in list form) for the given module."
305     from django.utils.text import capfirst
306     output = []
307     app_label = mod._MODELS[0]._meta.app_label
308     output.append('{%% if perms.%s %%}' % app_label)
309     output.append('<div class="module"><h2>%s</h2><table>' % app_label.title())
310     for klass in mod._MODELS:
311         if klass._meta.admin:
312             output.append(MODULE_TEMPLATE % {
313                 'app': app_label,
314                 'mod': klass._meta.module_name,
315                 'name': capfirst(klass._meta.verbose_name_plural),
316                 'addperm': klass._meta.get_add_permission(),
317                 'changeperm': klass._meta.get_change_permission(),
318             })
319     output.append('</table></div>')
320     output.append('{% endif %}')
321     return output
322 get_admin_index.help_doc = "Prints the admin-index template snippet for the given app(s)."
323 get_admin_index.args = APP_ARGS
324
325 def init():
326     "Initializes the database with auth and core."
327     from django.core import db, meta
328     auth = meta.get_app('auth')
329     core = meta.get_app('core')
330     try:
331         cursor = db.db.cursor()
332         for sql in get_sql_create(core) + get_sql_create(auth) + get_sql_initial_data(core) + get_sql_initial_data(auth):
333             cursor.execute(sql)
334         cursor.execute("INSERT INTO %s (domain, name) VALUES ('mysite.com', 'My Django site')" % core.Site._meta.db_table)
335     except Exception, e:
336         sys.stderr.write("Error: The database couldn't be initialized. Here's the full exception:\n%s\n" % e)
337         db.db.rollback()
338         sys.exit(1)
339     db.db.commit()
340 init.args = ''
341
342 def install(mod):
343     "Executes the equivalent of 'get_sql_all' in the current database."
344     from django.core import db
345     sql_list = get_sql_all(mod)
346     try:
347         cursor = db.db.cursor()
348         for sql in sql_list:
349             cursor.execute(sql)
350     except Exception, e:
351         mod_name = mod.__name__[mod.__name__.rindex('.')+1:]
352         sys.stderr.write("""Error: %s couldn't be installed. Possible reasons:
353   * The database isn't running or isn't configured correctly.
354   * At least one of the database tables already exists.
355   * The SQL was invalid.
356 Hint: Look at the output of 'django-admin.py sqlall %s'. That's the SQL this command wasn't able to run.
357 The full error: %s\n""" % \
358             (mod_name, mod_name, e))
359         db.db.rollback()
360         sys.exit(1)
361     db.db.commit()
362 install.help_doc = "Executes ``sqlall`` for the given app(s) in the current database."
363 install.args = APP_ARGS
364
365 def _start_helper(app_or_project, name, directory, other_name=''):
366     other = {'project': 'app', 'app': 'project'}[app_or_project]
367     if not _is_valid_dir_name(name):
368         sys.stderr.write("Error: %r is not a valid %s name. Please use only numbers, letters and underscores.\n" % (name, app_or_project))
369         sys.exit(1)
370     top_dir = os.path.join(directory, name)
371     try:
372         os.mkdir(top_dir)
373     except OSError, e:
374         sys.stderr.write("Error: %s\n" % e)
375         sys.exit(1)
376     template_dir = PROJECT_TEMPLATE_DIR % app_or_project
377     for d, subdirs, files in os.walk(template_dir):
378         relative_dir = d[len(template_dir)+1:].replace('%s_name' % app_or_project, name)
379         if relative_dir:
380             os.mkdir(os.path.join(top_dir, relative_dir))
381         for i, subdir in enumerate(subdirs):
382             if subdir.startswith('.'):
383                 del subdirs[i]
384         for f in files:
385             if f.endswith('.pyc'):
386                 continue
387             fp_old = open(os.path.join(d, f), 'r')
388             fp_new = open(os.path.join(top_dir, relative_dir, f.replace('%s_name' % app_or_project, name)), 'w')
389             fp_new.write(fp_old.read().replace('{{ %s_name }}' % app_or_project, name).replace('{{ %s_name }}' % other, other_name))
390             fp_old.close()
391             fp_new.close()
392
393 def startproject(project_name, directory):
394     "Creates a Django project for the given project_name in the given directory."
395     from random import choice
396     _start_helper('project', project_name, directory)
397     # Populate TEMPLATE_DIRS for the admin templates, based on where Django is
398     # installed.
399     admin_settings_file = os.path.join(directory, project_name, 'settings/admin.py')
400     settings_contents = open(admin_settings_file, 'r').read()
401     fp = open(admin_settings_file, 'w')
402     settings_contents = re.sub(r'(?s)\b(TEMPLATE_DIRS\s*=\s*\()(.*?)\)', "\\1\n    '%s',\\2)" % ADMIN_TEMPLATE_DIR, settings_contents)
403     fp.write(settings_contents)
404     fp.close()
405     # Create a random SECRET_KEY hash, and put it in the main settings.
406     main_settings_file = os.path.join(directory, project_name, 'settings/main.py')
407     settings_contents = open(main_settings_file, 'r').read()
408     fp = open(main_settings_file, 'w')
409     secret_key = ''.join([choice('abcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*(-_=+)') for i in range(50)])
410     settings_contents = re.sub(r"(?<=SECRET_KEY = ')'", secret_key + "'", settings_contents)
411     fp.write(settings_contents)
412     fp.close()
413 startproject.help_doc = "Creates a Django project directory structure for the given project name in the current directory."
414 startproject.args = "[projectname]"
415
416 def startapp(app_name, directory):
417     "Creates a Django app for the given project_name in the given directory."
418     # Determine the project_name a bit naively -- by looking at the name of
419     # the parent directory.
420     project_dir = os.path.normpath(os.path.join(directory, '../'))
421     project_name = os.path.basename(project_dir)
422     _start_helper('app', app_name, directory, project_name)
423 startapp.help_doc = "Creates a Django app directory structure for the given app name in the current directory."
424 startapp.args = "[appname]"
425
426 def createsuperuser():
427     "Creates a superuser account."
428     from