Debian Codegraph @

django/db/backends/postgresql/psycopg_any.py

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