PyGreSQL 6.3.0b1__cp315-cp315-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.
pgdb/connect.py ADDED
@@ -0,0 +1,73 @@
1
+ """The DB API 2 connect function."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Any
6
+
7
+ from pg.core import connect as get_cnx
8
+
9
+ from .connection import Connection
10
+
11
+ __all__ = ['connect']
12
+
13
+ def connect(dsn: str | None = None,
14
+ user: str | None = None, password: str | None = None,
15
+ host: str | None = None, database: str | None = None,
16
+ **kwargs: Any) -> Connection:
17
+ """Connect to a database."""
18
+ # first get params from DSN
19
+ dbport = -1
20
+ dbhost: str | None = ""
21
+ dbname: str | None = ""
22
+ dbuser: str | None = ""
23
+ dbpasswd: str | None = ""
24
+ dbopt: str | None = ""
25
+ if dsn:
26
+ try:
27
+ params = dsn.split(":", 4)
28
+ dbhost = params[0]
29
+ dbname = params[1]
30
+ dbuser = params[2]
31
+ dbpasswd = params[3]
32
+ dbopt = params[4]
33
+ except (AttributeError, IndexError, TypeError):
34
+ pass
35
+
36
+ # override if necessary
37
+ if user is not None:
38
+ dbuser = user
39
+ if password is not None:
40
+ dbpasswd = password
41
+ if database is not None:
42
+ dbname = database
43
+ if host:
44
+ try:
45
+ params = host.split(":", 1)
46
+ dbhost = params[0]
47
+ dbport = int(params[1])
48
+ except (AttributeError, IndexError, TypeError, ValueError):
49
+ pass
50
+
51
+ # empty host is localhost
52
+ if dbhost == "":
53
+ dbhost = None
54
+ if dbuser == "":
55
+ dbuser = None
56
+
57
+ # pass keyword arguments as connection info string
58
+ if kwargs:
59
+ kwarg_list = list(kwargs.items())
60
+ kw_parts = []
61
+ if dbname and '=' in dbname:
62
+ kw_parts.append(dbname)
63
+ else:
64
+ kwarg_list.insert(0, ('dbname', dbname))
65
+ for kw, value in kwarg_list:
66
+ # always quote, since libpq also treats quotes and
67
+ # backslashes in unquoted values specially
68
+ value = str(value).replace('\\', '\\\\').replace("'", "\\'")
69
+ kw_parts.append(f"{kw}='{value}'")
70
+ dbname = ' '.join(kw_parts)
71
+ # open the connection
72
+ cnx = get_cnx(dbname, dbhost, dbport, dbopt, dbuser, dbpasswd)
73
+ return Connection(cnx)
pgdb/connection.py ADDED
@@ -0,0 +1,164 @@
1
+ """The DB API 2 Connection objects."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from collections.abc import Mapping, Sequence
6
+ from contextlib import suppress
7
+ from typing import Any
8
+
9
+ from pg.core import Connection as Cnx
10
+ from pg.core import (
11
+ DatabaseError,
12
+ DataError,
13
+ Error,
14
+ IntegrityError,
15
+ InterfaceError,
16
+ InternalError,
17
+ NotSupportedError,
18
+ OperationalError,
19
+ ProgrammingError,
20
+ Warning,
21
+ )
22
+ from pg.error import op_error
23
+
24
+ from .cast import TypeCache
25
+ from .constants import shortcutmethods
26
+ from .cursor import Cursor
27
+
28
+ __all__ = ['Connection']
29
+
30
+ class Connection:
31
+ """Connection object."""
32
+
33
+ # expose the exceptions as attributes on the connection object
34
+ Error = Error
35
+ Warning = Warning
36
+ InterfaceError = InterfaceError
37
+ DatabaseError = DatabaseError
38
+ InternalError = InternalError
39
+ OperationalError = OperationalError
40
+ ProgrammingError = ProgrammingError
41
+ IntegrityError = IntegrityError
42
+ DataError = DataError
43
+ NotSupportedError = NotSupportedError
44
+
45
+ def __init__(self, cnx: Cnx) -> None:
46
+ """Create a database connection object."""
47
+ # check the connection first, the type cache also uses it
48
+ try:
49
+ cnx.source()
50
+ except Exception as e:
51
+ raise op_error("Invalid connection") from e
52
+ self._cnx: Cnx | None = cnx # connection
53
+ self._tnx = False # transaction state
54
+ self.type_cache = TypeCache(cnx)
55
+ self.cursor_type = Cursor
56
+ self.autocommit = False
57
+
58
+ def __enter__(self) -> Connection:
59
+ """Enter the runtime context for the connection object.
60
+
61
+ The runtime context can be used for running transactions.
62
+
63
+ This also starts a transaction in autocommit mode.
64
+ """
65
+ if self.autocommit:
66
+ cnx = self._cnx
67
+ if not cnx:
68
+ raise op_error("Connection has been closed")
69
+ try:
70
+ cnx.source().execute("BEGIN")
71
+ except DatabaseError:
72
+ raise # database provides error message
73
+ except Exception as e:
74
+ raise op_error("Can't start transaction") from e
75
+ else:
76
+ self._tnx = True
77
+ return self
78
+
79
+ def __exit__(self, et: type[BaseException] | None,
80
+ ev: BaseException | None, tb: Any) -> None:
81
+ """Exit the runtime context for the connection object.
82
+
83
+ This does not close the connection, but it ends a transaction.
84
+ """
85
+ if et is None and ev is None and tb is None:
86
+ self.commit()
87
+ else:
88
+ self.rollback()
89
+
90
+ def close(self) -> None:
91
+ """Close the connection object."""
92
+ if not self._cnx:
93
+ raise op_error("Connection has been closed")
94
+ if self._tnx:
95
+ with suppress(DatabaseError):
96
+ self.rollback()
97
+ self._cnx.close()
98
+ self._cnx = None
99
+
100
+ @property
101
+ def closed(self) -> bool:
102
+ """Check whether the connection has been closed or is broken."""
103
+ try:
104
+ return not self._cnx or self._cnx.status != 1
105
+ except TypeError:
106
+ return True
107
+
108
+ def commit(self) -> None:
109
+ """Commit any pending transaction to the database."""
110
+ if not self._cnx:
111
+ raise op_error("Connection has been closed")
112
+ if self._tnx:
113
+ try:
114
+ self._cnx.source().execute("COMMIT")
115
+ except DatabaseError:
116
+ self._tnx = False # the transaction has ended anyway
117
+ raise # database provides error message
118
+ except Exception as e:
119
+ # the command has not been sent, e.g. the connection is busy
120
+ raise op_error("Can't commit transaction") from e
121
+ self._tnx = False
122
+
123
+ def rollback(self) -> None:
124
+ """Roll back to the start of any pending transaction."""
125
+ if not self._cnx:
126
+ raise op_error("Connection has been closed")
127
+ if self._tnx:
128
+ try:
129
+ self._cnx.source().execute("ROLLBACK")
130
+ except DatabaseError:
131
+ self._tnx = False # the transaction has ended anyway
132
+ raise # database provides error message
133
+ except Exception as e:
134
+ # the command has not been sent, e.g. the connection is busy
135
+ raise op_error("Can't rollback transaction") from e
136
+ self._tnx = False
137
+
138
+ def cursor(self) -> Cursor:
139
+ """Return a new cursor object using the connection."""
140
+ if not self._cnx:
141
+ raise op_error("Connection has been closed")
142
+ try:
143
+ return self.cursor_type(self)
144
+ except Exception as e:
145
+ raise op_error("Invalid connection") from e
146
+
147
+ # a constant, otherwise do not implement and document this
148
+ if shortcutmethods: # pragma: no branch
149
+
150
+ def execute(self, operation: str | bytes,
151
+ parameters: Mapping | Sequence | None = None
152
+ ) -> Cursor:
153
+ """Shortcut method to run an operation on an implicit cursor."""
154
+ cursor = self.cursor()
155
+ cursor.execute(operation, parameters)
156
+ return cursor
157
+
158
+ def executemany(self, operation: str | bytes,
159
+ seq_of_parameters: Sequence[
160
+ Mapping | Sequence | None]) -> Cursor:
161
+ """Shortcut method to run an operation against a sequence."""
162
+ cursor = self.cursor()
163
+ cursor.executemany(operation, seq_of_parameters)
164
+ return cursor
pgdb/constants.py ADDED
@@ -0,0 +1,14 @@
1
+ """The DB API 2 module constants."""
2
+
3
+ # compliant with DB API 2.0
4
+ apilevel = '2.0'
5
+
6
+ # module may be shared, but not connections
7
+ threadsafety = 1
8
+
9
+ # this module use extended python format codes
10
+ paramstyle = 'pyformat'
11
+
12
+ # shortcut methods have been excluded from DB API 2 and
13
+ # are not recommended by the DB SIG, but they can be handy
14
+ shortcutmethods = 1