datastructures.py 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. """
  2. Useful auxiliary data structures for query construction. Not useful outside
  3. the SQL domain.
  4. """
  5. class Col(object):
  6. def __init__(self, alias, target, source):
  7. self.alias, self.target, self.source = alias, target, source
  8. def as_sql(self, qn, connection):
  9. return "%s.%s" % (qn(self.alias), qn(self.target.column)), []
  10. @property
  11. def output_field(self):
  12. return self.source
  13. def relabeled_clone(self, relabels):
  14. return self.__class__(relabels.get(self.alias, self.alias), self.target, self.source)
  15. def get_group_by_cols(self):
  16. return [(self.alias, self.target.column)]
  17. def get_lookup(self, name):
  18. return self.output_field.get_lookup(name)
  19. def get_transform(self, name):
  20. return self.output_field.get_transform(name)
  21. def prepare(self):
  22. return self
  23. class EmptyResultSet(Exception):
  24. pass
  25. class MultiJoin(Exception):
  26. """
  27. Used by join construction code to indicate the point at which a
  28. multi-valued join was attempted (if the caller wants to treat that
  29. exceptionally).
  30. """
  31. def __init__(self, names_pos, path_with_names):
  32. self.level = names_pos
  33. # The path travelled, this includes the path to the multijoin.
  34. self.names_with_path = path_with_names
  35. class Empty(object):
  36. pass
  37. class Date(object):
  38. """
  39. Add a date selection column.
  40. """
  41. def __init__(self, col, lookup_type):
  42. self.col = col
  43. self.lookup_type = lookup_type
  44. def relabeled_clone(self, change_map):
  45. return self.__class__((change_map.get(self.col[0], self.col[0]), self.col[1]))
  46. def as_sql(self, qn, connection):
  47. if isinstance(self.col, (list, tuple)):
  48. col = '%s.%s' % tuple(qn(c) for c in self.col)
  49. else:
  50. col = self.col
  51. return connection.ops.date_trunc_sql(self.lookup_type, col), []
  52. class DateTime(object):
  53. """
  54. Add a datetime selection column.
  55. """
  56. def __init__(self, col, lookup_type, tzname):
  57. self.col = col
  58. self.lookup_type = lookup_type
  59. self.tzname = tzname
  60. def relabeled_clone(self, change_map):
  61. return self.__class__((change_map.get(self.col[0], self.col[0]), self.col[1]))
  62. def as_sql(self, qn, connection):
  63. if isinstance(self.col, (list, tuple)):
  64. col = '%s.%s' % tuple(qn(c) for c in self.col)
  65. else:
  66. col = self.col
  67. return connection.ops.datetime_trunc_sql(self.lookup_type, col, self.tzname)