app/django/core/management/commands/createcachetable.py
changeset 54 03e267d67478
child 323 ff1a9aa48cfd
equal deleted inserted replaced
53:57b4279d8c4e 54:03e267d67478
       
     1 from django.core.management.base import LabelCommand
       
     2 
       
     3 class Command(LabelCommand):
       
     4     help = "Creates the table needed to use the SQL cache backend."
       
     5     args = "<tablename>"
       
     6     label = 'tablename'
       
     7 
       
     8     requires_model_validation = False
       
     9 
       
    10     def handle_label(self, tablename, **options):
       
    11         from django.db import connection, transaction, models
       
    12         fields = (
       
    13             # "key" is a reserved word in MySQL, so use "cache_key" instead.
       
    14             models.CharField(name='cache_key', max_length=255, unique=True, primary_key=True),
       
    15             models.TextField(name='value'),
       
    16             models.DateTimeField(name='expires', db_index=True),
       
    17         )
       
    18         table_output = []
       
    19         index_output = []
       
    20         qn = connection.ops.quote_name
       
    21         for f in fields:
       
    22             field_output = [qn(f.name), f.db_type()]
       
    23             field_output.append("%sNULL" % (not f.null and "NOT " or ""))
       
    24             if f.unique:
       
    25                 field_output.append("UNIQUE")
       
    26             if f.primary_key:
       
    27                 field_output.append("PRIMARY KEY")
       
    28             if f.db_index:
       
    29                 unique = f.unique and "UNIQUE " or ""
       
    30                 index_output.append("CREATE %sINDEX %s_%s ON %s (%s);" % \
       
    31                     (unique, tablename, f.name, qn(tablename),
       
    32                     qn(f.name)))
       
    33             table_output.append(" ".join(field_output))
       
    34         full_statement = ["CREATE TABLE %s (" % qn(tablename)]
       
    35         for i, line in enumerate(table_output):
       
    36             full_statement.append('    %s%s' % (line, i < len(table_output)-1 and ',' or ''))
       
    37         full_statement.append(');')
       
    38         curs = connection.cursor()
       
    39         curs.execute("\n".join(full_statement))
       
    40         for statement in index_output:
       
    41             curs.execute(statement)
       
    42         transaction.commit_unless_managed()