south.db.generic: 569 total statements, 0.0% covered

Generated: Wed 2013-03-13 10:33 CET

Source file: /media/Envs/Envs/filer-gallery/lib/python2.7/site-packages/south/db/generic.py

Stats: 0 executed, 552 missed, 17 excluded, 570 ignored

  1. import re
  2. import sys
  3. from django.core.management.color import no_style
  4. from django.db import transaction, models
  5. from django.db.utils import DatabaseError
  6. from django.db.backends.util import truncate_name
  7. from django.db.backends.creation import BaseDatabaseCreation
  8. from django.db.models.fields import NOT_PROVIDED
  9. from django.dispatch import dispatcher
  10. from django.conf import settings
  11. from django.utils.datastructures import SortedDict
  12. try:
  13. from django.utils.functional import cached_property
  14. except ImportError:
  15. class cached_property(object):
  16. """
  17. Decorator that creates converts a method with a single
  18. self argument into a property cached on the instance.
  19. """
  20. def __init__(self, func):
  21. self.func = func
  22. def __get__(self, instance, type):
  23. res = instance.__dict__[self.func.__name__] = self.func(instance)
  24. return res
  25. from south.logger import get_logger
  26. def alias(attrname):
  27. """
  28. Returns a function which calls 'attrname' - for function aliasing.
  29. We can't just use foo = bar, as this breaks subclassing.
  30. """
  31. def func(self, *args, **kwds):
  32. return getattr(self, attrname)(*args, **kwds)
  33. return func
  34. def invalidate_table_constraints(func):
  35. def _cache_clear(self, table, *args, **opts):
  36. self._set_cache(table, value=INVALID)
  37. return func(self, table, *args, **opts)
  38. return _cache_clear
  39. def delete_column_constraints(func):
  40. def _column_rm(self, table, column, *args, **opts):
  41. self._set_cache(table, column, value=[])
  42. return func(self, table, column, *args, **opts)
  43. return _column_rm
  44. def copy_column_constraints(func):
  45. def _column_cp(self, table, column_old, column_new, *args, **opts):
  46. db_name = self._get_setting('NAME')
  47. self._set_cache(table, column_new, value=self.lookup_constraint(db_name, table, column_old))
  48. return func(self, table, column_old, column_new, *args, **opts)
  49. return _column_cp
  50. class INVALID(Exception):
  51. def __repr__(self):
  52. return 'INVALID'
  53. class DryRunError(ValueError):
  54. pass
  55. class DatabaseOperations(object):
  56. """
  57. Generic SQL implementation of the DatabaseOperations.
  58. Some of this code comes from Django Evolution.
  59. """
  60. alter_string_set_type = 'ALTER COLUMN %(column)s TYPE %(type)s'
  61. alter_string_set_null = 'ALTER COLUMN %(column)s DROP NOT NULL'
  62. alter_string_drop_null = 'ALTER COLUMN %(column)s SET NOT NULL'
  63. delete_check_sql = 'ALTER TABLE %(table)s DROP CONSTRAINT %(constraint)s'
  64. add_column_string = 'ALTER TABLE %s ADD COLUMN %s;'
  65. delete_unique_sql = "ALTER TABLE %s DROP CONSTRAINT %s"
  66. delete_foreign_key_sql = 'ALTER TABLE %(table)s DROP CONSTRAINT %(constraint)s'
  67. max_index_name_length = 63
  68. drop_index_string = 'DROP INDEX %(index_name)s'
  69. delete_column_string = 'ALTER TABLE %s DROP COLUMN %s CASCADE;'
  70. create_primary_key_string = "ALTER TABLE %(table)s ADD CONSTRAINT %(constraint)s PRIMARY KEY (%(columns)s)"
  71. delete_primary_key_sql = "ALTER TABLE %(table)s DROP CONSTRAINT %(constraint)s"
  72. add_check_constraint_fragment = "ADD CONSTRAINT %(constraint)s CHECK (%(check)s)"
  73. rename_table_sql = "ALTER TABLE %s RENAME TO %s;"
  74. backend_name = None
  75. default_schema_name = "public"
  76. # Features
  77. allows_combined_alters = True
  78. supports_foreign_keys = True
  79. has_check_constraints = True
  80. has_booleans = True
  81. @cached_property
  82. def has_ddl_transactions(self):
  83. """
  84. Tests the database using feature detection to see if it has
  85. transactional DDL support.
  86. """
  87. self._possibly_initialise()
  88. connection = self._get_connection()
  89. if hasattr(connection.features, "confirm") and not connection.features._confirmed:
  90. connection.features.confirm()
  91. # Django 1.3's MySQLdb backend doesn't raise DatabaseError
  92. exceptions = (DatabaseError, )
  93. try:
  94. from MySQLdb import OperationalError
  95. exceptions += (OperationalError, )
  96. except ImportError:
  97. pass
  98. # Now do the test
  99. if getattr(connection.features, 'supports_transactions', True):
  100. cursor = connection.cursor()
  101. self.start_transaction()
  102. cursor.execute('CREATE TABLE DDL_TRANSACTION_TEST (X INT)')
  103. self.rollback_transaction()
  104. try:
  105. try:
  106. cursor.execute('CREATE TABLE DDL_TRANSACTION_TEST (X INT)')
  107. except exceptions:
  108. return False
  109. else:
  110. return True
  111. finally:
  112. cursor.execute('DROP TABLE DDL_TRANSACTION_TEST')
  113. else:
  114. return False
  115. def __init__(self, db_alias):
  116. self.debug = False
  117. self.deferred_sql = []
  118. self.dry_run = False
  119. self.pending_transactions = 0
  120. self.pending_create_signals = []
  121. self.db_alias = db_alias
  122. self._constraint_cache = {}
  123. self._initialised = False
  124. def lookup_constraint(self, db_name, table_name, column_name=None):
  125. """ return a set() of constraints for db_name.table_name.column_name """
  126. def _lookup():
  127. table = self._constraint_cache[db_name][table_name]
  128. if table is INVALID:
  129. raise INVALID
  130. elif column_name is None:
  131. return table.items()
  132. else:
  133. return table[column_name]
  134. try:
  135. ret = _lookup()
  136. return ret
  137. except INVALID:
  138. del self._constraint_cache[db_name][table_name]
  139. self._fill_constraint_cache(db_name, table_name)
  140. except KeyError:
  141. if self._is_valid_cache(db_name, table_name):
  142. return []
  143. self._fill_constraint_cache(db_name, table_name)
  144. return self.lookup_constraint(db_name, table_name, column_name)
  145. def _set_cache(self, table_name, column_name=None, value=INVALID):
  146. db_name = self._get_setting('NAME')
  147. try:
  148. if column_name is not None:
  149. self._constraint_cache[db_name][table_name][column_name] = value
  150. else:
  151. self._constraint_cache[db_name][table_name] = value
  152. except (LookupError, TypeError):
  153. pass
  154. def _is_valid_cache(self, db_name, table_name):
  155. # we cache per-table so if the table is there it is valid
  156. try:
  157. return self._constraint_cache[db_name][table_name] is not INVALID
  158. except KeyError:
  159. return False
  160. def _is_multidb(self):
  161. try:
  162. from django.db import connections
  163. connections # Prevents "unused import" warning
  164. except ImportError:
  165. return False
  166. else:
  167. return True
  168. def _get_connection(self):
  169. """
  170. Returns a django connection for a given DB Alias
  171. """
  172. if self._is_multidb():
  173. from django.db import connections
  174. return connections[self.db_alias]
  175. else:
  176. from django.db import connection
  177. return connection
  178. def _get_setting(self, setting_name):
  179. """
  180. Allows code to get a setting (like, for example, STORAGE_ENGINE)
  181. """
  182. setting_name = setting_name.upper()
  183. connection = self._get_connection()
  184. if self._is_multidb():
  185. # Django 1.2 and above
  186. return connection.settings_dict[setting_name]
  187. else:
  188. # Django 1.1 and below
  189. return getattr(settings, "DATABASE_%s" % setting_name)
  190. def _has_setting(self, setting_name):
  191. """
  192. Existence-checking version of _get_setting.
  193. """
  194. try:
  195. self._get_setting(setting_name)
  196. except (KeyError, AttributeError):
  197. return False
  198. else:
  199. return True
  200. def _get_schema_name(self):
  201. try:
  202. return self._get_setting('schema')
  203. except (KeyError, AttributeError):
  204. return self.default_schema_name
  205. def _possibly_initialise(self):
  206. if not self._initialised:
  207. self.connection_init()
  208. self._initialised = True
  209. def connection_init(self):
  210. """
  211. Run before any SQL to let database-specific config be sent as a command,
  212. e.g. which storage engine (MySQL) or transaction serialisability level.
  213. """
  214. pass
  215. def quote_name(self, name):
  216. """
  217. Uses the database backend to quote the given table/column name.
  218. """
  219. return self._get_connection().ops.quote_name(name)
  220. def execute(self, sql, params=[]):
  221. """
  222. Executes the given SQL statement, with optional parameters.
  223. If the instance's debug attribute is True, prints out what it executes.
  224. """
  225. self._possibly_initialise()
  226. cursor = self._get_connection().cursor()
  227. if self.debug:
  228. print " = %s" % sql, params
  229. if self.dry_run:
  230. return []
  231. get_logger().debug('execute "%s" with params "%s"' % (sql, params))
  232. try:
  233. cursor.execute(sql, params)
  234. except DatabaseError, e:
  235. print >> sys.stderr, 'FATAL ERROR - The following SQL query failed: %s' % sql
  236. print >> sys.stderr, 'The error was: %s' % e
  237. raise
  238. try:
  239. return cursor.fetchall()
  240. except:
  241. return []
  242. def execute_many(self, sql, regex=r"(?mx) ([^';]* (?:'[^']*'[^';]*)*)", comment_regex=r"(?mx) (?:^\s*$)|(?:--.*$)"):
  243. """
  244. Takes a SQL file and executes it as many separate statements.
  245. (Some backends, such as Postgres, don't work otherwise.)
  246. """
  247. # Be warned: This function is full of dark magic. Make sure you really
  248. # know regexes before trying to edit it.
  249. # First, strip comments
  250. sql = "\n".join([x.strip().replace("%", "%%") for x in re.split(comment_regex, sql) if x.strip()])
  251. # Now execute each statement
  252. for st in re.split(regex, sql)[1:][::2]:
  253. self.execute(st)
  254. def add_deferred_sql(self, sql):
  255. """
  256. Add a SQL statement to the deferred list, that won't be executed until
  257. this instance's execute_deferred_sql method is run.
  258. """
  259. self.deferred_sql.append(sql)
  260. def execute_deferred_sql(self):
  261. """
  262. Executes all deferred SQL, resetting the deferred_sql list
  263. """
  264. for sql in self.deferred_sql:
  265. self.execute(sql)
  266. self.deferred_sql = []
  267. def clear_deferred_sql(self):
  268. """
  269. Resets the deferred_sql list to empty.
  270. """
  271. self.deferred_sql = []
  272. def clear_run_data(self, pending_creates = None):
  273. """
  274. Resets variables to how they should be before a run. Used for dry runs.
  275. If you want, pass in an old panding_creates to reset to.
  276. """
  277. self.clear_deferred_sql()
  278. self.pending_create_signals = pending_creates or []
  279. def get_pending_creates(self):
  280. return self.pending_create_signals
  281. @invalidate_table_constraints
  282. def create_table(self, table_name, fields):
  283. """
  284. Creates the table 'table_name'. 'fields' is a tuple of fields,
  285. each repsented by a 2-part tuple of field name and a
  286. django.db.models.fields.Field object
  287. """
  288. if len(table_name) > 63:
  289. print " ! WARNING: You have a table name longer than 63 characters; this will not fully work on PostgreSQL or MySQL."
  290. # avoid default values in CREATE TABLE statements (#925)
  291. for field_name, field in fields:
  292. field._suppress_default = True
  293. columns = [
  294. self.column_sql(table_name, field_name, field)
  295. for field_name, field in fields
  296. ]
  297. self.execute('CREATE TABLE %s (%s);' % (
  298. self.quote_name(table_name),
  299. ', '.join([col for col in columns if col]),
  300. ))
  301. add_table = alias('create_table') # Alias for consistency's sake
  302. @invalidate_table_constraints
  303. def rename_table(self, old_table_name, table_name):
  304. """
  305. Renames the table 'old_table_name' to 'table_name'.
  306. """
  307. if old_table_name == table_name:
  308. # Short-circuit out.
  309. return
  310. params = (self.quote_name(old_table_name), self.quote_name(table_name))
  311. self.execute(self.rename_table_sql % params)
  312. # Invalidate the not-yet-indexed table
  313. self._set_cache(table_name, value=INVALID)
  314. @invalidate_table_constraints
  315. def delete_table(self, table_name, cascade=True):
  316. """
  317. Deletes the table 'table_name'.
  318. """
  319. params = (self.quote_name(table_name), )
  320. if cascade:
  321. self.execute('DROP TABLE %s CASCADE;' % params)
  322. else:
  323. self.execute('DROP TABLE %s;' % params)
  324. drop_table = alias('delete_table')
  325. @invalidate_table_constraints
  326. def clear_table(self, table_name):
  327. """
  328. Deletes all rows from 'table_name'.
  329. """
  330. params = (self.quote_name(table_name), )
  331. self.execute('DELETE FROM %s;' % params)
  332. @invalidate_table_constraints
  333. def add_column(self, table_name, name, field, keep_default=True):
  334. """
  335. Adds the column 'name' to the table 'table_name'.
  336. Uses the 'field' paramater, a django.db.models.fields.Field instance,
  337. to generate the necessary sql
  338. @param table_name: The name of the table to add the column to
  339. @param name: The name of the column to add
  340. @param field: The field to use
  341. """
  342. sql = self.column_sql(table_name, name, field)
  343. if sql:
  344. params = (
  345. self.quote_name(table_name),
  346. sql,
  347. )
  348. sql = self.add_column_string % params
  349. self.execute(sql)
  350. # Now, drop the default if we need to
  351. if not keep_default and field.default is not None:
  352. field.default = NOT_PROVIDED
  353. self.alter_column(table_name, name, field, explicit_name=False, ignore_constraints=True)
  354. def _db_type_for_alter_column(self, field):
  355. """
  356. Returns a field's type suitable for ALTER COLUMN.
  357. By default it just returns field.db_type().
  358. To be overriden by backend specific subclasses
  359. @param field: The field to generate type for
  360. """
  361. try:
  362. return field.db_type(connection=self._get_connection())
  363. except TypeError:
  364. return field.db_type()
  365. def _alter_add_column_mods(self, field, name, params, sqls):
  366. """
  367. Subcommand of alter_column that modifies column definitions beyond
  368. the type string -- e.g. adding constraints where they cannot be specified
  369. as part of the type (overrideable)
  370. """
  371. pass
  372. def _alter_set_defaults(self, field, name, params, sqls):
  373. "Subcommand of alter_column that sets default values (overrideable)"
  374. # Next, set any default
  375. if not field.null and field.has_default():
  376. default = field.get_default()
  377. sqls.append(('ALTER COLUMN %s SET DEFAULT %%s ' % (self.quote_name(name),), [default]))
  378. else:
  379. sqls.append(('ALTER COLUMN %s DROP DEFAULT' % (self.quote_name(name),), []))
  380. @invalidate_table_constraints
  381. def alter_column(self, table_name, name, field, explicit_name=True, ignore_constraints=False):
  382. """
  383. Alters the given column name so it will match the given field.
  384. Note that conversion between the two by the database must be possible.
  385. Will not automatically add _id by default; to have this behavour, pass
  386. explicit_name=False.
  387. @param table_name: The name of the table to add the column to
  388. @param name: The name of the column to alter
  389. @param field: The new field definition to use
  390. """
  391. if self.dry_run:
  392. if self.debug:
  393. print ' - no dry run output for alter_column() due to dynamic DDL, sorry'
  394. return
  395. # hook for the field to do any resolution prior to it's attributes being queried
  396. if hasattr(field, 'south_init'):
  397. field.south_init()
  398. # Add _id or whatever if we need to
  399. field.set_attributes_from_name(name)
  400. if not explicit_name:
  401. name = field.column
  402. else:
  403. field.column = name
  404. if not ignore_constraints:
  405. # Drop all check constraints. Note that constraints will be added back
  406. # with self.alter_string_set_type and self.alter_string_drop_null.
  407. if self.has_check_constraints:
  408. check_constraints = self._constraints_affecting_columns(table_name, [name], "CHECK")
  409. for constraint in check_constraints:
  410. self.execute(self.delete_check_sql % {
  411. 'table': self.quote_name(table_name),
  412. 'constraint': self.quote_name(constraint),
  413. })
  414. # Drop all foreign key constraints
  415. try:
  416. self.delete_foreign_key(table_name, name)
  417. except ValueError:
  418. # There weren't any
  419. pass
  420. # First, change the type
  421. params = {
  422. "column": self.quote_name(name),
  423. "type": self._db_type_for_alter_column(field),
  424. "table_name": table_name
  425. }
  426. # SQLs is a list of (SQL, values) pairs.
  427. sqls = []
  428. # Only alter the column if it has a type (Geometry ones sometimes don't)
  429. if params["type"] is not None:
  430. sqls.append((self.alter_string_set_type % params, []))
  431. # Add any field- and backend- specific modifications
  432. self._alter_add_column_mods(field, name, params, sqls)
  433. # Next, nullity
  434. if field.null:
  435. sqls.append((self.alter_string_set_null % params, []))
  436. else:
  437. sqls.append((self.alter_string_drop_null % params, []))
  438. # Next, set any default
  439. self._alter_set_defaults(field, name, params, sqls)
  440. # Finally, actually change the column
  441. if self.allows_combined_alters:
  442. sqls, values = zip(*sqls)
  443. self.execute(
  444. "ALTER TABLE %s %s;" % (self.quote_name(table_name), ", ".join(sqls)),
  445. flatten(values),
  446. )
  447. else:
  448. # Databases like e.g. MySQL don't like more than one alter at once.
  449. for sql, values in sqls:
  450. self.execute("ALTER TABLE %s %s;" % (self.quote_name(table_name), sql), values)
  451. if not ignore_constraints:
  452. # Add back FK constraints if needed
  453. if field.rel and self.supports_foreign_keys:
  454. self.execute(
  455. self.foreign_key_sql(
  456. table_name,
  457. field.column,
  458. field.rel.to._meta.db_table,
  459. field.rel.to._meta.get_field(field.rel.field_name).column
  460. )
  461. )
  462. def _fill_constraint_cache(self, db_name, table_name):
  463. schema = self._get_schema_name()
  464. ifsc_tables = ["constraint_column_usage", "key_column_usage"]
  465. self._constraint_cache.setdefault(db_name, {})
  466. self._constraint_cache[db_name][table_name] = {}
  467. for ifsc_table in ifsc_tables:
  468. rows = self.execute("""
  469. SELECT kc.constraint_name, kc.column_name, c.constraint_type
  470. FROM information_schema.%s AS kc
  471. JOIN information_schema.table_constraints AS c ON
  472. kc.table_schema = c.table_schema AND
  473. kc.table_name = c.table_name AND
  474. kc.constraint_name = c.constraint_name
  475. WHERE
  476. kc.table_schema = %%s AND
  477. kc.table_name = %%s
  478. """ % ifsc_table, [schema, table_name])
  479. for constraint, column, kind in rows:
  480. self._constraint_cache[db_name][table_name].setdefault(column, set())
  481. self._constraint_cache[db_name][table_name][column].add((kind, constraint))
  482. return
  483. def _constraints_affecting_columns(self, table_name, columns, type="UNIQUE"):
  484. """
  485. Gets the names of the constraints affecting the given columns.
  486. If columns is None, returns all constraints of the type on the table.
  487. """
  488. if self.dry_run:
  489. raise DryRunError("Cannot get constraints for columns.")
  490. if columns is not None:
  491. columns = set(map(lambda s: s.lower(), columns))
  492. db_name = self._get_setting('NAME')
  493. cnames = {}
  494. for col, constraints in self.lookup_constraint(db_name, table_name):
  495. for kind, cname in constraints:
  496. if kind == type:
  497. cnames.setdefault(cname, set())
  498. cnames[cname].add(col.lower())
  499. for cname, cols in cnames.items():
  500. if cols == columns or columns is None:
  501. yield cname
  502. @invalidate_table_constraints
  503. def create_unique(self, table_name, columns):
  504. """
  505. Creates a UNIQUE constraint on the columns on the given table.
  506. """
  507. if not isinstance(columns, (list, tuple)):
  508. columns = [columns]
  509. name = self.create_index_name(table_name, columns, suffix="_uniq")
  510. cols = ", ".join(map(self.quote_name, columns))
  511. self.execute("ALTER TABLE %s ADD CONSTRAINT %s UNIQUE (%s)" % (
  512. self.quote_name(table_name),
  513. self.quote_name(name),
  514. cols,
  515. ))
  516. return name
  517. @invalidate_table_constraints
  518. def delete_unique(self, table_name, columns):
  519. """
  520. Deletes a UNIQUE constraint on precisely the columns on the given table.
  521. """
  522. if not isinstance(columns, (list, tuple)):
  523. columns = [columns]
  524. # Dry runs mean we can't do anything.
  525. if self.dry_run:
  526. if self.debug:
  527. print ' - no dry run output for delete_unique_column() due to dynamic DDL, sorry'
  528. return
  529. constraints = list(self._constraints_affecting_columns(table_name, columns))
  530. if not constraints:
  531. raise ValueError("Cannot find a UNIQUE constraint on table %s, columns %r" % (table_name, columns))
  532. for constraint in constraints:
  533. self.execute(self.delete_unique_sql % (
  534. self.quote_name(table_name),
  535. self.quote_name(constraint),
  536. ))
  537. def column_sql(self, table_name, field_name, field, tablespace='', with_name=True, field_prepared=False):
  538. """
  539. Creates the SQL snippet for a column. Used by add_column and add_table.
  540. """
  541. # If the field hasn't already been told its attribute name, do so.
  542. if not field_prepared:
  543. field.set_attributes_from_name(field_name)
  544. # hook for the field to do any resolution prior to it's attributes being queried
  545. if hasattr(field, 'south_init'):
  546. field.south_init()
  547. # Possible hook to fiddle with the fields (e.g. defaults & TEXT on MySQL)
  548. field = self._field_sanity(field)
  549. try:
  550. sql = field.db_type(connection=self._get_connection())
  551. except TypeError:
  552. sql = field.db_type()
  553. if sql:
  554. # Some callers, like the sqlite stuff, just want the extended type.
  555. if with_name:
  556. field_output = [self.quote_name(field.column), sql]
  557. else:
  558. field_output = [sql]
  559. field_output.append('%sNULL' % (not field.null and 'NOT ' or ''))
  560. if field.primary_key:
  561. field_output.append('PRIMARY KEY')
  562. elif field.unique:
  563. # Just use UNIQUE (no indexes any more, we have delete_unique)
  564. field_output.append('UNIQUE')
  565. tablespace = field.db_tablespace or tablespace
  566. if tablespace and getattr(self._get_connection().features, "supports_tablespaces", False) and field.unique:
  567. # We must specify the index tablespace inline, because we
  568. # won't be generating a CREATE INDEX statement for this field.
  569. field_output.append(self._get_connection().ops.tablespace_sql(tablespace, inline=True))
  570. sql = ' '.join(field_output)
  571. sqlparams = ()
  572. # if the field is "NOT NULL" and a default value is provided, create the column with it
  573. # this allows the addition of a NOT NULL field to a table with existing rows
  574. if not getattr(field, '_suppress_default', False):
  575. if field.has_default():
  576. default = field.get_default()
  577. # If the default is actually None, don't add a default term
  578. if default is not None:
  579. # If the default is a callable, then call it!
  580. if callable(default):
  581. default = default()
  582. default = field.get_db_prep_save(default, connection=self._get_connection())
  583. default = self._default_value_workaround(default)
  584. # Now do some very cheap quoting. TODO: Redesign return values to avoid this.
  585. if isinstance(default, basestring):
  586. default = "'%s'" % default.replace("'", "''")
  587. # Escape any % signs in the output (bug #317)
  588. if isinstance(default, basestring):
  589. default = default.replace("%", "%%")
  590. # Add it in
  591. sql += " DEFAULT %s"
  592. sqlparams = (default)
  593. elif (not field.null and field.blank) or (field.get_default() == ''):
  594. if field.empty_strings_allowed and self._get_connection().features.interprets_empty_strings_as_nulls:
  595. sql += " DEFAULT ''"
  596. # Error here would be nice, but doesn't seem to play fair.
  597. #else:
  598. # raise ValueError("Attempting to add a non null column that isn't character based without an explicit default value.")
  599. if field.rel and self.supports_foreign_keys:
  600. self.add_deferred_sql(
  601. self.foreign_key_sql(
  602. table_name,
  603. field.column,
  604. field.rel.to._meta.db_table,
  605. field.rel.to._meta.get_field(field.rel.field_name).column
  606. )
  607. )
  608. # Things like the contrib.gis module fields have this in 1.1 and below
  609. if hasattr(field, 'post_create_sql'):
  610. for stmt in field.post_create_sql(no_style(), table_name):
  611. self.add_deferred_sql(stmt)
  612. # In 1.2 and above, you have to ask the DatabaseCreation stuff for it.
  613. # This also creates normal indexes in 1.1.
  614. if hasattr(self._get_connection().creation, "sql_indexes_for_field"):
  615. # Make a fake model to pass in, with only db_table
  616. model = self.mock_model("FakeModelForGISCreation", table_name)
  617. for stmt in self._get_connection().creation.sql_indexes_for_field(model, field, no_style()):
  618. self.add_deferred_sql(stmt)
  619. if sql:
  620. return sql % sqlparams
  621. else:
  622. return None
  623. def _field_sanity(self, field):
  624. """
  625. Placeholder for DBMS-specific field alterations (some combos aren't valid,
  626. e.g. DEFAULT and TEXT on MySQL)
  627. """
  628. return field
  629. def _default_value_workaround(self, value):
  630. """
  631. DBMS-specific value alterations (this really works around
  632. missing functionality in Django backends)
  633. """
  634. if isinstance(value, bool) and not self.has_booleans:
  635. return int(value)
  636. else:
  637. return value
  638. def foreign_key_sql(self, from_table_name, from_column_name, to_table_name, to_column_name):
  639. """
  640. Generates a full SQL statement to add a foreign key constraint
  641. """
  642. constraint_name = '%s_refs_%s_%x' % (from_column_name, to_column_name, abs(hash((from_table_name, to_table_name))))
  643. return 'ALTER TABLE %s ADD CONSTRAINT %s FOREIGN KEY (%s) REFERENCES %s (%s)%s;' % (
  644. self.quote_name(from_table_name),
  645. self.quote_name(truncate_name(constraint_name, self._get_connection().ops.max_name_length())),
  646. self.quote_name(from_column_name),
  647. self.quote_name(to_table_name),
  648. self.quote_name(to_column_name),
  649. self._get_connection().ops.deferrable_sql() # Django knows this
  650. )
  651. @invalidate_table_constraints
  652. def delete_foreign_key(self, table_name, column):
  653. """
  654. Drop a foreign key constraint
  655. """
  656. if self.dry_run:
  657. if self.debug:
  658. print ' - no dry run output for delete_foreign_key() due to dynamic DDL, sorry'
  659. return # We can't look at the DB to get the constraints
  660. constraints = self._find_foreign_constraints(table_name, column)
  661. if not constraints:
  662. raise ValueError("Cannot find a FOREIGN KEY constraint on table %s, column %s" % (table_name, column))
  663. for constraint_name in constraints:
  664. self.execute(self.delete_foreign_key_sql % {
  665. "table": self.quote_name(table_name),
  666. "constraint": self.quote_name(constraint_name),
  667. })
  668. drop_foreign_key = alias('delete_foreign_key')
  669. def _find_foreign_constraints(self, table_name, column_name=None):
  670. constraints = self._constraints_affecting_columns(
  671. table_name, [column_name], "FOREIGN KEY")
  672. primary_key_columns = self._find_primary_key_columns(table_name)
  673. if len(primary_key_columns) > 1:
  674. # Composite primary keys cannot be referenced by a foreign key
  675. return list(constraints)
  676. else:
  677. primary_key_columns.add(column_name)
  678. recursive_constraints = set(self._constraints_affecting_columns(
  679. table_name, primary_key_columns, "FOREIGN KEY"))
  680. return list(recursive_constraints.union(constraints))
  681. def _digest(self, *args):
  682. """
  683. Use django.db.backends.creation.BaseDatabaseCreation._digest
  684. to create index name in Django style. An evil hack :(
  685. """
  686. if not hasattr(self, '_django_db_creation'):
  687. self._django_db_creation = BaseDatabaseCreation(self._get_connection())
  688. return self._django_db_creation._digest(*args)
  689. def create_index_name(self, table_name, column_names, suffix=""):
  690. """
  691. Generate a unique name for the index
  692. """
  693. # If there is just one column in the index, use a default algorithm from Django
  694. if len(column_names) == 1 and not suffix:
  695. return truncate_name(
  696. '%s_%s' % (table_name, self._digest(column_names[0])),
  697. self._get_connection().ops.max_name_length()
  698. )
  699. # Else generate the name for the index by South
  700. table_name = table_name.replace('"', '').replace('.', '_')
  701. index_unique_name = '_%x' % abs(hash((table_name, ','.join(column_names))))
  702. # If the index name is too long, truncate it
  703. index_name = ('%s_%s%s%s' % (table_name, column_names[0], index_unique_name, suffix)).replace('"', '').replace('.', '_')
  704. if len(index_name) > self.max_index_name_length:
  705. part = ('_%s%s%s' % (column_names[0], index_unique_name, suffix))
  706. index_name = '%s%s' % (table_name[:(self.max_index_name_length - len(part))], part)
  707. return index_name
  708. def create_index_sql(self, table_name, column_names, unique=False, db_tablespace=''):
  709. """
  710. Generates a create index statement on 'table_name' for a list of 'column_names'
  711. """
  712. if not column_names:
  713. print "No column names supplied on which to create an index"
  714. return ''
  715. connection = self._get_connection()
  716. if db_tablespace and connection.features.supports_tablespaces:
  717. tablespace_sql = ' ' + connection.ops.tablespace_sql(db_tablespace)
  718. else:
  719. tablespace_sql = ''
  720. index_name = self.create_index_name(table_name, column_names)
  721. return 'CREATE %sINDEX %s ON %s (%s)%s;' % (
  722. unique and 'UNIQUE ' or '',
  723. self.quote_name(index_name),
  724. self.quote_name(table_name),
  725. ','.join([self.quote_name(field) for field in column_names]),
  726. tablespace_sql
  727. )
  728. @invalidate_table_constraints
  729. def create_index(self, table_name, column_names, unique=False, db_tablespace=''):
  730. """ Executes a create index statement """
  731. sql = self.create_index_sql(table_name, column_names, unique, db_tablespace)
  732. self.execute(sql)
  733. @invalidate_table_constraints
  734. def delete_index(self, table_name, column_names, db_tablespace=''):
  735. """
  736. Deletes an index created with create_index.
  737. This is possible using only columns due to the deterministic
  738. index naming function which relies on column names.
  739. """
  740. if isinstance(column_names, (str, unicode)):
  741. column_names = [column_names]
  742. name = self.create_index_name(table_name, column_names)
  743. sql = self.drop_index_string % {
  744. "index_name": self.quote_name(name),
  745. "table_name": self.quote_name(table_name),
  746. }
  747. self.execute(sql)
  748. drop_index = alias('delete_index')
  749. @delete_column_constraints
  750. def delete_column(self, table_name, name):
  751. """
  752. Deletes the column 'column_name' from the table 'table_name'.
  753. """
  754. params = (self.quote_name(table_name), self.quote_name(name))
  755. self.execute(self.delete_column_string % params, [])
  756. drop_column = alias('delete_column')
  757. def rename_column(self, table_name, old, new):
  758. """
  759. Renames the column 'old' from the table 'table_name' to 'new'.
  760. """
  761. raise NotImplementedError("rename_column has no generic SQL syntax")
  762. @invalidate_table_constraints
  763. def delete_primary_key(self, table_name):
  764. """
  765. Drops the old primary key.
  766. """
  767. # Dry runs mean we can't do anything.
  768. if self.dry_run:
  769. if self.debug:
  770. print ' - no dry run output for delete_primary_key() due to dynamic DDL, sorry'
  771. return
  772. constraints = list(self._constraints_affecting_columns(table_name, None, type="PRIMARY KEY"))
  773. if not constraints:
  774. raise ValueError("Cannot find a PRIMARY KEY constraint on table %s" % (table_name,))
  775. for constraint in constraints:
  776. self.execute(self.delete_primary_key_sql % {
  777. "table": self.quote_name(table_name),
  778. "constraint": self.quote_name(constraint),
  779. })
  780. drop_primary_key = alias('delete_primary_key')
  781. @invalidate_table_constraints
  782. def create_primary_key(self, table_name, columns):
  783. """
  784. Creates a new primary key on the specified columns.
  785. """
  786. if not isinstance(columns, (list, tuple)):
  787. columns = [columns]
  788. self.execute(self.create_primary_key_string % {
  789. "table": self.quote_name(table_name),
  790. "constraint": self.quote_name(table_name + "_pkey"),
  791. "columns": ", ".join(map(self.quote_name, columns)),
  792. })
  793. def _find_primary_key_columns(self, table_name):
  794. """
  795. Find all columns of the primary key of the specified table
  796. """
  797. db_name = self._get_setting('NAME')
  798. primary_key_columns = set()
  799. for col, constraints in self.lookup_constraint(db_name, table_name):
  800. for kind, cname in constraints:
  801. if kind == 'PRIMARY KEY':
  802. primary_key_columns.add(col.lower())
  803. return primary_key_columns
  804. def start_transaction(self):
  805. """
  806. Makes sure the following commands are inside a transaction.
  807. Must be followed by a (commit|rollback)_transaction call.
  808. """
  809. if self.dry_run:
  810. self.pending_transactions += 1
  811. transaction.commit_unless_managed(using=self.db_alias)
  812. transaction.enter_transaction_management(using=self.db_alias)
  813. transaction.managed(True, using=self.db_alias)
  814. def commit_transaction(self):
  815. """
  816. Commits the current transaction.
  817. Must be preceded by a start_transaction call.
  818. """
  819. if self.dry_run:
  820. return
  821. transaction.commit(using=self.db_alias)
  822. transaction.leave_transaction_management(using=self.db_alias)
  823. def rollback_transaction(self):
  824. """
  825. Rolls back the current transaction.
  826. Must be preceded by a start_transaction call.
  827. """
  828. if self.dry_run:
  829. self.pending_transactions -= 1
  830. transaction.rollback(using=self.db_alias)
  831. transaction.leave_transaction_management(using=self.db_alias)
  832. def rollback_transactions_dry_run(self):
  833. """
  834. Rolls back all pending_transactions during this dry run.
  835. """
  836. if not self.dry_run:
  837. return
  838. while self.pending_transactions > 0:
  839. self.rollback_transaction()
  840. if transaction.is_dirty(using=self.db_alias):
  841. # Force an exception, if we're still in a dirty transaction.
  842. # This means we are missing a COMMIT/ROLLBACK.
  843. transaction.leave_transaction_management(using=self.db_alias)
  844. def send_create_signal(self, app_label, model_names):
  845. self.pending_create_signals.append((app_label, model_names))
  846. def send_pending_create_signals(self, verbosity=0, interactive=False):
  847. # Group app_labels together
  848. signals = SortedDict()
  849. for (app_label, model_names) in self.pending_create_signals:
  850. try:
  851. signals[app_label].extend(model_names)
  852. except KeyError:
  853. signals[app_label] = list(model_names)
  854. # Send only one signal per app.
  855. for (app_label, model_names) in signals.iteritems():
  856. self.really_send_create_signal(app_label, list(set(model_names)),
  857. verbosity=verbosity,
  858. interactive=interactive)
  859. self.pending_create_signals = []
  860. def really_send_create_signal(self, app_label, model_names,
  861. verbosity=0, interactive=False):
  862. """
  863. Sends a post_syncdb signal for the model specified.
  864. If the model is not found (perhaps it's been deleted?),
  865. no signal is sent.
  866. TODO: The behavior of django.contrib.* apps seems flawed in that
  867. they don't respect created_models. Rather, they blindly execute
  868. over all models within the app sending the signal. This is a
  869. patch we should push Django to make For now, this should work.
  870. """
  871. if self.debug:
  872. print " - Sending post_syncdb signal for %s: %s" % (app_label, model_names)
  873. app = models.get_app(app_label)
  874. if not app:
  875. return
  876. created_models = []
  877. for model_name in model_names:
  878. model = models.get_model(app_label, model_name)
  879. if model:
  880. created_models.append(model)
  881. if created_models:
  882. if hasattr(dispatcher, "send"):
  883. # Older djangos
  884. dispatcher.send(signal=models.signals.post_syncdb, sender=app,
  885. app=app, created_models=created_models,
  886. verbosity=verbosity, interactive=interactive)
  887. else:
  888. if self._is_multidb():
  889. # Django 1.2+
  890. models.signals.post_syncdb.send(
  891. sender=app,
  892. app=app,
  893. created_models=created_models,
  894. verbosity=verbosity,
  895. interactive=interactive,
  896. db=self.db_alias,
  897. )
  898. else:
  899. # Django 1.1 - 1.0
  900. models.signals.post_syncdb.send(
  901. sender=app,
  902. app=app,
  903. created_models=created_models,
  904. verbosity=verbosity,
  905. interactive=interactive,
  906. )
  907. def mock_model(self, model_name, db_table, db_tablespace='',
  908. pk_field_name='id', pk_field_type=models.AutoField,
  909. pk_field_args=[], pk_field_kwargs={}):
  910. """
  911. Generates a MockModel class that provides enough information
  912. to be used by a foreign key/many-to-many relationship.
  913. Migrations should prefer to use these rather than actual models
  914. as models could get deleted over time, but these can remain in
  915. migration files forever.
  916. Depreciated.
  917. """
  918. class MockOptions(object):
  919. def __init__(self):
  920. self.db_table = db_table
  921. self.db_tablespace = db_tablespace or settings.DEFAULT_TABLESPACE
  922. self.object_name = model_name
  923. self.module_name = model_name.lower()
  924. if pk_field_type == models.AutoField:
  925. pk_field_kwargs['primary_key'] = True
  926. self.pk = pk_field_type(*pk_field_args, **pk_field_kwargs)
  927. self.pk.set_attributes_from_name(pk_field_name)
  928. self.abstract = False
  929. def get_field_by_name(self, field_name):
  930. # we only care about the pk field
  931. return (self.pk, self.model, True, False)
  932. def get_field(self, name):
  933. # we only care about the pk field
  934. return self.pk
  935. class MockModel(object):
  936. _meta = None
  937. # We need to return an actual class object here, not an instance
  938. MockModel._meta = MockOptions()
  939. MockModel._meta.model = MockModel
  940. return MockModel
  941. def _db_positive_type_for_alter_column(self, klass, field):
  942. """
  943. A helper for subclasses overriding _db_type_for_alter_column:
  944. Remove the check constraint from the type string for PositiveInteger
  945. and PositiveSmallInteger fields.
  946. @param klass: The type of the child (required to allow this to be used when it is subclassed)
  947. @param field: The field to generate type for
  948. """
  949. super_result = super(klass, self)._db_type_for_alter_column(field)
  950. if isinstance(field, (models.PositiveSmallIntegerField, models.PositiveIntegerField)):
  951. return super_result.split(" ", 1)[0]
  952. return super_result
  953. def _alter_add_positive_check(self, klass, field, name, params, sqls):
  954. """
  955. A helper for subclasses overriding _alter_add_column_mods:
  956. Add a check constraint verifying positivity to PositiveInteger and
  957. PositiveSmallInteger fields.
  958. """
  959. super(klass, self)._alter_add_column_mods(field, name, params, sqls)
  960. if isinstance(field, (models.PositiveSmallIntegerField, models.PositiveIntegerField)):
  961. uniq_hash = abs(hash(tuple(params.values())))
  962. d = dict(
  963. constraint = "CK_%s_PSTV_%s" % (name, hex(uniq_hash)[2:]),
  964. check = "%s >= 0" % self.quote_name(name))
  965. sqls.append((self.add_check_constraint_fragment % d, []))
  966. # Single-level flattening of lists
  967. def flatten(ls):
  968. nl = []
  969. for l in ls:
  970. nl += l
  971. return nl