PageRenderTime 30ms CodeModel.GetById 17ms RepoModel.GetById 0ms app.codeStats 0ms

/django/contrib/gis/db/models/sql/compiler.py

https://code.google.com/p/mango-py/
Python | 278 lines | 223 code | 10 blank | 45 comment | 24 complexity | 801b0e58caeff4b52f25e32616cbca2c MD5 | raw file
Possible License(s): BSD-3-Clause
  1. from itertools import izip
  2. from django.db.backends.util import truncate_name
  3. from django.db.models.sql import compiler
  4. from django.db.models.sql.constants import TABLE_NAME
  5. from django.db.models.sql.query import get_proxied_model
  6. SQLCompiler = compiler.SQLCompiler
  7. class GeoSQLCompiler(compiler.SQLCompiler):
  8. def get_columns(self, with_aliases=False):
  9. """
  10. Return the list of columns to use in the select statement. If no
  11. columns have been specified, returns all columns relating to fields in
  12. the model.
  13. If 'with_aliases' is true, any column names that are duplicated
  14. (without the table names) are given unique aliases. This is needed in
  15. some cases to avoid ambiguitity with nested queries.
  16. This routine is overridden from Query to handle customized selection of
  17. geometry columns.
  18. """
  19. qn = self.quote_name_unless_alias
  20. qn2 = self.connection.ops.quote_name
  21. result = ['(%s) AS %s' % (self.get_extra_select_format(alias) % col[0], qn2(alias))
  22. for alias, col in self.query.extra_select.iteritems()]
  23. aliases = set(self.query.extra_select.keys())
  24. if with_aliases:
  25. col_aliases = aliases.copy()
  26. else:
  27. col_aliases = set()
  28. if self.query.select:
  29. only_load = self.deferred_to_columns()
  30. # This loop customized for GeoQuery.
  31. for col, field in izip(self.query.select, self.query.select_fields):
  32. if isinstance(col, (list, tuple)):
  33. alias, column = col
  34. table = self.query.alias_map[alias][TABLE_NAME]
  35. if table in only_load and col not in only_load[table]:
  36. continue
  37. r = self.get_field_select(field, alias, column)
  38. if with_aliases:
  39. if col[1] in col_aliases:
  40. c_alias = 'Col%d' % len(col_aliases)
  41. result.append('%s AS %s' % (r, c_alias))
  42. aliases.add(c_alias)
  43. col_aliases.add(c_alias)
  44. else:
  45. result.append('%s AS %s' % (r, qn2(col[1])))
  46. aliases.add(r)
  47. col_aliases.add(col[1])
  48. else:
  49. result.append(r)
  50. aliases.add(r)
  51. col_aliases.add(col[1])
  52. else:
  53. result.append(col.as_sql(qn, self.connection))
  54. if hasattr(col, 'alias'):
  55. aliases.add(col.alias)
  56. col_aliases.add(col.alias)
  57. elif self.query.default_cols:
  58. cols, new_aliases = self.get_default_columns(with_aliases,
  59. col_aliases)
  60. result.extend(cols)
  61. aliases.update(new_aliases)
  62. max_name_length = self.connection.ops.max_name_length()
  63. result.extend([
  64. '%s%s' % (
  65. self.get_extra_select_format(alias) % aggregate.as_sql(qn, self.connection),
  66. alias is not None
  67. and ' AS %s' % qn(truncate_name(alias, max_name_length))
  68. or ''
  69. )
  70. for alias, aggregate in self.query.aggregate_select.items()
  71. ])
  72. # This loop customized for GeoQuery.
  73. for (table, col), field in izip(self.query.related_select_cols, self.query.related_select_fields):
  74. r = self.get_field_select(field, table, col)
  75. if with_aliases and col in col_aliases:
  76. c_alias = 'Col%d' % len(col_aliases)
  77. result.append('%s AS %s' % (r, c_alias))
  78. aliases.add(c_alias)
  79. col_aliases.add(c_alias)
  80. else:
  81. result.append(r)
  82. aliases.add(r)
  83. col_aliases.add(col)
  84. self._select_aliases = aliases
  85. return result
  86. def get_default_columns(self, with_aliases=False, col_aliases=None,
  87. start_alias=None, opts=None, as_pairs=False, local_only=False):
  88. """
  89. Computes the default columns for selecting every field in the base
  90. model. Will sometimes be called to pull in related models (e.g. via
  91. select_related), in which case "opts" and "start_alias" will be given
  92. to provide a starting point for the traversal.
  93. Returns a list of strings, quoted appropriately for use in SQL
  94. directly, as well as a set of aliases used in the select statement (if
  95. 'as_pairs' is True, returns a list of (alias, col_name) pairs instead
  96. of strings as the first component and None as the second component).
  97. This routine is overridden from Query to handle customized selection of
  98. geometry columns.
  99. """
  100. result = []
  101. if opts is None:
  102. opts = self.query.model._meta
  103. aliases = set()
  104. only_load = self.deferred_to_columns()
  105. # Skip all proxy to the root proxied model
  106. proxied_model = get_proxied_model(opts)
  107. if start_alias:
  108. seen = {None: start_alias}
  109. for field, model in opts.get_fields_with_model():
  110. if local_only and model is not None:
  111. continue
  112. if start_alias:
  113. try:
  114. alias = seen[model]
  115. except KeyError:
  116. if model is proxied_model:
  117. alias = start_alias
  118. else:
  119. link_field = opts.get_ancestor_link(model)
  120. alias = self.query.join((start_alias, model._meta.db_table,
  121. link_field.column, model._meta.pk.column))
  122. seen[model] = alias
  123. else:
  124. # If we're starting from the base model of the queryset, the
  125. # aliases will have already been set up in pre_sql_setup(), so
  126. # we can save time here.
  127. alias = self.query.included_inherited_models[model]
  128. table = self.query.alias_map[alias][TABLE_NAME]
  129. if table in only_load and field.column not in only_load[table]:
  130. continue
  131. if as_pairs:
  132. result.append((alias, field.column))
  133. aliases.add(alias)
  134. continue
  135. # This part of the function is customized for GeoQuery. We
  136. # see if there was any custom selection specified in the
  137. # dictionary, and set up the selection format appropriately.
  138. field_sel = self.get_field_select(field, alias)
  139. if with_aliases and field.column in col_aliases:
  140. c_alias = 'Col%d' % len(col_aliases)
  141. result.append('%s AS %s' % (field_sel, c_alias))
  142. col_aliases.add(c_alias)
  143. aliases.add(c_alias)
  144. else:
  145. r = field_sel
  146. result.append(r)
  147. aliases.add(r)
  148. if with_aliases:
  149. col_aliases.add(field.column)
  150. return result, aliases
  151. def resolve_columns(self, row, fields=()):
  152. """
  153. This routine is necessary so that distances and geometries returned
  154. from extra selection SQL get resolved appropriately into Python
  155. objects.
  156. """
  157. values = []
  158. aliases = self.query.extra_select.keys()
  159. if self.query.aggregates:
  160. # If we have an aggregate annotation, must extend the aliases
  161. # so their corresponding row values are included.
  162. aliases.extend([None for i in xrange(len(self.query.aggregates))])
  163. # Have to set a starting row number offset that is used for
  164. # determining the correct starting row index -- needed for
  165. # doing pagination with Oracle.
  166. rn_offset = 0
  167. if self.connection.ops.oracle:
  168. if self.query.high_mark is not None or self.query.low_mark: rn_offset = 1
  169. index_start = rn_offset + len(aliases)
  170. # Converting any extra selection values (e.g., geometries and
  171. # distance objects added by GeoQuerySet methods).
  172. values = [self.query.convert_values(v,
  173. self.query.extra_select_fields.get(a, None),
  174. self.connection)
  175. for v, a in izip(row[rn_offset:index_start], aliases)]
  176. if self.connection.ops.oracle or getattr(self.query, 'geo_values', False):
  177. # We resolve the rest of the columns if we're on Oracle or if
  178. # the `geo_values` attribute is defined.
  179. for value, field in map(None, row[index_start:], fields):
  180. values.append(self.query.convert_values(value, field, connection=self.connection))
  181. else:
  182. values.extend(row[index_start:])
  183. return tuple(values)
  184. #### Routines unique to GeoQuery ####
  185. def get_extra_select_format(self, alias):
  186. sel_fmt = '%s'
  187. if hasattr(self.query, 'custom_select') and alias in self.query.custom_select:
  188. sel_fmt = sel_fmt % self.query.custom_select[alias]
  189. return sel_fmt
  190. def get_field_select(self, field, alias=None, column=None):
  191. """
  192. Returns the SELECT SQL string for the given field. Figures out
  193. if any custom selection SQL is needed for the column The `alias`
  194. keyword may be used to manually specify the database table where
  195. the column exists, if not in the model associated with this
  196. `GeoQuery`. Similarly, `column` may be used to specify the exact
  197. column name, rather than using the `column` attribute on `field`.
  198. """
  199. sel_fmt = self.get_select_format(field)
  200. if field in self.query.custom_select:
  201. field_sel = sel_fmt % self.query.custom_select[field]
  202. else:
  203. field_sel = sel_fmt % self._field_column(field, alias, column)
  204. return field_sel
  205. def get_select_format(self, fld):
  206. """
  207. Returns the selection format string, depending on the requirements
  208. of the spatial backend. For example, Oracle and MySQL require custom
  209. selection formats in order to retrieve geometries in OGC WKT. For all
  210. other fields a simple '%s' format string is returned.
  211. """
  212. if self.connection.ops.select and hasattr(fld, 'geom_type'):
  213. # This allows operations to be done on fields in the SELECT,
  214. # overriding their values -- used by the Oracle and MySQL
  215. # spatial backends to get database values as WKT, and by the
  216. # `transform` method.
  217. sel_fmt = self.connection.ops.select
  218. # Because WKT doesn't contain spatial reference information,
  219. # the SRID is prefixed to the returned WKT to ensure that the
  220. # transformed geometries have an SRID different than that of the
  221. # field -- this is only used by `transform` for Oracle and
  222. # SpatiaLite backends.
  223. if self.query.transformed_srid and ( self.connection.ops.oracle or
  224. self.connection.ops.spatialite ):
  225. sel_fmt = "'SRID=%d;'||%s" % (self.query.transformed_srid, sel_fmt)
  226. else:
  227. sel_fmt = '%s'
  228. return sel_fmt
  229. # Private API utilities, subject to change.
  230. def _field_column(self, field, table_alias=None, column=None):
  231. """
  232. Helper function that returns the database column for the given field.
  233. The table and column are returned (quoted) in the proper format, e.g.,
  234. `"geoapp_city"."point"`. If `table_alias` is not specified, the
  235. database table associated with the model of this `GeoQuery` will be
  236. used. If `column` is specified, it will be used instead of the value
  237. in `field.column`.
  238. """
  239. if table_alias is None: table_alias = self.query.model._meta.db_table
  240. return "%s.%s" % (self.quote_name_unless_alias(table_alias),
  241. self.connection.ops.quote_name(column or field.column))
  242. class SQLInsertCompiler(compiler.SQLInsertCompiler, GeoSQLCompiler):
  243. pass
  244. class SQLDeleteCompiler(compiler.SQLDeleteCompiler, GeoSQLCompiler):
  245. pass
  246. class SQLUpdateCompiler(compiler.SQLUpdateCompiler, GeoSQLCompiler):
  247. pass
  248. class SQLAggregateCompiler(compiler.SQLAggregateCompiler, GeoSQLCompiler):
  249. pass
  250. class SQLDateCompiler(compiler.SQLDateCompiler, GeoSQLCompiler):
  251. pass