psycopg_any.py 4.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120
  1. import ipaddress
  2. from functools import lru_cache
  3. try:
  4. from psycopg import ClientCursor, IsolationLevel, adapt, adapters, errors, pq, sql
  5. from psycopg.postgres import types
  6. from psycopg.types.json import Jsonb
  7. from psycopg.types.range import Range, RangeDumper
  8. from psycopg.types.string import TextLoader
  9. Inet = ipaddress.ip_address
  10. DateRange = DateTimeRange = DateTimeTZRange = NumericRange = Range
  11. RANGE_TYPES = (Range,)
  12. TSRANGE_OID = types["tsrange"].oid
  13. TSTZRANGE_OID = types["tstzrange"].oid
  14. orig_tz_loader_cls = adapters.get_loader(
  15. types["timestamptz"].oid,
  16. pq.Format.TEXT,
  17. )
  18. def mogrify(sql, params, connection):
  19. with connection.cursor() as cursor:
  20. return ClientCursor(cursor.connection).mogrify(sql, params)
  21. # Adapters.
  22. class BaseTzLoader(adapt.Loader):
  23. """
  24. Load a PostgreSQL timestamptz using a specific timezone.
  25. The timezone can be None too, in which case it will be chopped.
  26. """
  27. timezone = None
  28. def __init__(self, oid, context):
  29. super().__init__(oid, context)
  30. self.orig_loader = orig_tz_loader_cls(oid, context)
  31. def load(self, data):
  32. return self.orig_loader.load(data).replace(tzinfo=self.timezone)
  33. def register_tzloader(tz, context):
  34. class SpecificTzLoader(BaseTzLoader):
  35. timezone = tz
  36. context.adapters.register_loader("timestamptz", SpecificTzLoader)
  37. class DjangoRangeDumper(RangeDumper):
  38. """A Range dumper customized for Django."""
  39. def upgrade(self, obj, format):
  40. # Dump ranges containing naive datetimes as tstzrange, because
  41. # Django doesn't use tz-aware ones.
  42. dumper = super().upgrade(obj, format)
  43. if dumper is not self and dumper.oid == TSRANGE_OID:
  44. dumper.oid = TSTZRANGE_OID
  45. return dumper
  46. @lru_cache
  47. def get_adapters_template(use_tz, timezone):
  48. # Create an adapters map extending the base one.
  49. ctx = adapt.AdaptersMap(adapters)
  50. # Register a no-op dumper to avoid a round trip from psycopg version 3
  51. # decode to json.dumps() to json.loads(), when using a custom decoder
  52. # in JSONField.
  53. ctx.register_loader("jsonb", TextLoader)
  54. # Don't convert automatically from PostgreSQL network types to Python
  55. # ipaddress.
  56. ctx.register_loader("inet", TextLoader)
  57. ctx.register_loader("cidr", TextLoader)
  58. ctx.register_dumper(Range, DjangoRangeDumper)
  59. # Register a timestamptz loader configured on self.timezone.
  60. # This, however, can be overridden by create_cursor.
  61. register_tzloader(timezone, ctx)
  62. return ctx
  63. is_psycopg3 = True
  64. except ImportError:
  65. from enum import IntEnum
  66. from psycopg2 import errors, extensions, sql # NOQA
  67. from psycopg2.extras import ( # NOQA
  68. DateRange,
  69. DateTimeRange,
  70. DateTimeTZRange,
  71. Inet,
  72. Json,
  73. NumericRange,
  74. Range,
  75. )
  76. RANGE_TYPES = (DateRange, DateTimeRange, DateTimeTZRange, NumericRange)
  77. class IsolationLevel(IntEnum):
  78. READ_UNCOMMITTED = extensions.ISOLATION_LEVEL_READ_UNCOMMITTED
  79. READ_COMMITTED = extensions.ISOLATION_LEVEL_READ_COMMITTED
  80. REPEATABLE_READ = extensions.ISOLATION_LEVEL_REPEATABLE_READ
  81. SERIALIZABLE = extensions.ISOLATION_LEVEL_SERIALIZABLE
  82. def _quote(value, connection=None):
  83. adapted = extensions.adapt(value)
  84. if hasattr(adapted, "encoding"):
  85. adapted.encoding = "utf8"
  86. # getquoted() returns a quoted bytestring of the adapted value.
  87. return adapted.getquoted().decode()
  88. sql.quote = _quote
  89. def mogrify(sql, params, connection):
  90. with connection.cursor() as cursor:
  91. return cursor.mogrify(sql, params).decode()
  92. is_psycopg3 = False
  93. class Jsonb(Json):
  94. def getquoted(self):
  95. quoted = super().getquoted()
  96. return quoted + b"::jsonb"