Debian Codegraph @

django/core/management/commands/createcachetable.py

raw
1 from django.conf import settings
2 from django.core.cache import caches
3 from django.core.cache.backends.db import BaseDatabaseCache
4 from django.core.management.base import BaseCommand, CommandError
5 from django.db import (
6 DEFAULT_DB_ALIAS,
7 DatabaseError,
8 connections,
9 models,
10 router,
11 transaction,
12 )
13
14
15 class Command(BaseCommand):
16 help = "Creates the tables needed to use the SQL cache backend."
17
18 requires_system_checks = []
19
20 def add_arguments(self, parser):
21 parser.add_argument(
22 "args",
23 metavar="table_name",
24 nargs="*",
25 help=(
26 "Optional table names. Otherwise, settings.CACHES is used to find "
27 "cache tables."
28 ),
29 )
30 parser.add_argument(
31 "--database",
32 default=DEFAULT_DB_ALIAS,
33 choices=tuple(connections),
34 help="Nominates a database onto which the cache tables will be "
35 'installed. Defaults to the "default" database.',
36 )
37 parser.add_argument(
38 "--dry-run",
39 action="store_true",
40 help="Does not create the table, just prints the SQL that would be run.",
41 )
42
43 def handle(self, *tablenames, **options):
44 db = options["database"]
45 self.verbosity = options["verbosity"]
46 dry_run = options["dry_run"]
47 if tablenames:
48 # Legacy behavior, tablename specified as argument
49 for tablename in tablenames:
50 self.create_table(db, tablename, dry_run)
51 else:
52 for cache_alias in settings.CACHES:
53 cache = caches[cache_alias]
54 if isinstance(cache, BaseDatabaseCache):
55 self.create_table(db, cache._table, dry_run)
56
57 def create_table(self, database, tablename, dry_run):
58 cache = BaseDatabaseCache(tablename, {})
59 if not router.allow_migrate_model(database, cache.cache_model_class):
60 return
61 connection = connections[database]
62
63 if tablename in connection.introspection.table_names():
64 if self.verbosity > 0:
65 self.stdout.write("Cache table '%s' already exists." % tablename)
66 return
67
68 fields = (
69 # "key" is a reserved word in MySQL, so use "cache_key" instead.
70 models.CharField(
71 name="cache_key", max_length=255, unique=True, primary_key=True
72 ),
73 models.TextField(name="value"),
74 models.DateTimeField(name="expires", db_index=True),
75 )
76 table_output = []
77 index_output = []
78 qn = connection.ops.quote_name
79 for f in fields:
80 field_output = [
81 qn(f.name),
82 f.db_type(connection=connection),
83 "%sNULL" % ("NOT " if not f.null else ""),
84 ]
85 if f.primary_key:
86 field_output.append("PRIMARY KEY")
87 elif f.unique:
88 field_output.append("UNIQUE")
89 if f.db_index:
90 unique = "UNIQUE " if f.unique else ""
91 index_output.append(
92 "CREATE %sINDEX %s ON %s (%s);"
93 % (
94 unique,
95 qn("%s_%s" % (tablename, f.name)),
96 qn(tablename),
97 qn(f.name),
98 )
99 )
100 table_output.append(" ".join(field_output))
101 full_statement = ["CREATE TABLE %s (" % qn(tablename)]
102 for i, line in enumerate(table_output):
103 full_statement.append(
104 " %s%s" % (line, "," if i < len(table_output) - 1 else "")
105 )
106 full_statement.append(");")
107
108 full_statement = "\n".join(full_statement)
109
110 if dry_run:
111 self.stdout.write(full_statement)
112 for statement in index_output:
113 self.stdout.write(statement)
114 return
115
116 with transaction.atomic(
117 using=database, savepoint=connection.features.can_rollback_ddl
118 ):
119 with connection.cursor() as curs:
120 try:
121 curs.execute(full_statement)
122 except DatabaseError as e:
123 raise CommandError(
124 "Cache table '%s' could not be created.\nThe error was: %s."
125 % (tablename, e)
126 )
127 for statement in index_output:
128 curs.execute(statement)
129
130 if self.verbosity > 1:
131 self.stdout.write("Cache table '%s' created." % tablename)