|
29
|
1 |
from optparse import make_option |
|
|
2 |
|
|
0
|
3 |
from django.core.management.base import LabelCommand |
|
29
|
4 |
from django.db import connections, transaction, models, DEFAULT_DB_ALIAS |
|
0
|
5 |
|
|
|
6 |
class Command(LabelCommand): |
|
|
7 |
help = "Creates the table needed to use the SQL cache backend." |
|
|
8 |
args = "<tablename>" |
|
|
9 |
label = 'tablename' |
|
|
10 |
|
|
29
|
11 |
option_list = LabelCommand.option_list + ( |
|
|
12 |
make_option('--database', action='store', dest='database', |
|
|
13 |
default=DEFAULT_DB_ALIAS, help='Nominates a database onto ' |
|
|
14 |
'which the cache table will be installed. ' |
|
|
15 |
'Defaults to the "default" database.'), |
|
|
16 |
) |
|
|
17 |
|
|
0
|
18 |
requires_model_validation = False |
|
|
19 |
|
|
|
20 |
def handle_label(self, tablename, **options): |
|
29
|
21 |
alias = options.get('database', DEFAULT_DB_ALIAS) |
|
|
22 |
connection = connections[alias] |
|
0
|
23 |
fields = ( |
|
|
24 |
# "key" is a reserved word in MySQL, so use "cache_key" instead. |
|
|
25 |
models.CharField(name='cache_key', max_length=255, unique=True, primary_key=True), |
|
|
26 |
models.TextField(name='value'), |
|
|
27 |
models.DateTimeField(name='expires', db_index=True), |
|
|
28 |
) |
|
|
29 |
table_output = [] |
|
|
30 |
index_output = [] |
|
|
31 |
qn = connection.ops.quote_name |
|
|
32 |
for f in fields: |
|
29
|
33 |
field_output = [qn(f.name), f.db_type(connection=connection)] |
|
0
|
34 |
field_output.append("%sNULL" % (not f.null and "NOT " or "")) |
|
|
35 |
if f.primary_key: |
|
|
36 |
field_output.append("PRIMARY KEY") |
|
|
37 |
elif f.unique: |
|
|
38 |
field_output.append("UNIQUE") |
|
|
39 |
if f.db_index: |
|
|
40 |
unique = f.unique and "UNIQUE " or "" |
|
29
|
41 |
index_output.append("CREATE %sINDEX %s ON %s (%s);" % \ |
|
|
42 |
(unique, qn('%s_%s' % (tablename, f.name)), qn(tablename), |
|
0
|
43 |
qn(f.name))) |
|
|
44 |
table_output.append(" ".join(field_output)) |
|
|
45 |
full_statement = ["CREATE TABLE %s (" % qn(tablename)] |
|
|
46 |
for i, line in enumerate(table_output): |
|
|
47 |
full_statement.append(' %s%s' % (line, i < len(table_output)-1 and ',' or '')) |
|
|
48 |
full_statement.append(');') |
|
|
49 |
curs = connection.cursor() |
|
|
50 |
curs.execute("\n".join(full_statement)) |
|
|
51 |
for statement in index_output: |
|
|
52 |
curs.execute(statement) |
|
29
|
53 |
transaction.commit_unless_managed(using=alias) |