PyGreSQL 6.2.0__cp314-cp314-win_amd64.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
pg/error.py ADDED
@@ -0,0 +1,59 @@
1
+ """Error helpers."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import TypeVar
6
+
7
+ from .core import (
8
+ DatabaseError,
9
+ Error,
10
+ InterfaceError,
11
+ InternalError,
12
+ OperationalError,
13
+ ProgrammingError,
14
+ )
15
+
16
+ __all__ = [
17
+ 'db_error',
18
+ 'error',
19
+ 'if_error',
20
+ 'int_error',
21
+ 'op_error',
22
+ 'prg_error'
23
+ ]
24
+
25
+ # Error messages
26
+
27
+ E = TypeVar('E', bound=Error)
28
+
29
+ def error(msg: str, cls: type[E]) -> E:
30
+ """Return specified error object with empty sqlstate attribute."""
31
+ error = cls(msg)
32
+ if isinstance(error, DatabaseError):
33
+ error.sqlstate = None
34
+ return error
35
+
36
+
37
+ def db_error(msg: str) -> DatabaseError:
38
+ """Return DatabaseError."""
39
+ return error(msg, DatabaseError)
40
+
41
+
42
+ def int_error(msg: str) -> InternalError:
43
+ """Return InternalError."""
44
+ return error(msg, InternalError)
45
+
46
+
47
+ def prg_error(msg: str) -> ProgrammingError:
48
+ """Return ProgrammingError."""
49
+ return error(msg, ProgrammingError)
50
+
51
+
52
+ def if_error(msg: str) -> InterfaceError:
53
+ """Return InterfaceError."""
54
+ return error(msg, InterfaceError)
55
+
56
+
57
+ def op_error(msg: str) -> OperationalError:
58
+ """Return OperationalError."""
59
+ return error(msg, OperationalError)
pg/helpers.py ADDED
@@ -0,0 +1,124 @@
1
+ """Helper functions."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from collections import namedtuple
6
+ from decimal import Decimal
7
+ from functools import lru_cache
8
+ from json import loads as jsondecode
9
+ from typing import Any, Callable, Generator, NamedTuple, Sequence
10
+
11
+ from .core import Query, set_decimal, set_jsondecode, set_query_helpers
12
+
13
+ SomeNamedTuple = Any # alias for accessing arbitrary named tuples
14
+
15
+ __all__ = [
16
+ 'QuoteDict',
17
+ 'RowCache',
18
+ 'dictiter',
19
+ 'namediter',
20
+ 'namednext',
21
+ 'oid_key',
22
+ 'quote_if_unqualified',
23
+ 'scalariter'
24
+ ]
25
+
26
+
27
+ # Small helper functions
28
+
29
+ def quote_if_unqualified(param: str, name: int | str) -> str:
30
+ """Quote parameter representing a qualified name.
31
+
32
+ Puts a quote_ident() call around the given parameter unless
33
+ the name contains a dot, in which case the name is ambiguous
34
+ (could be a qualified name or just a name with a dot in it)
35
+ and must be quoted manually by the caller.
36
+ """
37
+ if isinstance(name, str) and '.' not in name:
38
+ return f'quote_ident({param})'
39
+ return param
40
+
41
+ def oid_key(table: str) -> str:
42
+ """Build oid key from a table name."""
43
+ return f'oid({table})'
44
+
45
+ class QuoteDict(dict):
46
+ """Dictionary with auto quoting of its items.
47
+
48
+ The quote attribute must be set to the desired quote function.
49
+ """
50
+
51
+ quote: Callable[[str], str]
52
+
53
+ def __getitem__(self, key: str) -> str:
54
+ """Get a quoted value."""
55
+ return self.quote(super().__getitem__(key))
56
+
57
+
58
+ class RowCache:
59
+ """Global cache for the named tuples used for table rows.
60
+
61
+ The result rows for database operations are returned as named tuples
62
+ by default. Since creating namedtuple classes is a somewhat expensive
63
+ operation, we cache up to 1024 of these classes by default.
64
+ """
65
+
66
+ @staticmethod
67
+ @lru_cache(maxsize=1024)
68
+ def row_factory(names: Sequence[str]) -> Callable[[Sequence], NamedTuple]:
69
+ """Get a namedtuple factory for row results with the given names."""
70
+ try:
71
+ return namedtuple('Row', names, rename=True)._make # type: ignore
72
+ except ValueError: # there is still a problem with the field names
73
+ names = [f'column_{n}' for n in range(len(names))]
74
+ return namedtuple('Row', names)._make # type: ignore
75
+
76
+ @classmethod
77
+ def clear(cls) -> None:
78
+ """Clear the namedtuple factory cache."""
79
+ cls.row_factory.cache_clear()
80
+
81
+ @classmethod
82
+ def change_size(cls, maxsize: int | None) -> None:
83
+ """Change the size of the namedtuple factory cache.
84
+
85
+ If maxsize is set to None, the cache can grow without bound.
86
+ """
87
+ row_factory = cls.row_factory.__wrapped__
88
+ cls.row_factory = lru_cache(maxsize)(row_factory) # type: ignore
89
+
90
+
91
+ # Helper functions used by the query object
92
+
93
+ def dictiter(q: Query) -> Generator[dict[str, Any], None, None]:
94
+ """Get query result as an iterator of dictionaries."""
95
+ fields: tuple[str, ...] = q.listfields()
96
+ for r in q:
97
+ yield dict(zip(fields, r))
98
+
99
+
100
+ def namediter(q: Query) -> Generator[SomeNamedTuple, None, None]:
101
+ """Get query result as an iterator of named tuples."""
102
+ row = RowCache.row_factory(q.listfields())
103
+ for r in q:
104
+ yield row(r)
105
+
106
+
107
+ def namednext(q: Query) -> SomeNamedTuple:
108
+ """Get next row from query result as a named tuple."""
109
+ return RowCache.row_factory(q.listfields())(next(q))
110
+
111
+
112
+ def scalariter(q: Query) -> Generator[Any, None, None]:
113
+ """Get query result as an iterator of scalar values."""
114
+ for r in q:
115
+ yield r[0]
116
+
117
+
118
+ # Initialization
119
+
120
+ def init_core() -> None:
121
+ """Initialize the C extension module."""
122
+ set_decimal(Decimal)
123
+ set_jsondecode(jsondecode)
124
+ set_query_helpers(dictiter, namediter, namednext, scalariter)
pg/notify.py ADDED
@@ -0,0 +1,149 @@
1
+ """Handling of notifications."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import select
6
+ from typing import TYPE_CHECKING, Callable
7
+
8
+ from .core import Query
9
+ from .error import db_error
10
+
11
+ if TYPE_CHECKING:
12
+ from .db import DB
13
+
14
+ __all__ = ['NotificationHandler']
15
+
16
+ # The notification handler
17
+
18
+ class NotificationHandler:
19
+ """A PostgreSQL client-side asynchronous notification handler."""
20
+
21
+ def __init__(self, db: DB, event: str, callback: Callable,
22
+ arg_dict: dict | None = None,
23
+ timeout: int | float | None = None,
24
+ stop_event: str | None = None):
25
+ """Initialize the notification handler.
26
+
27
+ You must pass a PyGreSQL database connection, the name of an
28
+ event (notification channel) to listen for and a callback function.
29
+
30
+ You can also specify a dictionary arg_dict that will be passed as
31
+ the single argument to the callback function, and a timeout value
32
+ in seconds (a floating point number denotes fractions of seconds).
33
+ If it is absent or None, the callers will never time out. If the
34
+ timeout is reached, the callback function will be called with a
35
+ single argument that is None. If you set the timeout to zero,
36
+ the handler will poll notifications synchronously and return.
37
+
38
+ You can specify the name of the event that will be used to signal
39
+ the handler to stop listening as stop_event. By default, it will
40
+ be the event name prefixed with 'stop_'.
41
+ """
42
+ self.db: DB | None = db
43
+ self.event = event
44
+ self.stop_event = stop_event or f'stop_{event}'
45
+ self.listening = False
46
+ self.callback = callback
47
+ if arg_dict is None:
48
+ arg_dict = {}
49
+ self.arg_dict = arg_dict
50
+ self.timeout = timeout
51
+
52
+ def __del__(self) -> None:
53
+ """Delete the notification handler."""
54
+ self.unlisten()
55
+
56
+ def close(self) -> None:
57
+ """Stop listening and close the connection."""
58
+ if self.db:
59
+ self.unlisten()
60
+ self.db.close()
61
+ self.db = None
62
+
63
+ def listen(self) -> None:
64
+ """Start listening for the event and the stop event."""
65
+ db = self.db
66
+ if db and not self.listening:
67
+ db.query(f'listen "{self.event}"')
68
+ db.query(f'listen "{self.stop_event}"')
69
+ self.listening = True
70
+
71
+ def unlisten(self) -> None:
72
+ """Stop listening for the event and the stop event."""
73
+ db = self.db
74
+ if db and self.listening:
75
+ db.query(f'unlisten "{self.event}"')
76
+ db.query(f'unlisten "{self.stop_event}"')
77
+ self.listening = False
78
+
79
+ def notify(self, db: DB | None = None, stop: bool = False,
80
+ payload: str | None = None) -> Query | None:
81
+ """Generate a notification.
82
+
83
+ Optionally, you can pass a payload with the notification.
84
+
85
+ If you set the stop flag, a stop notification will be sent that
86
+ will cause the handler to stop listening.
87
+
88
+ Note: If the notification handler is running in another thread, you
89
+ must pass a different database connection since PyGreSQL database
90
+ connections are not thread-safe.
91
+ """
92
+ if not self.listening:
93
+ return None
94
+ if not db:
95
+ db = self.db
96
+ if not db:
97
+ return None
98
+ event = self.stop_event if stop else self.event
99
+ cmd = f'notify "{event}"'
100
+ if payload:
101
+ cmd += f", '{payload}'"
102
+ return db.query(cmd)
103
+
104
+ def __call__(self) -> None:
105
+ """Invoke the notification handler.
106
+
107
+ The handler is a loop that listens for notifications on the event
108
+ and stop event channels. When either of these notifications are
109
+ received, its associated 'pid', 'event' and 'extra' (the payload
110
+ passed with the notification) are inserted into its arg_dict
111
+ dictionary and the callback is invoked with this dictionary as
112
+ a single argument. When the handler receives a stop event, it
113
+ stops listening to both events and return.
114
+
115
+ In the special case that the timeout of the handler has been set
116
+ to zero, the handler will poll all events synchronously and return.
117
+ If will keep listening until it receives a stop event.
118
+
119
+ Note: If you run this loop in another thread, don't use the same
120
+ database connection for database operations in the main thread.
121
+ """
122
+ if not self.db:
123
+ return
124
+ self.listen()
125
+ poll = self.timeout == 0
126
+ rlist = [] if poll else [self.db.fileno()]
127
+ while self.db and self.listening:
128
+ # noinspection PyUnboundLocalVariable
129
+ if poll or select.select(rlist, [], [], self.timeout)[0]:
130
+ while self.db and self.listening:
131
+ notice = self.db.getnotify()
132
+ if not notice: # no more messages
133
+ break
134
+ event, pid, extra = notice
135
+ if event not in (self.event, self.stop_event):
136
+ self.unlisten()
137
+ raise db_error(
138
+ f'Listening for "{self.event}"'
139
+ f' and "{self.stop_event}",'
140
+ f' but notified of "{event}"')
141
+ if event == self.stop_event:
142
+ self.unlisten()
143
+ self.arg_dict.update(pid=pid, event=event, extra=extra)
144
+ self.callback(self.arg_dict)
145
+ if poll:
146
+ break
147
+ else: # we timed out
148
+ self.unlisten()
149
+ self.callback(None)
pg/py.typed ADDED
@@ -0,0 +1,4 @@
1
+ # Marker file for PEP 561.
2
+
3
+ # The pg package use inline types,
4
+ # except for the _pg extension module which uses a stub file.
pg/tz.py ADDED
@@ -0,0 +1,21 @@
1
+ """Timezone helpers."""
2
+
3
+ from __future__ import annotations
4
+
5
+ __all__ = ['timezone_as_offset']
6
+
7
+ # time zones used in Postgres timestamptz output
8
+ _timezone_offsets: dict[str, str] = {
9
+ 'CET': '+0100', 'EET': '+0200', 'EST': '-0500',
10
+ 'GMT': '+0000', 'HST': '-1000', 'MET': '+0100', 'MST': '-0700',
11
+ 'UCT': '+0000', 'UTC': '+0000', 'WET': '+0000'
12
+ }
13
+
14
+
15
+ def timezone_as_offset(tz: str) -> str:
16
+ """Convert timezone abbreviation to offset."""
17
+ if tz.startswith(('+', '-')):
18
+ if len(tz) < 5:
19
+ return tz + '00'
20
+ return tz.replace(':', '')
21
+ return _timezone_offsets.get(tz, '+0000')
pgdb/__init__.py ADDED
@@ -0,0 +1,182 @@
1
+ #!/usr/bin/python
2
+ #
3
+ # PyGreSQL - a Python interface for the PostgreSQL database.
4
+ #
5
+ # This file contains the DB-API 2 compatible pgdb module.
6
+ #
7
+ # Copyright (c) 2025 by the PyGreSQL Development Team
8
+ #
9
+ # Please see the LICENSE.TXT file for specific restrictions.
10
+
11
+ """pgdb - DB-API 2.0 compliant module for PyGreSQL.
12
+
13
+ (c) 1999, Pascal Andre <andre@via.ecp.fr>.
14
+ See package documentation for further information on copyright.
15
+
16
+ Inline documentation is sparse.
17
+ See DB-API 2.0 specification for usage information:
18
+ http://www.python.org/peps/pep-0249.html
19
+
20
+ Basic usage:
21
+
22
+ pgdb.connect(connect_string) # open a connection
23
+ # connect_string = 'host:database:user:password:opt'
24
+ # All parts are optional. You may also pass host through
25
+ # password as keyword arguments. To pass a port,
26
+ # pass it in the host keyword parameter:
27
+ connection = pgdb.connect(host='localhost:5432')
28
+
29
+ cursor = connection.cursor() # open a cursor
30
+
31
+ cursor.execute(query[, params])
32
+ # Execute a query, binding params (a dictionary) if they are
33
+ # passed. The binding syntax is the same as the % operator
34
+ # for dictionaries, and no quoting is done.
35
+
36
+ cursor.executemany(query, list of params)
37
+ # Execute a query many times, binding each param dictionary
38
+ # from the list.
39
+
40
+ cursor.fetchone() # fetch one row, [value, value, ...]
41
+
42
+ cursor.fetchall() # fetch all rows, [[value, value, ...], ...]
43
+
44
+ cursor.fetchmany([size])
45
+ # returns size or cursor.arraysize number of rows,
46
+ # [[value, value, ...], ...] from result set.
47
+ # Default cursor.arraysize is 1.
48
+
49
+ cursor.description # returns information about the columns
50
+ # [(column_name, type_name, display_size,
51
+ # internal_size, precision, scale, null_ok), ...]
52
+ # Note that display_size, precision, scale and null_ok
53
+ # are not implemented.
54
+
55
+ cursor.rowcount # number of rows available in the result set
56
+ # Available after a call to execute.
57
+
58
+ connection.commit() # commit transaction
59
+
60
+ connection.rollback() # or rollback transaction
61
+
62
+ cursor.close() # close the cursor
63
+
64
+ connection.close() # close the connection
65
+ """
66
+
67
+ from pg.core import (
68
+ DatabaseError,
69
+ DataError,
70
+ Error,
71
+ IntegrityError,
72
+ InterfaceError,
73
+ InternalError,
74
+ NotSupportedError,
75
+ OperationalError,
76
+ ProgrammingError,
77
+ Warning,
78
+ version,
79
+ )
80
+
81
+ from .adapt import (
82
+ ARRAY,
83
+ BINARY,
84
+ BOOL,
85
+ DATE,
86
+ DATETIME,
87
+ FLOAT,
88
+ HSTORE,
89
+ INTEGER,
90
+ INTERVAL,
91
+ JSON,
92
+ LONG,
93
+ MONEY,
94
+ NUMBER,
95
+ NUMERIC,
96
+ RECORD,
97
+ ROWID,
98
+ SMALLINT,
99
+ STRING,
100
+ TIME,
101
+ TIMESTAMP,
102
+ UUID,
103
+ Binary,
104
+ Date,
105
+ DateFromTicks,
106
+ DbType,
107
+ Hstore,
108
+ Interval,
109
+ Json,
110
+ Literal,
111
+ Time,
112
+ TimeFromTicks,
113
+ Timestamp,
114
+ TimestampFromTicks,
115
+ Uuid,
116
+ )
117
+ from .cast import get_typecast, reset_typecast, set_typecast
118
+ from .connect import connect
119
+ from .connection import Connection
120
+ from .constants import apilevel, paramstyle, shortcutmethods, threadsafety
121
+ from .cursor import Cursor
122
+
123
+ __all__ = [
124
+ 'ARRAY',
125
+ 'BINARY',
126
+ 'BOOL',
127
+ 'DATE',
128
+ 'DATETIME',
129
+ 'FLOAT',
130
+ 'HSTORE',
131
+ 'INTEGER',
132
+ 'INTERVAL',
133
+ 'JSON',
134
+ 'LONG',
135
+ 'MONEY',
136
+ 'NUMBER',
137
+ 'NUMERIC',
138
+ 'RECORD',
139
+ 'ROWID',
140
+ 'SMALLINT',
141
+ 'STRING',
142
+ 'TIME',
143
+ 'TIMESTAMP',
144
+ 'UUID',
145
+ 'Binary',
146
+ 'Connection',
147
+ 'Cursor',
148
+ 'DataError',
149
+ 'DatabaseError',
150
+ 'Date',
151
+ 'DateFromTicks',
152
+ 'DbType',
153
+ 'Error',
154
+ 'Hstore',
155
+ 'IntegrityError',
156
+ 'InterfaceError',
157
+ 'InternalError',
158
+ 'Interval',
159
+ 'Json',
160
+ 'Literal',
161
+ 'NotSupportedError',
162
+ 'OperationalError',
163
+ 'ProgrammingError',
164
+ 'Time',
165
+ 'TimeFromTicks',
166
+ 'Timestamp',
167
+ 'TimestampFromTicks',
168
+ 'Uuid',
169
+ 'Warning',
170
+ '__version__',
171
+ 'apilevel',
172
+ 'connect',
173
+ 'get_typecast',
174
+ 'paramstyle',
175
+ 'reset_typecast',
176
+ 'set_typecast',
177
+ 'shortcutmethods',
178
+ 'threadsafety',
179
+ 'version',
180
+ ]
181
+
182
+ __version__ = version