techprotrade commited on
Commit
b68670c
·
verified ·
1 Parent(s): 1bb25c7

Add loan-advisor-agent

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .gitattributes +1 -0
  2. loan-advisor-agent/.venv/Lib/site-packages/sqlalchemy/__init__.py +283 -0
  3. loan-advisor-agent/.venv/Lib/site-packages/sqlalchemy/connectors/__init__.py +18 -0
  4. loan-advisor-agent/.venv/Lib/site-packages/sqlalchemy/connectors/aioodbc.py +194 -0
  5. loan-advisor-agent/.venv/Lib/site-packages/sqlalchemy/connectors/asyncio.py +429 -0
  6. loan-advisor-agent/.venv/Lib/site-packages/sqlalchemy/connectors/pyodbc.py +250 -0
  7. loan-advisor-agent/.venv/Lib/site-packages/sqlalchemy/cyextension/__init__.py +6 -0
  8. loan-advisor-agent/.venv/Lib/site-packages/sqlalchemy/cyextension/collections.cp312-win_amd64.pyd +3 -0
  9. loan-advisor-agent/.venv/Lib/site-packages/sqlalchemy/cyextension/collections.pyx +409 -0
  10. loan-advisor-agent/.venv/Lib/site-packages/sqlalchemy/cyextension/immutabledict.cp312-win_amd64.pyd +0 -0
  11. loan-advisor-agent/.venv/Lib/site-packages/sqlalchemy/cyextension/immutabledict.pxd +8 -0
  12. loan-advisor-agent/.venv/Lib/site-packages/sqlalchemy/cyextension/immutabledict.pyx +133 -0
  13. loan-advisor-agent/.venv/Lib/site-packages/sqlalchemy/cyextension/processors.cp312-win_amd64.pyd +0 -0
  14. loan-advisor-agent/.venv/Lib/site-packages/sqlalchemy/cyextension/processors.pyx +68 -0
  15. loan-advisor-agent/.venv/Lib/site-packages/sqlalchemy/cyextension/resultproxy.cp312-win_amd64.pyd +0 -0
  16. loan-advisor-agent/.venv/Lib/site-packages/sqlalchemy/cyextension/resultproxy.pyx +102 -0
  17. loan-advisor-agent/.venv/Lib/site-packages/sqlalchemy/cyextension/util.cp312-win_amd64.pyd +0 -0
  18. loan-advisor-agent/.venv/Lib/site-packages/sqlalchemy/cyextension/util.pyx +90 -0
  19. loan-advisor-agent/.venv/Lib/site-packages/sqlalchemy/dialects/__init__.py +62 -0
  20. loan-advisor-agent/.venv/Lib/site-packages/sqlalchemy/dialects/_typing.py +30 -0
  21. loan-advisor-agent/.venv/Lib/site-packages/sqlalchemy/dialects/mssql/__init__.py +88 -0
  22. loan-advisor-agent/.venv/Lib/site-packages/sqlalchemy/dialects/mssql/aioodbc.py +63 -0
  23. loan-advisor-agent/.venv/Lib/site-packages/sqlalchemy/dialects/mssql/base.py +0 -0
  24. loan-advisor-agent/.venv/Lib/site-packages/sqlalchemy/dialects/mssql/information_schema.py +285 -0
  25. loan-advisor-agent/.venv/Lib/site-packages/sqlalchemy/dialects/mssql/json.py +129 -0
  26. loan-advisor-agent/.venv/Lib/site-packages/sqlalchemy/dialects/mssql/provision.py +185 -0
  27. loan-advisor-agent/.venv/Lib/site-packages/sqlalchemy/dialects/mssql/pymssql.py +126 -0
  28. loan-advisor-agent/.venv/Lib/site-packages/sqlalchemy/dialects/mssql/pyodbc.py +760 -0
  29. loan-advisor-agent/.venv/Lib/site-packages/sqlalchemy/dialects/mysql/__init__.py +104 -0
  30. loan-advisor-agent/.venv/Lib/site-packages/sqlalchemy/dialects/mysql/aiomysql.py +250 -0
  31. loan-advisor-agent/.venv/Lib/site-packages/sqlalchemy/dialects/mysql/asyncmy.py +231 -0
  32. loan-advisor-agent/.venv/Lib/site-packages/sqlalchemy/dialects/mysql/base.py +0 -0
  33. loan-advisor-agent/.venv/Lib/site-packages/sqlalchemy/dialects/mysql/cymysql.py +106 -0
  34. loan-advisor-agent/.venv/Lib/site-packages/sqlalchemy/dialects/mysql/dml.py +225 -0
  35. loan-advisor-agent/.venv/Lib/site-packages/sqlalchemy/dialects/mysql/enumerated.py +282 -0
  36. loan-advisor-agent/.venv/Lib/site-packages/sqlalchemy/dialects/mysql/expression.py +146 -0
  37. loan-advisor-agent/.venv/Lib/site-packages/sqlalchemy/dialects/mysql/json.py +91 -0
  38. loan-advisor-agent/.venv/Lib/site-packages/sqlalchemy/dialects/mysql/mariadb.py +72 -0
  39. loan-advisor-agent/.venv/Lib/site-packages/sqlalchemy/dialects/mysql/mariadbconnector.py +322 -0
  40. loan-advisor-agent/.venv/Lib/site-packages/sqlalchemy/dialects/mysql/mysqlconnector.py +302 -0
  41. loan-advisor-agent/.venv/Lib/site-packages/sqlalchemy/dialects/mysql/mysqldb.py +314 -0
  42. loan-advisor-agent/.venv/Lib/site-packages/sqlalchemy/dialects/mysql/provision.py +153 -0
  43. loan-advisor-agent/.venv/Lib/site-packages/sqlalchemy/dialects/mysql/pymysql.py +158 -0
  44. loan-advisor-agent/.venv/Lib/site-packages/sqlalchemy/dialects/mysql/pyodbc.py +157 -0
  45. loan-advisor-agent/.venv/Lib/site-packages/sqlalchemy/dialects/mysql/reflection.py +727 -0
  46. loan-advisor-agent/.venv/Lib/site-packages/sqlalchemy/dialects/mysql/reserved_words.py +570 -0
  47. loan-advisor-agent/.venv/Lib/site-packages/sqlalchemy/dialects/mysql/types.py +835 -0
  48. loan-advisor-agent/.venv/Lib/site-packages/sqlalchemy/dialects/oracle/__init__.py +81 -0
  49. loan-advisor-agent/.venv/Lib/site-packages/sqlalchemy/dialects/oracle/base.py +0 -0
  50. loan-advisor-agent/.venv/Lib/site-packages/sqlalchemy/dialects/oracle/cx_oracle.py +1555 -0
.gitattributes CHANGED
@@ -707,3 +707,4 @@ loan-advisor-agent/.venv/Lib/site-packages/sklearn/utils/_cython_blas.cp312-win_
707
  loan-advisor-agent/.venv/Lib/site-packages/sklearn/utils/_random.cp312-win_amd64.pyd filter=lfs diff=lfs merge=lfs -text
708
  loan-advisor-agent/.venv/Lib/site-packages/sklearn/utils/_seq_dataset.cp312-win_amd64.pyd filter=lfs diff=lfs merge=lfs -text
709
  loan-advisor-agent/.venv/Lib/site-packages/sklearn/utils/sparsefuncs_fast.cp312-win_amd64.pyd filter=lfs diff=lfs merge=lfs -text
 
 
707
  loan-advisor-agent/.venv/Lib/site-packages/sklearn/utils/_random.cp312-win_amd64.pyd filter=lfs diff=lfs merge=lfs -text
708
  loan-advisor-agent/.venv/Lib/site-packages/sklearn/utils/_seq_dataset.cp312-win_amd64.pyd filter=lfs diff=lfs merge=lfs -text
709
  loan-advisor-agent/.venv/Lib/site-packages/sklearn/utils/sparsefuncs_fast.cp312-win_amd64.pyd filter=lfs diff=lfs merge=lfs -text
710
+ loan-advisor-agent/.venv/Lib/site-packages/sqlalchemy/cyextension/collections.cp312-win_amd64.pyd filter=lfs diff=lfs merge=lfs -text
loan-advisor-agent/.venv/Lib/site-packages/sqlalchemy/__init__.py ADDED
@@ -0,0 +1,283 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # __init__.py
2
+ # Copyright (C) 2005-2026 the SQLAlchemy authors and contributors
3
+ # <see AUTHORS file>
4
+ #
5
+ # This module is part of SQLAlchemy and is released under
6
+ # the MIT License: https://www.opensource.org/licenses/mit-license.php
7
+
8
+ from __future__ import annotations
9
+
10
+ from typing import Any
11
+
12
+ from . import util as _util
13
+ from .engine import AdaptedConnection as AdaptedConnection
14
+ from .engine import BaseRow as BaseRow
15
+ from .engine import BindTyping as BindTyping
16
+ from .engine import ChunkedIteratorResult as ChunkedIteratorResult
17
+ from .engine import Compiled as Compiled
18
+ from .engine import Connection as Connection
19
+ from .engine import create_engine as create_engine
20
+ from .engine import create_mock_engine as create_mock_engine
21
+ from .engine import create_pool_from_url as create_pool_from_url
22
+ from .engine import CreateEnginePlugin as CreateEnginePlugin
23
+ from .engine import CursorResult as CursorResult
24
+ from .engine import Dialect as Dialect
25
+ from .engine import Engine as Engine
26
+ from .engine import engine_from_config as engine_from_config
27
+ from .engine import ExceptionContext as ExceptionContext
28
+ from .engine import ExecutionContext as ExecutionContext
29
+ from .engine import FrozenResult as FrozenResult
30
+ from .engine import Inspector as Inspector
31
+ from .engine import IteratorResult as IteratorResult
32
+ from .engine import make_url as make_url
33
+ from .engine import MappingResult as MappingResult
34
+ from .engine import MergedResult as MergedResult
35
+ from .engine import NestedTransaction as NestedTransaction
36
+ from .engine import Result as Result
37
+ from .engine import result_tuple as result_tuple
38
+ from .engine import ResultProxy as ResultProxy
39
+ from .engine import RootTransaction as RootTransaction
40
+ from .engine import Row as Row
41
+ from .engine import RowMapping as RowMapping
42
+ from .engine import ScalarResult as ScalarResult
43
+ from .engine import Transaction as Transaction
44
+ from .engine import TwoPhaseTransaction as TwoPhaseTransaction
45
+ from .engine import TypeCompiler as TypeCompiler
46
+ from .engine import URL as URL
47
+ from .inspection import inspect as inspect
48
+ from .pool import AssertionPool as AssertionPool
49
+ from .pool import AsyncAdaptedQueuePool as AsyncAdaptedQueuePool
50
+ from .pool import (
51
+ FallbackAsyncAdaptedQueuePool as FallbackAsyncAdaptedQueuePool,
52
+ )
53
+ from .pool import NullPool as NullPool
54
+ from .pool import Pool as Pool
55
+ from .pool import PoolProxiedConnection as PoolProxiedConnection
56
+ from .pool import PoolResetState as PoolResetState
57
+ from .pool import QueuePool as QueuePool
58
+ from .pool import SingletonThreadPool as SingletonThreadPool
59
+ from .pool import StaticPool as StaticPool
60
+ from .schema import BaseDDLElement as BaseDDLElement
61
+ from .schema import BLANK_SCHEMA as BLANK_SCHEMA
62
+ from .schema import CheckConstraint as CheckConstraint
63
+ from .schema import Column as Column
64
+ from .schema import ColumnDefault as ColumnDefault
65
+ from .schema import Computed as Computed
66
+ from .schema import Constraint as Constraint
67
+ from .schema import DDL as DDL
68
+ from .schema import DDLElement as DDLElement
69
+ from .schema import DefaultClause as DefaultClause
70
+ from .schema import ExecutableDDLElement as ExecutableDDLElement
71
+ from .schema import FetchedValue as FetchedValue
72
+ from .schema import ForeignKey as ForeignKey
73
+ from .schema import ForeignKeyConstraint as ForeignKeyConstraint
74
+ from .schema import Identity as Identity
75
+ from .schema import Index as Index
76
+ from .schema import insert_sentinel as insert_sentinel
77
+ from .schema import MetaData as MetaData
78
+ from .schema import PrimaryKeyConstraint as PrimaryKeyConstraint
79
+ from .schema import Sequence as Sequence
80
+ from .schema import Table as Table
81
+ from .schema import UniqueConstraint as UniqueConstraint
82
+ from .sql import ColumnExpressionArgument as ColumnExpressionArgument
83
+ from .sql import NotNullable as NotNullable
84
+ from .sql import Nullable as Nullable
85
+ from .sql import SelectLabelStyle as SelectLabelStyle
86
+ from .sql.expression import Alias as Alias
87
+ from .sql.expression import alias as alias
88
+ from .sql.expression import AliasedReturnsRows as AliasedReturnsRows
89
+ from .sql.expression import all_ as all_
90
+ from .sql.expression import and_ as and_
91
+ from .sql.expression import any_ as any_
92
+ from .sql.expression import asc as asc
93
+ from .sql.expression import between as between
94
+ from .sql.expression import BinaryExpression as BinaryExpression
95
+ from .sql.expression import bindparam as bindparam
96
+ from .sql.expression import BindParameter as BindParameter
97
+ from .sql.expression import bitwise_not as bitwise_not
98
+ from .sql.expression import BooleanClauseList as BooleanClauseList
99
+ from .sql.expression import CacheKey as CacheKey
100
+ from .sql.expression import Case as Case
101
+ from .sql.expression import case as case
102
+ from .sql.expression import Cast as Cast
103
+ from .sql.expression import cast as cast
104
+ from .sql.expression import ClauseElement as ClauseElement
105
+ from .sql.expression import ClauseList as ClauseList
106
+ from .sql.expression import collate as collate
107
+ from .sql.expression import CollectionAggregate as CollectionAggregate
108
+ from .sql.expression import column as column
109
+ from .sql.expression import ColumnClause as ColumnClause
110
+ from .sql.expression import ColumnCollection as ColumnCollection
111
+ from .sql.expression import ColumnElement as ColumnElement
112
+ from .sql.expression import ColumnOperators as ColumnOperators
113
+ from .sql.expression import CompoundSelect as CompoundSelect
114
+ from .sql.expression import CTE as CTE
115
+ from .sql.expression import cte as cte
116
+ from .sql.expression import custom_op as custom_op
117
+ from .sql.expression import Delete as Delete
118
+ from .sql.expression import delete as delete
119
+ from .sql.expression import desc as desc
120
+ from .sql.expression import distinct as distinct
121
+ from .sql.expression import except_ as except_
122
+ from .sql.expression import except_all as except_all
123
+ from .sql.expression import Executable as Executable
124
+ from .sql.expression import Exists as Exists
125
+ from .sql.expression import exists as exists
126
+ from .sql.expression import Extract as Extract
127
+ from .sql.expression import extract as extract
128
+ from .sql.expression import false as false
129
+ from .sql.expression import False_ as False_
130
+ from .sql.expression import FromClause as FromClause
131
+ from .sql.expression import FromGrouping as FromGrouping
132
+ from .sql.expression import func as func
133
+ from .sql.expression import funcfilter as funcfilter
134
+ from .sql.expression import Function as Function
135
+ from .sql.expression import FunctionElement as FunctionElement
136
+ from .sql.expression import FunctionFilter as FunctionFilter
137
+ from .sql.expression import GenerativeSelect as GenerativeSelect
138
+ from .sql.expression import Grouping as Grouping
139
+ from .sql.expression import HasCTE as HasCTE
140
+ from .sql.expression import HasPrefixes as HasPrefixes
141
+ from .sql.expression import HasSuffixes as HasSuffixes
142
+ from .sql.expression import Insert as Insert
143
+ from .sql.expression import insert as insert
144
+ from .sql.expression import intersect as intersect
145
+ from .sql.expression import intersect_all as intersect_all
146
+ from .sql.expression import Join as Join
147
+ from .sql.expression import join as join
148
+ from .sql.expression import Label as Label
149
+ from .sql.expression import label as label
150
+ from .sql.expression import LABEL_STYLE_DEFAULT as LABEL_STYLE_DEFAULT
151
+ from .sql.expression import (
152
+ LABEL_STYLE_DISAMBIGUATE_ONLY as LABEL_STYLE_DISAMBIGUATE_ONLY,
153
+ )
154
+ from .sql.expression import LABEL_STYLE_NONE as LABEL_STYLE_NONE
155
+ from .sql.expression import (
156
+ LABEL_STYLE_TABLENAME_PLUS_COL as LABEL_STYLE_TABLENAME_PLUS_COL,
157
+ )
158
+ from .sql.expression import lambda_stmt as lambda_stmt
159
+ from .sql.expression import LambdaElement as LambdaElement
160
+ from .sql.expression import Lateral as Lateral
161
+ from .sql.expression import lateral as lateral
162
+ from .sql.expression import literal as literal
163
+ from .sql.expression import literal_column as literal_column
164
+ from .sql.expression import modifier as modifier
165
+ from .sql.expression import not_ as not_
166
+ from .sql.expression import Null as Null
167
+ from .sql.expression import null as null
168
+ from .sql.expression import nulls_first as nulls_first
169
+ from .sql.expression import nulls_last as nulls_last
170
+ from .sql.expression import nullsfirst as nullsfirst
171
+ from .sql.expression import nullslast as nullslast
172
+ from .sql.expression import Operators as Operators
173
+ from .sql.expression import or_ as or_
174
+ from .sql.expression import outerjoin as outerjoin
175
+ from .sql.expression import outparam as outparam
176
+ from .sql.expression import Over as Over
177
+ from .sql.expression import over as over
178
+ from .sql.expression import quoted_name as quoted_name
179
+ from .sql.expression import ReleaseSavepointClause as ReleaseSavepointClause
180
+ from .sql.expression import ReturnsRows as ReturnsRows
181
+ from .sql.expression import (
182
+ RollbackToSavepointClause as RollbackToSavepointClause,
183
+ )
184
+ from .sql.expression import SavepointClause as SavepointClause
185
+ from .sql.expression import ScalarSelect as ScalarSelect
186
+ from .sql.expression import Select as Select
187
+ from .sql.expression import select as select
188
+ from .sql.expression import Selectable as Selectable
189
+ from .sql.expression import SelectBase as SelectBase
190
+ from .sql.expression import SQLColumnExpression as SQLColumnExpression
191
+ from .sql.expression import StatementLambdaElement as StatementLambdaElement
192
+ from .sql.expression import Subquery as Subquery
193
+ from .sql.expression import table as table
194
+ from .sql.expression import TableClause as TableClause
195
+ from .sql.expression import TableSample as TableSample
196
+ from .sql.expression import tablesample as tablesample
197
+ from .sql.expression import TableValuedAlias as TableValuedAlias
198
+ from .sql.expression import text as text
199
+ from .sql.expression import TextAsFrom as TextAsFrom
200
+ from .sql.expression import TextClause as TextClause
201
+ from .sql.expression import TextualSelect as TextualSelect
202
+ from .sql.expression import true as true
203
+ from .sql.expression import True_ as True_
204
+ from .sql.expression import try_cast as try_cast
205
+ from .sql.expression import TryCast as TryCast
206
+ from .sql.expression import Tuple as Tuple
207
+ from .sql.expression import tuple_ as tuple_
208
+ from .sql.expression import type_coerce as type_coerce
209
+ from .sql.expression import TypeClause as TypeClause
210
+ from .sql.expression import TypeCoerce as TypeCoerce
211
+ from .sql.expression import UnaryExpression as UnaryExpression
212
+ from .sql.expression import union as union
213
+ from .sql.expression import union_all as union_all
214
+ from .sql.expression import Update as Update
215
+ from .sql.expression import update as update
216
+ from .sql.expression import UpdateBase as UpdateBase
217
+ from .sql.expression import Values as Values
218
+ from .sql.expression import values as values
219
+ from .sql.expression import ValuesBase as ValuesBase
220
+ from .sql.expression import Visitable as Visitable
221
+ from .sql.expression import within_group as within_group
222
+ from .sql.expression import WithinGroup as WithinGroup
223
+ from .types import ARRAY as ARRAY
224
+ from .types import BIGINT as BIGINT
225
+ from .types import BigInteger as BigInteger
226
+ from .types import BINARY as BINARY
227
+ from .types import BLOB as BLOB
228
+ from .types import BOOLEAN as BOOLEAN
229
+ from .types import Boolean as Boolean
230
+ from .types import CHAR as CHAR
231
+ from .types import CLOB as CLOB
232
+ from .types import DATE as DATE
233
+ from .types import Date as Date
234
+ from .types import DATETIME as DATETIME
235
+ from .types import DateTime as DateTime
236
+ from .types import DECIMAL as DECIMAL
237
+ from .types import DOUBLE as DOUBLE
238
+ from .types import Double as Double
239
+ from .types import DOUBLE_PRECISION as DOUBLE_PRECISION
240
+ from .types import Enum as Enum
241
+ from .types import FLOAT as FLOAT
242
+ from .types import Float as Float
243
+ from .types import INT as INT
244
+ from .types import INTEGER as INTEGER
245
+ from .types import Integer as Integer
246
+ from .types import Interval as Interval
247
+ from .types import JSON as JSON
248
+ from .types import LargeBinary as LargeBinary
249
+ from .types import NCHAR as NCHAR
250
+ from .types import NUMERIC as NUMERIC
251
+ from .types import Numeric as Numeric
252
+ from .types import NVARCHAR as NVARCHAR
253
+ from .types import PickleType as PickleType
254
+ from .types import REAL as REAL
255
+ from .types import SMALLINT as SMALLINT
256
+ from .types import SmallInteger as SmallInteger
257
+ from .types import String as String
258
+ from .types import TEXT as TEXT
259
+ from .types import Text as Text
260
+ from .types import TIME as TIME
261
+ from .types import Time as Time
262
+ from .types import TIMESTAMP as TIMESTAMP
263
+ from .types import TupleType as TupleType
264
+ from .types import TypeDecorator as TypeDecorator
265
+ from .types import Unicode as Unicode
266
+ from .types import UnicodeText as UnicodeText
267
+ from .types import UUID as UUID
268
+ from .types import Uuid as Uuid
269
+ from .types import VARBINARY as VARBINARY
270
+ from .types import VARCHAR as VARCHAR
271
+
272
+ __version__ = "2.0.49"
273
+
274
+
275
+ def __go(lcls: Any) -> None:
276
+ _util.preloaded.import_prefix("sqlalchemy")
277
+
278
+ from . import exc
279
+
280
+ exc._version_token = "".join(__version__.split(".")[0:2])
281
+
282
+
283
+ __go(locals())
loan-advisor-agent/.venv/Lib/site-packages/sqlalchemy/connectors/__init__.py ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # connectors/__init__.py
2
+ # Copyright (C) 2005-2026 the SQLAlchemy authors and contributors
3
+ # <see AUTHORS file>
4
+ #
5
+ # This module is part of SQLAlchemy and is released under
6
+ # the MIT License: https://www.opensource.org/licenses/mit-license.php
7
+
8
+
9
+ from ..engine.interfaces import Dialect
10
+
11
+
12
+ class Connector(Dialect):
13
+ """Base class for dialect mixins, for DBAPIs that work
14
+ across entirely different database backends.
15
+
16
+ Currently the only such mixin is pyodbc.
17
+
18
+ """
loan-advisor-agent/.venv/Lib/site-packages/sqlalchemy/connectors/aioodbc.py ADDED
@@ -0,0 +1,194 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # connectors/aioodbc.py
2
+ # Copyright (C) 2005-2026 the SQLAlchemy authors and contributors
3
+ # <see AUTHORS file>
4
+ #
5
+ # This module is part of SQLAlchemy and is released under
6
+ # the MIT License: https://www.opensource.org/licenses/mit-license.php
7
+ # mypy: ignore-errors
8
+
9
+ from __future__ import annotations
10
+
11
+ from typing import TYPE_CHECKING
12
+
13
+ from .asyncio import AsyncAdapt_dbapi_connection
14
+ from .asyncio import AsyncAdapt_dbapi_cursor
15
+ from .asyncio import AsyncAdapt_dbapi_ss_cursor
16
+ from .asyncio import AsyncAdaptFallback_dbapi_connection
17
+ from .pyodbc import PyODBCConnector
18
+ from .. import pool
19
+ from .. import util
20
+ from ..util.concurrency import await_fallback
21
+ from ..util.concurrency import await_only
22
+
23
+
24
+ if TYPE_CHECKING:
25
+ from ..engine.interfaces import ConnectArgsType
26
+ from ..engine.url import URL
27
+
28
+
29
+ class AsyncAdapt_aioodbc_cursor(AsyncAdapt_dbapi_cursor):
30
+ __slots__ = ()
31
+
32
+ def setinputsizes(self, *inputsizes):
33
+ # see https://github.com/aio-libs/aioodbc/issues/451
34
+ return self._cursor._impl.setinputsizes(*inputsizes)
35
+
36
+ # how it's supposed to work
37
+ # return self.await_(self._cursor.setinputsizes(*inputsizes))
38
+
39
+ @property
40
+ def fast_executemany(self):
41
+ return self._cursor._impl.fast_executemany
42
+
43
+ @fast_executemany.setter
44
+ def fast_executemany(self, value):
45
+ self._cursor._impl.fast_executemany = value
46
+
47
+
48
+ class AsyncAdapt_aioodbc_ss_cursor(
49
+ AsyncAdapt_aioodbc_cursor, AsyncAdapt_dbapi_ss_cursor
50
+ ):
51
+ __slots__ = ()
52
+
53
+
54
+ class AsyncAdapt_aioodbc_connection(AsyncAdapt_dbapi_connection):
55
+ _cursor_cls = AsyncAdapt_aioodbc_cursor
56
+ _ss_cursor_cls = AsyncAdapt_aioodbc_ss_cursor
57
+ __slots__ = ()
58
+
59
+ @property
60
+ def autocommit(self):
61
+ return self._connection.autocommit
62
+
63
+ @autocommit.setter
64
+ def autocommit(self, value):
65
+ # https://github.com/aio-libs/aioodbc/issues/448
66
+ # self._connection.autocommit = value
67
+
68
+ self._connection._conn.autocommit = value
69
+
70
+ def ping(self, reconnect):
71
+ return self.await_(self._connection.ping(reconnect))
72
+
73
+ def add_output_converter(self, *arg, **kw):
74
+ self._connection.add_output_converter(*arg, **kw)
75
+
76
+ def character_set_name(self):
77
+ return self._connection.character_set_name()
78
+
79
+ def cursor(self, server_side=False):
80
+ # aioodbc sets connection=None when closed and just fails with
81
+ # AttributeError here. Here we use the same ProgrammingError +
82
+ # message that pyodbc uses, so it triggers is_disconnect() as well.
83
+ if self._connection.closed:
84
+ raise self.dbapi.ProgrammingError(
85
+ "Attempt to use a closed connection."
86
+ )
87
+ return super().cursor(server_side=server_side)
88
+
89
+ def rollback(self):
90
+ # aioodbc sets connection=None when closed and just fails with
91
+ # AttributeError here. should be a no-op
92
+ if not self._connection.closed:
93
+ super().rollback()
94
+
95
+ def commit(self):
96
+ # aioodbc sets connection=None when closed and just fails with
97
+ # AttributeError here. should be a no-op
98
+ if not self._connection.closed:
99
+ super().commit()
100
+
101
+ def close(self):
102
+ # aioodbc sets connection=None when closed and just fails with
103
+ # AttributeError here. should be a no-op
104
+ if not self._connection.closed:
105
+ super().close()
106
+
107
+
108
+ class AsyncAdaptFallback_aioodbc_connection(
109
+ AsyncAdaptFallback_dbapi_connection, AsyncAdapt_aioodbc_connection
110
+ ):
111
+ __slots__ = ()
112
+
113
+
114
+ class AsyncAdapt_aioodbc_dbapi:
115
+ def __init__(self, aioodbc, pyodbc):
116
+ self.aioodbc = aioodbc
117
+ self.pyodbc = pyodbc
118
+ self.paramstyle = pyodbc.paramstyle
119
+ self._init_dbapi_attributes()
120
+ self.Cursor = AsyncAdapt_dbapi_cursor
121
+ self.version = pyodbc.version
122
+
123
+ def _init_dbapi_attributes(self):
124
+ for name in (
125
+ "Warning",
126
+ "Error",
127
+ "InterfaceError",
128
+ "DataError",
129
+ "DatabaseError",
130
+ "OperationalError",
131
+ "InterfaceError",
132
+ "IntegrityError",
133
+ "ProgrammingError",
134
+ "InternalError",
135
+ "NotSupportedError",
136
+ "SQL_DRIVER_NAME",
137
+ "NUMBER",
138
+ "STRING",
139
+ "DATETIME",
140
+ "BINARY",
141
+ "Binary",
142
+ "BinaryNull",
143
+ "SQL_VARCHAR",
144
+ "SQL_WVARCHAR",
145
+ "SQL_DECIMAL",
146
+ ):
147
+ setattr(self, name, getattr(self.pyodbc, name))
148
+
149
+ def connect(self, *arg, **kw):
150
+ async_fallback = kw.pop("async_fallback", False)
151
+ creator_fn = kw.pop("async_creator_fn", self.aioodbc.connect)
152
+
153
+ if util.asbool(async_fallback):
154
+ return AsyncAdaptFallback_aioodbc_connection(
155
+ self,
156
+ await_fallback(creator_fn(*arg, **kw)),
157
+ )
158
+ else:
159
+ return AsyncAdapt_aioodbc_connection(
160
+ self,
161
+ await_only(creator_fn(*arg, **kw)),
162
+ )
163
+
164
+
165
+ class aiodbcConnector(PyODBCConnector):
166
+ is_async = True
167
+ supports_statement_cache = True
168
+
169
+ supports_server_side_cursors = True
170
+
171
+ @classmethod
172
+ def import_dbapi(cls):
173
+ return AsyncAdapt_aioodbc_dbapi(
174
+ __import__("aioodbc"), __import__("pyodbc")
175
+ )
176
+
177
+ def create_connect_args(self, url: URL) -> ConnectArgsType:
178
+ arg, kw = super().create_connect_args(url)
179
+ if arg and arg[0]:
180
+ kw["dsn"] = arg[0]
181
+
182
+ return (), kw
183
+
184
+ @classmethod
185
+ def get_pool_class(cls, url):
186
+ async_fallback = url.query.get("async_fallback", False)
187
+
188
+ if util.asbool(async_fallback):
189
+ return pool.FallbackAsyncAdaptedQueuePool
190
+ else:
191
+ return pool.AsyncAdaptedQueuePool
192
+
193
+ def get_driver_connection(self, connection):
194
+ return connection._connection
loan-advisor-agent/.venv/Lib/site-packages/sqlalchemy/connectors/asyncio.py ADDED
@@ -0,0 +1,429 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # connectors/asyncio.py
2
+ # Copyright (C) 2005-2026 the SQLAlchemy authors and contributors
3
+ # <see AUTHORS file>
4
+ #
5
+ # This module is part of SQLAlchemy and is released under
6
+ # the MIT License: https://www.opensource.org/licenses/mit-license.php
7
+
8
+ """generic asyncio-adapted versions of DBAPI connection and cursor"""
9
+
10
+ from __future__ import annotations
11
+
12
+ import asyncio
13
+ import collections
14
+ import sys
15
+ from typing import Any
16
+ from typing import AsyncIterator
17
+ from typing import Deque
18
+ from typing import Iterator
19
+ from typing import NoReturn
20
+ from typing import Optional
21
+ from typing import Sequence
22
+ from typing import Tuple
23
+ from typing import Type
24
+ from typing import TYPE_CHECKING
25
+
26
+ from ..engine import AdaptedConnection
27
+ from ..util import EMPTY_DICT
28
+ from ..util.concurrency import await_fallback
29
+ from ..util.concurrency import await_only
30
+ from ..util.concurrency import in_greenlet
31
+ from ..util.typing import Protocol
32
+
33
+ if TYPE_CHECKING:
34
+ from ..engine.interfaces import _DBAPICursorDescription
35
+ from ..engine.interfaces import _DBAPIMultiExecuteParams
36
+ from ..engine.interfaces import _DBAPISingleExecuteParams
37
+ from ..engine.interfaces import DBAPIModule
38
+ from ..util.typing import Self
39
+
40
+
41
+ class AsyncIODBAPIConnection(Protocol):
42
+ """protocol representing an async adapted version of a
43
+ :pep:`249` database connection.
44
+
45
+
46
+ """
47
+
48
+ # note that async DBAPIs dont agree if close() should be awaitable,
49
+ # so it is omitted here and picked up by the __getattr__ hook below
50
+
51
+ async def commit(self) -> None: ...
52
+
53
+ def cursor(self, *args: Any, **kwargs: Any) -> AsyncIODBAPICursor: ...
54
+
55
+ async def rollback(self) -> None: ...
56
+
57
+ def __getattr__(self, key: str) -> Any: ...
58
+
59
+ def __setattr__(self, key: str, value: Any) -> None: ...
60
+
61
+
62
+ class AsyncIODBAPICursor(Protocol):
63
+ """protocol representing an async adapted version
64
+ of a :pep:`249` database cursor.
65
+
66
+
67
+ """
68
+
69
+ def __aenter__(self) -> Any: ...
70
+
71
+ @property
72
+ def description(
73
+ self,
74
+ ) -> _DBAPICursorDescription:
75
+ """The description attribute of the Cursor."""
76
+ ...
77
+
78
+ @property
79
+ def rowcount(self) -> int: ...
80
+
81
+ arraysize: int
82
+
83
+ lastrowid: int
84
+
85
+ async def close(self) -> None: ...
86
+
87
+ async def execute(
88
+ self,
89
+ operation: Any,
90
+ parameters: Optional[_DBAPISingleExecuteParams] = None,
91
+ ) -> Any: ...
92
+
93
+ async def executemany(
94
+ self,
95
+ operation: Any,
96
+ parameters: _DBAPIMultiExecuteParams,
97
+ ) -> Any: ...
98
+
99
+ async def fetchone(self) -> Optional[Any]: ...
100
+
101
+ async def fetchmany(self, size: Optional[int] = ...) -> Sequence[Any]: ...
102
+
103
+ async def fetchall(self) -> Sequence[Any]: ...
104
+
105
+ async def setinputsizes(self, sizes: Sequence[Any]) -> None: ...
106
+
107
+ def setoutputsize(self, size: Any, column: Any) -> None: ...
108
+
109
+ async def callproc(
110
+ self, procname: str, parameters: Sequence[Any] = ...
111
+ ) -> Any: ...
112
+
113
+ async def nextset(self) -> Optional[bool]: ...
114
+
115
+ def __aiter__(self) -> AsyncIterator[Any]: ...
116
+
117
+
118
+ class AsyncAdapt_dbapi_module:
119
+ if TYPE_CHECKING:
120
+ Error = DBAPIModule.Error
121
+ OperationalError = DBAPIModule.OperationalError
122
+ InterfaceError = DBAPIModule.InterfaceError
123
+ IntegrityError = DBAPIModule.IntegrityError
124
+
125
+ def __getattr__(self, key: str) -> Any: ...
126
+
127
+
128
+ class AsyncAdapt_dbapi_cursor:
129
+ server_side = False
130
+ __slots__ = (
131
+ "_adapt_connection",
132
+ "_connection",
133
+ "await_",
134
+ "_cursor",
135
+ "_rows",
136
+ "_soft_closed_memoized",
137
+ )
138
+
139
+ _awaitable_cursor_close: bool = True
140
+
141
+ _cursor: AsyncIODBAPICursor
142
+ _adapt_connection: AsyncAdapt_dbapi_connection
143
+ _connection: AsyncIODBAPIConnection
144
+ _rows: Deque[Any]
145
+
146
+ def __init__(self, adapt_connection: AsyncAdapt_dbapi_connection):
147
+ self._adapt_connection = adapt_connection
148
+ self._connection = adapt_connection._connection
149
+
150
+ self.await_ = adapt_connection.await_
151
+
152
+ cursor = self._make_new_cursor(self._connection)
153
+ self._cursor = self._aenter_cursor(cursor)
154
+ self._soft_closed_memoized = EMPTY_DICT
155
+ if not self.server_side:
156
+ self._rows = collections.deque()
157
+
158
+ def _aenter_cursor(self, cursor: AsyncIODBAPICursor) -> AsyncIODBAPICursor:
159
+ return self.await_(cursor.__aenter__()) # type: ignore[no-any-return]
160
+
161
+ def _make_new_cursor(
162
+ self, connection: AsyncIODBAPIConnection
163
+ ) -> AsyncIODBAPICursor:
164
+ return connection.cursor()
165
+
166
+ @property
167
+ def description(self) -> Optional[_DBAPICursorDescription]:
168
+ if "description" in self._soft_closed_memoized:
169
+ return self._soft_closed_memoized["description"] # type: ignore[no-any-return] # noqa: E501
170
+ return self._cursor.description
171
+
172
+ @property
173
+ def rowcount(self) -> int:
174
+ return self._cursor.rowcount
175
+
176
+ @property
177
+ def arraysize(self) -> int:
178
+ return self._cursor.arraysize
179
+
180
+ @arraysize.setter
181
+ def arraysize(self, value: int) -> None:
182
+ self._cursor.arraysize = value
183
+
184
+ @property
185
+ def lastrowid(self) -> int:
186
+ return self._cursor.lastrowid
187
+
188
+ async def _async_soft_close(self) -> None:
189
+ """close the cursor but keep the results pending, and memoize the
190
+ description.
191
+
192
+ .. versionadded:: 2.0.44
193
+
194
+ """
195
+
196
+ if not self._awaitable_cursor_close or self.server_side:
197
+ return
198
+
199
+ self._soft_closed_memoized = self._soft_closed_memoized.union(
200
+ {
201
+ "description": self._cursor.description,
202
+ }
203
+ )
204
+ await self._cursor.close()
205
+
206
+ def close(self) -> None:
207
+ self._rows.clear()
208
+
209
+ # updated as of 2.0.44
210
+ # try to "close" the cursor based on what we know about the driver
211
+ # and if we are able to. otherwise, hope that the asyncio
212
+ # extension called _async_soft_close() if the cursor is going into
213
+ # a sync context
214
+ if self._cursor is None or bool(self._soft_closed_memoized):
215
+ return
216
+
217
+ if not self._awaitable_cursor_close:
218
+ self._cursor.close() # type: ignore[unused-coroutine]
219
+ elif in_greenlet():
220
+ self.await_(self._cursor.close())
221
+
222
+ def execute(
223
+ self,
224
+ operation: Any,
225
+ parameters: Optional[_DBAPISingleExecuteParams] = None,
226
+ ) -> Any:
227
+ try:
228
+ return self.await_(self._execute_async(operation, parameters))
229
+ except Exception as error:
230
+ self._adapt_connection._handle_exception(error)
231
+
232
+ def executemany(
233
+ self,
234
+ operation: Any,
235
+ seq_of_parameters: _DBAPIMultiExecuteParams,
236
+ ) -> Any:
237
+ try:
238
+ return self.await_(
239
+ self._executemany_async(operation, seq_of_parameters)
240
+ )
241
+ except Exception as error:
242
+ self._adapt_connection._handle_exception(error)
243
+
244
+ async def _execute_async(
245
+ self, operation: Any, parameters: Optional[_DBAPISingleExecuteParams]
246
+ ) -> Any:
247
+ async with self._adapt_connection._execute_mutex:
248
+ if parameters is None:
249
+ result = await self._cursor.execute(operation)
250
+ else:
251
+ result = await self._cursor.execute(operation, parameters)
252
+
253
+ if self._cursor.description and not self.server_side:
254
+ self._rows = collections.deque(await self._cursor.fetchall())
255
+ return result
256
+
257
+ async def _executemany_async(
258
+ self,
259
+ operation: Any,
260
+ seq_of_parameters: _DBAPIMultiExecuteParams,
261
+ ) -> Any:
262
+ async with self._adapt_connection._execute_mutex:
263
+ return await self._cursor.executemany(operation, seq_of_parameters)
264
+
265
+ def nextset(self) -> None:
266
+ self.await_(self._cursor.nextset())
267
+ if self._cursor.description and not self.server_side:
268
+ self._rows = collections.deque(
269
+ self.await_(self._cursor.fetchall())
270
+ )
271
+
272
+ def setinputsizes(self, *inputsizes: Any) -> None:
273
+ # NOTE: this is overridden in aioodbc due to
274
+ # see https://github.com/aio-libs/aioodbc/issues/451
275
+ # right now
276
+
277
+ return self.await_(self._cursor.setinputsizes(*inputsizes))
278
+
279
+ def __enter__(self) -> Self:
280
+ return self
281
+
282
+ def __exit__(self, type_: Any, value: Any, traceback: Any) -> None:
283
+ self.close()
284
+
285
+ def __iter__(self) -> Iterator[Any]:
286
+ while self._rows:
287
+ yield self._rows.popleft()
288
+
289
+ def fetchone(self) -> Optional[Any]:
290
+ if self._rows:
291
+ return self._rows.popleft()
292
+ else:
293
+ return None
294
+
295
+ def fetchmany(self, size: Optional[int] = None) -> Sequence[Any]:
296
+ if size is None:
297
+ size = self.arraysize
298
+ rr = self._rows
299
+ return [rr.popleft() for _ in range(min(size, len(rr)))]
300
+
301
+ def fetchall(self) -> Sequence[Any]:
302
+ retval = list(self._rows)
303
+ self._rows.clear()
304
+ return retval
305
+
306
+
307
+ class AsyncAdapt_dbapi_ss_cursor(AsyncAdapt_dbapi_cursor):
308
+ __slots__ = ()
309
+ server_side = True
310
+
311
+ def close(self) -> None:
312
+ if self._cursor is not None:
313
+ self.await_(self._cursor.close())
314
+ self._cursor = None # type: ignore
315
+
316
+ def fetchone(self) -> Optional[Any]:
317
+ return self.await_(self._cursor.fetchone())
318
+
319
+ def fetchmany(self, size: Optional[int] = None) -> Any:
320
+ return self.await_(self._cursor.fetchmany(size=size))
321
+
322
+ def fetchall(self) -> Sequence[Any]:
323
+ return self.await_(self._cursor.fetchall())
324
+
325
+ def __iter__(self) -> Iterator[Any]:
326
+ iterator = self._cursor.__aiter__()
327
+ while True:
328
+ try:
329
+ yield self.await_(iterator.__anext__())
330
+ except StopAsyncIteration:
331
+ break
332
+
333
+
334
+ class AsyncAdapt_dbapi_connection(AdaptedConnection):
335
+ _cursor_cls = AsyncAdapt_dbapi_cursor
336
+ _ss_cursor_cls = AsyncAdapt_dbapi_ss_cursor
337
+
338
+ await_ = staticmethod(await_only)
339
+
340
+ __slots__ = ("dbapi", "_execute_mutex")
341
+
342
+ _connection: AsyncIODBAPIConnection
343
+
344
+ def __init__(self, dbapi: Any, connection: AsyncIODBAPIConnection):
345
+ self.dbapi = dbapi
346
+ self._connection = connection
347
+ self._execute_mutex = asyncio.Lock()
348
+
349
+ def cursor(self, server_side: bool = False) -> AsyncAdapt_dbapi_cursor:
350
+ if server_side:
351
+ return self._ss_cursor_cls(self)
352
+ else:
353
+ return self._cursor_cls(self)
354
+
355
+ def execute(
356
+ self,
357
+ operation: Any,
358
+ parameters: Optional[_DBAPISingleExecuteParams] = None,
359
+ ) -> Any:
360
+ """lots of DBAPIs seem to provide this, so include it"""
361
+ cursor = self.cursor()
362
+ cursor.execute(operation, parameters)
363
+ return cursor
364
+
365
+ def _handle_exception(self, error: Exception) -> NoReturn:
366
+ exc_info = sys.exc_info()
367
+
368
+ raise error.with_traceback(exc_info[2])
369
+
370
+ def rollback(self) -> None:
371
+ try:
372
+ self.await_(self._connection.rollback())
373
+ except Exception as error:
374
+ self._handle_exception(error)
375
+
376
+ def commit(self) -> None:
377
+ try:
378
+ self.await_(self._connection.commit())
379
+ except Exception as error:
380
+ self._handle_exception(error)
381
+
382
+ def close(self) -> None:
383
+ self.await_(self._connection.close())
384
+
385
+
386
+ class AsyncAdaptFallback_dbapi_connection(AsyncAdapt_dbapi_connection):
387
+ __slots__ = ()
388
+
389
+ await_ = staticmethod(await_fallback)
390
+
391
+
392
+ class AsyncAdapt_terminate:
393
+ """Mixin for a AsyncAdapt_dbapi_connection to add terminate support."""
394
+
395
+ __slots__ = ()
396
+
397
+ def terminate(self) -> None:
398
+ if in_greenlet():
399
+ # in a greenlet; this is the connection was invalidated case.
400
+ try:
401
+ # try to gracefully close; see #10717
402
+ self.await_(asyncio.shield(self._terminate_graceful_close())) # type: ignore[attr-defined] # noqa: E501
403
+ except self._terminate_handled_exceptions() as e:
404
+ # in the case where we are recycling an old connection
405
+ # that may have already been disconnected, close() will
406
+ # fail. In this case, terminate
407
+ # the connection without any further waiting.
408
+ # see issue #8419
409
+ self._terminate_force_close()
410
+ if isinstance(e, asyncio.CancelledError):
411
+ # re-raise CancelledError if we were cancelled
412
+ raise
413
+ else:
414
+ # not in a greenlet; this is the gc cleanup case
415
+ self._terminate_force_close()
416
+
417
+ def _terminate_handled_exceptions(self) -> Tuple[Type[BaseException], ...]:
418
+ """Returns the exceptions that should be handled when
419
+ calling _graceful_close.
420
+ """
421
+ return (asyncio.TimeoutError, asyncio.CancelledError, OSError)
422
+
423
+ async def _terminate_graceful_close(self) -> None:
424
+ """Try to close connection gracefully"""
425
+ raise NotImplementedError
426
+
427
+ def _terminate_force_close(self) -> None:
428
+ """Terminate the connection"""
429
+ raise NotImplementedError
loan-advisor-agent/.venv/Lib/site-packages/sqlalchemy/connectors/pyodbc.py ADDED
@@ -0,0 +1,250 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # connectors/pyodbc.py
2
+ # Copyright (C) 2005-2026 the SQLAlchemy authors and contributors
3
+ # <see AUTHORS file>
4
+ #
5
+ # This module is part of SQLAlchemy and is released under
6
+ # the MIT License: https://www.opensource.org/licenses/mit-license.php
7
+
8
+ from __future__ import annotations
9
+
10
+ import re
11
+ import typing
12
+ from typing import Any
13
+ from typing import Dict
14
+ from typing import List
15
+ from typing import Optional
16
+ from typing import Tuple
17
+ from typing import Union
18
+ from urllib.parse import unquote_plus
19
+
20
+ from . import Connector
21
+ from .. import ExecutionContext
22
+ from .. import pool
23
+ from .. import util
24
+ from ..engine import ConnectArgsType
25
+ from ..engine import Connection
26
+ from ..engine import interfaces
27
+ from ..engine import URL
28
+ from ..sql.type_api import TypeEngine
29
+
30
+ if typing.TYPE_CHECKING:
31
+ from ..engine.interfaces import DBAPIModule
32
+ from ..engine.interfaces import IsolationLevel
33
+
34
+
35
+ class PyODBCConnector(Connector):
36
+ driver = "pyodbc"
37
+
38
+ # this is no longer False for pyodbc in general
39
+ supports_sane_rowcount_returning = True
40
+ supports_sane_multi_rowcount = False
41
+
42
+ supports_native_decimal = True
43
+ default_paramstyle = "named"
44
+
45
+ fast_executemany = False
46
+
47
+ # for non-DSN connections, this *may* be used to
48
+ # hold the desired driver name
49
+ pyodbc_driver_name: Optional[str] = None
50
+
51
+ def __init__(self, use_setinputsizes: bool = False, **kw: Any):
52
+ super().__init__(**kw)
53
+ if use_setinputsizes:
54
+ self.bind_typing = interfaces.BindTyping.SETINPUTSIZES
55
+
56
+ @classmethod
57
+ def import_dbapi(cls) -> DBAPIModule:
58
+ return __import__("pyodbc")
59
+
60
+ def create_connect_args(self, url: URL) -> ConnectArgsType:
61
+ opts = url.translate_connect_args(username="user")
62
+ opts.update(url.query)
63
+
64
+ keys = opts
65
+
66
+ query = url.query
67
+
68
+ connect_args: Dict[str, Any] = {}
69
+ connectors: List[str]
70
+
71
+ for param in ("ansi", "unicode_results", "autocommit"):
72
+ if param in keys:
73
+ connect_args[param] = util.asbool(keys.pop(param))
74
+
75
+ if "odbc_connect" in keys:
76
+ connectors = [unquote_plus(keys.pop("odbc_connect"))]
77
+ else:
78
+
79
+ def check_quote(token: str) -> str:
80
+ if ";" in str(token) or str(token).startswith("{"):
81
+ token = "{%s}" % token.replace("}", "}}")
82
+ return token
83
+
84
+ keys = {k: check_quote(v) for k, v in keys.items()}
85
+
86
+ dsn_connection = "dsn" in keys or (
87
+ "host" in keys and "database" not in keys
88
+ )
89
+ if dsn_connection:
90
+ connectors = [
91
+ "dsn=%s" % (keys.pop("host", "") or keys.pop("dsn", ""))
92
+ ]
93
+ else:
94
+ port = ""
95
+ if "port" in keys and "port" not in query:
96
+ port = ",%d" % int(keys.pop("port"))
97
+
98
+ connectors = []
99
+ driver = keys.pop("driver", self.pyodbc_driver_name)
100
+ if driver is None and keys:
101
+ # note if keys is empty, this is a totally blank URL
102
+ util.warn(
103
+ "No driver name specified; "
104
+ "this is expected by PyODBC when using "
105
+ "DSN-less connections"
106
+ )
107
+ else:
108
+ connectors.append("DRIVER={%s}" % driver)
109
+
110
+ connectors.extend(
111
+ [
112
+ "Server=%s%s" % (keys.pop("host", ""), port),
113
+ "Database=%s" % keys.pop("database", ""),
114
+ ]
115
+ )
116
+
117
+ user = keys.pop("user", None)
118
+ if user:
119
+ connectors.append("UID=%s" % user)
120
+ pwd = keys.pop("password", "")
121
+ if pwd:
122
+ connectors.append("PWD=%s" % pwd)
123
+ else:
124
+ authentication = keys.pop("authentication", None)
125
+ if authentication:
126
+ connectors.append("Authentication=%s" % authentication)
127
+ else:
128
+ connectors.append("Trusted_Connection=Yes")
129
+
130
+ # if set to 'Yes', the ODBC layer will try to automagically
131
+ # convert textual data from your database encoding to your
132
+ # client encoding. This should obviously be set to 'No' if
133
+ # you query a cp1253 encoded database from a latin1 client...
134
+ if "odbc_autotranslate" in keys:
135
+ connectors.append(
136
+ "AutoTranslate=%s" % keys.pop("odbc_autotranslate")
137
+ )
138
+
139
+ connectors.extend(["%s=%s" % (k, v) for k, v in keys.items()])
140
+
141
+ return ((";".join(connectors),), connect_args)
142
+
143
+ def is_disconnect(
144
+ self,
145
+ e: Exception,
146
+ connection: Optional[
147
+ Union[pool.PoolProxiedConnection, interfaces.DBAPIConnection]
148
+ ],
149
+ cursor: Optional[interfaces.DBAPICursor],
150
+ ) -> bool:
151
+ if isinstance(e, self.loaded_dbapi.ProgrammingError):
152
+ return "The cursor's connection has been closed." in str(
153
+ e
154
+ ) or "Attempt to use a closed connection." in str(e)
155
+ else:
156
+ return False
157
+
158
+ def _dbapi_version(self) -> interfaces.VersionInfoType:
159
+ if not self.dbapi:
160
+ return ()
161
+ return self._parse_dbapi_version(self.dbapi.version)
162
+
163
+ def _parse_dbapi_version(self, vers: str) -> interfaces.VersionInfoType:
164
+ m = re.match(r"(?:py.*-)?([\d\.]+)(?:-(\w+))?", vers)
165
+ if not m:
166
+ return ()
167
+ vers_tuple: interfaces.VersionInfoType = tuple(
168
+ [int(x) for x in m.group(1).split(".")]
169
+ )
170
+ if m.group(2):
171
+ vers_tuple += (m.group(2),)
172
+ return vers_tuple
173
+
174
+ def _get_server_version_info(
175
+ self, connection: Connection
176
+ ) -> interfaces.VersionInfoType:
177
+ # NOTE: this function is not reliable, particularly when
178
+ # freetds is in use. Implement database-specific server version
179
+ # queries.
180
+ dbapi_con = connection.connection.dbapi_connection
181
+ version: Tuple[Union[int, str], ...] = ()
182
+ r = re.compile(r"[.\-]")
183
+ for n in r.split(dbapi_con.getinfo(self.dbapi.SQL_DBMS_VER)): # type: ignore[union-attr] # noqa: E501
184
+ try:
185
+ version += (int(n),)
186
+ except ValueError:
187
+ pass
188
+ return tuple(version)
189
+
190
+ def do_set_input_sizes(
191
+ self,
192
+ cursor: interfaces.DBAPICursor,
193
+ list_of_tuples: List[Tuple[str, Any, TypeEngine[Any]]],
194
+ context: ExecutionContext,
195
+ ) -> None:
196
+ # the rules for these types seems a little strange, as you can pass
197
+ # non-tuples as well as tuples, however it seems to assume "0"
198
+ # for the subsequent values if you don't pass a tuple which fails
199
+ # for types such as pyodbc.SQL_WLONGVARCHAR, which is the datatype
200
+ # that ticket #5649 is targeting.
201
+
202
+ # NOTE: as of #6058, this won't be called if the use_setinputsizes
203
+ # parameter were not passed to the dialect, or if no types were
204
+ # specified in list_of_tuples
205
+
206
+ # as of #8177 for 2.0 we assume use_setinputsizes=True and only
207
+ # omit the setinputsizes calls for .executemany() with
208
+ # fast_executemany=True
209
+
210
+ if (
211
+ context.execute_style is interfaces.ExecuteStyle.EXECUTEMANY
212
+ and self.fast_executemany
213
+ ):
214
+ return
215
+
216
+ cursor.setinputsizes(
217
+ [
218
+ (
219
+ (dbtype, None, None)
220
+ if not isinstance(dbtype, tuple)
221
+ else dbtype
222
+ )
223
+ for key, dbtype, sqltype in list_of_tuples
224
+ ]
225
+ )
226
+
227
+ def get_isolation_level_values(
228
+ self, dbapi_conn: interfaces.DBAPIConnection
229
+ ) -> List[IsolationLevel]:
230
+ return [*super().get_isolation_level_values(dbapi_conn), "AUTOCOMMIT"]
231
+
232
+ def set_isolation_level(
233
+ self,
234
+ dbapi_connection: interfaces.DBAPIConnection,
235
+ level: IsolationLevel,
236
+ ) -> None:
237
+ # adjust for ConnectionFairy being present
238
+ # allows attribute set e.g. "connection.autocommit = True"
239
+ # to work properly
240
+
241
+ if level == "AUTOCOMMIT":
242
+ dbapi_connection.autocommit = True
243
+ else:
244
+ dbapi_connection.autocommit = False
245
+ super().set_isolation_level(dbapi_connection, level)
246
+
247
+ def detect_autocommit_setting(
248
+ self, dbapi_conn: interfaces.DBAPIConnection
249
+ ) -> bool:
250
+ return bool(dbapi_conn.autocommit)
loan-advisor-agent/.venv/Lib/site-packages/sqlalchemy/cyextension/__init__.py ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ # cyextension/__init__.py
2
+ # Copyright (C) 2005-2026 the SQLAlchemy authors and contributors
3
+ # <see AUTHORS file>
4
+ #
5
+ # This module is part of SQLAlchemy and is released under
6
+ # the MIT License: https://www.opensource.org/licenses/mit-license.php
loan-advisor-agent/.venv/Lib/site-packages/sqlalchemy/cyextension/collections.cp312-win_amd64.pyd ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:bce60068089dc32513c8cebbf6ec12f272cf4802cf346587d250f77df0f9c1bf
3
+ size 163840
loan-advisor-agent/.venv/Lib/site-packages/sqlalchemy/cyextension/collections.pyx ADDED
@@ -0,0 +1,409 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # cyextension/collections.pyx
2
+ # Copyright (C) 2005-2024 the SQLAlchemy authors and contributors
3
+ # <see AUTHORS file>
4
+ #
5
+ # This module is part of SQLAlchemy and is released under
6
+ # the MIT License: https://www.opensource.org/licenses/mit-license.php
7
+ cimport cython
8
+ from cpython.long cimport PyLong_FromLongLong
9
+ from cpython.set cimport PySet_Add
10
+
11
+ from collections.abc import Collection
12
+ from itertools import filterfalse
13
+
14
+ cdef bint add_not_present(set seen, object item, hashfunc):
15
+ hash_value = hashfunc(item)
16
+ if hash_value not in seen:
17
+ PySet_Add(seen, hash_value)
18
+ return True
19
+ else:
20
+ return False
21
+
22
+ cdef list cunique_list(seq, hashfunc=None):
23
+ cdef set seen = set()
24
+ if not hashfunc:
25
+ return [x for x in seq if x not in seen and not PySet_Add(seen, x)]
26
+ else:
27
+ return [x for x in seq if add_not_present(seen, x, hashfunc)]
28
+
29
+ def unique_list(seq, hashfunc=None):
30
+ return cunique_list(seq, hashfunc)
31
+
32
+ cdef class OrderedSet(set):
33
+
34
+ cdef list _list
35
+
36
+ @classmethod
37
+ def __class_getitem__(cls, key):
38
+ return cls
39
+
40
+ def __init__(self, d=None):
41
+ set.__init__(self)
42
+ if d is not None:
43
+ self._list = cunique_list(d)
44
+ set.update(self, self._list)
45
+ else:
46
+ self._list = []
47
+
48
+ cpdef OrderedSet copy(self):
49
+ cdef OrderedSet cp = OrderedSet.__new__(OrderedSet)
50
+ cp._list = list(self._list)
51
+ set.update(cp, cp._list)
52
+ return cp
53
+
54
+ @cython.final
55
+ cdef OrderedSet _from_list(self, list new_list):
56
+ cdef OrderedSet new = OrderedSet.__new__(OrderedSet)
57
+ new._list = new_list
58
+ set.update(new, new_list)
59
+ return new
60
+
61
+ def add(self, element):
62
+ if element not in self:
63
+ self._list.append(element)
64
+ PySet_Add(self, element)
65
+
66
+ def remove(self, element):
67
+ # set.remove will raise if element is not in self
68
+ set.remove(self, element)
69
+ self._list.remove(element)
70
+
71
+ def pop(self):
72
+ try:
73
+ value = self._list.pop()
74
+ except IndexError:
75
+ raise KeyError("pop from an empty set") from None
76
+ set.remove(self, value)
77
+ return value
78
+
79
+ def insert(self, Py_ssize_t pos, element):
80
+ if element not in self:
81
+ self._list.insert(pos, element)
82
+ PySet_Add(self, element)
83
+
84
+ def discard(self, element):
85
+ if element in self:
86
+ set.remove(self, element)
87
+ self._list.remove(element)
88
+
89
+ def clear(self):
90
+ set.clear(self)
91
+ self._list = []
92
+
93
+ def __getitem__(self, key):
94
+ return self._list[key]
95
+
96
+ def __iter__(self):
97
+ return iter(self._list)
98
+
99
+ def __add__(self, other):
100
+ return self.union(other)
101
+
102
+ def __repr__(self):
103
+ return "%s(%r)" % (self.__class__.__name__, self._list)
104
+
105
+ __str__ = __repr__
106
+
107
+ def update(self, *iterables):
108
+ for iterable in iterables:
109
+ for e in iterable:
110
+ if e not in self:
111
+ self._list.append(e)
112
+ set.add(self, e)
113
+
114
+ def __ior__(self, iterable):
115
+ self.update(iterable)
116
+ return self
117
+
118
+ def union(self, *other):
119
+ result = self.copy()
120
+ result.update(*other)
121
+ return result
122
+
123
+ def __or__(self, other):
124
+ return self.union(other)
125
+
126
+ def intersection(self, *other):
127
+ cdef set other_set = set.intersection(self, *other)
128
+ return self._from_list([a for a in self._list if a in other_set])
129
+
130
+ def __and__(self, other):
131
+ return self.intersection(other)
132
+
133
+ def symmetric_difference(self, other):
134
+ cdef set other_set
135
+ if isinstance(other, set):
136
+ other_set = <set> other
137
+ collection = other_set
138
+ elif isinstance(other, Collection):
139
+ collection = other
140
+ other_set = set(other)
141
+ else:
142
+ collection = list(other)
143
+ other_set = set(collection)
144
+ result = self._from_list([a for a in self._list if a not in other_set])
145
+ result.update(a for a in collection if a not in self)
146
+ return result
147
+
148
+ def __xor__(self, other):
149
+ return self.symmetric_difference(other)
150
+
151
+ def difference(self, *other):
152
+ cdef set other_set = set.difference(self, *other)
153
+ return self._from_list([a for a in self._list if a in other_set])
154
+
155
+ def __sub__(self, other):
156
+ return self.difference(other)
157
+
158
+ def intersection_update(self, *other):
159
+ set.intersection_update(self, *other)
160
+ self._list = [a for a in self._list if a in self]
161
+
162
+ def __iand__(self, other):
163
+ self.intersection_update(other)
164
+ return self
165
+
166
+ cpdef symmetric_difference_update(self, other):
167
+ collection = other if isinstance(other, Collection) else list(other)
168
+ set.symmetric_difference_update(self, collection)
169
+ self._list = [a for a in self._list if a in self]
170
+ self._list += [a for a in collection if a in self]
171
+
172
+ def __ixor__(self, other):
173
+ self.symmetric_difference_update(other)
174
+ return self
175
+
176
+ def difference_update(self, *other):
177
+ set.difference_update(self, *other)
178
+ self._list = [a for a in self._list if a in self]
179
+
180
+ def __isub__(self, other):
181
+ self.difference_update(other)
182
+ return self
183
+
184
+ cdef object cy_id(object item):
185
+ return PyLong_FromLongLong(<long long> (<void *>item))
186
+
187
+ # NOTE: cython 0.x will call __add__, __sub__, etc with the parameter swapped
188
+ # instead of the __rmeth__, so they need to check that also self is of the
189
+ # correct type. This is fixed in cython 3.x. See:
190
+ # https://docs.cython.org/en/latest/src/userguide/special_methods.html#arithmetic-methods
191
+ cdef class IdentitySet:
192
+ """A set that considers only object id() for uniqueness.
193
+
194
+ This strategy has edge cases for builtin types- it's possible to have
195
+ two 'foo' strings in one of these sets, for example. Use sparingly.
196
+
197
+ """
198
+
199
+ cdef dict _members
200
+
201
+ def __init__(self, iterable=None):
202
+ self._members = {}
203
+ if iterable:
204
+ self.update(iterable)
205
+
206
+ def add(self, value):
207
+ self._members[cy_id(value)] = value
208
+
209
+ def __contains__(self, value):
210
+ return cy_id(value) in self._members
211
+
212
+ cpdef remove(self, value):
213
+ del self._members[cy_id(value)]
214
+
215
+ def discard(self, value):
216
+ try:
217
+ self.remove(value)
218
+ except KeyError:
219
+ pass
220
+
221
+ def pop(self):
222
+ cdef tuple pair
223
+ try:
224
+ pair = self._members.popitem()
225
+ return pair[1]
226
+ except KeyError:
227
+ raise KeyError("pop from an empty set")
228
+
229
+ def clear(self):
230
+ self._members.clear()
231
+
232
+ def __eq__(self, other):
233
+ cdef IdentitySet other_
234
+ if isinstance(other, IdentitySet):
235
+ other_ = other
236
+ return self._members == other_._members
237
+ else:
238
+ return False
239
+
240
+ def __ne__(self, other):
241
+ cdef IdentitySet other_
242
+ if isinstance(other, IdentitySet):
243
+ other_ = other
244
+ return self._members != other_._members
245
+ else:
246
+ return True
247
+
248
+ cpdef issubset(self, iterable):
249
+ cdef IdentitySet other
250
+ if isinstance(iterable, self.__class__):
251
+ other = iterable
252
+ else:
253
+ other = self.__class__(iterable)
254
+
255
+ if len(self) > len(other):
256
+ return False
257
+ for m in filterfalse(other._members.__contains__, self._members):
258
+ return False
259
+ return True
260
+
261
+ def __le__(self, other):
262
+ if not isinstance(other, IdentitySet):
263
+ return NotImplemented
264
+ return self.issubset(other)
265
+
266
+ def __lt__(self, other):
267
+ if not isinstance(other, IdentitySet):
268
+ return NotImplemented
269
+ return len(self) < len(other) and self.issubset(other)
270
+
271
+ cpdef issuperset(self, iterable):
272
+ cdef IdentitySet other
273
+ if isinstance(iterable, self.__class__):
274
+ other = iterable
275
+ else:
276
+ other = self.__class__(iterable)
277
+
278
+ if len(self) < len(other):
279
+ return False
280
+ for m in filterfalse(self._members.__contains__, other._members):
281
+ return False
282
+ return True
283
+
284
+ def __ge__(self, other):
285
+ if not isinstance(other, IdentitySet):
286
+ return NotImplemented
287
+ return self.issuperset(other)
288
+
289
+ def __gt__(self, other):
290
+ if not isinstance(other, IdentitySet):
291
+ return NotImplemented
292
+ return len(self) > len(other) and self.issuperset(other)
293
+
294
+ cpdef IdentitySet union(self, iterable):
295
+ cdef IdentitySet result = self.__class__()
296
+ result._members.update(self._members)
297
+ result.update(iterable)
298
+ return result
299
+
300
+ def __or__(self, other):
301
+ if not isinstance(other, IdentitySet) or not isinstance(self, IdentitySet):
302
+ return NotImplemented
303
+ return self.union(other)
304
+
305
+ cpdef update(self, iterable):
306
+ for obj in iterable:
307
+ self._members[cy_id(obj)] = obj
308
+
309
+ def __ior__(self, other):
310
+ if not isinstance(other, IdentitySet):
311
+ return NotImplemented
312
+ self.update(other)
313
+ return self
314
+
315
+ cpdef IdentitySet difference(self, iterable):
316
+ cdef IdentitySet result = self.__new__(self.__class__)
317
+ if isinstance(iterable, self.__class__):
318
+ other = (<IdentitySet>iterable)._members
319
+ else:
320
+ other = {cy_id(obj) for obj in iterable}
321
+ result._members = {k:v for k, v in self._members.items() if k not in other}
322
+ return result
323
+
324
+ def __sub__(self, other):
325
+ if not isinstance(other, IdentitySet) or not isinstance(self, IdentitySet):
326
+ return NotImplemented
327
+ return self.difference(other)
328
+
329
+ cpdef difference_update(self, iterable):
330
+ cdef IdentitySet other = self.difference(iterable)
331
+ self._members = other._members
332
+
333
+ def __isub__(self, other):
334
+ if not isinstance(other, IdentitySet):
335
+ return NotImplemented
336
+ self.difference_update(other)
337
+ return self
338
+
339
+ cpdef IdentitySet intersection(self, iterable):
340
+ cdef IdentitySet result = self.__new__(self.__class__)
341
+ if isinstance(iterable, self.__class__):
342
+ other = (<IdentitySet>iterable)._members
343
+ else:
344
+ other = {cy_id(obj) for obj in iterable}
345
+ result._members = {k: v for k, v in self._members.items() if k in other}
346
+ return result
347
+
348
+ def __and__(self, other):
349
+ if not isinstance(other, IdentitySet) or not isinstance(self, IdentitySet):
350
+ return NotImplemented
351
+ return self.intersection(other)
352
+
353
+ cpdef intersection_update(self, iterable):
354
+ cdef IdentitySet other = self.intersection(iterable)
355
+ self._members = other._members
356
+
357
+ def __iand__(self, other):
358
+ if not isinstance(other, IdentitySet):
359
+ return NotImplemented
360
+ self.intersection_update(other)
361
+ return self
362
+
363
+ cpdef IdentitySet symmetric_difference(self, iterable):
364
+ cdef IdentitySet result = self.__new__(self.__class__)
365
+ cdef dict other
366
+ if isinstance(iterable, self.__class__):
367
+ other = (<IdentitySet>iterable)._members
368
+ else:
369
+ other = {cy_id(obj): obj for obj in iterable}
370
+ result._members = {k: v for k, v in self._members.items() if k not in other}
371
+ result._members.update(
372
+ [(k, v) for k, v in other.items() if k not in self._members]
373
+ )
374
+ return result
375
+
376
+ def __xor__(self, other):
377
+ if not isinstance(other, IdentitySet) or not isinstance(self, IdentitySet):
378
+ return NotImplemented
379
+ return self.symmetric_difference(other)
380
+
381
+ cpdef symmetric_difference_update(self, iterable):
382
+ cdef IdentitySet other = self.symmetric_difference(iterable)
383
+ self._members = other._members
384
+
385
+ def __ixor__(self, other):
386
+ if not isinstance(other, IdentitySet):
387
+ return NotImplemented
388
+ self.symmetric_difference(other)
389
+ return self
390
+
391
+ cpdef IdentitySet copy(self):
392
+ cdef IdentitySet cp = self.__new__(self.__class__)
393
+ cp._members = self._members.copy()
394
+ return cp
395
+
396
+ def __copy__(self):
397
+ return self.copy()
398
+
399
+ def __len__(self):
400
+ return len(self._members)
401
+
402
+ def __iter__(self):
403
+ return iter(self._members.values())
404
+
405
+ def __hash__(self):
406
+ raise TypeError("set objects are unhashable")
407
+
408
+ def __repr__(self):
409
+ return "%s(%r)" % (type(self).__name__, list(self._members.values()))
loan-advisor-agent/.venv/Lib/site-packages/sqlalchemy/cyextension/immutabledict.cp312-win_amd64.pyd ADDED
Binary file (68.6 kB). View file
 
loan-advisor-agent/.venv/Lib/site-packages/sqlalchemy/cyextension/immutabledict.pxd ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ # cyextension/immutabledict.pxd
2
+ # Copyright (C) 2005-2024 the SQLAlchemy authors and contributors
3
+ # <see AUTHORS file>
4
+ #
5
+ # This module is part of SQLAlchemy and is released under
6
+ # the MIT License: https://www.opensource.org/licenses/mit-license.php
7
+ cdef class immutabledict(dict):
8
+ pass
loan-advisor-agent/.venv/Lib/site-packages/sqlalchemy/cyextension/immutabledict.pyx ADDED
@@ -0,0 +1,133 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # cyextension/immutabledict.pyx
2
+ # Copyright (C) 2005-2024 the SQLAlchemy authors and contributors
3
+ # <see AUTHORS file>
4
+ #
5
+ # This module is part of SQLAlchemy and is released under
6
+ # the MIT License: https://www.opensource.org/licenses/mit-license.php
7
+ from cpython.dict cimport PyDict_New, PyDict_Update, PyDict_Size
8
+
9
+
10
+ def _readonly_fn(obj):
11
+ raise TypeError(
12
+ "%s object is immutable and/or readonly" % obj.__class__.__name__)
13
+
14
+
15
+ def _immutable_fn(obj):
16
+ raise TypeError(
17
+ "%s object is immutable" % obj.__class__.__name__)
18
+
19
+
20
+ class ReadOnlyContainer:
21
+
22
+ __slots__ = ()
23
+
24
+ def _readonly(self, *a,**kw):
25
+ _readonly_fn(self)
26
+
27
+ __delitem__ = __setitem__ = __setattr__ = _readonly
28
+
29
+
30
+ class ImmutableDictBase(dict):
31
+ def _immutable(self, *a,**kw):
32
+ _immutable_fn(self)
33
+
34
+ @classmethod
35
+ def __class_getitem__(cls, key):
36
+ return cls
37
+
38
+ __delitem__ = __setitem__ = __setattr__ = _immutable
39
+ clear = pop = popitem = setdefault = update = _immutable
40
+
41
+
42
+ cdef class immutabledict(dict):
43
+ def __repr__(self):
44
+ return f"immutabledict({dict.__repr__(self)})"
45
+
46
+ @classmethod
47
+ def __class_getitem__(cls, key):
48
+ return cls
49
+
50
+ def union(self, *args, **kw):
51
+ cdef dict to_merge = None
52
+ cdef immutabledict result
53
+ cdef Py_ssize_t args_len = len(args)
54
+ if args_len > 1:
55
+ raise TypeError(
56
+ f'union expected at most 1 argument, got {args_len}'
57
+ )
58
+ if args_len == 1:
59
+ attribute = args[0]
60
+ if isinstance(attribute, dict):
61
+ to_merge = <dict> attribute
62
+ if to_merge is None:
63
+ to_merge = dict(*args, **kw)
64
+
65
+ if PyDict_Size(to_merge) == 0:
66
+ return self
67
+
68
+ # new + update is faster than immutabledict(self)
69
+ result = immutabledict()
70
+ PyDict_Update(result, self)
71
+ PyDict_Update(result, to_merge)
72
+ return result
73
+
74
+ def merge_with(self, *other):
75
+ cdef immutabledict result = None
76
+ cdef object d
77
+ cdef bint update = False
78
+ if not other:
79
+ return self
80
+ for d in other:
81
+ if d:
82
+ if update == False:
83
+ update = True
84
+ # new + update is faster than immutabledict(self)
85
+ result = immutabledict()
86
+ PyDict_Update(result, self)
87
+ PyDict_Update(
88
+ result, <dict>(d if isinstance(d, dict) else dict(d))
89
+ )
90
+
91
+ return self if update == False else result
92
+
93
+ def copy(self):
94
+ return self
95
+
96
+ def __reduce__(self):
97
+ return immutabledict, (dict(self), )
98
+
99
+ def __delitem__(self, k):
100
+ _immutable_fn(self)
101
+
102
+ def __setitem__(self, k, v):
103
+ _immutable_fn(self)
104
+
105
+ def __setattr__(self, k, v):
106
+ _immutable_fn(self)
107
+
108
+ def clear(self, *args, **kw):
109
+ _immutable_fn(self)
110
+
111
+ def pop(self, *args, **kw):
112
+ _immutable_fn(self)
113
+
114
+ def popitem(self, *args, **kw):
115
+ _immutable_fn(self)
116
+
117
+ def setdefault(self, *args, **kw):
118
+ _immutable_fn(self)
119
+
120
+ def update(self, *args, **kw):
121
+ _immutable_fn(self)
122
+
123
+ # PEP 584
124
+ def __ior__(self, other):
125
+ _immutable_fn(self)
126
+
127
+ def __or__(self, other):
128
+ return immutabledict(dict.__or__(self, other))
129
+
130
+ def __ror__(self, other):
131
+ # NOTE: this is used only in cython 3.x;
132
+ # version 0.x will call __or__ with args inversed
133
+ return immutabledict(dict.__ror__(self, other))
loan-advisor-agent/.venv/Lib/site-packages/sqlalchemy/cyextension/processors.cp312-win_amd64.pyd ADDED
Binary file (58.9 kB). View file
 
loan-advisor-agent/.venv/Lib/site-packages/sqlalchemy/cyextension/processors.pyx ADDED
@@ -0,0 +1,68 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # cyextension/processors.pyx
2
+ # Copyright (C) 2005-2024 the SQLAlchemy authors and contributors
3
+ # <see AUTHORS file>
4
+ #
5
+ # This module is part of SQLAlchemy and is released under
6
+ # the MIT License: https://www.opensource.org/licenses/mit-license.php
7
+ import datetime
8
+ from datetime import datetime as datetime_cls
9
+ from datetime import time as time_cls
10
+ from datetime import date as date_cls
11
+ import re
12
+
13
+ from cpython.object cimport PyObject_Str
14
+ from cpython.unicode cimport PyUnicode_AsASCIIString, PyUnicode_Check, PyUnicode_Decode
15
+ from libc.stdio cimport sscanf
16
+
17
+
18
+ def int_to_boolean(value):
19
+ if value is None:
20
+ return None
21
+ return True if value else False
22
+
23
+ def to_str(value):
24
+ return PyObject_Str(value) if value is not None else None
25
+
26
+ def to_float(value):
27
+ return float(value) if value is not None else None
28
+
29
+ cdef inline bytes to_bytes(object value, str type_name):
30
+ try:
31
+ return PyUnicode_AsASCIIString(value)
32
+ except Exception as e:
33
+ raise ValueError(
34
+ f"Couldn't parse {type_name} string '{value!r}' "
35
+ "- value is not a string."
36
+ ) from e
37
+
38
+ def str_to_datetime(value):
39
+ if value is not None:
40
+ value = datetime_cls.fromisoformat(value)
41
+ return value
42
+
43
+ def str_to_time(value):
44
+ if value is not None:
45
+ value = time_cls.fromisoformat(value)
46
+ return value
47
+
48
+
49
+ def str_to_date(value):
50
+ if value is not None:
51
+ value = date_cls.fromisoformat(value)
52
+ return value
53
+
54
+
55
+
56
+ cdef class DecimalResultProcessor:
57
+ cdef object type_
58
+ cdef str format_
59
+
60
+ def __cinit__(self, type_, format_):
61
+ self.type_ = type_
62
+ self.format_ = format_
63
+
64
+ def process(self, object value):
65
+ if value is None:
66
+ return None
67
+ else:
68
+ return self.type_(self.format_ % value)
loan-advisor-agent/.venv/Lib/site-packages/sqlalchemy/cyextension/resultproxy.cp312-win_amd64.pyd ADDED
Binary file (59.4 kB). View file
 
loan-advisor-agent/.venv/Lib/site-packages/sqlalchemy/cyextension/resultproxy.pyx ADDED
@@ -0,0 +1,102 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # cyextension/resultproxy.pyx
2
+ # Copyright (C) 2005-2024 the SQLAlchemy authors and contributors
3
+ # <see AUTHORS file>
4
+ #
5
+ # This module is part of SQLAlchemy and is released under
6
+ # the MIT License: https://www.opensource.org/licenses/mit-license.php
7
+ import operator
8
+
9
+ cdef class BaseRow:
10
+ cdef readonly object _parent
11
+ cdef readonly dict _key_to_index
12
+ cdef readonly tuple _data
13
+
14
+ def __init__(self, object parent, object processors, dict key_to_index, object data):
15
+ """Row objects are constructed by CursorResult objects."""
16
+
17
+ self._parent = parent
18
+
19
+ self._key_to_index = key_to_index
20
+
21
+ if processors:
22
+ self._data = _apply_processors(processors, data)
23
+ else:
24
+ self._data = tuple(data)
25
+
26
+ def __reduce__(self):
27
+ return (
28
+ rowproxy_reconstructor,
29
+ (self.__class__, self.__getstate__()),
30
+ )
31
+
32
+ def __getstate__(self):
33
+ return {"_parent": self._parent, "_data": self._data}
34
+
35
+ def __setstate__(self, dict state):
36
+ parent = state["_parent"]
37
+ self._parent = parent
38
+ self._data = state["_data"]
39
+ self._key_to_index = parent._key_to_index
40
+
41
+ def _values_impl(self):
42
+ return list(self)
43
+
44
+ def __iter__(self):
45
+ return iter(self._data)
46
+
47
+ def __len__(self):
48
+ return len(self._data)
49
+
50
+ def __hash__(self):
51
+ return hash(self._data)
52
+
53
+ def __getitem__(self, index):
54
+ return self._data[index]
55
+
56
+ def _get_by_key_impl_mapping(self, key):
57
+ return self._get_by_key_impl(key, 0)
58
+
59
+ cdef _get_by_key_impl(self, object key, int attr_err):
60
+ index = self._key_to_index.get(key)
61
+ if index is not None:
62
+ return self._data[<int>index]
63
+ self._parent._key_not_found(key, attr_err != 0)
64
+
65
+ def __getattr__(self, name):
66
+ return self._get_by_key_impl(name, 1)
67
+
68
+ def _to_tuple_instance(self):
69
+ return self._data
70
+
71
+
72
+ cdef tuple _apply_processors(proc, data):
73
+ res = []
74
+ for i in range(len(proc)):
75
+ p = proc[i]
76
+ if p is None:
77
+ res.append(data[i])
78
+ else:
79
+ res.append(p(data[i]))
80
+ return tuple(res)
81
+
82
+
83
+ def rowproxy_reconstructor(cls, state):
84
+ obj = cls.__new__(cls)
85
+ obj.__setstate__(state)
86
+ return obj
87
+
88
+
89
+ cdef int is_contiguous(tuple indexes):
90
+ cdef int i
91
+ for i in range(1, len(indexes)):
92
+ if indexes[i-1] != indexes[i] -1:
93
+ return 0
94
+ return 1
95
+
96
+
97
+ def tuplegetter(*indexes):
98
+ if len(indexes) == 1 or is_contiguous(indexes) != 0:
99
+ # slice form is faster but returns a list if input is list
100
+ return operator.itemgetter(slice(indexes[0], indexes[-1] + 1))
101
+ else:
102
+ return operator.itemgetter(*indexes)
loan-advisor-agent/.venv/Lib/site-packages/sqlalchemy/cyextension/util.cp312-win_amd64.pyd ADDED
Binary file (70.7 kB). View file
 
loan-advisor-agent/.venv/Lib/site-packages/sqlalchemy/cyextension/util.pyx ADDED
@@ -0,0 +1,90 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # cyextension/util.pyx
2
+ # Copyright (C) 2005-2024 the SQLAlchemy authors and contributors
3
+ # <see AUTHORS file>
4
+ #
5
+ # This module is part of SQLAlchemy and is released under
6
+ # the MIT License: https://www.opensource.org/licenses/mit-license.php
7
+ from collections.abc import Mapping
8
+
9
+ from sqlalchemy import exc
10
+
11
+ cdef tuple _Empty_Tuple = ()
12
+
13
+ cdef inline bint _is_mapping_or_tuple(object value):
14
+ return isinstance(value, dict) or isinstance(value, tuple) or isinstance(value, Mapping)
15
+
16
+
17
+ cdef inline bint _is_mapping(object value):
18
+ return isinstance(value, dict) or isinstance(value, Mapping)
19
+
20
+
21
+ def _distill_params_20(object params):
22
+ if params is None:
23
+ return _Empty_Tuple
24
+ elif isinstance(params, list) or isinstance(params, tuple):
25
+ if params and not _is_mapping(params[0]):
26
+ raise exc.ArgumentError(
27
+ "List argument must consist only of dictionaries"
28
+ )
29
+ return params
30
+ elif _is_mapping(params):
31
+ return [params]
32
+ else:
33
+ raise exc.ArgumentError("mapping or list expected for parameters")
34
+
35
+
36
+ def _distill_raw_params(object params):
37
+ if params is None:
38
+ return _Empty_Tuple
39
+ elif isinstance(params, list):
40
+ if params and not _is_mapping_or_tuple(params[0]):
41
+ raise exc.ArgumentError(
42
+ "List argument must consist only of tuples or dictionaries"
43
+ )
44
+ return params
45
+ elif _is_mapping_or_tuple(params):
46
+ return [params]
47
+ else:
48
+ raise exc.ArgumentError("mapping or sequence expected for parameters")
49
+
50
+ cdef class prefix_anon_map(dict):
51
+ def __missing__(self, str key):
52
+ cdef str derived
53
+ cdef int anonymous_counter
54
+ cdef dict self_dict = self
55
+
56
+ derived = key.split(" ", 1)[1]
57
+
58
+ anonymous_counter = self_dict.get(derived, 1)
59
+ self_dict[derived] = anonymous_counter + 1
60
+ value = f"{derived}_{anonymous_counter}"
61
+ self_dict[key] = value
62
+ return value
63
+
64
+
65
+ cdef class cache_anon_map(dict):
66
+ cdef int _index
67
+
68
+ def __init__(self):
69
+ self._index = 0
70
+
71
+ def get_anon(self, obj):
72
+ cdef long long idself
73
+ cdef str id_
74
+ cdef dict self_dict = self
75
+
76
+ idself = id(obj)
77
+ if idself in self_dict:
78
+ return self_dict[idself], True
79
+ else:
80
+ id_ = self.__missing__(idself)
81
+ return id_, False
82
+
83
+ def __missing__(self, key):
84
+ cdef str val
85
+ cdef dict self_dict = self
86
+
87
+ self_dict[key] = val = str(self._index)
88
+ self._index += 1
89
+ return val
90
+
loan-advisor-agent/.venv/Lib/site-packages/sqlalchemy/dialects/__init__.py ADDED
@@ -0,0 +1,62 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # dialects/__init__.py
2
+ # Copyright (C) 2005-2026 the SQLAlchemy authors and contributors
3
+ # <see AUTHORS file>
4
+ #
5
+ # This module is part of SQLAlchemy and is released under
6
+ # the MIT License: https://www.opensource.org/licenses/mit-license.php
7
+
8
+ from __future__ import annotations
9
+
10
+ from typing import Any
11
+ from typing import Callable
12
+ from typing import Optional
13
+ from typing import Type
14
+ from typing import TYPE_CHECKING
15
+
16
+ from .. import util
17
+
18
+ if TYPE_CHECKING:
19
+ from ..engine.interfaces import Dialect
20
+
21
+ __all__ = ("mssql", "mysql", "oracle", "postgresql", "sqlite")
22
+
23
+
24
+ def _auto_fn(name: str) -> Optional[Callable[[], Type[Dialect]]]:
25
+ """default dialect importer.
26
+
27
+ plugs into the :class:`.PluginLoader`
28
+ as a first-hit system.
29
+
30
+ """
31
+ if "." in name:
32
+ dialect, driver = name.split(".")
33
+ else:
34
+ dialect = name
35
+ driver = "base"
36
+
37
+ try:
38
+ if dialect == "mariadb":
39
+ # it's "OK" for us to hardcode here since _auto_fn is already
40
+ # hardcoded. if mysql / mariadb etc were third party dialects
41
+ # they would just publish all the entrypoints, which would actually
42
+ # look much nicer.
43
+ module: Any = __import__(
44
+ "sqlalchemy.dialects.mysql.mariadb"
45
+ ).dialects.mysql.mariadb
46
+ return module.loader(driver) # type: ignore
47
+ else:
48
+ module = __import__("sqlalchemy.dialects.%s" % (dialect,)).dialects
49
+ module = getattr(module, dialect)
50
+ except ImportError:
51
+ return None
52
+
53
+ if hasattr(module, driver):
54
+ module = getattr(module, driver)
55
+ return lambda: module.dialect
56
+ else:
57
+ return None
58
+
59
+
60
+ registry = util.PluginLoader("sqlalchemy.dialects", auto_fn=_auto_fn)
61
+
62
+ plugins = util.PluginLoader("sqlalchemy.plugins")
loan-advisor-agent/.venv/Lib/site-packages/sqlalchemy/dialects/_typing.py ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # dialects/_typing.py
2
+ # Copyright (C) 2005-2026 the SQLAlchemy authors and contributors
3
+ # <see AUTHORS file>
4
+ #
5
+ # This module is part of SQLAlchemy and is released under
6
+ # the MIT License: https://www.opensource.org/licenses/mit-license.php
7
+ from __future__ import annotations
8
+
9
+ from typing import Any
10
+ from typing import Iterable
11
+ from typing import Mapping
12
+ from typing import Optional
13
+ from typing import Union
14
+
15
+ from ..sql import roles
16
+ from ..sql.base import ColumnCollection
17
+ from ..sql.schema import Column
18
+ from ..sql.schema import ColumnCollectionConstraint
19
+ from ..sql.schema import Index
20
+
21
+
22
+ _OnConflictConstraintT = Union[str, ColumnCollectionConstraint, Index, None]
23
+ _OnConflictIndexElementsT = Optional[
24
+ Iterable[Union[Column[Any], str, roles.DDLConstraintColumnRole]]
25
+ ]
26
+ _OnConflictIndexWhereT = Optional[roles.WhereHavingRole]
27
+ _OnConflictSetT = Optional[
28
+ Union[Mapping[Any, Any], ColumnCollection[Any, Any]]
29
+ ]
30
+ _OnConflictWhereT = Optional[roles.WhereHavingRole]
loan-advisor-agent/.venv/Lib/site-packages/sqlalchemy/dialects/mssql/__init__.py ADDED
@@ -0,0 +1,88 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # dialects/mssql/__init__.py
2
+ # Copyright (C) 2005-2026 the SQLAlchemy authors and contributors
3
+ # <see AUTHORS file>
4
+ #
5
+ # This module is part of SQLAlchemy and is released under
6
+ # the MIT License: https://www.opensource.org/licenses/mit-license.php
7
+ # mypy: ignore-errors
8
+
9
+ from . import aioodbc # noqa
10
+ from . import base # noqa
11
+ from . import pymssql # noqa
12
+ from . import pyodbc # noqa
13
+ from .base import BIGINT
14
+ from .base import BINARY
15
+ from .base import BIT
16
+ from .base import CHAR
17
+ from .base import DATE
18
+ from .base import DATETIME
19
+ from .base import DATETIME2
20
+ from .base import DATETIMEOFFSET
21
+ from .base import DECIMAL
22
+ from .base import DOUBLE_PRECISION
23
+ from .base import FLOAT
24
+ from .base import IMAGE
25
+ from .base import INTEGER
26
+ from .base import JSON
27
+ from .base import MONEY
28
+ from .base import NCHAR
29
+ from .base import NTEXT
30
+ from .base import NUMERIC
31
+ from .base import NVARCHAR
32
+ from .base import REAL
33
+ from .base import ROWVERSION
34
+ from .base import SMALLDATETIME
35
+ from .base import SMALLINT
36
+ from .base import SMALLMONEY
37
+ from .base import SQL_VARIANT
38
+ from .base import TEXT
39
+ from .base import TIME
40
+ from .base import TIMESTAMP
41
+ from .base import TINYINT
42
+ from .base import UNIQUEIDENTIFIER
43
+ from .base import VARBINARY
44
+ from .base import VARCHAR
45
+ from .base import XML
46
+ from ...sql import try_cast
47
+
48
+
49
+ base.dialect = dialect = pyodbc.dialect
50
+
51
+
52
+ __all__ = (
53
+ "JSON",
54
+ "INTEGER",
55
+ "BIGINT",
56
+ "SMALLINT",
57
+ "TINYINT",
58
+ "VARCHAR",
59
+ "NVARCHAR",
60
+ "CHAR",
61
+ "NCHAR",
62
+ "TEXT",
63
+ "NTEXT",
64
+ "DECIMAL",
65
+ "NUMERIC",
66
+ "FLOAT",
67
+ "DATETIME",
68
+ "DATETIME2",
69
+ "DATETIMEOFFSET",
70
+ "DATE",
71
+ "DOUBLE_PRECISION",
72
+ "TIME",
73
+ "SMALLDATETIME",
74
+ "BINARY",
75
+ "VARBINARY",
76
+ "BIT",
77
+ "REAL",
78
+ "IMAGE",
79
+ "TIMESTAMP",
80
+ "ROWVERSION",
81
+ "MONEY",
82
+ "SMALLMONEY",
83
+ "UNIQUEIDENTIFIER",
84
+ "SQL_VARIANT",
85
+ "XML",
86
+ "dialect",
87
+ "try_cast",
88
+ )
loan-advisor-agent/.venv/Lib/site-packages/sqlalchemy/dialects/mssql/aioodbc.py ADDED
@@ -0,0 +1,63 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # dialects/mssql/aioodbc.py
2
+ # Copyright (C) 2005-2026 the SQLAlchemy authors and contributors
3
+ # <see AUTHORS file>
4
+ #
5
+ # This module is part of SQLAlchemy and is released under
6
+ # the MIT License: https://www.opensource.org/licenses/mit-license.php
7
+ # mypy: ignore-errors
8
+ r"""
9
+ .. dialect:: mssql+aioodbc
10
+ :name: aioodbc
11
+ :dbapi: aioodbc
12
+ :connectstring: mssql+aioodbc://<username>:<password>@<dsnname>
13
+ :url: https://pypi.org/project/aioodbc/
14
+
15
+
16
+ Support for the SQL Server database in asyncio style, using the aioodbc
17
+ driver which itself is a thread-wrapper around pyodbc.
18
+
19
+ .. versionadded:: 2.0.23 Added the mssql+aioodbc dialect which builds
20
+ on top of the pyodbc and general aio* dialect architecture.
21
+
22
+ Using a special asyncio mediation layer, the aioodbc dialect is usable
23
+ as the backend for the :ref:`SQLAlchemy asyncio <asyncio_toplevel>`
24
+ extension package.
25
+
26
+ Most behaviors and caveats for this driver are the same as that of the
27
+ pyodbc dialect used on SQL Server; see :ref:`mssql_pyodbc` for general
28
+ background.
29
+
30
+ This dialect should normally be used only with the
31
+ :func:`_asyncio.create_async_engine` engine creation function; connection
32
+ styles are otherwise equivalent to those documented in the pyodbc section::
33
+
34
+ from sqlalchemy.ext.asyncio import create_async_engine
35
+
36
+ engine = create_async_engine(
37
+ "mssql+aioodbc://scott:tiger@mssql2017:1433/test?"
38
+ "driver=ODBC+Driver+18+for+SQL+Server&TrustServerCertificate=yes"
39
+ )
40
+
41
+ """
42
+
43
+ from __future__ import annotations
44
+
45
+ from .pyodbc import MSDialect_pyodbc
46
+ from .pyodbc import MSExecutionContext_pyodbc
47
+ from ...connectors.aioodbc import aiodbcConnector
48
+
49
+
50
+ class MSExecutionContext_aioodbc(MSExecutionContext_pyodbc):
51
+ def create_server_side_cursor(self):
52
+ return self._dbapi_connection.cursor(server_side=True)
53
+
54
+
55
+ class MSDialectAsync_aioodbc(aiodbcConnector, MSDialect_pyodbc):
56
+ driver = "aioodbc"
57
+
58
+ supports_statement_cache = True
59
+
60
+ execution_ctx_cls = MSExecutionContext_aioodbc
61
+
62
+
63
+ dialect = MSDialectAsync_aioodbc
loan-advisor-agent/.venv/Lib/site-packages/sqlalchemy/dialects/mssql/base.py ADDED
The diff for this file is too large to render. See raw diff
 
loan-advisor-agent/.venv/Lib/site-packages/sqlalchemy/dialects/mssql/information_schema.py ADDED
@@ -0,0 +1,285 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # dialects/mssql/information_schema.py
2
+ # Copyright (C) 2005-2026 the SQLAlchemy authors and contributors
3
+ # <see AUTHORS file>
4
+ #
5
+ # This module is part of SQLAlchemy and is released under
6
+ # the MIT License: https://www.opensource.org/licenses/mit-license.php
7
+ # mypy: ignore-errors
8
+
9
+ from ... import cast
10
+ from ... import Column
11
+ from ... import MetaData
12
+ from ... import Table
13
+ from ...ext.compiler import compiles
14
+ from ...sql import expression
15
+ from ...types import Boolean
16
+ from ...types import Integer
17
+ from ...types import Numeric
18
+ from ...types import NVARCHAR
19
+ from ...types import String
20
+ from ...types import TypeDecorator
21
+ from ...types import Unicode
22
+
23
+
24
+ ischema = MetaData()
25
+
26
+
27
+ class CoerceUnicode(TypeDecorator):
28
+ impl = Unicode
29
+ cache_ok = True
30
+
31
+ def bind_expression(self, bindvalue):
32
+ return _cast_on_2005(bindvalue)
33
+
34
+
35
+ class _cast_on_2005(expression.ColumnElement):
36
+ def __init__(self, bindvalue):
37
+ self.bindvalue = bindvalue
38
+
39
+
40
+ @compiles(_cast_on_2005)
41
+ def _compile(element, compiler, **kw):
42
+ from . import base
43
+
44
+ if (
45
+ compiler.dialect.server_version_info is None
46
+ or compiler.dialect.server_version_info < base.MS_2005_VERSION
47
+ ):
48
+ return compiler.process(element.bindvalue, **kw)
49
+ else:
50
+ return compiler.process(cast(element.bindvalue, Unicode), **kw)
51
+
52
+
53
+ schemata = Table(
54
+ "SCHEMATA",
55
+ ischema,
56
+ Column("CATALOG_NAME", CoerceUnicode, key="catalog_name"),
57
+ Column("SCHEMA_NAME", CoerceUnicode, key="schema_name"),
58
+ Column("SCHEMA_OWNER", CoerceUnicode, key="schema_owner"),
59
+ schema="INFORMATION_SCHEMA",
60
+ )
61
+
62
+ tables = Table(
63
+ "TABLES",
64
+ ischema,
65
+ Column("TABLE_CATALOG", CoerceUnicode, key="table_catalog"),
66
+ Column("TABLE_SCHEMA", CoerceUnicode, key="table_schema"),
67
+ Column("TABLE_NAME", CoerceUnicode, key="table_name"),
68
+ Column("TABLE_TYPE", CoerceUnicode, key="table_type"),
69
+ schema="INFORMATION_SCHEMA",
70
+ )
71
+
72
+ columns = Table(
73
+ "COLUMNS",
74
+ ischema,
75
+ Column("TABLE_SCHEMA", CoerceUnicode, key="table_schema"),
76
+ Column("TABLE_NAME", CoerceUnicode, key="table_name"),
77
+ Column("COLUMN_NAME", CoerceUnicode, key="column_name"),
78
+ Column("IS_NULLABLE", Integer, key="is_nullable"),
79
+ Column("DATA_TYPE", String, key="data_type"),
80
+ Column("ORDINAL_POSITION", Integer, key="ordinal_position"),
81
+ Column(
82
+ "CHARACTER_MAXIMUM_LENGTH", Integer, key="character_maximum_length"
83
+ ),
84
+ Column("NUMERIC_PRECISION", Integer, key="numeric_precision"),
85
+ Column("NUMERIC_SCALE", Integer, key="numeric_scale"),
86
+ Column("COLUMN_DEFAULT", Integer, key="column_default"),
87
+ Column("COLLATION_NAME", String, key="collation_name"),
88
+ schema="INFORMATION_SCHEMA",
89
+ )
90
+
91
+ sys_columns = Table(
92
+ "columns",
93
+ ischema,
94
+ Column("object_id", Integer),
95
+ Column("name", CoerceUnicode),
96
+ Column("column_id", Integer),
97
+ Column("default_object_id", Integer),
98
+ Column("user_type_id", Integer),
99
+ Column("is_nullable", Integer),
100
+ Column("ordinal_position", Integer),
101
+ Column("max_length", Integer),
102
+ Column("precision", Integer),
103
+ Column("scale", Integer),
104
+ Column("collation_name", String),
105
+ schema="sys",
106
+ )
107
+
108
+ sys_types = Table(
109
+ "types",
110
+ ischema,
111
+ Column("name", CoerceUnicode, key="name"),
112
+ Column("system_type_id", Integer, key="system_type_id"),
113
+ Column("user_type_id", Integer, key="user_type_id"),
114
+ Column("schema_id", Integer, key="schema_id"),
115
+ Column("max_length", Integer, key="max_length"),
116
+ Column("precision", Integer, key="precision"),
117
+ Column("scale", Integer, key="scale"),
118
+ Column("collation_name", CoerceUnicode, key="collation_name"),
119
+ Column("is_nullable", Boolean, key="is_nullable"),
120
+ Column("is_user_defined", Boolean, key="is_user_defined"),
121
+ Column("is_assembly_type", Boolean, key="is_assembly_type"),
122
+ Column("default_object_id", Integer, key="default_object_id"),
123
+ Column("rule_object_id", Integer, key="rule_object_id"),
124
+ Column("is_table_type", Boolean, key="is_table_type"),
125
+ schema="sys",
126
+ )
127
+
128
+ constraints = Table(
129
+ "TABLE_CONSTRAINTS",
130
+ ischema,
131
+ Column("TABLE_SCHEMA", CoerceUnicode, key="table_schema"),
132
+ Column("TABLE_NAME", CoerceUnicode, key="table_name"),
133
+ Column("CONSTRAINT_NAME", CoerceUnicode, key="constraint_name"),
134
+ Column("CONSTRAINT_TYPE", CoerceUnicode, key="constraint_type"),
135
+ schema="INFORMATION_SCHEMA",
136
+ )
137
+
138
+ sys_default_constraints = Table(
139
+ "default_constraints",
140
+ ischema,
141
+ Column("object_id", Integer),
142
+ Column("name", CoerceUnicode),
143
+ Column("schema_id", Integer),
144
+ Column("parent_column_id", Integer),
145
+ Column("definition", CoerceUnicode),
146
+ schema="sys",
147
+ )
148
+
149
+ column_constraints = Table(
150
+ "CONSTRAINT_COLUMN_USAGE",
151
+ ischema,
152
+ Column("TABLE_SCHEMA", CoerceUnicode, key="table_schema"),
153
+ Column("TABLE_NAME", CoerceUnicode, key="table_name"),
154
+ Column("COLUMN_NAME", CoerceUnicode, key="column_name"),
155
+ Column("CONSTRAINT_NAME", CoerceUnicode, key="constraint_name"),
156
+ schema="INFORMATION_SCHEMA",
157
+ )
158
+
159
+ key_constraints = Table(
160
+ "KEY_COLUMN_USAGE",
161
+ ischema,
162
+ Column("TABLE_SCHEMA", CoerceUnicode, key="table_schema"),
163
+ Column("TABLE_NAME", CoerceUnicode, key="table_name"),
164
+ Column("COLUMN_NAME", CoerceUnicode, key="column_name"),
165
+ Column("CONSTRAINT_NAME", CoerceUnicode, key="constraint_name"),
166
+ Column("CONSTRAINT_SCHEMA", CoerceUnicode, key="constraint_schema"),
167
+ Column("ORDINAL_POSITION", Integer, key="ordinal_position"),
168
+ schema="INFORMATION_SCHEMA",
169
+ )
170
+
171
+ ref_constraints = Table(
172
+ "REFERENTIAL_CONSTRAINTS",
173
+ ischema,
174
+ Column("CONSTRAINT_CATALOG", CoerceUnicode, key="constraint_catalog"),
175
+ Column("CONSTRAINT_SCHEMA", CoerceUnicode, key="constraint_schema"),
176
+ Column("CONSTRAINT_NAME", CoerceUnicode, key="constraint_name"),
177
+ # TODO: is CATLOG misspelled ?
178
+ Column(
179
+ "UNIQUE_CONSTRAINT_CATLOG",
180
+ CoerceUnicode,
181
+ key="unique_constraint_catalog",
182
+ ),
183
+ Column(
184
+ "UNIQUE_CONSTRAINT_SCHEMA",
185
+ CoerceUnicode,
186
+ key="unique_constraint_schema",
187
+ ),
188
+ Column(
189
+ "UNIQUE_CONSTRAINT_NAME", CoerceUnicode, key="unique_constraint_name"
190
+ ),
191
+ Column("MATCH_OPTION", String, key="match_option"),
192
+ Column("UPDATE_RULE", String, key="update_rule"),
193
+ Column("DELETE_RULE", String, key="delete_rule"),
194
+ schema="INFORMATION_SCHEMA",
195
+ )
196
+
197
+ views = Table(
198
+ "VIEWS",
199
+ ischema,
200
+ Column("TABLE_CATALOG", CoerceUnicode, key="table_catalog"),
201
+ Column("TABLE_SCHEMA", CoerceUnicode, key="table_schema"),
202
+ Column("TABLE_NAME", CoerceUnicode, key="table_name"),
203
+ Column("VIEW_DEFINITION", CoerceUnicode, key="view_definition"),
204
+ Column("CHECK_OPTION", String, key="check_option"),
205
+ Column("IS_UPDATABLE", String, key="is_updatable"),
206
+ schema="INFORMATION_SCHEMA",
207
+ )
208
+
209
+ computed_columns = Table(
210
+ "computed_columns",
211
+ ischema,
212
+ Column("object_id", Integer),
213
+ Column("name", CoerceUnicode),
214
+ Column("column_id", Integer),
215
+ Column("is_computed", Boolean),
216
+ Column("is_persisted", Boolean),
217
+ Column("definition", CoerceUnicode),
218
+ schema="sys",
219
+ )
220
+
221
+ sequences = Table(
222
+ "SEQUENCES",
223
+ ischema,
224
+ Column("SEQUENCE_CATALOG", CoerceUnicode, key="sequence_catalog"),
225
+ Column("SEQUENCE_SCHEMA", CoerceUnicode, key="sequence_schema"),
226
+ Column("SEQUENCE_NAME", CoerceUnicode, key="sequence_name"),
227
+ schema="INFORMATION_SCHEMA",
228
+ )
229
+
230
+
231
+ class NumericSqlVariant(TypeDecorator):
232
+ r"""This type casts sql_variant columns in the identity_columns view
233
+ to numeric. This is required because:
234
+
235
+ * pyodbc does not support sql_variant
236
+ * pymssql under python 2 return the byte representation of the number,
237
+ int 1 is returned as "\x01\x00\x00\x00". On python 3 it returns the
238
+ correct value as string.
239
+ """
240
+
241
+ impl = Unicode
242
+ cache_ok = True
243
+
244
+ def column_expression(self, colexpr):
245
+ return cast(colexpr, Numeric(38, 0))
246
+
247
+
248
+ identity_columns = Table(
249
+ "identity_columns",
250
+ ischema,
251
+ Column("object_id", Integer),
252
+ Column("name", CoerceUnicode),
253
+ Column("column_id", Integer),
254
+ Column("is_identity", Boolean),
255
+ Column("seed_value", NumericSqlVariant),
256
+ Column("increment_value", NumericSqlVariant),
257
+ Column("last_value", NumericSqlVariant),
258
+ Column("is_not_for_replication", Boolean),
259
+ schema="sys",
260
+ )
261
+
262
+
263
+ class NVarcharSqlVariant(TypeDecorator):
264
+ """This type casts sql_variant columns in the extended_properties view
265
+ to nvarchar. This is required because pyodbc does not support sql_variant
266
+ """
267
+
268
+ impl = Unicode
269
+ cache_ok = True
270
+
271
+ def column_expression(self, colexpr):
272
+ return cast(colexpr, NVARCHAR)
273
+
274
+
275
+ extended_properties = Table(
276
+ "extended_properties",
277
+ ischema,
278
+ Column("class", Integer), # TINYINT
279
+ Column("class_desc", CoerceUnicode),
280
+ Column("major_id", Integer),
281
+ Column("minor_id", Integer),
282
+ Column("name", CoerceUnicode),
283
+ Column("value", NVarcharSqlVariant),
284
+ schema="sys",
285
+ )
loan-advisor-agent/.venv/Lib/site-packages/sqlalchemy/dialects/mssql/json.py ADDED
@@ -0,0 +1,129 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # dialects/mssql/json.py
2
+ # Copyright (C) 2005-2026 the SQLAlchemy authors and contributors
3
+ # <see AUTHORS file>
4
+ #
5
+ # This module is part of SQLAlchemy and is released under
6
+ # the MIT License: https://www.opensource.org/licenses/mit-license.php
7
+ # mypy: ignore-errors
8
+
9
+ from ... import types as sqltypes
10
+
11
+ # technically, all the dialect-specific datatypes that don't have any special
12
+ # behaviors would be private with names like _MSJson. However, we haven't been
13
+ # doing this for mysql.JSON or sqlite.JSON which both have JSON / JSONIndexType
14
+ # / JSONPathType in their json.py files, so keep consistent with that
15
+ # sub-convention for now. A future change can update them all to be
16
+ # package-private at once.
17
+
18
+
19
+ class JSON(sqltypes.JSON):
20
+ """MSSQL JSON type.
21
+
22
+ MSSQL supports JSON-formatted data as of SQL Server 2016.
23
+
24
+ The :class:`_mssql.JSON` datatype at the DDL level will represent the
25
+ datatype as ``NVARCHAR(max)``, but provides for JSON-level comparison
26
+ functions as well as Python coercion behavior.
27
+
28
+ :class:`_mssql.JSON` is used automatically whenever the base
29
+ :class:`_types.JSON` datatype is used against a SQL Server backend.
30
+
31
+ .. seealso::
32
+
33
+ :class:`_types.JSON` - main documentation for the generic
34
+ cross-platform JSON datatype.
35
+
36
+ The :class:`_mssql.JSON` type supports persistence of JSON values
37
+ as well as the core index operations provided by :class:`_types.JSON`
38
+ datatype, by adapting the operations to render the ``JSON_VALUE``
39
+ or ``JSON_QUERY`` functions at the database level.
40
+
41
+ The SQL Server :class:`_mssql.JSON` type necessarily makes use of the
42
+ ``JSON_QUERY`` and ``JSON_VALUE`` functions when querying for elements
43
+ of a JSON object. These two functions have a major restriction in that
44
+ they are **mutually exclusive** based on the type of object to be returned.
45
+ The ``JSON_QUERY`` function **only** returns a JSON dictionary or list,
46
+ but not an individual string, numeric, or boolean element; the
47
+ ``JSON_VALUE`` function **only** returns an individual string, numeric,
48
+ or boolean element. **both functions either return NULL or raise
49
+ an error if they are not used against the correct expected value**.
50
+
51
+ To handle this awkward requirement, indexed access rules are as follows:
52
+
53
+ 1. When extracting a sub element from a JSON that is itself a JSON
54
+ dictionary or list, the :meth:`_types.JSON.Comparator.as_json` accessor
55
+ should be used::
56
+
57
+ stmt = select(data_table.c.data["some key"].as_json()).where(
58
+ data_table.c.data["some key"].as_json() == {"sub": "structure"}
59
+ )
60
+
61
+ 2. When extracting a sub element from a JSON that is a plain boolean,
62
+ string, integer, or float, use the appropriate method among
63
+ :meth:`_types.JSON.Comparator.as_boolean`,
64
+ :meth:`_types.JSON.Comparator.as_string`,
65
+ :meth:`_types.JSON.Comparator.as_integer`,
66
+ :meth:`_types.JSON.Comparator.as_float`::
67
+
68
+ stmt = select(data_table.c.data["some key"].as_string()).where(
69
+ data_table.c.data["some key"].as_string() == "some string"
70
+ )
71
+
72
+ .. versionadded:: 1.4
73
+
74
+
75
+ """
76
+
77
+ # note there was a result processor here that was looking for "number",
78
+ # but none of the tests seem to exercise it.
79
+
80
+
81
+ # Note: these objects currently match exactly those of MySQL, however since
82
+ # these are not generalizable to all JSON implementations, remain separately
83
+ # implemented for each dialect.
84
+ class _FormatTypeMixin:
85
+ def _format_value(self, value):
86
+ raise NotImplementedError()
87
+
88
+ def bind_processor(self, dialect):
89
+ super_proc = self.string_bind_processor(dialect)
90
+
91
+ def process(value):
92
+ value = self._format_value(value)
93
+ if super_proc:
94
+ value = super_proc(value)
95
+ return value
96
+
97
+ return process
98
+
99
+ def literal_processor(self, dialect):
100
+ super_proc = self.string_literal_processor(dialect)
101
+
102
+ def process(value):
103
+ value = self._format_value(value)
104
+ if super_proc:
105
+ value = super_proc(value)
106
+ return value
107
+
108
+ return process
109
+
110
+
111
+ class JSONIndexType(_FormatTypeMixin, sqltypes.JSON.JSONIndexType):
112
+ def _format_value(self, value):
113
+ if isinstance(value, int):
114
+ value = "$[%s]" % value
115
+ else:
116
+ value = '$."%s"' % value
117
+ return value
118
+
119
+
120
+ class JSONPathType(_FormatTypeMixin, sqltypes.JSON.JSONPathType):
121
+ def _format_value(self, value):
122
+ return "$%s" % (
123
+ "".join(
124
+ [
125
+ "[%s]" % elem if isinstance(elem, int) else '."%s"' % elem
126
+ for elem in value
127
+ ]
128
+ )
129
+ )
loan-advisor-agent/.venv/Lib/site-packages/sqlalchemy/dialects/mssql/provision.py ADDED
@@ -0,0 +1,185 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # dialects/mssql/provision.py
2
+ # Copyright (C) 2005-2026 the SQLAlchemy authors and contributors
3
+ # <see AUTHORS file>
4
+ #
5
+ # This module is part of SQLAlchemy and is released under
6
+ # the MIT License: https://www.opensource.org/licenses/mit-license.php
7
+ # mypy: ignore-errors
8
+
9
+ from sqlalchemy import inspect
10
+ from sqlalchemy import Integer
11
+ from ... import create_engine
12
+ from ... import exc
13
+ from ...schema import Column
14
+ from ...schema import DropConstraint
15
+ from ...schema import ForeignKeyConstraint
16
+ from ...schema import MetaData
17
+ from ...schema import Table
18
+ from ...testing.provision import create_db
19
+ from ...testing.provision import drop_all_schema_objects_pre_tables
20
+ from ...testing.provision import drop_db
21
+ from ...testing.provision import generate_driver_url
22
+ from ...testing.provision import get_temp_table_name
23
+ from ...testing.provision import log
24
+ from ...testing.provision import normalize_sequence
25
+ from ...testing.provision import post_configure_engine
26
+ from ...testing.provision import run_reap_dbs
27
+ from ...testing.provision import temp_table_keyword_args
28
+
29
+
30
+ @post_configure_engine.for_db("mssql")
31
+ def post_configure_engine(url, engine, follower_ident):
32
+ if engine.driver == "pyodbc":
33
+ engine.dialect.dbapi.pooling = False
34
+
35
+
36
+ @generate_driver_url.for_db("mssql")
37
+ def generate_driver_url(url, driver, query_str):
38
+ backend = url.get_backend_name()
39
+
40
+ new_url = url.set(drivername="%s+%s" % (backend, driver))
41
+
42
+ if driver not in ("pyodbc", "aioodbc"):
43
+ new_url = new_url.set(query="")
44
+
45
+ if driver == "aioodbc":
46
+ new_url = new_url.update_query_dict({"MARS_Connection": "Yes"})
47
+
48
+ if query_str:
49
+ new_url = new_url.update_query_string(query_str)
50
+
51
+ try:
52
+ new_url.get_dialect()
53
+ except exc.NoSuchModuleError:
54
+ return None
55
+ else:
56
+ return new_url
57
+
58
+
59
+ @create_db.for_db("mssql")
60
+ def _mssql_create_db(cfg, eng, ident):
61
+ with eng.connect().execution_options(isolation_level="AUTOCOMMIT") as conn:
62
+ conn.exec_driver_sql("create database %s" % ident)
63
+ conn.exec_driver_sql(
64
+ "ALTER DATABASE %s SET ALLOW_SNAPSHOT_ISOLATION ON" % ident
65
+ )
66
+ conn.exec_driver_sql(
67
+ "ALTER DATABASE %s SET READ_COMMITTED_SNAPSHOT ON" % ident
68
+ )
69
+ conn.exec_driver_sql("use %s" % ident)
70
+ conn.exec_driver_sql("create schema test_schema")
71
+ conn.exec_driver_sql("create schema test_schema_2")
72
+
73
+
74
+ @drop_db.for_db("mssql")
75
+ def _mssql_drop_db(cfg, eng, ident):
76
+ with eng.connect().execution_options(isolation_level="AUTOCOMMIT") as conn:
77
+ _mssql_drop_ignore(conn, ident)
78
+
79
+
80
+ def _mssql_drop_ignore(conn, ident):
81
+ try:
82
+ # typically when this happens, we can't KILL the session anyway,
83
+ # so let the cleanup process drop the DBs
84
+ # for row in conn.exec_driver_sql(
85
+ # "select session_id from sys.dm_exec_sessions "
86
+ # "where database_id=db_id('%s')" % ident):
87
+ # log.info("killing SQL server session %s", row['session_id'])
88
+ # conn.exec_driver_sql("kill %s" % row['session_id'])
89
+ conn.exec_driver_sql("drop database %s" % ident)
90
+ log.info("Reaped db: %s", ident)
91
+ return True
92
+ except exc.DatabaseError as err:
93
+ log.warning("couldn't drop db: %s", err)
94
+ return False
95
+
96
+
97
+ @run_reap_dbs.for_db("mssql")
98
+ def _reap_mssql_dbs(url, idents):
99
+ log.info("db reaper connecting to %r", url)
100
+ eng = create_engine(url)
101
+ with eng.connect().execution_options(isolation_level="AUTOCOMMIT") as conn:
102
+ log.info("identifiers in file: %s", ", ".join(idents))
103
+
104
+ to_reap = conn.exec_driver_sql(
105
+ "select d.name from sys.databases as d where name "
106
+ "like 'TEST_%' and not exists (select session_id "
107
+ "from sys.dm_exec_sessions "
108
+ "where database_id=d.database_id)"
109
+ )
110
+ all_names = {dbname.lower() for (dbname,) in to_reap}
111
+ to_drop = set()
112
+ for name in all_names:
113
+ if name in idents:
114
+ to_drop.add(name)
115
+
116
+ dropped = total = 0
117
+ for total, dbname in enumerate(to_drop, 1):
118
+ if _mssql_drop_ignore(conn, dbname):
119
+ dropped += 1
120
+ log.info(
121
+ "Dropped %d out of %d stale databases detected", dropped, total
122
+ )
123
+
124
+
125
+ @temp_table_keyword_args.for_db("mssql")
126
+ def _mssql_temp_table_keyword_args(cfg, eng):
127
+ return {}
128
+
129
+
130
+ @get_temp_table_name.for_db("mssql")
131
+ def _mssql_get_temp_table_name(cfg, eng, base_name):
132
+ return "##" + base_name
133
+
134
+
135
+ @drop_all_schema_objects_pre_tables.for_db("mssql")
136
+ def drop_all_schema_objects_pre_tables(cfg, eng):
137
+ with eng.connect().execution_options(isolation_level="AUTOCOMMIT") as conn:
138
+ inspector = inspect(conn)
139
+
140
+ # Drop all full-text indexes before dropping catalogs
141
+ fulltext_indexes = conn.exec_driver_sql(
142
+ "SELECT OBJECT_SCHEMA_NAME(object_id) AS schema_name, "
143
+ "OBJECT_NAME(object_id) AS table_name "
144
+ "FROM sys.fulltext_indexes"
145
+ ).fetchall()
146
+
147
+ for schema_name, table_name in fulltext_indexes:
148
+ if schema_name:
149
+ qualified_name = f"[{schema_name}].[{table_name}]"
150
+ else:
151
+ qualified_name = f"[{table_name}]"
152
+ conn.exec_driver_sql(f"DROP FULLTEXT INDEX ON {qualified_name}")
153
+
154
+ # Now drop all full-text catalogs
155
+ fulltext_catalogs = conn.exec_driver_sql(
156
+ "SELECT name FROM sys.fulltext_catalogs"
157
+ ).fetchall()
158
+
159
+ for (catalog_name,) in fulltext_catalogs:
160
+ conn.exec_driver_sql(f"DROP FULLTEXT CATALOG [{catalog_name}]")
161
+
162
+ for schema in (None, "dbo", cfg.test_schema, cfg.test_schema_2):
163
+ for tname in inspector.get_table_names(schema=schema):
164
+ tb = Table(
165
+ tname,
166
+ MetaData(),
167
+ Column("x", Integer),
168
+ Column("y", Integer),
169
+ schema=schema,
170
+ )
171
+ for fk in inspect(conn).get_foreign_keys(tname, schema=schema):
172
+ conn.execute(
173
+ DropConstraint(
174
+ ForeignKeyConstraint(
175
+ [tb.c.x], [tb.c.y], name=fk["name"]
176
+ )
177
+ )
178
+ )
179
+
180
+
181
+ @normalize_sequence.for_db("mssql")
182
+ def normalize_sequence(cfg, sequence):
183
+ if sequence.start is None:
184
+ sequence.start = 1
185
+ return sequence
loan-advisor-agent/.venv/Lib/site-packages/sqlalchemy/dialects/mssql/pymssql.py ADDED
@@ -0,0 +1,126 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # dialects/mssql/pymssql.py
2
+ # Copyright (C) 2005-2026 the SQLAlchemy authors and contributors
3
+ # <see AUTHORS file>
4
+ #
5
+ # This module is part of SQLAlchemy and is released under
6
+ # the MIT License: https://www.opensource.org/licenses/mit-license.php
7
+ # mypy: ignore-errors
8
+
9
+
10
+ """
11
+ .. dialect:: mssql+pymssql
12
+ :name: pymssql
13
+ :dbapi: pymssql
14
+ :connectstring: mssql+pymssql://<username>:<password>@<freetds_name>/?charset=utf8
15
+
16
+ pymssql is a Python module that provides a Python DBAPI interface around
17
+ `FreeTDS <https://www.freetds.org/>`_.
18
+
19
+ .. versionchanged:: 2.0.5
20
+
21
+ pymssql was restored to SQLAlchemy's continuous integration testing
22
+
23
+
24
+ """ # noqa
25
+ import re
26
+
27
+ from .base import MSDialect
28
+ from .base import MSIdentifierPreparer
29
+ from ... import types as sqltypes
30
+ from ... import util
31
+ from ...engine import processors
32
+
33
+
34
+ class _MSNumeric_pymssql(sqltypes.Numeric):
35
+ def result_processor(self, dialect, type_):
36
+ if not self.asdecimal:
37
+ return processors.to_float
38
+ else:
39
+ return sqltypes.Numeric.result_processor(self, dialect, type_)
40
+
41
+
42
+ class MSIdentifierPreparer_pymssql(MSIdentifierPreparer):
43
+ def __init__(self, dialect):
44
+ super().__init__(dialect)
45
+ # pymssql has the very unusual behavior that it uses pyformat
46
+ # yet does not require that percent signs be doubled
47
+ self._double_percents = False
48
+
49
+
50
+ class MSDialect_pymssql(MSDialect):
51
+ supports_statement_cache = True
52
+ supports_native_decimal = True
53
+ supports_native_uuid = True
54
+ driver = "pymssql"
55
+
56
+ preparer = MSIdentifierPreparer_pymssql
57
+
58
+ colspecs = util.update_copy(
59
+ MSDialect.colspecs,
60
+ {sqltypes.Numeric: _MSNumeric_pymssql, sqltypes.Float: sqltypes.Float},
61
+ )
62
+
63
+ @classmethod
64
+ def import_dbapi(cls):
65
+ module = __import__("pymssql")
66
+ # pymmsql < 2.1.1 doesn't have a Binary method. we use string
67
+ client_ver = tuple(int(x) for x in module.__version__.split("."))
68
+ if client_ver < (2, 1, 1):
69
+ # TODO: monkeypatching here is less than ideal
70
+ module.Binary = lambda x: x if hasattr(x, "decode") else str(x)
71
+
72
+ if client_ver < (1,):
73
+ util.warn(
74
+ "The pymssql dialect expects at least "
75
+ "the 1.0 series of the pymssql DBAPI."
76
+ )
77
+ return module
78
+
79
+ def _get_server_version_info(self, connection):
80
+ vers = connection.exec_driver_sql("select @@version").scalar()
81
+ m = re.match(r"Microsoft .*? - (\d+)\.(\d+)\.(\d+)\.(\d+)", vers)
82
+ if m:
83
+ return tuple(int(x) for x in m.group(1, 2, 3, 4))
84
+ else:
85
+ return None
86
+
87
+ def create_connect_args(self, url):
88
+ opts = url.translate_connect_args(username="user")
89
+ opts.update(url.query)
90
+ port = opts.pop("port", None)
91
+ if port and "host" in opts:
92
+ opts["host"] = "%s:%s" % (opts["host"], port)
93
+ return ([], opts)
94
+
95
+ def is_disconnect(self, e, connection, cursor):
96
+ for msg in (
97
+ "Adaptive Server connection timed out",
98
+ "Net-Lib error during Connection reset by peer",
99
+ "message 20003", # connection timeout
100
+ "Error 10054",
101
+ "Not connected to any MS SQL server",
102
+ "Connection is closed",
103
+ "message 20006", # Write to the server failed
104
+ "message 20017", # Unexpected EOF from the server
105
+ "message 20047", # DBPROCESS is dead or not enabled
106
+ "The server failed to resume the transaction",
107
+ ):
108
+ if msg in str(e):
109
+ return True
110
+ else:
111
+ return False
112
+
113
+ def get_isolation_level_values(self, dbapi_connection):
114
+ return super().get_isolation_level_values(dbapi_connection) + [
115
+ "AUTOCOMMIT"
116
+ ]
117
+
118
+ def set_isolation_level(self, dbapi_connection, level):
119
+ if level == "AUTOCOMMIT":
120
+ dbapi_connection.autocommit(True)
121
+ else:
122
+ dbapi_connection.autocommit(False)
123
+ super().set_isolation_level(dbapi_connection, level)
124
+
125
+
126
+ dialect = MSDialect_pymssql
loan-advisor-agent/.venv/Lib/site-packages/sqlalchemy/dialects/mssql/pyodbc.py ADDED
@@ -0,0 +1,760 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # dialects/mssql/pyodbc.py
2
+ # Copyright (C) 2005-2026 the SQLAlchemy authors and contributors
3
+ # <see AUTHORS file>
4
+ #
5
+ # This module is part of SQLAlchemy and is released under
6
+ # the MIT License: https://www.opensource.org/licenses/mit-license.php
7
+ # mypy: ignore-errors
8
+
9
+ r"""
10
+ .. dialect:: mssql+pyodbc
11
+ :name: PyODBC
12
+ :dbapi: pyodbc
13
+ :connectstring: mssql+pyodbc://<username>:<password>@<dsnname>
14
+ :url: https://pypi.org/project/pyodbc/
15
+
16
+ Connecting to PyODBC
17
+ --------------------
18
+
19
+ The URL here is to be translated to PyODBC connection strings, as
20
+ detailed in `ConnectionStrings <https://code.google.com/p/pyodbc/wiki/ConnectionStrings>`_.
21
+
22
+ DSN Connections
23
+ ^^^^^^^^^^^^^^^
24
+
25
+ A DSN connection in ODBC means that a pre-existing ODBC datasource is
26
+ configured on the client machine. The application then specifies the name
27
+ of this datasource, which encompasses details such as the specific ODBC driver
28
+ in use as well as the network address of the database. Assuming a datasource
29
+ is configured on the client, a basic DSN-based connection looks like::
30
+
31
+ engine = create_engine("mssql+pyodbc://scott:tiger@some_dsn")
32
+
33
+ Which above, will pass the following connection string to PyODBC:
34
+
35
+ .. sourcecode:: text
36
+
37
+ DSN=some_dsn;UID=scott;PWD=tiger
38
+
39
+ If the username and password are omitted, the DSN form will also add
40
+ the ``Trusted_Connection=yes`` directive to the ODBC string.
41
+
42
+ Hostname Connections
43
+ ^^^^^^^^^^^^^^^^^^^^
44
+
45
+ Hostname-based connections are also supported by pyodbc. These are often
46
+ easier to use than a DSN and have the additional advantage that the specific
47
+ database name to connect towards may be specified locally in the URL, rather
48
+ than it being fixed as part of a datasource configuration.
49
+
50
+ When using a hostname connection, the driver name must also be specified in the
51
+ query parameters of the URL. As these names usually have spaces in them, the
52
+ name must be URL encoded which means using plus signs for spaces::
53
+
54
+ engine = create_engine(
55
+ "mssql+pyodbc://scott:tiger@myhost:port/databasename?driver=ODBC+Driver+17+for+SQL+Server"
56
+ )
57
+
58
+ The ``driver`` keyword is significant to the pyodbc dialect and must be
59
+ specified in lowercase.
60
+
61
+ Any other names passed in the query string are passed through in the pyodbc
62
+ connect string, such as ``authentication``, ``TrustServerCertificate``, etc.
63
+ Multiple keyword arguments must be separated by an ampersand (``&``); these
64
+ will be translated to semicolons when the pyodbc connect string is generated
65
+ internally::
66
+
67
+ e = create_engine(
68
+ "mssql+pyodbc://scott:tiger@mssql2017:1433/test?"
69
+ "driver=ODBC+Driver+18+for+SQL+Server&TrustServerCertificate=yes"
70
+ "&authentication=ActiveDirectoryIntegrated"
71
+ )
72
+
73
+ The equivalent URL can be constructed using :class:`_sa.engine.URL`::
74
+
75
+ from sqlalchemy.engine import URL
76
+
77
+ connection_url = URL.create(
78
+ "mssql+pyodbc",
79
+ username="scott",
80
+ password="tiger",
81
+ host="mssql2017",
82
+ port=1433,
83
+ database="test",
84
+ query={
85
+ "driver": "ODBC Driver 18 for SQL Server",
86
+ "TrustServerCertificate": "yes",
87
+ "authentication": "ActiveDirectoryIntegrated",
88
+ },
89
+ )
90
+
91
+ Pass through exact Pyodbc string
92
+ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
93
+
94
+ A PyODBC connection string can also be sent in pyodbc's format directly, as
95
+ specified in `the PyODBC documentation
96
+ <https://github.com/mkleehammer/pyodbc/wiki/Connecting-to-databases>`_,
97
+ using the parameter ``odbc_connect``. A :class:`_sa.engine.URL` object
98
+ can help make this easier::
99
+
100
+ from sqlalchemy.engine import URL
101
+
102
+ connection_string = "DRIVER={SQL Server Native Client 10.0};SERVER=dagger;DATABASE=test;UID=user;PWD=password"
103
+ connection_url = URL.create(
104
+ "mssql+pyodbc", query={"odbc_connect": connection_string}
105
+ )
106
+
107
+ engine = create_engine(connection_url)
108
+
109
+ .. _mssql_pyodbc_access_tokens:
110
+
111
+ Connecting to databases with access tokens
112
+ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
113
+
114
+ Some database servers are set up to only accept access tokens for login. For
115
+ example, SQL Server allows the use of Azure Active Directory tokens to connect
116
+ to databases. This requires creating a credential object using the
117
+ ``azure-identity`` library. More information about the authentication step can be
118
+ found in `Microsoft's documentation
119
+ <https://docs.microsoft.com/en-us/azure/developer/python/azure-sdk-authenticate?tabs=bash>`_.
120
+
121
+ After getting an engine, the credentials need to be sent to ``pyodbc.connect``
122
+ each time a connection is requested. One way to do this is to set up an event
123
+ listener on the engine that adds the credential token to the dialect's connect
124
+ call. This is discussed more generally in :ref:`engines_dynamic_tokens`. For
125
+ SQL Server in particular, this is passed as an ODBC connection attribute with
126
+ a data structure `described by Microsoft
127
+ <https://docs.microsoft.com/en-us/sql/connect/odbc/using-azure-active-directory#authenticating-with-an-access-token>`_.
128
+
129
+ The following code snippet will create an engine that connects to an Azure SQL
130
+ database using Azure credentials::
131
+
132
+ import struct
133
+ from sqlalchemy import create_engine, event
134
+ from sqlalchemy.engine.url import URL
135
+ from azure import identity
136
+
137
+ # Connection option for access tokens, as defined in msodbcsql.h
138
+ SQL_COPT_SS_ACCESS_TOKEN = 1256
139
+ TOKEN_URL = "https://database.windows.net/" # The token URL for any Azure SQL database
140
+
141
+ connection_string = "mssql+pyodbc://@my-server.database.windows.net/myDb?driver=ODBC+Driver+17+for+SQL+Server"
142
+
143
+ engine = create_engine(connection_string)
144
+
145
+ azure_credentials = identity.DefaultAzureCredential()
146
+
147
+
148
+ @event.listens_for(engine, "do_connect")
149
+ def provide_token(dialect, conn_rec, cargs, cparams):
150
+ # remove the "Trusted_Connection" parameter that SQLAlchemy adds
151
+ cargs[0] = cargs[0].replace(";Trusted_Connection=Yes", "")
152
+
153
+ # create token credential
154
+ raw_token = azure_credentials.get_token(TOKEN_URL).token.encode(
155
+ "utf-16-le"
156
+ )
157
+ token_struct = struct.pack(
158
+ f"<I{len(raw_token)}s", len(raw_token), raw_token
159
+ )
160
+
161
+ # apply it to keyword arguments
162
+ cparams["attrs_before"] = {SQL_COPT_SS_ACCESS_TOKEN: token_struct}
163
+
164
+ .. tip::
165
+
166
+ The ``Trusted_Connection`` token is currently added by the SQLAlchemy
167
+ pyodbc dialect when no username or password is present. This needs
168
+ to be removed per Microsoft's
169
+ `documentation for Azure access tokens
170
+ <https://docs.microsoft.com/en-us/sql/connect/odbc/using-azure-active-directory#authenticating-with-an-access-token>`_,
171
+ stating that a connection string when using an access token must not contain
172
+ ``UID``, ``PWD``, ``Authentication`` or ``Trusted_Connection`` parameters.
173
+
174
+ .. _azure_synapse_ignore_no_transaction_on_rollback:
175
+
176
+ Avoiding transaction-related exceptions on Azure Synapse Analytics
177
+ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
178
+
179
+ Azure Synapse Analytics has a significant difference in its transaction
180
+ handling compared to plain SQL Server; in some cases an error within a Synapse
181
+ transaction can cause it to be arbitrarily terminated on the server side, which
182
+ then causes the DBAPI ``.rollback()`` method (as well as ``.commit()``) to
183
+ fail. The issue prevents the usual DBAPI contract of allowing ``.rollback()``
184
+ to pass silently if no transaction is present as the driver does not expect
185
+ this condition. The symptom of this failure is an exception with a message
186
+ resembling 'No corresponding transaction found. (111214)' when attempting to
187
+ emit a ``.rollback()`` after an operation had a failure of some kind.
188
+
189
+ This specific case can be handled by passing ``ignore_no_transaction_on_rollback=True`` to
190
+ the SQL Server dialect via the :func:`_sa.create_engine` function as follows::
191
+
192
+ engine = create_engine(
193
+ connection_url, ignore_no_transaction_on_rollback=True
194
+ )
195
+
196
+ Using the above parameter, the dialect will catch ``ProgrammingError``
197
+ exceptions raised during ``connection.rollback()`` and emit a warning
198
+ if the error message contains code ``111214``, however will not raise
199
+ an exception.
200
+
201
+ .. versionadded:: 1.4.40 Added the
202
+ ``ignore_no_transaction_on_rollback=True`` parameter.
203
+
204
+ Enable autocommit for Azure SQL Data Warehouse (DW) connections
205
+ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
206
+
207
+ Azure SQL Data Warehouse does not support transactions,
208
+ and that can cause problems with SQLAlchemy's "autobegin" (and implicit
209
+ commit/rollback) behavior. We can avoid these problems by enabling autocommit
210
+ at both the pyodbc and engine levels::
211
+
212
+ connection_url = sa.engine.URL.create(
213
+ "mssql+pyodbc",
214
+ username="scott",
215
+ password="tiger",
216
+ host="dw.azure.example.com",
217
+ database="mydb",
218
+ query={
219
+ "driver": "ODBC Driver 17 for SQL Server",
220
+ "autocommit": "True",
221
+ },
222
+ )
223
+
224
+ engine = create_engine(connection_url).execution_options(
225
+ isolation_level="AUTOCOMMIT"
226
+ )
227
+
228
+ Avoiding sending large string parameters as TEXT/NTEXT
229
+ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
230
+
231
+ By default, for historical reasons, Microsoft's ODBC drivers for SQL Server
232
+ send long string parameters (greater than 4000 SBCS characters or 2000 Unicode
233
+ characters) as TEXT/NTEXT values. TEXT and NTEXT have been deprecated for many
234
+ years and are starting to cause compatibility issues with newer versions of
235
+ SQL_Server/Azure. For example, see `this
236
+ issue <https://github.com/mkleehammer/pyodbc/issues/835>`_.
237
+
238
+ Starting with ODBC Driver 18 for SQL Server we can override the legacy
239
+ behavior and pass long strings as varchar(max)/nvarchar(max) using the
240
+ ``LongAsMax=Yes`` connection string parameter::
241
+
242
+ connection_url = sa.engine.URL.create(
243
+ "mssql+pyodbc",
244
+ username="scott",
245
+ password="tiger",
246
+ host="mssqlserver.example.com",
247
+ database="mydb",
248
+ query={
249
+ "driver": "ODBC Driver 18 for SQL Server",
250
+ "LongAsMax": "Yes",
251
+ },
252
+ )
253
+
254
+ Pyodbc Pooling / connection close behavior
255
+ ------------------------------------------
256
+
257
+ PyODBC uses internal `pooling
258
+ <https://github.com/mkleehammer/pyodbc/wiki/The-pyodbc-Module#pooling>`_ by
259
+ default, which means connections will be longer lived than they are within
260
+ SQLAlchemy itself. As SQLAlchemy has its own pooling behavior, it is often
261
+ preferable to disable this behavior. This behavior can only be disabled
262
+ globally at the PyODBC module level, **before** any connections are made::
263
+
264
+ import pyodbc
265
+
266
+ pyodbc.pooling = False
267
+
268
+ # don't use the engine before pooling is set to False
269
+ engine = create_engine("mssql+pyodbc://user:pass@dsn")
270
+
271
+ If this variable is left at its default value of ``True``, **the application
272
+ will continue to maintain active database connections**, even when the
273
+ SQLAlchemy engine itself fully discards a connection or if the engine is
274
+ disposed.
275
+
276
+ .. seealso::
277
+
278
+ `pooling <https://github.com/mkleehammer/pyodbc/wiki/The-pyodbc-Module#pooling>`_ -
279
+ in the PyODBC documentation.
280
+
281
+ Driver / Unicode Support
282
+ -------------------------
283
+
284
+ PyODBC works best with Microsoft ODBC drivers, particularly in the area
285
+ of Unicode support on both Python 2 and Python 3.
286
+
287
+ Using the FreeTDS ODBC drivers on Linux or OSX with PyODBC is **not**
288
+ recommended; there have been historically many Unicode-related issues
289
+ in this area, including before Microsoft offered ODBC drivers for Linux
290
+ and OSX. Now that Microsoft offers drivers for all platforms, for
291
+ PyODBC support these are recommended. FreeTDS remains relevant for
292
+ non-ODBC drivers such as pymssql where it works very well.
293
+
294
+
295
+ Rowcount Support
296
+ ----------------
297
+
298
+ Previous limitations with the SQLAlchemy ORM's "versioned rows" feature with
299
+ Pyodbc have been resolved as of SQLAlchemy 2.0.5. See the notes at
300
+ :ref:`mssql_rowcount_versioning`.
301
+
302
+ .. _mssql_pyodbc_fastexecutemany:
303
+
304
+ Fast Executemany Mode
305
+ ---------------------
306
+
307
+ The PyODBC driver includes support for a "fast executemany" mode of execution
308
+ which greatly reduces round trips for a DBAPI ``executemany()`` call when using
309
+ Microsoft ODBC drivers, for **limited size batches that fit in memory**. The
310
+ feature is enabled by setting the attribute ``.fast_executemany`` on the DBAPI
311
+ cursor when an executemany call is to be used. The SQLAlchemy PyODBC SQL
312
+ Server dialect supports this parameter by passing the
313
+ ``fast_executemany`` parameter to
314
+ :func:`_sa.create_engine` , when using the **Microsoft ODBC driver only**::
315
+
316
+ engine = create_engine(
317
+ "mssql+pyodbc://scott:tiger@mssql2017:1433/test?driver=ODBC+Driver+17+for+SQL+Server",
318
+ fast_executemany=True,
319
+ )
320
+
321
+ .. versionchanged:: 2.0.9 - the ``fast_executemany`` parameter now has its
322
+ intended effect of this PyODBC feature taking effect for all INSERT
323
+ statements that are executed with multiple parameter sets, which don't
324
+ include RETURNING. Previously, SQLAlchemy 2.0's :term:`insertmanyvalues`
325
+ feature would cause ``fast_executemany`` to not be used in most cases
326
+ even if specified.
327
+
328
+ .. versionadded:: 1.3
329
+
330
+ .. seealso::
331
+
332
+ `fast executemany <https://github.com/mkleehammer/pyodbc/wiki/Features-beyond-the-DB-API#fast_executemany>`_
333
+ - on github
334
+
335
+ .. _mssql_pyodbc_setinputsizes:
336
+
337
+ Setinputsizes Support
338
+ -----------------------
339
+
340
+ As of version 2.0, the pyodbc ``cursor.setinputsizes()`` method is used for
341
+ all statement executions, except for ``cursor.executemany()`` calls when
342
+ fast_executemany=True where it is not supported (assuming
343
+ :ref:`insertmanyvalues <engine_insertmanyvalues>` is kept enabled,
344
+ "fastexecutemany" will not take place for INSERT statements in any case).
345
+
346
+ The use of ``cursor.setinputsizes()`` can be disabled by passing
347
+ ``use_setinputsizes=False`` to :func:`_sa.create_engine`.
348
+
349
+ When ``use_setinputsizes`` is left at its default of ``True``, the
350
+ specific per-type symbols passed to ``cursor.setinputsizes()`` can be
351
+ programmatically customized using the :meth:`.DialectEvents.do_setinputsizes`
352
+ hook. See that method for usage examples.
353
+
354
+ .. versionchanged:: 2.0 The mssql+pyodbc dialect now defaults to using
355
+ ``use_setinputsizes=True`` for all statement executions with the exception of
356
+ cursor.executemany() calls when fast_executemany=True. The behavior can
357
+ be turned off by passing ``use_setinputsizes=False`` to
358
+ :func:`_sa.create_engine`.
359
+
360
+ """ # noqa
361
+
362
+
363
+ import datetime
364
+ import decimal
365
+ import re
366
+ import struct
367
+
368
+ from .base import _MSDateTime
369
+ from .base import _MSUnicode
370
+ from .base import _MSUnicodeText
371
+ from .base import BINARY
372
+ from .base import DATETIMEOFFSET
373
+ from .base import MSDialect
374
+ from .base import MSExecutionContext
375
+ from .base import VARBINARY
376
+ from .json import JSON as _MSJson
377
+ from .json import JSONIndexType as _MSJsonIndexType
378
+ from .json import JSONPathType as _MSJsonPathType
379
+ from ... import exc
380
+ from ... import types as sqltypes
381
+ from ... import util
382
+ from ...connectors.pyodbc import PyODBCConnector
383
+ from ...engine import cursor as _cursor
384
+
385
+
386
+ class _ms_numeric_pyodbc:
387
+ """Turns Decimals with adjusted() < 0 or > 7 into strings.
388
+
389
+ The routines here are needed for older pyodbc versions
390
+ as well as current mxODBC versions.
391
+
392
+ """
393
+
394
+ def bind_processor(self, dialect):
395
+ super_process = super().bind_processor(dialect)
396
+
397
+ if not dialect._need_decimal_fix:
398
+ return super_process
399
+
400
+ def process(value):
401
+ if self.asdecimal and isinstance(value, decimal.Decimal):
402
+ adjusted = value.adjusted()
403
+ if adjusted < 0:
404
+ return self._small_dec_to_string(value)
405
+ elif adjusted > 7:
406
+ return self._large_dec_to_string(value)
407
+
408
+ if super_process:
409
+ return super_process(value)
410
+ else:
411
+ return value
412
+
413
+ return process
414
+
415
+ # these routines needed for older versions of pyodbc.
416
+ # as of 2.1.8 this logic is integrated.
417
+
418
+ def _small_dec_to_string(self, value):
419
+ return "%s0.%s%s" % (
420
+ (value < 0 and "-" or ""),
421
+ "0" * (abs(value.adjusted()) - 1),
422
+ "".join([str(nint) for nint in value.as_tuple()[1]]),
423
+ )
424
+
425
+ def _large_dec_to_string(self, value):
426
+ _int = value.as_tuple()[1]
427
+ if "E" in str(value):
428
+ result = "%s%s%s" % (
429
+ (value < 0 and "-" or ""),
430
+ "".join([str(s) for s in _int]),
431
+ "0" * (value.adjusted() - (len(_int) - 1)),
432
+ )
433
+ else:
434
+ if (len(_int) - 1) > value.adjusted():
435
+ result = "%s%s.%s" % (
436
+ (value < 0 and "-" or ""),
437
+ "".join([str(s) for s in _int][0 : value.adjusted() + 1]),
438
+ "".join([str(s) for s in _int][value.adjusted() + 1 :]),
439
+ )
440
+ else:
441
+ result = "%s%s" % (
442
+ (value < 0 and "-" or ""),
443
+ "".join([str(s) for s in _int][0 : value.adjusted() + 1]),
444
+ )
445
+ return result
446
+
447
+
448
+ class _MSNumeric_pyodbc(_ms_numeric_pyodbc, sqltypes.Numeric):
449
+ pass
450
+
451
+
452
+ class _MSFloat_pyodbc(_ms_numeric_pyodbc, sqltypes.Float):
453
+ pass
454
+
455
+
456
+ class _ms_binary_pyodbc:
457
+ """Wraps binary values in dialect-specific Binary wrapper.
458
+ If the value is null, return a pyodbc-specific BinaryNull
459
+ object to prevent pyODBC [and FreeTDS] from defaulting binary
460
+ NULL types to SQLWCHAR and causing implicit conversion errors.
461
+ """
462
+
463
+ def bind_processor(self, dialect):
464
+ if dialect.dbapi is None:
465
+ return None
466
+
467
+ DBAPIBinary = dialect.dbapi.Binary
468
+
469
+ def process(value):
470
+ if value is not None:
471
+ return DBAPIBinary(value)
472
+ else:
473
+ # pyodbc-specific
474
+ return dialect.dbapi.BinaryNull
475
+
476
+ return process
477
+
478
+
479
+ class _ODBCDateTimeBindProcessor:
480
+ """Add bind processors to handle datetimeoffset behaviors"""
481
+
482
+ has_tz = False
483
+
484
+ def bind_processor(self, dialect):
485
+ def process(value):
486
+ if value is None:
487
+ return None
488
+ elif isinstance(value, str):
489
+ # if a string was passed directly, allow it through
490
+ return value
491
+ elif not value.tzinfo or (not self.timezone and not self.has_tz):
492
+ # for DateTime(timezone=False)
493
+ return value
494
+ else:
495
+ # for DATETIMEOFFSET or DateTime(timezone=True)
496
+ #
497
+ # Convert to string format required by T-SQL
498
+ dto_string = value.strftime("%Y-%m-%d %H:%M:%S.%f %z")
499
+ # offset needs a colon, e.g., -0700 -> -07:00
500
+ # "UTC offset in the form (+-)HHMM[SS[.ffffff]]"
501
+ # backend currently rejects seconds / fractional seconds
502
+ dto_string = re.sub(
503
+ r"([\+\-]\d{2})([\d\.]+)$", r"\1:\2", dto_string
504
+ )
505
+ return dto_string
506
+
507
+ return process
508
+
509
+
510
+ class _ODBCDateTime(_ODBCDateTimeBindProcessor, _MSDateTime):
511
+ pass
512
+
513
+
514
+ class _ODBCDATETIMEOFFSET(_ODBCDateTimeBindProcessor, DATETIMEOFFSET):
515
+ has_tz = True
516
+
517
+
518
+ class _VARBINARY_pyodbc(_ms_binary_pyodbc, VARBINARY):
519
+ pass
520
+
521
+
522
+ class _BINARY_pyodbc(_ms_binary_pyodbc, BINARY):
523
+ pass
524
+
525
+
526
+ class _String_pyodbc(sqltypes.String):
527
+ def get_dbapi_type(self, dbapi):
528
+ if self.length in (None, "max") or self.length >= 2000:
529
+ return (dbapi.SQL_VARCHAR, 0, 0)
530
+ else:
531
+ return dbapi.SQL_VARCHAR
532
+
533
+
534
+ class _Unicode_pyodbc(_MSUnicode):
535
+ def get_dbapi_type(self, dbapi):
536
+ if self.length in (None, "max") or self.length >= 2000:
537
+ return (dbapi.SQL_WVARCHAR, 0, 0)
538
+ else:
539
+ return dbapi.SQL_WVARCHAR
540
+
541
+
542
+ class _UnicodeText_pyodbc(_MSUnicodeText):
543
+ def get_dbapi_type(self, dbapi):
544
+ if self.length in (None, "max") or self.length >= 2000:
545
+ return (dbapi.SQL_WVARCHAR, 0, 0)
546
+ else:
547
+ return dbapi.SQL_WVARCHAR
548
+
549
+
550
+ class _JSON_pyodbc(_MSJson):
551
+ def get_dbapi_type(self, dbapi):
552
+ return (dbapi.SQL_WVARCHAR, 0, 0)
553
+
554
+
555
+ class _JSONIndexType_pyodbc(_MSJsonIndexType):
556
+ def get_dbapi_type(self, dbapi):
557
+ return dbapi.SQL_WVARCHAR
558
+
559
+
560
+ class _JSONPathType_pyodbc(_MSJsonPathType):
561
+ def get_dbapi_type(self, dbapi):
562
+ return dbapi.SQL_WVARCHAR
563
+
564
+
565
+ class MSExecutionContext_pyodbc(MSExecutionContext):
566
+ _embedded_scope_identity = False
567
+
568
+ def pre_exec(self):
569
+ """where appropriate, issue "select scope_identity()" in the same
570
+ statement.
571
+
572
+ Background on why "scope_identity()" is preferable to "@@identity":
573
+ https://msdn.microsoft.com/en-us/library/ms190315.aspx
574
+
575
+ Background on why we attempt to embed "scope_identity()" into the same
576
+ statement as the INSERT:
577
+ https://code.google.com/p/pyodbc/wiki/FAQs#How_do_I_retrieve_autogenerated/identity_values?
578
+
579
+ """
580
+
581
+ super().pre_exec()
582
+
583
+ # don't embed the scope_identity select into an
584
+ # "INSERT .. DEFAULT VALUES"
585
+ if (
586
+ self._select_lastrowid
587
+ and self.dialect.use_scope_identity
588
+ and len(self.parameters[0])
589
+ ):
590
+ self._embedded_scope_identity = True
591
+
592
+ self.statement += "; select scope_identity()"
593
+
594
+ def post_exec(self):
595
+ if self._embedded_scope_identity:
596
+ # Fetch the last inserted id from the manipulated statement
597
+ # We may have to skip over a number of result sets with
598
+ # no data (due to triggers, etc.)
599
+ while True:
600
+ try:
601
+ # fetchall() ensures the cursor is consumed
602
+ # without closing it (FreeTDS particularly)
603
+ rows = self.cursor.fetchall()
604
+ except self.dialect.dbapi.Error:
605
+ # no way around this - nextset() consumes the previous set
606
+ # so we need to just keep flipping
607
+ self.cursor.nextset()
608
+ else:
609
+ if not rows:
610
+ # async adapter drivers just return None here
611
+ self.cursor.nextset()
612
+ continue
613
+ row = rows[0]
614
+ break
615
+
616
+ self._lastrowid = int(row[0])
617
+
618
+ self.cursor_fetch_strategy = _cursor._NO_CURSOR_DML
619
+ else:
620
+ super().post_exec()
621
+
622
+
623
+ class MSDialect_pyodbc(PyODBCConnector, MSDialect):
624
+ supports_statement_cache = True
625
+
626
+ # note this parameter is no longer used by the ORM or default dialect
627
+ # see #9414
628
+ supports_sane_rowcount_returning = False
629
+
630
+ execution_ctx_cls = MSExecutionContext_pyodbc
631
+
632
+ colspecs = util.update_copy(
633
+ MSDialect.colspecs,
634
+ {
635
+ sqltypes.Numeric: _MSNumeric_pyodbc,
636
+ sqltypes.Float: _MSFloat_pyodbc,
637
+ BINARY: _BINARY_pyodbc,
638
+ # support DateTime(timezone=True)
639
+ sqltypes.DateTime: _ODBCDateTime,
640
+ DATETIMEOFFSET: _ODBCDATETIMEOFFSET,
641
+ # SQL Server dialect has a VARBINARY that is just to support
642
+ # "deprecate_large_types" w/ VARBINARY(max), but also we must
643
+ # handle the usual SQL standard VARBINARY
644
+ VARBINARY: _VARBINARY_pyodbc,
645
+ sqltypes.VARBINARY: _VARBINARY_pyodbc,
646
+ sqltypes.LargeBinary: _VARBINARY_pyodbc,
647
+ sqltypes.String: _String_pyodbc,
648
+ sqltypes.Unicode: _Unicode_pyodbc,
649
+ sqltypes.UnicodeText: _UnicodeText_pyodbc,
650
+ sqltypes.JSON: _JSON_pyodbc,
651
+ sqltypes.JSON.JSONIndexType: _JSONIndexType_pyodbc,
652
+ sqltypes.JSON.JSONPathType: _JSONPathType_pyodbc,
653
+ # this excludes Enum from the string/VARCHAR thing for now
654
+ # it looks like Enum's adaptation doesn't really support the
655
+ # String type itself having a dialect-level impl
656
+ sqltypes.Enum: sqltypes.Enum,
657
+ },
658
+ )
659
+
660
+ def __init__(
661
+ self,
662
+ fast_executemany=False,
663
+ use_setinputsizes=True,
664
+ **params,
665
+ ):
666
+ super().__init__(use_setinputsizes=use_setinputsizes, **params)
667
+ self.use_scope_identity = (
668
+ self.use_scope_identity
669
+ and self.dbapi
670
+ and hasattr(self.dbapi.Cursor, "nextset")
671
+ )
672
+ self._need_decimal_fix = self.dbapi and self._dbapi_version() < (
673
+ 2,
674
+ 1,
675
+ 8,
676
+ )
677
+ self.fast_executemany = fast_executemany
678
+ if fast_executemany:
679
+ self.use_insertmanyvalues_wo_returning = False
680
+
681
+ def _get_server_version_info(self, connection):
682
+ try:
683
+ # "Version of the instance of SQL Server, in the form
684
+ # of 'major.minor.build.revision'"
685
+ raw = connection.exec_driver_sql(
686
+ "SELECT CAST(SERVERPROPERTY('ProductVersion') AS VARCHAR)"
687
+ ).scalar()
688
+ except exc.DBAPIError:
689
+ # SQL Server docs indicate this function isn't present prior to
690
+ # 2008. Before we had the VARCHAR cast above, pyodbc would also
691
+ # fail on this query.
692
+ return super()._get_server_version_info(connection)
693
+ else:
694
+ version = []
695
+ r = re.compile(r"[.\-]")
696
+ for n in r.split(raw):
697
+ try:
698
+ version.append(int(n))
699
+ except ValueError:
700
+ pass
701
+ return tuple(version)
702
+
703
+ def on_connect(self):
704
+ super_ = super().on_connect()
705
+
706
+ def on_connect(conn):
707
+ if super_ is not None:
708
+ super_(conn)
709
+
710
+ self._setup_timestampoffset_type(conn)
711
+
712
+ return on_connect
713
+
714
+ def _setup_timestampoffset_type(self, connection):
715
+ # output converter function for datetimeoffset
716
+ def _handle_datetimeoffset(dto_value):
717
+ tup = struct.unpack("<6hI2h", dto_value)
718
+ return datetime.datetime(
719
+ tup[0],
720
+ tup[1],
721
+ tup[2],
722
+ tup[3],
723
+ tup[4],
724
+ tup[5],
725
+ tup[6] // 1000,
726
+ datetime.timezone(
727
+ datetime.timedelta(hours=tup[7], minutes=tup[8])
728
+ ),
729
+ )
730
+
731
+ odbc_SQL_SS_TIMESTAMPOFFSET = -155 # as defined in SQLNCLI.h
732
+ connection.add_output_converter(
733
+ odbc_SQL_SS_TIMESTAMPOFFSET, _handle_datetimeoffset
734
+ )
735
+
736
+ def do_executemany(self, cursor, statement, parameters, context=None):
737
+ if self.fast_executemany:
738
+ cursor.fast_executemany = True
739
+ super().do_executemany(cursor, statement, parameters, context=context)
740
+
741
+ def is_disconnect(self, e, connection, cursor):
742
+ if isinstance(e, self.dbapi.Error):
743
+ code = e.args[0]
744
+ if code in {
745
+ "08S01",
746
+ "01000",
747
+ "01002",
748
+ "08003",
749
+ "08007",
750
+ "08S02",
751
+ "08001",
752
+ "HYT00",
753
+ "HY010",
754
+ "10054",
755
+ }:
756
+ return True
757
+ return super().is_disconnect(e, connection, cursor)
758
+
759
+
760
+ dialect = MSDialect_pyodbc
loan-advisor-agent/.venv/Lib/site-packages/sqlalchemy/dialects/mysql/__init__.py ADDED
@@ -0,0 +1,104 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # dialects/mysql/__init__.py
2
+ # Copyright (C) 2005-2026 the SQLAlchemy authors and contributors
3
+ # <see AUTHORS file>
4
+ #
5
+ # This module is part of SQLAlchemy and is released under
6
+ # the MIT License: https://www.opensource.org/licenses/mit-license.php
7
+ # mypy: ignore-errors
8
+
9
+
10
+ from . import aiomysql # noqa
11
+ from . import asyncmy # noqa
12
+ from . import base # noqa
13
+ from . import cymysql # noqa
14
+ from . import mariadbconnector # noqa
15
+ from . import mysqlconnector # noqa
16
+ from . import mysqldb # noqa
17
+ from . import pymysql # noqa
18
+ from . import pyodbc # noqa
19
+ from .base import BIGINT
20
+ from .base import BINARY
21
+ from .base import BIT
22
+ from .base import BLOB
23
+ from .base import BOOLEAN
24
+ from .base import CHAR
25
+ from .base import DATE
26
+ from .base import DATETIME
27
+ from .base import DECIMAL
28
+ from .base import DOUBLE
29
+ from .base import ENUM
30
+ from .base import FLOAT
31
+ from .base import INTEGER
32
+ from .base import JSON
33
+ from .base import LONGBLOB
34
+ from .base import LONGTEXT
35
+ from .base import MEDIUMBLOB
36
+ from .base import MEDIUMINT
37
+ from .base import MEDIUMTEXT
38
+ from .base import NCHAR
39
+ from .base import NUMERIC
40
+ from .base import NVARCHAR
41
+ from .base import REAL
42
+ from .base import SET
43
+ from .base import SMALLINT
44
+ from .base import TEXT
45
+ from .base import TIME
46
+ from .base import TIMESTAMP
47
+ from .base import TINYBLOB
48
+ from .base import TINYINT
49
+ from .base import TINYTEXT
50
+ from .base import VARBINARY
51
+ from .base import VARCHAR
52
+ from .base import YEAR
53
+ from .dml import Insert
54
+ from .dml import insert
55
+ from .expression import match
56
+ from .mariadb import INET4
57
+ from .mariadb import INET6
58
+
59
+ # default dialect
60
+ base.dialect = dialect = mysqldb.dialect
61
+
62
+ __all__ = (
63
+ "BIGINT",
64
+ "BINARY",
65
+ "BIT",
66
+ "BLOB",
67
+ "BOOLEAN",
68
+ "CHAR",
69
+ "DATE",
70
+ "DATETIME",
71
+ "DECIMAL",
72
+ "DOUBLE",
73
+ "ENUM",
74
+ "FLOAT",
75
+ "INET4",
76
+ "INET6",
77
+ "INTEGER",
78
+ "INTEGER",
79
+ "JSON",
80
+ "LONGBLOB",
81
+ "LONGTEXT",
82
+ "MEDIUMBLOB",
83
+ "MEDIUMINT",
84
+ "MEDIUMTEXT",
85
+ "NCHAR",
86
+ "NVARCHAR",
87
+ "NUMERIC",
88
+ "SET",
89
+ "SMALLINT",
90
+ "REAL",
91
+ "TEXT",
92
+ "TIME",
93
+ "TIMESTAMP",
94
+ "TINYBLOB",
95
+ "TINYINT",
96
+ "TINYTEXT",
97
+ "VARBINARY",
98
+ "VARCHAR",
99
+ "YEAR",
100
+ "dialect",
101
+ "insert",
102
+ "Insert",
103
+ "match",
104
+ )
loan-advisor-agent/.venv/Lib/site-packages/sqlalchemy/dialects/mysql/aiomysql.py ADDED
@@ -0,0 +1,250 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # dialects/mysql/aiomysql.py
2
+ # Copyright (C) 2005-2026 the SQLAlchemy authors and contributors <see AUTHORS
3
+ # file>
4
+ #
5
+ # This module is part of SQLAlchemy and is released under
6
+ # the MIT License: https://www.opensource.org/licenses/mit-license.php
7
+
8
+ r"""
9
+ .. dialect:: mysql+aiomysql
10
+ :name: aiomysql
11
+ :dbapi: aiomysql
12
+ :connectstring: mysql+aiomysql://user:password@host:port/dbname[?key=value&key=value...]
13
+ :url: https://github.com/aio-libs/aiomysql
14
+
15
+ The aiomysql dialect is SQLAlchemy's second Python asyncio dialect.
16
+
17
+ Using a special asyncio mediation layer, the aiomysql dialect is usable
18
+ as the backend for the :ref:`SQLAlchemy asyncio <asyncio_toplevel>`
19
+ extension package.
20
+
21
+ This dialect should normally be used only with the
22
+ :func:`_asyncio.create_async_engine` engine creation function::
23
+
24
+ from sqlalchemy.ext.asyncio import create_async_engine
25
+
26
+ engine = create_async_engine(
27
+ "mysql+aiomysql://user:pass@hostname/dbname?charset=utf8mb4"
28
+ )
29
+
30
+ """ # noqa
31
+ from __future__ import annotations
32
+
33
+ from types import ModuleType
34
+ from typing import Any
35
+ from typing import Dict
36
+ from typing import Optional
37
+ from typing import Tuple
38
+ from typing import TYPE_CHECKING
39
+ from typing import Union
40
+
41
+ from .pymysql import MySQLDialect_pymysql
42
+ from ... import pool
43
+ from ... import util
44
+ from ...connectors.asyncio import AsyncAdapt_dbapi_connection
45
+ from ...connectors.asyncio import AsyncAdapt_dbapi_cursor
46
+ from ...connectors.asyncio import AsyncAdapt_dbapi_module
47
+ from ...connectors.asyncio import AsyncAdapt_dbapi_ss_cursor
48
+ from ...connectors.asyncio import AsyncAdapt_terminate
49
+ from ...util.concurrency import await_fallback
50
+ from ...util.concurrency import await_only
51
+
52
+ if TYPE_CHECKING:
53
+
54
+ from ...connectors.asyncio import AsyncIODBAPIConnection
55
+ from ...connectors.asyncio import AsyncIODBAPICursor
56
+ from ...engine.interfaces import ConnectArgsType
57
+ from ...engine.interfaces import DBAPIConnection
58
+ from ...engine.interfaces import DBAPICursor
59
+ from ...engine.interfaces import DBAPIModule
60
+ from ...engine.interfaces import PoolProxiedConnection
61
+ from ...engine.url import URL
62
+
63
+
64
+ class AsyncAdapt_aiomysql_cursor(AsyncAdapt_dbapi_cursor):
65
+ __slots__ = ()
66
+
67
+ def _make_new_cursor(
68
+ self, connection: AsyncIODBAPIConnection
69
+ ) -> AsyncIODBAPICursor:
70
+ return connection.cursor(self._adapt_connection.dbapi.Cursor)
71
+
72
+
73
+ class AsyncAdapt_aiomysql_ss_cursor(
74
+ AsyncAdapt_dbapi_ss_cursor, AsyncAdapt_aiomysql_cursor
75
+ ):
76
+ __slots__ = ()
77
+
78
+ def _make_new_cursor(
79
+ self, connection: AsyncIODBAPIConnection
80
+ ) -> AsyncIODBAPICursor:
81
+ return connection.cursor(
82
+ self._adapt_connection.dbapi.aiomysql.cursors.SSCursor
83
+ )
84
+
85
+
86
+ class AsyncAdapt_aiomysql_connection(
87
+ AsyncAdapt_terminate, AsyncAdapt_dbapi_connection
88
+ ):
89
+ __slots__ = ()
90
+
91
+ _cursor_cls = AsyncAdapt_aiomysql_cursor
92
+ _ss_cursor_cls = AsyncAdapt_aiomysql_ss_cursor
93
+
94
+ def ping(self, reconnect: bool) -> None:
95
+ assert not reconnect
96
+ self.await_(self._connection.ping(reconnect))
97
+
98
+ def character_set_name(self) -> Optional[str]:
99
+ return self._connection.character_set_name() # type: ignore[no-any-return] # noqa: E501
100
+
101
+ def autocommit(self, value: Any) -> None:
102
+ self.await_(self._connection.autocommit(value))
103
+
104
+ def get_autocommit(self) -> bool:
105
+ return self._connection.get_autocommit() # type: ignore
106
+
107
+ def close(self) -> None:
108
+ self.await_(self._connection.ensure_closed())
109
+
110
+ async def _terminate_graceful_close(self) -> None:
111
+ await self._connection.ensure_closed()
112
+
113
+ def _terminate_force_close(self) -> None:
114
+ # it's not awaitable.
115
+ self._connection.close()
116
+
117
+
118
+ class AsyncAdaptFallback_aiomysql_connection(AsyncAdapt_aiomysql_connection):
119
+ __slots__ = ()
120
+
121
+ await_ = staticmethod(await_fallback)
122
+
123
+
124
+ class AsyncAdapt_aiomysql_dbapi(AsyncAdapt_dbapi_module):
125
+ def __init__(self, aiomysql: ModuleType, pymysql: ModuleType):
126
+ self.aiomysql = aiomysql
127
+ self.pymysql = pymysql
128
+ self.paramstyle = "format"
129
+ self._init_dbapi_attributes()
130
+ self.Cursor, self.SSCursor = self._init_cursors_subclasses()
131
+
132
+ def _init_dbapi_attributes(self) -> None:
133
+ for name in (
134
+ "Warning",
135
+ "Error",
136
+ "InterfaceError",
137
+ "DataError",
138
+ "DatabaseError",
139
+ "OperationalError",
140
+ "InterfaceError",
141
+ "IntegrityError",
142
+ "ProgrammingError",
143
+ "InternalError",
144
+ "NotSupportedError",
145
+ ):
146
+ setattr(self, name, getattr(self.aiomysql, name))
147
+
148
+ for name in (
149
+ "NUMBER",
150
+ "STRING",
151
+ "DATETIME",
152
+ "BINARY",
153
+ "TIMESTAMP",
154
+ "Binary",
155
+ ):
156
+ setattr(self, name, getattr(self.pymysql, name))
157
+
158
+ def connect(self, *arg: Any, **kw: Any) -> AsyncAdapt_aiomysql_connection:
159
+ async_fallback = kw.pop("async_fallback", False)
160
+ creator_fn = kw.pop("async_creator_fn", self.aiomysql.connect)
161
+
162
+ if util.asbool(async_fallback):
163
+ return AsyncAdaptFallback_aiomysql_connection(
164
+ self,
165
+ await_fallback(creator_fn(*arg, **kw)),
166
+ )
167
+ else:
168
+ return AsyncAdapt_aiomysql_connection(
169
+ self,
170
+ await_only(creator_fn(*arg, **kw)),
171
+ )
172
+
173
+ def _init_cursors_subclasses(
174
+ self,
175
+ ) -> Tuple[AsyncIODBAPICursor, AsyncIODBAPICursor]:
176
+ # suppress unconditional warning emitted by aiomysql
177
+ class Cursor(self.aiomysql.Cursor): # type: ignore[misc, name-defined]
178
+ async def _show_warnings(
179
+ self, conn: AsyncIODBAPIConnection
180
+ ) -> None:
181
+ pass
182
+
183
+ class SSCursor(self.aiomysql.SSCursor): # type: ignore[misc, name-defined] # noqa: E501
184
+ async def _show_warnings(
185
+ self, conn: AsyncIODBAPIConnection
186
+ ) -> None:
187
+ pass
188
+
189
+ return Cursor, SSCursor # type: ignore[return-value]
190
+
191
+
192
+ class MySQLDialect_aiomysql(MySQLDialect_pymysql):
193
+ driver = "aiomysql"
194
+ supports_statement_cache = True
195
+
196
+ supports_server_side_cursors = True
197
+ _sscursor = AsyncAdapt_aiomysql_ss_cursor
198
+
199
+ is_async = True
200
+ has_terminate = True
201
+
202
+ @classmethod
203
+ def import_dbapi(cls) -> AsyncAdapt_aiomysql_dbapi:
204
+ return AsyncAdapt_aiomysql_dbapi(
205
+ __import__("aiomysql"), __import__("pymysql")
206
+ )
207
+
208
+ @classmethod
209
+ def get_pool_class(cls, url: URL) -> type:
210
+ async_fallback = url.query.get("async_fallback", False)
211
+
212
+ if util.asbool(async_fallback):
213
+ return pool.FallbackAsyncAdaptedQueuePool
214
+ else:
215
+ return pool.AsyncAdaptedQueuePool
216
+
217
+ def do_terminate(self, dbapi_connection: DBAPIConnection) -> None:
218
+ dbapi_connection.terminate()
219
+
220
+ def create_connect_args(
221
+ self, url: URL, _translate_args: Optional[Dict[str, Any]] = None
222
+ ) -> ConnectArgsType:
223
+ return super().create_connect_args(
224
+ url, _translate_args=dict(username="user", database="db")
225
+ )
226
+
227
+ def is_disconnect(
228
+ self,
229
+ e: DBAPIModule.Error,
230
+ connection: Optional[Union[PoolProxiedConnection, DBAPIConnection]],
231
+ cursor: Optional[DBAPICursor],
232
+ ) -> bool:
233
+ if super().is_disconnect(e, connection, cursor):
234
+ return True
235
+ else:
236
+ str_e = str(e).lower()
237
+ return "not connected" in str_e
238
+
239
+ def _found_rows_client_flag(self) -> int:
240
+ from pymysql.constants import CLIENT # type: ignore
241
+
242
+ return CLIENT.FOUND_ROWS # type: ignore[no-any-return]
243
+
244
+ def get_driver_connection(
245
+ self, connection: DBAPIConnection
246
+ ) -> AsyncIODBAPIConnection:
247
+ return connection._connection # type: ignore[no-any-return]
248
+
249
+
250
+ dialect = MySQLDialect_aiomysql
loan-advisor-agent/.venv/Lib/site-packages/sqlalchemy/dialects/mysql/asyncmy.py ADDED
@@ -0,0 +1,231 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # dialects/mysql/asyncmy.py
2
+ # Copyright (C) 2005-2026 the SQLAlchemy authors and contributors <see AUTHORS
3
+ # file>
4
+ #
5
+ # This module is part of SQLAlchemy and is released under
6
+ # the MIT License: https://www.opensource.org/licenses/mit-license.php
7
+
8
+ r"""
9
+ .. dialect:: mysql+asyncmy
10
+ :name: asyncmy
11
+ :dbapi: asyncmy
12
+ :connectstring: mysql+asyncmy://user:password@host:port/dbname[?key=value&key=value...]
13
+ :url: https://github.com/long2ice/asyncmy
14
+
15
+ Using a special asyncio mediation layer, the asyncmy dialect is usable
16
+ as the backend for the :ref:`SQLAlchemy asyncio <asyncio_toplevel>`
17
+ extension package.
18
+
19
+ This dialect should normally be used only with the
20
+ :func:`_asyncio.create_async_engine` engine creation function::
21
+
22
+ from sqlalchemy.ext.asyncio import create_async_engine
23
+
24
+ engine = create_async_engine(
25
+ "mysql+asyncmy://user:pass@hostname/dbname?charset=utf8mb4"
26
+ )
27
+
28
+ """ # noqa
29
+ from __future__ import annotations
30
+
31
+ from types import ModuleType
32
+ from typing import Any
33
+ from typing import NoReturn
34
+ from typing import Optional
35
+ from typing import TYPE_CHECKING
36
+ from typing import Union
37
+
38
+ from .pymysql import MySQLDialect_pymysql
39
+ from ... import pool
40
+ from ... import util
41
+ from ...connectors.asyncio import AsyncAdapt_dbapi_connection
42
+ from ...connectors.asyncio import AsyncAdapt_dbapi_cursor
43
+ from ...connectors.asyncio import AsyncAdapt_dbapi_module
44
+ from ...connectors.asyncio import AsyncAdapt_dbapi_ss_cursor
45
+ from ...connectors.asyncio import AsyncAdapt_terminate
46
+ from ...util.concurrency import await_fallback
47
+ from ...util.concurrency import await_only
48
+
49
+ if TYPE_CHECKING:
50
+ from ...connectors.asyncio import AsyncIODBAPIConnection
51
+ from ...connectors.asyncio import AsyncIODBAPICursor
52
+ from ...engine.interfaces import ConnectArgsType
53
+ from ...engine.interfaces import DBAPIConnection
54
+ from ...engine.interfaces import DBAPICursor
55
+ from ...engine.interfaces import DBAPIModule
56
+ from ...engine.interfaces import PoolProxiedConnection
57
+ from ...engine.url import URL
58
+
59
+
60
+ class AsyncAdapt_asyncmy_cursor(AsyncAdapt_dbapi_cursor):
61
+ __slots__ = ()
62
+
63
+
64
+ class AsyncAdapt_asyncmy_ss_cursor(
65
+ AsyncAdapt_dbapi_ss_cursor, AsyncAdapt_asyncmy_cursor
66
+ ):
67
+ __slots__ = ()
68
+
69
+ def _make_new_cursor(
70
+ self, connection: AsyncIODBAPIConnection
71
+ ) -> AsyncIODBAPICursor:
72
+ return connection.cursor(
73
+ self._adapt_connection.dbapi.asyncmy.cursors.SSCursor
74
+ )
75
+
76
+
77
+ class AsyncAdapt_asyncmy_connection(
78
+ AsyncAdapt_terminate, AsyncAdapt_dbapi_connection
79
+ ):
80
+ __slots__ = ()
81
+
82
+ _cursor_cls = AsyncAdapt_asyncmy_cursor
83
+ _ss_cursor_cls = AsyncAdapt_asyncmy_ss_cursor
84
+
85
+ def _handle_exception(self, error: Exception) -> NoReturn:
86
+ if isinstance(error, AttributeError):
87
+ raise self.dbapi.InternalError(
88
+ "network operation failed due to asyncmy attribute error"
89
+ )
90
+
91
+ raise error
92
+
93
+ def ping(self, reconnect: bool) -> None:
94
+ assert not reconnect
95
+ return self.await_(self._do_ping())
96
+
97
+ async def _do_ping(self) -> None:
98
+ try:
99
+ async with self._execute_mutex:
100
+ await self._connection.ping(False)
101
+ except Exception as error:
102
+ self._handle_exception(error)
103
+
104
+ def character_set_name(self) -> Optional[str]:
105
+ return self._connection.character_set_name() # type: ignore[no-any-return] # noqa: E501
106
+
107
+ def autocommit(self, value: Any) -> None:
108
+ self.await_(self._connection.autocommit(value))
109
+
110
+ def get_autocommit(self) -> bool:
111
+ return self._connection.get_autocommit() # type: ignore
112
+
113
+ def close(self) -> None:
114
+ self.await_(self._connection.ensure_closed())
115
+
116
+ async def _terminate_graceful_close(self) -> None:
117
+ await self._connection.ensure_closed()
118
+
119
+ def _terminate_force_close(self) -> None:
120
+ # it's not awaitable.
121
+ self._connection.close()
122
+
123
+
124
+ class AsyncAdaptFallback_asyncmy_connection(AsyncAdapt_asyncmy_connection):
125
+ __slots__ = ()
126
+
127
+ await_ = staticmethod(await_fallback)
128
+
129
+
130
+ class AsyncAdapt_asyncmy_dbapi(AsyncAdapt_dbapi_module):
131
+ def __init__(self, asyncmy: ModuleType):
132
+ self.asyncmy = asyncmy
133
+ self.paramstyle = "format"
134
+ self._init_dbapi_attributes()
135
+
136
+ def _init_dbapi_attributes(self) -> None:
137
+ for name in (
138
+ "Warning",
139
+ "Error",
140
+ "InterfaceError",
141
+ "DataError",
142
+ "DatabaseError",
143
+ "OperationalError",
144
+ "InterfaceError",
145
+ "IntegrityError",
146
+ "ProgrammingError",
147
+ "InternalError",
148
+ "NotSupportedError",
149
+ ):
150
+ setattr(self, name, getattr(self.asyncmy.errors, name))
151
+
152
+ STRING = util.symbol("STRING")
153
+ NUMBER = util.symbol("NUMBER")
154
+ BINARY = util.symbol("BINARY")
155
+ DATETIME = util.symbol("DATETIME")
156
+ TIMESTAMP = util.symbol("TIMESTAMP")
157
+ Binary = staticmethod(bytes)
158
+
159
+ def connect(self, *arg: Any, **kw: Any) -> AsyncAdapt_asyncmy_connection:
160
+ async_fallback = kw.pop("async_fallback", False)
161
+ creator_fn = kw.pop("async_creator_fn", self.asyncmy.connect)
162
+
163
+ if util.asbool(async_fallback):
164
+ return AsyncAdaptFallback_asyncmy_connection(
165
+ self,
166
+ await_fallback(creator_fn(*arg, **kw)),
167
+ )
168
+ else:
169
+ return AsyncAdapt_asyncmy_connection(
170
+ self,
171
+ await_only(creator_fn(*arg, **kw)),
172
+ )
173
+
174
+
175
+ class MySQLDialect_asyncmy(MySQLDialect_pymysql):
176
+ driver = "asyncmy"
177
+ supports_statement_cache = True
178
+
179
+ supports_server_side_cursors = True
180
+ _sscursor = AsyncAdapt_asyncmy_ss_cursor
181
+
182
+ is_async = True
183
+ has_terminate = True
184
+
185
+ @classmethod
186
+ def import_dbapi(cls) -> DBAPIModule:
187
+ return AsyncAdapt_asyncmy_dbapi(__import__("asyncmy"))
188
+
189
+ @classmethod
190
+ def get_pool_class(cls, url: URL) -> type:
191
+ async_fallback = url.query.get("async_fallback", False)
192
+
193
+ if util.asbool(async_fallback):
194
+ return pool.FallbackAsyncAdaptedQueuePool
195
+ else:
196
+ return pool.AsyncAdaptedQueuePool
197
+
198
+ def do_terminate(self, dbapi_connection: DBAPIConnection) -> None:
199
+ dbapi_connection.terminate()
200
+
201
+ def create_connect_args(self, url: URL) -> ConnectArgsType: # type: ignore[override] # noqa: E501
202
+ return super().create_connect_args(
203
+ url, _translate_args=dict(username="user", database="db")
204
+ )
205
+
206
+ def is_disconnect(
207
+ self,
208
+ e: DBAPIModule.Error,
209
+ connection: Optional[Union[PoolProxiedConnection, DBAPIConnection]],
210
+ cursor: Optional[DBAPICursor],
211
+ ) -> bool:
212
+ if super().is_disconnect(e, connection, cursor):
213
+ return True
214
+ else:
215
+ str_e = str(e).lower()
216
+ return (
217
+ "not connected" in str_e or "network operation failed" in str_e
218
+ )
219
+
220
+ def _found_rows_client_flag(self) -> int:
221
+ from asyncmy.constants import CLIENT # type: ignore
222
+
223
+ return CLIENT.FOUND_ROWS # type: ignore[no-any-return]
224
+
225
+ def get_driver_connection(
226
+ self, connection: DBAPIConnection
227
+ ) -> AsyncIODBAPIConnection:
228
+ return connection._connection # type: ignore[no-any-return]
229
+
230
+
231
+ dialect = MySQLDialect_asyncmy
loan-advisor-agent/.venv/Lib/site-packages/sqlalchemy/dialects/mysql/base.py ADDED
The diff for this file is too large to render. See raw diff
 
loan-advisor-agent/.venv/Lib/site-packages/sqlalchemy/dialects/mysql/cymysql.py ADDED
@@ -0,0 +1,106 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # dialects/mysql/cymysql.py
2
+ # Copyright (C) 2005-2026 the SQLAlchemy authors and contributors
3
+ # <see AUTHORS file>
4
+ #
5
+ # This module is part of SQLAlchemy and is released under
6
+ # the MIT License: https://www.opensource.org/licenses/mit-license.php
7
+
8
+ r"""
9
+
10
+ .. dialect:: mysql+cymysql
11
+ :name: CyMySQL
12
+ :dbapi: cymysql
13
+ :connectstring: mysql+cymysql://<username>:<password>@<host>/<dbname>[?<options>]
14
+ :url: https://github.com/nakagami/CyMySQL
15
+
16
+ .. note::
17
+
18
+ The CyMySQL dialect is **not tested as part of SQLAlchemy's continuous
19
+ integration** and may have unresolved issues. The recommended MySQL
20
+ dialects are mysqlclient and PyMySQL.
21
+
22
+ """ # noqa
23
+ from __future__ import annotations
24
+
25
+ from typing import Any
26
+ from typing import Iterable
27
+ from typing import Optional
28
+ from typing import TYPE_CHECKING
29
+ from typing import Union
30
+
31
+ from .base import MySQLDialect
32
+ from .mysqldb import MySQLDialect_mysqldb
33
+ from .types import BIT
34
+ from ... import util
35
+
36
+ if TYPE_CHECKING:
37
+ from ...engine.base import Connection
38
+ from ...engine.interfaces import DBAPIConnection
39
+ from ...engine.interfaces import DBAPICursor
40
+ from ...engine.interfaces import DBAPIModule
41
+ from ...engine.interfaces import Dialect
42
+ from ...engine.interfaces import PoolProxiedConnection
43
+ from ...sql.type_api import _ResultProcessorType
44
+
45
+
46
+ class _cymysqlBIT(BIT):
47
+ def result_processor(
48
+ self, dialect: Dialect, coltype: object
49
+ ) -> Optional[_ResultProcessorType[Any]]:
50
+ """Convert MySQL's 64 bit, variable length binary string to a long."""
51
+
52
+ def process(value: Optional[Iterable[int]]) -> Optional[int]:
53
+ if value is not None:
54
+ v = 0
55
+ for i in iter(value):
56
+ v = v << 8 | i
57
+ return v
58
+ return value
59
+
60
+ return process
61
+
62
+
63
+ class MySQLDialect_cymysql(MySQLDialect_mysqldb):
64
+ driver = "cymysql"
65
+ supports_statement_cache = True
66
+
67
+ description_encoding = None
68
+ supports_sane_rowcount = True
69
+ supports_sane_multi_rowcount = False
70
+ supports_unicode_statements = True
71
+
72
+ colspecs = util.update_copy(MySQLDialect.colspecs, {BIT: _cymysqlBIT})
73
+
74
+ @classmethod
75
+ def import_dbapi(cls) -> DBAPIModule:
76
+ return __import__("cymysql")
77
+
78
+ def _detect_charset(self, connection: Connection) -> str:
79
+ return connection.connection.charset # type: ignore[no-any-return]
80
+
81
+ def _extract_error_code(self, exception: DBAPIModule.Error) -> int:
82
+ return exception.errno # type: ignore[no-any-return]
83
+
84
+ def is_disconnect(
85
+ self,
86
+ e: DBAPIModule.Error,
87
+ connection: Optional[Union[PoolProxiedConnection, DBAPIConnection]],
88
+ cursor: Optional[DBAPICursor],
89
+ ) -> bool:
90
+ if isinstance(e, self.loaded_dbapi.OperationalError):
91
+ return self._extract_error_code(e) in (
92
+ 2006,
93
+ 2013,
94
+ 2014,
95
+ 2045,
96
+ 2055,
97
+ )
98
+ elif isinstance(e, self.loaded_dbapi.InterfaceError):
99
+ # if underlying connection is closed,
100
+ # this is the error you get
101
+ return True
102
+ else:
103
+ return False
104
+
105
+
106
+ dialect = MySQLDialect_cymysql
loan-advisor-agent/.venv/Lib/site-packages/sqlalchemy/dialects/mysql/dml.py ADDED
@@ -0,0 +1,225 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # dialects/mysql/dml.py
2
+ # Copyright (C) 2005-2026 the SQLAlchemy authors and contributors
3
+ # <see AUTHORS file>
4
+ #
5
+ # This module is part of SQLAlchemy and is released under
6
+ # the MIT License: https://www.opensource.org/licenses/mit-license.php
7
+ from __future__ import annotations
8
+
9
+ from typing import Any
10
+ from typing import Dict
11
+ from typing import List
12
+ from typing import Mapping
13
+ from typing import Optional
14
+ from typing import Tuple
15
+ from typing import Union
16
+
17
+ from ... import exc
18
+ from ... import util
19
+ from ...sql._typing import _DMLTableArgument
20
+ from ...sql.base import _exclusive_against
21
+ from ...sql.base import _generative
22
+ from ...sql.base import ColumnCollection
23
+ from ...sql.base import ReadOnlyColumnCollection
24
+ from ...sql.dml import Insert as StandardInsert
25
+ from ...sql.elements import ClauseElement
26
+ from ...sql.elements import KeyedColumnElement
27
+ from ...sql.expression import alias
28
+ from ...sql.selectable import NamedFromClause
29
+ from ...util.typing import Self
30
+
31
+
32
+ __all__ = ("Insert", "insert")
33
+
34
+
35
+ def insert(table: _DMLTableArgument) -> Insert:
36
+ """Construct a MySQL/MariaDB-specific variant :class:`_mysql.Insert`
37
+ construct.
38
+
39
+ .. container:: inherited_member
40
+
41
+ The :func:`sqlalchemy.dialects.mysql.insert` function creates
42
+ a :class:`sqlalchemy.dialects.mysql.Insert`. This class is based
43
+ on the dialect-agnostic :class:`_sql.Insert` construct which may
44
+ be constructed using the :func:`_sql.insert` function in
45
+ SQLAlchemy Core.
46
+
47
+ The :class:`_mysql.Insert` construct includes additional methods
48
+ :meth:`_mysql.Insert.on_duplicate_key_update`.
49
+
50
+ """
51
+ return Insert(table)
52
+
53
+
54
+ class Insert(StandardInsert):
55
+ """MySQL-specific implementation of INSERT.
56
+
57
+ Adds methods for MySQL-specific syntaxes such as ON DUPLICATE KEY UPDATE.
58
+
59
+ The :class:`~.mysql.Insert` object is created using the
60
+ :func:`sqlalchemy.dialects.mysql.insert` function.
61
+
62
+ .. versionadded:: 1.2
63
+
64
+ """
65
+
66
+ stringify_dialect = "mysql"
67
+ inherit_cache = False
68
+
69
+ @property
70
+ def inserted(
71
+ self,
72
+ ) -> ReadOnlyColumnCollection[str, KeyedColumnElement[Any]]:
73
+ """Provide the "inserted" namespace for an ON DUPLICATE KEY UPDATE
74
+ statement
75
+
76
+ MySQL's ON DUPLICATE KEY UPDATE clause allows reference to the row
77
+ that would be inserted, via a special function called ``VALUES()``.
78
+ This attribute provides all columns in this row to be referenceable
79
+ such that they will render within a ``VALUES()`` function inside the
80
+ ON DUPLICATE KEY UPDATE clause. The attribute is named ``.inserted``
81
+ so as not to conflict with the existing
82
+ :meth:`_expression.Insert.values` method.
83
+
84
+ .. tip:: The :attr:`_mysql.Insert.inserted` attribute is an instance
85
+ of :class:`_expression.ColumnCollection`, which provides an
86
+ interface the same as that of the :attr:`_schema.Table.c`
87
+ collection described at :ref:`metadata_tables_and_columns`.
88
+ With this collection, ordinary names are accessible like attributes
89
+ (e.g. ``stmt.inserted.some_column``), but special names and
90
+ dictionary method names should be accessed using indexed access,
91
+ such as ``stmt.inserted["column name"]`` or
92
+ ``stmt.inserted["values"]``. See the docstring for
93
+ :class:`_expression.ColumnCollection` for further examples.
94
+
95
+ .. seealso::
96
+
97
+ :ref:`mysql_insert_on_duplicate_key_update` - example of how
98
+ to use :attr:`_expression.Insert.inserted`
99
+
100
+ """
101
+ return self.inserted_alias.columns
102
+
103
+ @util.memoized_property
104
+ def inserted_alias(self) -> NamedFromClause:
105
+ return alias(self.table, name="inserted")
106
+
107
+ @_generative
108
+ @_exclusive_against(
109
+ "_post_values_clause",
110
+ msgs={
111
+ "_post_values_clause": "This Insert construct already "
112
+ "has an ON DUPLICATE KEY clause present"
113
+ },
114
+ )
115
+ def on_duplicate_key_update(self, *args: _UpdateArg, **kw: Any) -> Self:
116
+ r"""
117
+ Specifies the ON DUPLICATE KEY UPDATE clause.
118
+
119
+ :param \**kw: Column keys linked to UPDATE values. The
120
+ values may be any SQL expression or supported literal Python
121
+ values.
122
+
123
+ .. warning:: This dictionary does **not** take into account
124
+ Python-specified default UPDATE values or generation functions,
125
+ e.g. those specified using :paramref:`_schema.Column.onupdate`.
126
+ These values will not be exercised for an ON DUPLICATE KEY UPDATE
127
+ style of UPDATE, unless values are manually specified here.
128
+
129
+ :param \*args: As an alternative to passing key/value parameters,
130
+ a dictionary or list of 2-tuples can be passed as a single positional
131
+ argument.
132
+
133
+ Passing a single dictionary is equivalent to the keyword argument
134
+ form::
135
+
136
+ insert().on_duplicate_key_update({"name": "some name"})
137
+
138
+ Passing a list of 2-tuples indicates that the parameter assignments
139
+ in the UPDATE clause should be ordered as sent, in a manner similar
140
+ to that described for the :class:`_expression.Update`
141
+ construct overall
142
+ in :ref:`tutorial_parameter_ordered_updates`::
143
+
144
+ insert().on_duplicate_key_update(
145
+ [
146
+ ("name", "some name"),
147
+ ("value", "some value"),
148
+ ]
149
+ )
150
+
151
+ .. versionchanged:: 1.3 parameters can be specified as a dictionary
152
+ or list of 2-tuples; the latter form provides for parameter
153
+ ordering.
154
+
155
+
156
+ .. versionadded:: 1.2
157
+
158
+ .. seealso::
159
+
160
+ :ref:`mysql_insert_on_duplicate_key_update`
161
+
162
+ """
163
+ if args and kw:
164
+ raise exc.ArgumentError(
165
+ "Can't pass kwargs and positional arguments simultaneously"
166
+ )
167
+
168
+ if args:
169
+ if len(args) > 1:
170
+ raise exc.ArgumentError(
171
+ "Only a single dictionary or list of tuples "
172
+ "is accepted positionally."
173
+ )
174
+ values = args[0]
175
+ else:
176
+ values = kw
177
+
178
+ self._post_values_clause = OnDuplicateClause(
179
+ self.inserted_alias, values
180
+ )
181
+ return self
182
+
183
+
184
+ class OnDuplicateClause(ClauseElement):
185
+ __visit_name__ = "on_duplicate_key_update"
186
+
187
+ _parameter_ordering: Optional[List[str]] = None
188
+
189
+ update: Dict[str, Any]
190
+ stringify_dialect = "mysql"
191
+
192
+ def __init__(
193
+ self, inserted_alias: NamedFromClause, update: _UpdateArg
194
+ ) -> None:
195
+ self.inserted_alias = inserted_alias
196
+
197
+ # auto-detect that parameters should be ordered. This is copied from
198
+ # Update._proces_colparams(), however we don't look for a special flag
199
+ # in this case since we are not disambiguating from other use cases as
200
+ # we are in Update.values().
201
+ if isinstance(update, list) and (
202
+ update and isinstance(update[0], tuple)
203
+ ):
204
+ self._parameter_ordering = [key for key, value in update]
205
+ update = dict(update)
206
+
207
+ if isinstance(update, dict):
208
+ if not update:
209
+ raise ValueError(
210
+ "update parameter dictionary must not be empty"
211
+ )
212
+ elif isinstance(update, ColumnCollection):
213
+ update = dict(update)
214
+ else:
215
+ raise ValueError(
216
+ "update parameter must be a non-empty dictionary "
217
+ "or a ColumnCollection such as the `.c.` collection "
218
+ "of a Table object"
219
+ )
220
+ self.update = update
221
+
222
+
223
+ _UpdateArg = Union[
224
+ Mapping[Any, Any], List[Tuple[str, Any]], ColumnCollection[Any, Any]
225
+ ]
loan-advisor-agent/.venv/Lib/site-packages/sqlalchemy/dialects/mysql/enumerated.py ADDED
@@ -0,0 +1,282 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # dialects/mysql/enumerated.py
2
+ # Copyright (C) 2005-2026 the SQLAlchemy authors and contributors
3
+ # <see AUTHORS file>
4
+ #
5
+ # This module is part of SQLAlchemy and is released under
6
+ # the MIT License: https://www.opensource.org/licenses/mit-license.php
7
+
8
+ from __future__ import annotations
9
+
10
+ import enum
11
+ import re
12
+ from typing import Any
13
+ from typing import Dict
14
+ from typing import Optional
15
+ from typing import Set
16
+ from typing import Type
17
+ from typing import TYPE_CHECKING
18
+ from typing import Union
19
+
20
+ from .types import _StringType
21
+ from ... import exc
22
+ from ... import sql
23
+ from ... import util
24
+ from ...sql import sqltypes
25
+ from ...sql import type_api
26
+
27
+ if TYPE_CHECKING:
28
+ from ...engine.interfaces import Dialect
29
+ from ...sql.elements import ColumnElement
30
+ from ...sql.type_api import _BindProcessorType
31
+ from ...sql.type_api import _ResultProcessorType
32
+ from ...sql.type_api import TypeEngine
33
+ from ...sql.type_api import TypeEngineMixin
34
+
35
+
36
+ class ENUM(type_api.NativeForEmulated, sqltypes.Enum, _StringType):
37
+ """MySQL ENUM type."""
38
+
39
+ __visit_name__ = "ENUM"
40
+
41
+ native_enum = True
42
+
43
+ def __init__(self, *enums: Union[str, Type[enum.Enum]], **kw: Any) -> None:
44
+ """Construct an ENUM.
45
+
46
+ E.g.::
47
+
48
+ Column("myenum", ENUM("foo", "bar", "baz"))
49
+
50
+ :param enums: The range of valid values for this ENUM. Values in
51
+ enums are not quoted, they will be escaped and surrounded by single
52
+ quotes when generating the schema. This object may also be a
53
+ PEP-435-compliant enumerated type.
54
+
55
+ .. versionadded: 1.1 added support for PEP-435-compliant enumerated
56
+ types.
57
+
58
+ :param strict: This flag has no effect.
59
+
60
+ .. versionchanged:: The MySQL ENUM type as well as the base Enum
61
+ type now validates all Python data values.
62
+
63
+ :param charset: Optional, a column-level character set for this string
64
+ value. Takes precedence to 'ascii' or 'unicode' short-hand.
65
+
66
+ :param collation: Optional, a column-level collation for this string
67
+ value. Takes precedence to 'binary' short-hand.
68
+
69
+ :param ascii: Defaults to False: short-hand for the ``latin1``
70
+ character set, generates ASCII in schema.
71
+
72
+ :param unicode: Defaults to False: short-hand for the ``ucs2``
73
+ character set, generates UNICODE in schema.
74
+
75
+ :param binary: Defaults to False: short-hand, pick the binary
76
+ collation type that matches the column's character set. Generates
77
+ BINARY in schema. This does not affect the type of data stored,
78
+ only the collation of character data.
79
+
80
+ """
81
+ kw.pop("strict", None)
82
+ self._enum_init(enums, kw) # type: ignore[arg-type]
83
+ _StringType.__init__(self, length=self.length, **kw)
84
+
85
+ @classmethod
86
+ def adapt_emulated_to_native(
87
+ cls,
88
+ impl: Union[TypeEngine[Any], TypeEngineMixin],
89
+ **kw: Any,
90
+ ) -> ENUM:
91
+ """Produce a MySQL native :class:`.mysql.ENUM` from plain
92
+ :class:`.Enum`.
93
+
94
+ """
95
+ if TYPE_CHECKING:
96
+ assert isinstance(impl, ENUM)
97
+ kw.setdefault("validate_strings", impl.validate_strings)
98
+ kw.setdefault("values_callable", impl.values_callable)
99
+ kw.setdefault("omit_aliases", impl._omit_aliases)
100
+ return cls(**kw)
101
+
102
+ def _object_value_for_elem(self, elem: str) -> Union[str, enum.Enum]:
103
+ # mysql sends back a blank string for any value that
104
+ # was persisted that was not in the enums; that is, it does no
105
+ # validation on the incoming data, it "truncates" it to be
106
+ # the blank string. Return it straight.
107
+ if elem == "":
108
+ return elem
109
+ else:
110
+ return super()._object_value_for_elem(elem)
111
+
112
+ def __repr__(self) -> str:
113
+ return util.generic_repr(
114
+ self, to_inspect=[ENUM, _StringType, sqltypes.Enum]
115
+ )
116
+
117
+
118
+ # TODO: SET is a string as far as configuration but does not act like
119
+ # a string at the python level. We either need to make a py-type agnostic
120
+ # version of String as a base to be used for this, make this some kind of
121
+ # TypeDecorator, or just vendor it out as its own type.
122
+ class SET(_StringType):
123
+ """MySQL SET type."""
124
+
125
+ __visit_name__ = "SET"
126
+
127
+ def __init__(self, *values: str, **kw: Any):
128
+ """Construct a SET.
129
+
130
+ E.g.::
131
+
132
+ Column("myset", SET("foo", "bar", "baz"))
133
+
134
+ The list of potential values is required in the case that this
135
+ set will be used to generate DDL for a table, or if the
136
+ :paramref:`.SET.retrieve_as_bitwise` flag is set to True.
137
+
138
+ :param values: The range of valid values for this SET. The values
139
+ are not quoted, they will be escaped and surrounded by single
140
+ quotes when generating the schema.
141
+
142
+ :param convert_unicode: Same flag as that of
143
+ :paramref:`.String.convert_unicode`.
144
+
145
+ :param collation: same as that of :paramref:`.String.collation`
146
+
147
+ :param charset: same as that of :paramref:`.VARCHAR.charset`.
148
+
149
+ :param ascii: same as that of :paramref:`.VARCHAR.ascii`.
150
+
151
+ :param unicode: same as that of :paramref:`.VARCHAR.unicode`.
152
+
153
+ :param binary: same as that of :paramref:`.VARCHAR.binary`.
154
+
155
+ :param retrieve_as_bitwise: if True, the data for the set type will be
156
+ persisted and selected using an integer value, where a set is coerced
157
+ into a bitwise mask for persistence. MySQL allows this mode which
158
+ has the advantage of being able to store values unambiguously,
159
+ such as the blank string ``''``. The datatype will appear
160
+ as the expression ``col + 0`` in a SELECT statement, so that the
161
+ value is coerced into an integer value in result sets.
162
+ This flag is required if one wishes
163
+ to persist a set that can store the blank string ``''`` as a value.
164
+
165
+ .. warning::
166
+
167
+ When using :paramref:`.mysql.SET.retrieve_as_bitwise`, it is
168
+ essential that the list of set values is expressed in the
169
+ **exact same order** as exists on the MySQL database.
170
+
171
+ """
172
+ self.retrieve_as_bitwise = kw.pop("retrieve_as_bitwise", False)
173
+ self.values = tuple(values)
174
+ if not self.retrieve_as_bitwise and "" in values:
175
+ raise exc.ArgumentError(
176
+ "Can't use the blank value '' in a SET without "
177
+ "setting retrieve_as_bitwise=True"
178
+ )
179
+ if self.retrieve_as_bitwise:
180
+ self._inversed_bitmap: Dict[str, int] = {
181
+ value: 2**idx for idx, value in enumerate(self.values)
182
+ }
183
+ self._bitmap: Dict[int, str] = {
184
+ 2**idx: value for idx, value in enumerate(self.values)
185
+ }
186
+ length = max([len(v) for v in values] + [0])
187
+ kw.setdefault("length", length)
188
+ super().__init__(**kw)
189
+
190
+ def column_expression(
191
+ self, colexpr: ColumnElement[Any]
192
+ ) -> ColumnElement[Any]:
193
+ if self.retrieve_as_bitwise:
194
+ return sql.type_coerce(
195
+ sql.type_coerce(colexpr, sqltypes.Integer) + 0, self
196
+ )
197
+ else:
198
+ return colexpr
199
+
200
+ def result_processor(
201
+ self, dialect: Dialect, coltype: Any
202
+ ) -> Optional[_ResultProcessorType[Any]]:
203
+ if self.retrieve_as_bitwise:
204
+
205
+ def process(value: Union[str, int, None]) -> Optional[Set[str]]:
206
+ if value is not None:
207
+ value = int(value)
208
+
209
+ return set(util.map_bits(self._bitmap.__getitem__, value))
210
+ else:
211
+ return None
212
+
213
+ else:
214
+ super_convert = super().result_processor(dialect, coltype)
215
+
216
+ def process(value: Union[str, Set[str], None]) -> Optional[Set[str]]: # type: ignore[misc] # noqa: E501
217
+ if isinstance(value, str):
218
+ # MySQLdb returns a string, let's parse
219
+ if super_convert:
220
+ value = super_convert(value)
221
+ assert value is not None
222
+ if TYPE_CHECKING:
223
+ assert isinstance(value, str)
224
+ return set(re.findall(r"[^,]+", value))
225
+ else:
226
+ # mysql-connector-python does a naive
227
+ # split(",") which throws in an empty string
228
+ if value is not None:
229
+ value.discard("")
230
+ return value
231
+
232
+ return process
233
+
234
+ def bind_processor(
235
+ self, dialect: Dialect
236
+ ) -> _BindProcessorType[Union[str, int]]:
237
+ super_convert = super().bind_processor(dialect)
238
+ if self.retrieve_as_bitwise:
239
+
240
+ def process(
241
+ value: Union[str, int, set[str], None],
242
+ ) -> Union[str, int, None]:
243
+ if value is None:
244
+ return None
245
+ elif isinstance(value, (int, str)):
246
+ if super_convert:
247
+ return super_convert(value) # type: ignore[arg-type, no-any-return] # noqa: E501
248
+ else:
249
+ return value
250
+ else:
251
+ int_value = 0
252
+ for v in value:
253
+ int_value |= self._inversed_bitmap[v]
254
+ return int_value
255
+
256
+ else:
257
+
258
+ def process(
259
+ value: Union[str, int, set[str], None],
260
+ ) -> Union[str, int, None]:
261
+ # accept strings and int (actually bitflag) values directly
262
+ if value is not None and not isinstance(value, (int, str)):
263
+ value = ",".join(value)
264
+ if super_convert:
265
+ return super_convert(value) # type: ignore
266
+ else:
267
+ return value
268
+
269
+ return process
270
+
271
+ def adapt(self, cls: type, **kw: Any) -> Any:
272
+ kw["retrieve_as_bitwise"] = self.retrieve_as_bitwise
273
+ return util.constructor_copy(self, cls, *self.values, **kw)
274
+
275
+ def __repr__(self) -> str:
276
+ return util.generic_repr(
277
+ self,
278
+ to_inspect=[SET, _StringType],
279
+ additional_kw=[
280
+ ("retrieve_as_bitwise", False),
281
+ ],
282
+ )
loan-advisor-agent/.venv/Lib/site-packages/sqlalchemy/dialects/mysql/expression.py ADDED
@@ -0,0 +1,146 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # dialects/mysql/expression.py
2
+ # Copyright (C) 2005-2026 the SQLAlchemy authors and contributors
3
+ # <see AUTHORS file>
4
+ #
5
+ # This module is part of SQLAlchemy and is released under
6
+ # the MIT License: https://www.opensource.org/licenses/mit-license.php
7
+
8
+ from __future__ import annotations
9
+
10
+ from typing import Any
11
+
12
+ from ... import exc
13
+ from ... import util
14
+ from ...sql import coercions
15
+ from ...sql import elements
16
+ from ...sql import operators
17
+ from ...sql import roles
18
+ from ...sql.base import _generative
19
+ from ...sql.base import Generative
20
+ from ...util.typing import Self
21
+
22
+
23
+ class match(Generative, elements.BinaryExpression[Any]):
24
+ """Produce a ``MATCH (X, Y) AGAINST ('TEXT')`` clause.
25
+
26
+ E.g.::
27
+
28
+ from sqlalchemy import desc
29
+ from sqlalchemy.dialects.mysql import match
30
+
31
+ match_expr = match(
32
+ users_table.c.firstname,
33
+ users_table.c.lastname,
34
+ against="Firstname Lastname",
35
+ )
36
+
37
+ stmt = (
38
+ select(users_table)
39
+ .where(match_expr.in_boolean_mode())
40
+ .order_by(desc(match_expr))
41
+ )
42
+
43
+ Would produce SQL resembling:
44
+
45
+ .. sourcecode:: sql
46
+
47
+ SELECT id, firstname, lastname
48
+ FROM user
49
+ WHERE MATCH(firstname, lastname) AGAINST (:param_1 IN BOOLEAN MODE)
50
+ ORDER BY MATCH(firstname, lastname) AGAINST (:param_2) DESC
51
+
52
+ The :func:`_mysql.match` function is a standalone version of the
53
+ :meth:`_sql.ColumnElement.match` method available on all
54
+ SQL expressions, as when :meth:`_expression.ColumnElement.match` is
55
+ used, but allows to pass multiple columns
56
+
57
+ :param cols: column expressions to match against
58
+
59
+ :param against: expression to be compared towards
60
+
61
+ :param in_boolean_mode: boolean, set "boolean mode" to true
62
+
63
+ :param in_natural_language_mode: boolean , set "natural language" to true
64
+
65
+ :param with_query_expansion: boolean, set "query expansion" to true
66
+
67
+ .. versionadded:: 1.4.19
68
+
69
+ .. seealso::
70
+
71
+ :meth:`_expression.ColumnElement.match`
72
+
73
+ """
74
+
75
+ __visit_name__ = "mysql_match"
76
+
77
+ inherit_cache = True
78
+ modifiers: util.immutabledict[str, Any]
79
+
80
+ def __init__(self, *cols: elements.ColumnElement[Any], **kw: Any):
81
+ if not cols:
82
+ raise exc.ArgumentError("columns are required")
83
+
84
+ against = kw.pop("against", None)
85
+
86
+ if against is None:
87
+ raise exc.ArgumentError("against is required")
88
+ against = coercions.expect(
89
+ roles.ExpressionElementRole,
90
+ against,
91
+ )
92
+
93
+ left = elements.BooleanClauseList._construct_raw(
94
+ operators.comma_op,
95
+ clauses=cols,
96
+ )
97
+ left.group = False
98
+
99
+ flags = util.immutabledict(
100
+ {
101
+ "mysql_boolean_mode": kw.pop("in_boolean_mode", False),
102
+ "mysql_natural_language": kw.pop(
103
+ "in_natural_language_mode", False
104
+ ),
105
+ "mysql_query_expansion": kw.pop("with_query_expansion", False),
106
+ }
107
+ )
108
+
109
+ if kw:
110
+ raise exc.ArgumentError("unknown arguments: %s" % (", ".join(kw)))
111
+
112
+ super().__init__(left, against, operators.match_op, modifiers=flags)
113
+
114
+ @_generative
115
+ def in_boolean_mode(self) -> Self:
116
+ """Apply the "IN BOOLEAN MODE" modifier to the MATCH expression.
117
+
118
+ :return: a new :class:`_mysql.match` instance with modifications
119
+ applied.
120
+ """
121
+
122
+ self.modifiers = self.modifiers.union({"mysql_boolean_mode": True})
123
+ return self
124
+
125
+ @_generative
126
+ def in_natural_language_mode(self) -> Self:
127
+ """Apply the "IN NATURAL LANGUAGE MODE" modifier to the MATCH
128
+ expression.
129
+
130
+ :return: a new :class:`_mysql.match` instance with modifications
131
+ applied.
132
+ """
133
+
134
+ self.modifiers = self.modifiers.union({"mysql_natural_language": True})
135
+ return self
136
+
137
+ @_generative
138
+ def with_query_expansion(self) -> Self:
139
+ """Apply the "WITH QUERY EXPANSION" modifier to the MATCH expression.
140
+
141
+ :return: a new :class:`_mysql.match` instance with modifications
142
+ applied.
143
+ """
144
+
145
+ self.modifiers = self.modifiers.union({"mysql_query_expansion": True})
146
+ return self
loan-advisor-agent/.venv/Lib/site-packages/sqlalchemy/dialects/mysql/json.py ADDED
@@ -0,0 +1,91 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # dialects/mysql/json.py
2
+ # Copyright (C) 2005-2026 the SQLAlchemy authors and contributors
3
+ # <see AUTHORS file>
4
+ #
5
+ # This module is part of SQLAlchemy and is released under
6
+ # the MIT License: https://www.opensource.org/licenses/mit-license.php
7
+ from __future__ import annotations
8
+
9
+ from typing import Any
10
+ from typing import TYPE_CHECKING
11
+
12
+ from ... import types as sqltypes
13
+
14
+ if TYPE_CHECKING:
15
+ from ...engine.interfaces import Dialect
16
+ from ...sql.type_api import _BindProcessorType
17
+ from ...sql.type_api import _LiteralProcessorType
18
+
19
+
20
+ class JSON(sqltypes.JSON):
21
+ """MySQL JSON type.
22
+
23
+ MySQL supports JSON as of version 5.7.
24
+ MariaDB supports JSON (as an alias for LONGTEXT) as of version 10.2.
25
+
26
+ :class:`_mysql.JSON` is used automatically whenever the base
27
+ :class:`_types.JSON` datatype is used against a MySQL or MariaDB backend.
28
+
29
+ .. seealso::
30
+
31
+ :class:`_types.JSON` - main documentation for the generic
32
+ cross-platform JSON datatype.
33
+
34
+ The :class:`.mysql.JSON` type supports persistence of JSON values
35
+ as well as the core index operations provided by :class:`_types.JSON`
36
+ datatype, by adapting the operations to render the ``JSON_EXTRACT``
37
+ function at the database level.
38
+
39
+ """
40
+
41
+ pass
42
+
43
+
44
+ class _FormatTypeMixin:
45
+ def _format_value(self, value: Any) -> str:
46
+ raise NotImplementedError()
47
+
48
+ def bind_processor(self, dialect: Dialect) -> _BindProcessorType[Any]:
49
+ super_proc = self.string_bind_processor(dialect) # type: ignore[attr-defined] # noqa: E501
50
+
51
+ def process(value: Any) -> Any:
52
+ value = self._format_value(value)
53
+ if super_proc:
54
+ value = super_proc(value)
55
+ return value
56
+
57
+ return process
58
+
59
+ def literal_processor(
60
+ self, dialect: Dialect
61
+ ) -> _LiteralProcessorType[Any]:
62
+ super_proc = self.string_literal_processor(dialect) # type: ignore[attr-defined] # noqa: E501
63
+
64
+ def process(value: Any) -> str:
65
+ value = self._format_value(value)
66
+ if super_proc:
67
+ value = super_proc(value)
68
+ return value # type: ignore[no-any-return]
69
+
70
+ return process
71
+
72
+
73
+ class JSONIndexType(_FormatTypeMixin, sqltypes.JSON.JSONIndexType):
74
+ def _format_value(self, value: Any) -> str:
75
+ if isinstance(value, int):
76
+ formatted_value = "$[%s]" % value
77
+ else:
78
+ formatted_value = '$."%s"' % value
79
+ return formatted_value
80
+
81
+
82
+ class JSONPathType(_FormatTypeMixin, sqltypes.JSON.JSONPathType):
83
+ def _format_value(self, value: Any) -> str:
84
+ return "$%s" % (
85
+ "".join(
86
+ [
87
+ "[%s]" % elem if isinstance(elem, int) else '."%s"' % elem
88
+ for elem in value
89
+ ]
90
+ )
91
+ )
loan-advisor-agent/.venv/Lib/site-packages/sqlalchemy/dialects/mysql/mariadb.py ADDED
@@ -0,0 +1,72 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # dialects/mysql/mariadb.py
2
+ # Copyright (C) 2005-2026 the SQLAlchemy authors and contributors
3
+ # <see AUTHORS file>
4
+ #
5
+ # This module is part of SQLAlchemy and is released under
6
+ # the MIT License: https://www.opensource.org/licenses/mit-license.php
7
+
8
+ from __future__ import annotations
9
+
10
+ from typing import Any
11
+
12
+ from .base import MariaDBIdentifierPreparer
13
+ from .base import MySQLDialect
14
+ from .base import MySQLIdentifierPreparer
15
+ from .base import MySQLTypeCompiler
16
+ from ...sql import sqltypes
17
+
18
+
19
+ class INET4(sqltypes.TypeEngine[str]):
20
+ """INET4 column type for MariaDB
21
+
22
+ .. versionadded:: 2.0.37
23
+ """
24
+
25
+ __visit_name__ = "INET4"
26
+
27
+
28
+ class INET6(sqltypes.TypeEngine[str]):
29
+ """INET6 column type for MariaDB
30
+
31
+ .. versionadded:: 2.0.37
32
+ """
33
+
34
+ __visit_name__ = "INET6"
35
+
36
+
37
+ class MariaDBTypeCompiler(MySQLTypeCompiler):
38
+ def visit_INET4(self, type_: INET4, **kwargs: Any) -> str:
39
+ return "INET4"
40
+
41
+ def visit_INET6(self, type_: INET6, **kwargs: Any) -> str:
42
+ return "INET6"
43
+
44
+
45
+ class MariaDBDialect(MySQLDialect):
46
+ is_mariadb = True
47
+ supports_statement_cache = True
48
+ name = "mariadb"
49
+ preparer: type[MySQLIdentifierPreparer] = MariaDBIdentifierPreparer
50
+ type_compiler_cls = MariaDBTypeCompiler
51
+
52
+
53
+ def loader(driver: str) -> type[MariaDBDialect]:
54
+ dialect_mod = __import__(
55
+ "sqlalchemy.dialects.mysql.%s" % driver
56
+ ).dialects.mysql
57
+
58
+ driver_mod = getattr(dialect_mod, driver)
59
+ if hasattr(driver_mod, "mariadb_dialect"):
60
+ driver_cls = driver_mod.mariadb_dialect
61
+ return driver_cls # type: ignore[no-any-return]
62
+ else:
63
+ driver_cls = driver_mod.dialect
64
+
65
+ return type(
66
+ "MariaDBDialect_%s" % driver,
67
+ (
68
+ MariaDBDialect,
69
+ driver_cls,
70
+ ),
71
+ {"supports_statement_cache": True},
72
+ )
loan-advisor-agent/.venv/Lib/site-packages/sqlalchemy/dialects/mysql/mariadbconnector.py ADDED
@@ -0,0 +1,322 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # dialects/mysql/mariadbconnector.py
2
+ # Copyright (C) 2005-2026 the SQLAlchemy authors and contributors
3
+ # <see AUTHORS file>
4
+ #
5
+ # This module is part of SQLAlchemy and is released under
6
+ # the MIT License: https://www.opensource.org/licenses/mit-license.php
7
+
8
+ """
9
+
10
+ .. dialect:: mysql+mariadbconnector
11
+ :name: MariaDB Connector/Python
12
+ :dbapi: mariadb
13
+ :connectstring: mariadb+mariadbconnector://<user>:<password>@<host>[:<port>]/<dbname>
14
+ :url: https://pypi.org/project/mariadb/
15
+
16
+ Driver Status
17
+ -------------
18
+
19
+ MariaDB Connector/Python enables Python programs to access MariaDB and MySQL
20
+ databases using an API which is compliant with the Python DB API 2.0 (PEP-249).
21
+ It is written in C and uses MariaDB Connector/C client library for client server
22
+ communication.
23
+
24
+ Note that the default driver for a ``mariadb://`` connection URI continues to
25
+ be ``mysqldb``. ``mariadb+mariadbconnector://`` is required to use this driver.
26
+
27
+ .. mariadb: https://github.com/mariadb-corporation/mariadb-connector-python
28
+
29
+ """ # noqa
30
+ from __future__ import annotations
31
+
32
+ import re
33
+ from typing import Any
34
+ from typing import Optional
35
+ from typing import Sequence
36
+ from typing import Tuple
37
+ from typing import TYPE_CHECKING
38
+ from typing import Union
39
+ from uuid import UUID as _python_UUID
40
+
41
+ from .base import MySQLCompiler
42
+ from .base import MySQLDialect
43
+ from .base import MySQLExecutionContext
44
+ from ... import sql
45
+ from ... import util
46
+ from ...sql import sqltypes
47
+
48
+ if TYPE_CHECKING:
49
+ from ...engine.base import Connection
50
+ from ...engine.interfaces import ConnectArgsType
51
+ from ...engine.interfaces import DBAPIConnection
52
+ from ...engine.interfaces import DBAPICursor
53
+ from ...engine.interfaces import DBAPIModule
54
+ from ...engine.interfaces import Dialect
55
+ from ...engine.interfaces import IsolationLevel
56
+ from ...engine.interfaces import PoolProxiedConnection
57
+ from ...engine.url import URL
58
+ from ...sql.compiler import SQLCompiler
59
+ from ...sql.type_api import _ResultProcessorType
60
+
61
+
62
+ mariadb_cpy_minimum_version = (1, 0, 1)
63
+
64
+
65
+ class _MariaDBUUID(sqltypes.UUID[sqltypes._UUID_RETURN]):
66
+ # work around JIRA issue
67
+ # https://jira.mariadb.org/browse/CONPY-270. When that issue is fixed,
68
+ # this type can be removed.
69
+ def result_processor(
70
+ self, dialect: Dialect, coltype: object
71
+ ) -> Optional[_ResultProcessorType[Any]]:
72
+ if self.as_uuid:
73
+
74
+ def process(value: Any) -> Any:
75
+ if value is not None:
76
+ if hasattr(value, "decode"):
77
+ value = value.decode("ascii")
78
+ value = _python_UUID(value)
79
+ return value
80
+
81
+ return process
82
+ else:
83
+
84
+ def process(value: Any) -> Any:
85
+ if value is not None:
86
+ if hasattr(value, "decode"):
87
+ value = value.decode("ascii")
88
+ value = str(_python_UUID(value))
89
+ return value
90
+
91
+ return process
92
+
93
+
94
+ class MySQLExecutionContext_mariadbconnector(MySQLExecutionContext):
95
+ _lastrowid: Optional[int] = None
96
+
97
+ def create_server_side_cursor(self) -> DBAPICursor:
98
+ return self._dbapi_connection.cursor(buffered=False)
99
+
100
+ def create_default_cursor(self) -> DBAPICursor:
101
+ return self._dbapi_connection.cursor(buffered=True)
102
+
103
+ def post_exec(self) -> None:
104
+ super().post_exec()
105
+
106
+ self._rowcount = self.cursor.rowcount
107
+
108
+ if TYPE_CHECKING:
109
+ assert isinstance(self.compiled, SQLCompiler)
110
+ if self.isinsert and self.compiled.postfetch_lastrowid:
111
+ self._lastrowid = self.cursor.lastrowid
112
+
113
+ def get_lastrowid(self) -> int:
114
+ if TYPE_CHECKING:
115
+ assert self._lastrowid is not None
116
+ return self._lastrowid
117
+
118
+
119
+ class MySQLCompiler_mariadbconnector(MySQLCompiler):
120
+ pass
121
+
122
+
123
+ class MySQLDialect_mariadbconnector(MySQLDialect):
124
+ driver = "mariadbconnector"
125
+ supports_statement_cache = True
126
+
127
+ # set this to True at the module level to prevent the driver from running
128
+ # against a backend that server detects as MySQL. currently this appears to
129
+ # be unnecessary as MariaDB client libraries have always worked against
130
+ # MySQL databases. However, if this changes at some point, this can be
131
+ # adjusted, but PLEASE ADD A TEST in test/dialect/mysql/test_dialect.py if
132
+ # this change is made at some point to ensure the correct exception
133
+ # is raised at the correct point when running the driver against
134
+ # a MySQL backend.
135
+ # is_mariadb = True
136
+
137
+ supports_unicode_statements = True
138
+ encoding = "utf8mb4"
139
+ convert_unicode = True
140
+ supports_sane_rowcount = True
141
+ supports_sane_multi_rowcount = True
142
+ supports_native_decimal = True
143
+ default_paramstyle = "qmark"
144
+ execution_ctx_cls = MySQLExecutionContext_mariadbconnector
145
+ statement_compiler = MySQLCompiler_mariadbconnector
146
+
147
+ supports_server_side_cursors = True
148
+
149
+ colspecs = util.update_copy(
150
+ MySQLDialect.colspecs, {sqltypes.Uuid: _MariaDBUUID}
151
+ )
152
+
153
+ @util.memoized_property
154
+ def _dbapi_version(self) -> Tuple[int, ...]:
155
+ if self.dbapi and hasattr(self.dbapi, "__version__"):
156
+ return tuple(
157
+ [
158
+ int(x)
159
+ for x in re.findall(
160
+ r"(\d+)(?:[-\.]?|$)", self.dbapi.__version__
161
+ )
162
+ ]
163
+ )
164
+ else:
165
+ return (99, 99, 99)
166
+
167
+ def __init__(self, **kwargs: Any) -> None:
168
+ super().__init__(**kwargs)
169
+ self.paramstyle = "qmark"
170
+ if self.dbapi is not None:
171
+ if self._dbapi_version < mariadb_cpy_minimum_version:
172
+ raise NotImplementedError(
173
+ "The minimum required version for MariaDB "
174
+ "Connector/Python is %s"
175
+ % ".".join(str(x) for x in mariadb_cpy_minimum_version)
176
+ )
177
+
178
+ @classmethod
179
+ def import_dbapi(cls) -> DBAPIModule:
180
+ return __import__("mariadb")
181
+
182
+ def is_disconnect(
183
+ self,
184
+ e: DBAPIModule.Error,
185
+ connection: Optional[Union[PoolProxiedConnection, DBAPIConnection]],
186
+ cursor: Optional[DBAPICursor],
187
+ ) -> bool:
188
+ if super().is_disconnect(e, connection, cursor):
189
+ return True
190
+ elif isinstance(e, self.loaded_dbapi.Error):
191
+ str_e = str(e).lower()
192
+ return "not connected" in str_e or "isn't valid" in str_e
193
+ else:
194
+ return False
195
+
196
+ def create_connect_args(self, url: URL) -> ConnectArgsType:
197
+ opts = url.translate_connect_args()
198
+ opts.update(url.query)
199
+
200
+ int_params = [
201
+ "connect_timeout",
202
+ "read_timeout",
203
+ "write_timeout",
204
+ "client_flag",
205
+ "port",
206
+ "pool_size",
207
+ ]
208
+ bool_params = [
209
+ "local_infile",
210
+ "ssl_verify_cert",
211
+ "ssl",
212
+ "pool_reset_connection",
213
+ "compress",
214
+ ]
215
+
216
+ for key in int_params:
217
+ util.coerce_kw_type(opts, key, int)
218
+ for key in bool_params:
219
+ util.coerce_kw_type(opts, key, bool)
220
+
221
+ # FOUND_ROWS must be set in CLIENT_FLAGS to enable
222
+ # supports_sane_rowcount.
223
+ client_flag = opts.get("client_flag", 0)
224
+ if self.dbapi is not None:
225
+ try:
226
+ CLIENT_FLAGS = __import__(
227
+ self.dbapi.__name__ + ".constants.CLIENT"
228
+ ).constants.CLIENT
229
+ client_flag |= CLIENT_FLAGS.FOUND_ROWS
230
+ except (AttributeError, ImportError):
231
+ self.supports_sane_rowcount = False
232
+ opts["client_flag"] = client_flag
233
+ return [], opts
234
+
235
+ def _extract_error_code(self, exception: DBAPIModule.Error) -> int:
236
+ try:
237
+ rc: int = exception.errno
238
+ except:
239
+ rc = -1
240
+ return rc
241
+
242
+ def _detect_charset(self, connection: Connection) -> str:
243
+ return "utf8mb4"
244
+
245
+ def get_isolation_level_values(
246
+ self, dbapi_conn: DBAPIConnection
247
+ ) -> Sequence[IsolationLevel]:
248
+ return (
249
+ "SERIALIZABLE",
250
+ "READ UNCOMMITTED",
251
+ "READ COMMITTED",
252
+ "REPEATABLE READ",
253
+ "AUTOCOMMIT",
254
+ )
255
+
256
+ def detect_autocommit_setting(self, dbapi_conn: DBAPIConnection) -> bool:
257
+ return bool(dbapi_conn.autocommit)
258
+
259
+ def set_isolation_level(
260
+ self, dbapi_connection: DBAPIConnection, level: IsolationLevel
261
+ ) -> None:
262
+ if level == "AUTOCOMMIT":
263
+ dbapi_connection.autocommit = True
264
+ else:
265
+ dbapi_connection.autocommit = False
266
+ super().set_isolation_level(dbapi_connection, level)
267
+
268
+ def do_begin_twophase(self, connection: Connection, xid: Any) -> None:
269
+ connection.execute(
270
+ sql.text("XA BEGIN :xid").bindparams(
271
+ sql.bindparam("xid", xid, literal_execute=True)
272
+ )
273
+ )
274
+
275
+ def do_prepare_twophase(self, connection: Connection, xid: Any) -> None:
276
+ connection.execute(
277
+ sql.text("XA END :xid").bindparams(
278
+ sql.bindparam("xid", xid, literal_execute=True)
279
+ )
280
+ )
281
+ connection.execute(
282
+ sql.text("XA PREPARE :xid").bindparams(
283
+ sql.bindparam("xid", xid, literal_execute=True)
284
+ )
285
+ )
286
+
287
+ def do_rollback_twophase(
288
+ self,
289
+ connection: Connection,
290
+ xid: Any,
291
+ is_prepared: bool = True,
292
+ recover: bool = False,
293
+ ) -> None:
294
+ if not is_prepared:
295
+ connection.execute(
296
+ sql.text("XA END :xid").bindparams(
297
+ sql.bindparam("xid", xid, literal_execute=True)
298
+ )
299
+ )
300
+ connection.execute(
301
+ sql.text("XA ROLLBACK :xid").bindparams(
302
+ sql.bindparam("xid", xid, literal_execute=True)
303
+ )
304
+ )
305
+
306
+ def do_commit_twophase(
307
+ self,
308
+ connection: Connection,
309
+ xid: Any,
310
+ is_prepared: bool = True,
311
+ recover: bool = False,
312
+ ) -> None:
313
+ if not is_prepared:
314
+ self.do_prepare_twophase(connection, xid)
315
+ connection.execute(
316
+ sql.text("XA COMMIT :xid").bindparams(
317
+ sql.bindparam("xid", xid, literal_execute=True)
318
+ )
319
+ )
320
+
321
+
322
+ dialect = MySQLDialect_mariadbconnector
loan-advisor-agent/.venv/Lib/site-packages/sqlalchemy/dialects/mysql/mysqlconnector.py ADDED
@@ -0,0 +1,302 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # dialects/mysql/mysqlconnector.py
2
+ # Copyright (C) 2005-2026 the SQLAlchemy authors and contributors
3
+ # <see AUTHORS file>
4
+ #
5
+ # This module is part of SQLAlchemy and is released under
6
+ # the MIT License: https://www.opensource.org/licenses/mit-license.php
7
+
8
+
9
+ r"""
10
+ .. dialect:: mysql+mysqlconnector
11
+ :name: MySQL Connector/Python
12
+ :dbapi: myconnpy
13
+ :connectstring: mysql+mysqlconnector://<user>:<password>@<host>[:<port>]/<dbname>
14
+ :url: https://pypi.org/project/mysql-connector-python/
15
+
16
+ Driver Status
17
+ -------------
18
+
19
+ MySQL Connector/Python is supported as of SQLAlchemy 2.0.39 to the
20
+ degree which the driver is functional. There are still ongoing issues
21
+ with features such as server side cursors which remain disabled until
22
+ upstream issues are repaired.
23
+
24
+ .. warning:: The MySQL Connector/Python driver published by Oracle is subject
25
+ to frequent, major regressions of essential functionality such as being able
26
+ to correctly persist simple binary strings which indicate it is not well
27
+ tested. The SQLAlchemy project is not able to maintain this dialect fully as
28
+ regressions in the driver prevent it from being included in continuous
29
+ integration.
30
+
31
+ .. versionchanged:: 2.0.39
32
+
33
+ The MySQL Connector/Python dialect has been updated to support the
34
+ latest version of this DBAPI. Previously, MySQL Connector/Python
35
+ was not fully supported. However, support remains limited due to ongoing
36
+ regressions introduced in this driver.
37
+
38
+ Connecting to MariaDB with MySQL Connector/Python
39
+ --------------------------------------------------
40
+
41
+ MySQL Connector/Python may attempt to pass an incompatible collation to the
42
+ database when connecting to MariaDB. Experimentation has shown that using
43
+ ``?charset=utf8mb4&collation=utfmb4_general_ci`` or similar MariaDB-compatible
44
+ charset/collation will allow connectivity.
45
+
46
+
47
+ """ # noqa
48
+ from __future__ import annotations
49
+
50
+ import re
51
+ from typing import Any
52
+ from typing import cast
53
+ from typing import Optional
54
+ from typing import Sequence
55
+ from typing import Tuple
56
+ from typing import TYPE_CHECKING
57
+ from typing import Union
58
+
59
+ from .base import MariaDBIdentifierPreparer
60
+ from .base import MySQLCompiler
61
+ from .base import MySQLDialect
62
+ from .base import MySQLExecutionContext
63
+ from .base import MySQLIdentifierPreparer
64
+ from .mariadb import MariaDBDialect
65
+ from .types import BIT
66
+ from ... import util
67
+
68
+ if TYPE_CHECKING:
69
+
70
+ from ...engine.base import Connection
71
+ from ...engine.cursor import CursorResult
72
+ from ...engine.interfaces import ConnectArgsType
73
+ from ...engine.interfaces import DBAPIConnection
74
+ from ...engine.interfaces import DBAPICursor
75
+ from ...engine.interfaces import DBAPIModule
76
+ from ...engine.interfaces import IsolationLevel
77
+ from ...engine.interfaces import PoolProxiedConnection
78
+ from ...engine.row import Row
79
+ from ...engine.url import URL
80
+ from ...sql.elements import BinaryExpression
81
+
82
+
83
+ class MySQLExecutionContext_mysqlconnector(MySQLExecutionContext):
84
+ def create_server_side_cursor(self) -> DBAPICursor:
85
+ return self._dbapi_connection.cursor(buffered=False)
86
+
87
+ def create_default_cursor(self) -> DBAPICursor:
88
+ return self._dbapi_connection.cursor(buffered=True)
89
+
90
+
91
+ class MySQLCompiler_mysqlconnector(MySQLCompiler):
92
+ def visit_mod_binary(
93
+ self, binary: BinaryExpression[Any], operator: Any, **kw: Any
94
+ ) -> str:
95
+ return (
96
+ self.process(binary.left, **kw)
97
+ + " % "
98
+ + self.process(binary.right, **kw)
99
+ )
100
+
101
+
102
+ class IdentifierPreparerCommon_mysqlconnector:
103
+ @property
104
+ def _double_percents(self) -> bool:
105
+ return False
106
+
107
+ @_double_percents.setter
108
+ def _double_percents(self, value: Any) -> None:
109
+ pass
110
+
111
+ def _escape_identifier(self, value: str) -> str:
112
+ value = value.replace(
113
+ self.escape_quote, # type:ignore[attr-defined]
114
+ self.escape_to_quote, # type:ignore[attr-defined]
115
+ )
116
+ return value
117
+
118
+
119
+ class MySQLIdentifierPreparer_mysqlconnector(
120
+ IdentifierPreparerCommon_mysqlconnector, MySQLIdentifierPreparer
121
+ ):
122
+ pass
123
+
124
+
125
+ class MariaDBIdentifierPreparer_mysqlconnector(
126
+ IdentifierPreparerCommon_mysqlconnector, MariaDBIdentifierPreparer
127
+ ):
128
+ pass
129
+
130
+
131
+ class _myconnpyBIT(BIT):
132
+ def result_processor(self, dialect: Any, coltype: Any) -> None:
133
+ """MySQL-connector already converts mysql bits, so."""
134
+
135
+ return None
136
+
137
+
138
+ class MySQLDialect_mysqlconnector(MySQLDialect):
139
+ driver = "mysqlconnector"
140
+ supports_statement_cache = True
141
+
142
+ supports_sane_rowcount = True
143
+ supports_sane_multi_rowcount = True
144
+
145
+ supports_native_decimal = True
146
+
147
+ supports_native_bit = True
148
+
149
+ # not until https://bugs.mysql.com/bug.php?id=117548
150
+ supports_server_side_cursors = False
151
+
152
+ default_paramstyle = "format"
153
+ statement_compiler = MySQLCompiler_mysqlconnector
154
+
155
+ execution_ctx_cls = MySQLExecutionContext_mysqlconnector
156
+
157
+ preparer: type[MySQLIdentifierPreparer] = (
158
+ MySQLIdentifierPreparer_mysqlconnector
159
+ )
160
+
161
+ colspecs = util.update_copy(MySQLDialect.colspecs, {BIT: _myconnpyBIT})
162
+
163
+ @classmethod
164
+ def import_dbapi(cls) -> DBAPIModule:
165
+ return cast("DBAPIModule", __import__("mysql.connector").connector)
166
+
167
+ def do_ping(self, dbapi_connection: DBAPIConnection) -> bool:
168
+ dbapi_connection.ping(False)
169
+ return True
170
+
171
+ def create_connect_args(self, url: URL) -> ConnectArgsType:
172
+ opts = url.translate_connect_args(username="user")
173
+
174
+ opts.update(url.query)
175
+
176
+ util.coerce_kw_type(opts, "allow_local_infile", bool)
177
+ util.coerce_kw_type(opts, "autocommit", bool)
178
+ util.coerce_kw_type(opts, "buffered", bool)
179
+ util.coerce_kw_type(opts, "client_flag", int)
180
+ util.coerce_kw_type(opts, "compress", bool)
181
+ util.coerce_kw_type(opts, "connection_timeout", int)
182
+ util.coerce_kw_type(opts, "connect_timeout", int)
183
+ util.coerce_kw_type(opts, "consume_results", bool)
184
+ util.coerce_kw_type(opts, "force_ipv6", bool)
185
+ util.coerce_kw_type(opts, "get_warnings", bool)
186
+ util.coerce_kw_type(opts, "pool_reset_session", bool)
187
+ util.coerce_kw_type(opts, "pool_size", int)
188
+ util.coerce_kw_type(opts, "raise_on_warnings", bool)
189
+ util.coerce_kw_type(opts, "raw", bool)
190
+ util.coerce_kw_type(opts, "ssl_verify_cert", bool)
191
+ util.coerce_kw_type(opts, "use_pure", bool)
192
+ util.coerce_kw_type(opts, "use_unicode", bool)
193
+
194
+ # note that "buffered" is set to False by default in MySQL/connector
195
+ # python. If you set it to True, then there is no way to get a server
196
+ # side cursor because the logic is written to disallow that.
197
+
198
+ # leaving this at True until
199
+ # https://bugs.mysql.com/bug.php?id=117548 can be fixed
200
+ opts["buffered"] = True
201
+
202
+ # FOUND_ROWS must be set in ClientFlag to enable
203
+ # supports_sane_rowcount.
204
+ if self.dbapi is not None:
205
+ try:
206
+ from mysql.connector import constants # type: ignore
207
+
208
+ ClientFlag = constants.ClientFlag
209
+
210
+ client_flags = opts.get(
211
+ "client_flags", ClientFlag.get_default()
212
+ )
213
+ client_flags |= ClientFlag.FOUND_ROWS
214
+ opts["client_flags"] = client_flags
215
+ except Exception:
216
+ pass
217
+
218
+ return [], opts
219
+
220
+ @util.memoized_property
221
+ def _mysqlconnector_version_info(self) -> Optional[Tuple[int, ...]]:
222
+ if self.dbapi and hasattr(self.dbapi, "__version__"):
223
+ m = re.match(r"(\d+)\.(\d+)(?:\.(\d+))?", self.dbapi.__version__)
224
+ if m:
225
+ return tuple(int(x) for x in m.group(1, 2, 3) if x is not None)
226
+ return None
227
+
228
+ def _detect_charset(self, connection: Connection) -> str:
229
+ return connection.connection.charset # type: ignore
230
+
231
+ def _extract_error_code(self, exception: BaseException) -> int:
232
+ return exception.errno # type: ignore
233
+
234
+ def is_disconnect(
235
+ self,
236
+ e: Exception,
237
+ connection: Optional[Union[PoolProxiedConnection, DBAPIConnection]],
238
+ cursor: Optional[DBAPICursor],
239
+ ) -> bool:
240
+ errnos = (2006, 2013, 2014, 2045, 2055, 2048)
241
+ exceptions = (
242
+ self.loaded_dbapi.OperationalError, #
243
+ self.loaded_dbapi.InterfaceError,
244
+ self.loaded_dbapi.ProgrammingError,
245
+ )
246
+ if isinstance(e, exceptions):
247
+ return (
248
+ e.errno in errnos
249
+ or "MySQL Connection not available." in str(e)
250
+ or "Connection to MySQL is not available" in str(e)
251
+ )
252
+ else:
253
+ return False
254
+
255
+ def _compat_fetchall(
256
+ self,
257
+ rp: CursorResult[Tuple[Any, ...]],
258
+ charset: Optional[str] = None,
259
+ ) -> Sequence[Row[Tuple[Any, ...]]]:
260
+ return rp.fetchall()
261
+
262
+ def _compat_fetchone(
263
+ self,
264
+ rp: CursorResult[Tuple[Any, ...]],
265
+ charset: Optional[str] = None,
266
+ ) -> Optional[Row[Tuple[Any, ...]]]:
267
+ return rp.fetchone()
268
+
269
+ def get_isolation_level_values(
270
+ self, dbapi_conn: DBAPIConnection
271
+ ) -> Sequence[IsolationLevel]:
272
+ return (
273
+ "SERIALIZABLE",
274
+ "READ UNCOMMITTED",
275
+ "READ COMMITTED",
276
+ "REPEATABLE READ",
277
+ "AUTOCOMMIT",
278
+ )
279
+
280
+ def detect_autocommit_setting(self, dbapi_conn: DBAPIConnection) -> bool:
281
+ return bool(dbapi_conn.autocommit)
282
+
283
+ def set_isolation_level(
284
+ self, dbapi_connection: DBAPIConnection, level: IsolationLevel
285
+ ) -> None:
286
+ if level == "AUTOCOMMIT":
287
+ dbapi_connection.autocommit = True
288
+ else:
289
+ dbapi_connection.autocommit = False
290
+ super().set_isolation_level(dbapi_connection, level)
291
+
292
+
293
+ class MariaDBDialect_mysqlconnector(
294
+ MariaDBDialect, MySQLDialect_mysqlconnector
295
+ ):
296
+ supports_statement_cache = True
297
+ _allows_uuid_binds = False
298
+ preparer = MariaDBIdentifierPreparer_mysqlconnector
299
+
300
+
301
+ dialect = MySQLDialect_mysqlconnector
302
+ mariadb_dialect = MariaDBDialect_mysqlconnector
loan-advisor-agent/.venv/Lib/site-packages/sqlalchemy/dialects/mysql/mysqldb.py ADDED
@@ -0,0 +1,314 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # dialects/mysql/mysqldb.py
2
+ # Copyright (C) 2005-2026 the SQLAlchemy authors and contributors
3
+ # <see AUTHORS file>
4
+ #
5
+ # This module is part of SQLAlchemy and is released under
6
+ # the MIT License: https://www.opensource.org/licenses/mit-license.php
7
+
8
+ """
9
+
10
+ .. dialect:: mysql+mysqldb
11
+ :name: mysqlclient (maintained fork of MySQL-Python)
12
+ :dbapi: mysqldb
13
+ :connectstring: mysql+mysqldb://<user>:<password>@<host>[:<port>]/<dbname>
14
+ :url: https://pypi.org/project/mysqlclient/
15
+
16
+ Driver Status
17
+ -------------
18
+
19
+ The mysqlclient DBAPI is a maintained fork of the
20
+ `MySQL-Python <https://sourceforge.net/projects/mysql-python>`_ DBAPI
21
+ that is no longer maintained. `mysqlclient`_ supports Python 2 and Python 3
22
+ and is very stable.
23
+
24
+ .. _mysqlclient: https://github.com/PyMySQL/mysqlclient-python
25
+
26
+ .. _mysqldb_unicode:
27
+
28
+ Unicode
29
+ -------
30
+
31
+ Please see :ref:`mysql_unicode` for current recommendations on unicode
32
+ handling.
33
+
34
+ .. _mysqldb_ssl:
35
+
36
+ SSL Connections
37
+ ----------------
38
+
39
+ The mysqlclient and PyMySQL DBAPIs accept an additional dictionary under the
40
+ key "ssl", which may be specified using the
41
+ :paramref:`_sa.create_engine.connect_args` dictionary::
42
+
43
+ engine = create_engine(
44
+ "mysql+mysqldb://scott:tiger@192.168.0.134/test",
45
+ connect_args={
46
+ "ssl": {
47
+ "ca": "/home/gord/client-ssl/ca.pem",
48
+ "cert": "/home/gord/client-ssl/client-cert.pem",
49
+ "key": "/home/gord/client-ssl/client-key.pem",
50
+ }
51
+ },
52
+ )
53
+
54
+ For convenience, the following keys may also be specified inline within the URL
55
+ where they will be interpreted into the "ssl" dictionary automatically:
56
+ "ssl_ca", "ssl_cert", "ssl_key", "ssl_capath", "ssl_cipher",
57
+ "ssl_check_hostname". An example is as follows::
58
+
59
+ connection_uri = (
60
+ "mysql+mysqldb://scott:tiger@192.168.0.134/test"
61
+ "?ssl_ca=/home/gord/client-ssl/ca.pem"
62
+ "&ssl_cert=/home/gord/client-ssl/client-cert.pem"
63
+ "&ssl_key=/home/gord/client-ssl/client-key.pem"
64
+ )
65
+
66
+ .. seealso::
67
+
68
+ :ref:`pymysql_ssl` in the PyMySQL dialect
69
+
70
+
71
+ Using MySQLdb with Google Cloud SQL
72
+ -----------------------------------
73
+
74
+ Google Cloud SQL now recommends use of the MySQLdb dialect. Connect
75
+ using a URL like the following:
76
+
77
+ .. sourcecode:: text
78
+
79
+ mysql+mysqldb://root@/<dbname>?unix_socket=/cloudsql/<projectid>:<instancename>
80
+
81
+ Server Side Cursors
82
+ -------------------
83
+
84
+ The mysqldb dialect supports server-side cursors. See :ref:`mysql_ss_cursors`.
85
+
86
+ """
87
+ from __future__ import annotations
88
+
89
+ import re
90
+ from typing import Any
91
+ from typing import Callable
92
+ from typing import cast
93
+ from typing import Dict
94
+ from typing import Optional
95
+ from typing import Tuple
96
+ from typing import TYPE_CHECKING
97
+
98
+ from .base import MySQLCompiler
99
+ from .base import MySQLDialect
100
+ from .base import MySQLExecutionContext
101
+ from .base import MySQLIdentifierPreparer
102
+ from ... import util
103
+ from ...util.typing import Literal
104
+
105
+ if TYPE_CHECKING:
106
+
107
+ from ...engine.base import Connection
108
+ from ...engine.interfaces import _DBAPIMultiExecuteParams
109
+ from ...engine.interfaces import ConnectArgsType
110
+ from ...engine.interfaces import DBAPIConnection
111
+ from ...engine.interfaces import DBAPICursor
112
+ from ...engine.interfaces import DBAPIModule
113
+ from ...engine.interfaces import ExecutionContext
114
+ from ...engine.interfaces import IsolationLevel
115
+ from ...engine.url import URL
116
+
117
+
118
+ class MySQLExecutionContext_mysqldb(MySQLExecutionContext):
119
+ pass
120
+
121
+
122
+ class MySQLCompiler_mysqldb(MySQLCompiler):
123
+ pass
124
+
125
+
126
+ class MySQLDialect_mysqldb(MySQLDialect):
127
+ driver = "mysqldb"
128
+ supports_statement_cache = True
129
+ supports_unicode_statements = True
130
+ supports_sane_rowcount = True
131
+ supports_sane_multi_rowcount = True
132
+
133
+ supports_native_decimal = True
134
+
135
+ default_paramstyle = "format"
136
+ execution_ctx_cls = MySQLExecutionContext_mysqldb
137
+ statement_compiler = MySQLCompiler_mysqldb
138
+ preparer = MySQLIdentifierPreparer
139
+ server_version_info: Tuple[int, ...]
140
+
141
+ def __init__(self, **kwargs: Any):
142
+ super().__init__(**kwargs)
143
+ self._mysql_dbapi_version = (
144
+ self._parse_dbapi_version(self.dbapi.__version__)
145
+ if self.dbapi is not None and hasattr(self.dbapi, "__version__")
146
+ else (0, 0, 0)
147
+ )
148
+
149
+ def _parse_dbapi_version(self, version: str) -> Tuple[int, ...]:
150
+ m = re.match(r"(\d+)\.(\d+)(?:\.(\d+))?", version)
151
+ if m:
152
+ return tuple(int(x) for x in m.group(1, 2, 3) if x is not None)
153
+ else:
154
+ return (0, 0, 0)
155
+
156
+ @util.langhelpers.memoized_property
157
+ def supports_server_side_cursors(self) -> bool:
158
+ try:
159
+ cursors = __import__("MySQLdb.cursors").cursors
160
+ self._sscursor = cursors.SSCursor
161
+ return True
162
+ except (ImportError, AttributeError):
163
+ return False
164
+
165
+ @classmethod
166
+ def import_dbapi(cls) -> DBAPIModule:
167
+ return __import__("MySQLdb")
168
+
169
+ def on_connect(self) -> Callable[[DBAPIConnection], None]:
170
+ super_ = super().on_connect()
171
+
172
+ def on_connect(conn: DBAPIConnection) -> None:
173
+ if super_ is not None:
174
+ super_(conn)
175
+
176
+ charset_name = conn.character_set_name()
177
+
178
+ if charset_name is not None:
179
+ cursor = conn.cursor()
180
+ cursor.execute("SET NAMES %s" % charset_name)
181
+ cursor.close()
182
+
183
+ return on_connect
184
+
185
+ def do_ping(self, dbapi_connection: DBAPIConnection) -> Literal[True]:
186
+ dbapi_connection.ping()
187
+ return True
188
+
189
+ def do_executemany(
190
+ self,
191
+ cursor: DBAPICursor,
192
+ statement: str,
193
+ parameters: _DBAPIMultiExecuteParams,
194
+ context: Optional[ExecutionContext] = None,
195
+ ) -> None:
196
+ rowcount = cursor.executemany(statement, parameters)
197
+ if context is not None:
198
+ cast(MySQLExecutionContext, context)._rowcount = rowcount
199
+
200
+ def create_connect_args(
201
+ self, url: URL, _translate_args: Optional[Dict[str, Any]] = None
202
+ ) -> ConnectArgsType:
203
+ if _translate_args is None:
204
+ _translate_args = dict(
205
+ database="db", username="user", password="passwd"
206
+ )
207
+
208
+ opts = url.translate_connect_args(**_translate_args)
209
+ opts.update(url.query)
210
+
211
+ util.coerce_kw_type(opts, "compress", bool)
212
+ util.coerce_kw_type(opts, "connect_timeout", int)
213
+ util.coerce_kw_type(opts, "read_timeout", int)
214
+ util.coerce_kw_type(opts, "write_timeout", int)
215
+ util.coerce_kw_type(opts, "client_flag", int)
216
+ util.coerce_kw_type(opts, "local_infile", bool)
217
+ # Note: using either of the below will cause all strings to be
218
+ # returned as Unicode, both in raw SQL operations and with column
219
+ # types like String and MSString.
220
+ util.coerce_kw_type(opts, "use_unicode", bool)
221
+ util.coerce_kw_type(opts, "charset", str)
222
+
223
+ # Rich values 'cursorclass' and 'conv' are not supported via
224
+ # query string.
225
+
226
+ ssl = {}
227
+ keys = [
228
+ ("ssl_ca", str),
229
+ ("ssl_key", str),
230
+ ("ssl_cert", str),
231
+ ("ssl_capath", str),
232
+ ("ssl_cipher", str),
233
+ ("ssl_check_hostname", bool),
234
+ ]
235
+ for key, kw_type in keys:
236
+ if key in opts:
237
+ ssl[key[4:]] = opts[key]
238
+ util.coerce_kw_type(ssl, key[4:], kw_type)
239
+ del opts[key]
240
+ if ssl:
241
+ opts["ssl"] = ssl
242
+
243
+ # FOUND_ROWS must be set in CLIENT_FLAGS to enable
244
+ # supports_sane_rowcount.
245
+ client_flag = opts.get("client_flag", 0)
246
+
247
+ client_flag_found_rows = self._found_rows_client_flag()
248
+ if client_flag_found_rows is not None:
249
+ client_flag |= client_flag_found_rows
250
+ opts["client_flag"] = client_flag
251
+ return [], opts
252
+
253
+ def _found_rows_client_flag(self) -> Optional[int]:
254
+ if self.dbapi is not None:
255
+ try:
256
+ CLIENT_FLAGS = __import__(
257
+ self.dbapi.__name__ + ".constants.CLIENT"
258
+ ).constants.CLIENT
259
+ except (AttributeError, ImportError):
260
+ return None
261
+ else:
262
+ return CLIENT_FLAGS.FOUND_ROWS # type: ignore
263
+ else:
264
+ return None
265
+
266
+ def _extract_error_code(self, exception: DBAPIModule.Error) -> int:
267
+ return exception.args[0] # type: ignore[no-any-return]
268
+
269
+ def _detect_charset(self, connection: Connection) -> str:
270
+ """Sniff out the character set in use for connection results."""
271
+
272
+ try:
273
+ # note: the SQL here would be
274
+ # "SHOW VARIABLES LIKE 'character_set%%'"
275
+
276
+ cset_name: Callable[[], str] = (
277
+ connection.connection.character_set_name
278
+ )
279
+ except AttributeError:
280
+ util.warn(
281
+ "No 'character_set_name' can be detected with "
282
+ "this MySQL-Python version; "
283
+ "please upgrade to a recent version of MySQL-Python. "
284
+ "Assuming latin1."
285
+ )
286
+ return "latin1"
287
+ else:
288
+ return cset_name()
289
+
290
+ def get_isolation_level_values(
291
+ self, dbapi_conn: DBAPIConnection
292
+ ) -> Tuple[IsolationLevel, ...]:
293
+ return (
294
+ "SERIALIZABLE",
295
+ "READ UNCOMMITTED",
296
+ "READ COMMITTED",
297
+ "REPEATABLE READ",
298
+ "AUTOCOMMIT",
299
+ )
300
+
301
+ def detect_autocommit_setting(self, dbapi_conn: DBAPIConnection) -> bool:
302
+ return dbapi_conn.get_autocommit() # type: ignore[no-any-return]
303
+
304
+ def set_isolation_level(
305
+ self, dbapi_connection: DBAPIConnection, level: IsolationLevel
306
+ ) -> None:
307
+ if level == "AUTOCOMMIT":
308
+ dbapi_connection.autocommit(True)
309
+ else:
310
+ dbapi_connection.autocommit(False)
311
+ super().set_isolation_level(dbapi_connection, level)
312
+
313
+
314
+ dialect = MySQLDialect_mysqldb
loan-advisor-agent/.venv/Lib/site-packages/sqlalchemy/dialects/mysql/provision.py ADDED
@@ -0,0 +1,153 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # dialects/mysql/provision.py
2
+ # Copyright (C) 2005-2026 the SQLAlchemy authors and contributors
3
+ # <see AUTHORS file>
4
+ #
5
+ # This module is part of SQLAlchemy and is released under
6
+ # the MIT License: https://www.opensource.org/licenses/mit-license.php
7
+ # mypy: ignore-errors
8
+ import contextlib
9
+
10
+ from ... import event
11
+ from ... import exc
12
+ from ...testing.provision import allow_stale_update_impl
13
+ from ...testing.provision import configure_follower
14
+ from ...testing.provision import create_db
15
+ from ...testing.provision import delete_from_all_tables
16
+ from ...testing.provision import drop_db
17
+ from ...testing.provision import generate_driver_url
18
+ from ...testing.provision import temp_table_keyword_args
19
+ from ...testing.provision import upsert
20
+
21
+
22
+ @generate_driver_url.for_db("mysql", "mariadb")
23
+ def generate_driver_url(url, driver, query_str):
24
+ backend = url.get_backend_name()
25
+
26
+ # NOTE: at the moment, tests are running mariadbconnector
27
+ # against both mariadb and mysql backends. if we want this to be
28
+ # limited, do the decision making here to reject a "mysql+mariadbconnector"
29
+ # URL. Optionally also re-enable the module level
30
+ # MySQLDialect_mariadbconnector.is_mysql flag as well, which must include
31
+ # a unit and/or functional test.
32
+
33
+ # all the Jenkins tests have been running mysqlclient Python library
34
+ # built against mariadb client drivers for years against all MySQL /
35
+ # MariaDB versions going back to MySQL 5.6, currently they can talk
36
+ # to MySQL databases without problems.
37
+
38
+ if backend == "mysql":
39
+ dialect_cls = url.get_dialect()
40
+ if dialect_cls._is_mariadb_from_url(url):
41
+ backend = "mariadb"
42
+
43
+ new_url = url.set(
44
+ drivername="%s+%s" % (backend, driver)
45
+ ).update_query_string(query_str)
46
+
47
+ if driver == "mariadbconnector":
48
+ new_url = new_url.difference_update_query(["charset"])
49
+ elif driver == "mysqlconnector":
50
+ new_url = new_url.update_query_pairs(
51
+ [("collation", "utf8mb4_general_ci")]
52
+ )
53
+
54
+ try:
55
+ new_url.get_dialect()
56
+ except exc.NoSuchModuleError:
57
+ return None
58
+ else:
59
+ return new_url
60
+
61
+
62
+ @create_db.for_db("mysql", "mariadb")
63
+ def _mysql_create_db(cfg, eng, ident):
64
+ with eng.begin() as conn:
65
+ try:
66
+ _mysql_drop_db(cfg, conn, ident)
67
+ except Exception:
68
+ pass
69
+
70
+ with eng.begin() as conn:
71
+ conn.exec_driver_sql(
72
+ "CREATE DATABASE %s CHARACTER SET utf8mb4" % ident
73
+ )
74
+ conn.exec_driver_sql(
75
+ "CREATE DATABASE %s_test_schema CHARACTER SET utf8mb4" % ident
76
+ )
77
+ conn.exec_driver_sql(
78
+ "CREATE DATABASE %s_test_schema_2 CHARACTER SET utf8mb4" % ident
79
+ )
80
+
81
+
82
+ @configure_follower.for_db("mysql", "mariadb")
83
+ def _mysql_configure_follower(config, ident):
84
+ config.test_schema = "%s_test_schema" % ident
85
+ config.test_schema_2 = "%s_test_schema_2" % ident
86
+
87
+
88
+ @drop_db.for_db("mysql", "mariadb")
89
+ def _mysql_drop_db(cfg, eng, ident):
90
+ with eng.begin() as conn:
91
+ conn.exec_driver_sql("DROP DATABASE %s_test_schema" % ident)
92
+ conn.exec_driver_sql("DROP DATABASE %s_test_schema_2" % ident)
93
+ conn.exec_driver_sql("DROP DATABASE %s" % ident)
94
+
95
+
96
+ @temp_table_keyword_args.for_db("mysql", "mariadb")
97
+ def _mysql_temp_table_keyword_args(cfg, eng):
98
+ return {"prefixes": ["TEMPORARY"]}
99
+
100
+
101
+ @upsert.for_db("mariadb")
102
+ def _upsert(
103
+ cfg,
104
+ table,
105
+ returning,
106
+ *,
107
+ set_lambda=None,
108
+ sort_by_parameter_order=False,
109
+ index_elements=None,
110
+ ):
111
+ from sqlalchemy.dialects.mysql import insert
112
+
113
+ stmt = insert(table)
114
+
115
+ if set_lambda:
116
+ stmt = stmt.on_duplicate_key_update(**set_lambda(stmt.inserted))
117
+ else:
118
+ pk1 = table.primary_key.c[0]
119
+ stmt = stmt.on_duplicate_key_update({pk1.key: pk1})
120
+
121
+ stmt = stmt.returning(
122
+ *returning, sort_by_parameter_order=sort_by_parameter_order
123
+ )
124
+ return stmt
125
+
126
+
127
+ @delete_from_all_tables.for_db("mysql", "mariadb")
128
+ def _delete_from_all_tables(connection, cfg, metadata):
129
+ connection.exec_driver_sql("SET foreign_key_checks = 0")
130
+ try:
131
+ delete_from_all_tables.call_original(connection, cfg, metadata)
132
+ finally:
133
+ connection.exec_driver_sql("SET foreign_key_checks = 1")
134
+
135
+
136
+ @allow_stale_update_impl.for_db("mariadb")
137
+ def _allow_stale_update_impl(cfg):
138
+ @contextlib.contextmanager
139
+ def go():
140
+ @event.listens_for(cfg.db, "engine_connect")
141
+ def turn_off_snapshot_isolation(conn):
142
+ conn.exec_driver_sql("SET innodb_snapshot_isolation = 'OFF'")
143
+ conn.rollback()
144
+
145
+ try:
146
+ yield
147
+ finally:
148
+ event.remove(cfg.db, "engine_connect", turn_off_snapshot_isolation)
149
+
150
+ # dispose the pool; quick way to just have those reset
151
+ cfg.db.dispose()
152
+
153
+ return go()
loan-advisor-agent/.venv/Lib/site-packages/sqlalchemy/dialects/mysql/pymysql.py ADDED
@@ -0,0 +1,158 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # dialects/mysql/pymysql.py
2
+ # Copyright (C) 2005-2026 the SQLAlchemy authors and contributors
3
+ # <see AUTHORS file>
4
+ #
5
+ # This module is part of SQLAlchemy and is released under
6
+ # the MIT License: https://www.opensource.org/licenses/mit-license.php
7
+
8
+ r"""
9
+
10
+ .. dialect:: mysql+pymysql
11
+ :name: PyMySQL
12
+ :dbapi: pymysql
13
+ :connectstring: mysql+pymysql://<username>:<password>@<host>/<dbname>[?<options>]
14
+ :url: https://pymysql.readthedocs.io/
15
+
16
+ Unicode
17
+ -------
18
+
19
+ Please see :ref:`mysql_unicode` for current recommendations on unicode
20
+ handling.
21
+
22
+ .. _pymysql_ssl:
23
+
24
+ SSL Connections
25
+ ------------------
26
+
27
+ The PyMySQL DBAPI accepts the same SSL arguments as that of MySQLdb,
28
+ described at :ref:`mysqldb_ssl`. See that section for additional examples.
29
+
30
+ If the server uses an automatically-generated certificate that is self-signed
31
+ or does not match the host name (as seen from the client), it may also be
32
+ necessary to indicate ``ssl_check_hostname=false`` in PyMySQL::
33
+
34
+ connection_uri = (
35
+ "mysql+pymysql://scott:tiger@192.168.0.134/test"
36
+ "?ssl_ca=/home/gord/client-ssl/ca.pem"
37
+ "&ssl_cert=/home/gord/client-ssl/client-cert.pem"
38
+ "&ssl_key=/home/gord/client-ssl/client-key.pem"
39
+ "&ssl_check_hostname=false"
40
+ )
41
+
42
+ MySQL-Python Compatibility
43
+ --------------------------
44
+
45
+ The pymysql DBAPI is a pure Python port of the MySQL-python (MySQLdb) driver,
46
+ and targets 100% compatibility. Most behavioral notes for MySQL-python apply
47
+ to the pymysql driver as well.
48
+
49
+ """ # noqa
50
+ from __future__ import annotations
51
+
52
+ from typing import Any
53
+ from typing import Dict
54
+ from typing import Optional
55
+ from typing import TYPE_CHECKING
56
+ from typing import Union
57
+
58
+ from .mysqldb import MySQLDialect_mysqldb
59
+ from ...util import langhelpers
60
+ from ...util.typing import Literal
61
+
62
+ if TYPE_CHECKING:
63
+
64
+ from ...engine.interfaces import ConnectArgsType
65
+ from ...engine.interfaces import DBAPIConnection
66
+ from ...engine.interfaces import DBAPICursor
67
+ from ...engine.interfaces import DBAPIModule
68
+ from ...engine.interfaces import PoolProxiedConnection
69
+ from ...engine.url import URL
70
+
71
+
72
+ class MySQLDialect_pymysql(MySQLDialect_mysqldb):
73
+ driver = "pymysql"
74
+ supports_statement_cache = True
75
+
76
+ description_encoding = None
77
+
78
+ @langhelpers.memoized_property
79
+ def supports_server_side_cursors(self) -> bool:
80
+ try:
81
+ cursors = __import__("pymysql.cursors").cursors
82
+ self._sscursor = cursors.SSCursor
83
+ return True
84
+ except (ImportError, AttributeError):
85
+ return False
86
+
87
+ @classmethod
88
+ def import_dbapi(cls) -> DBAPIModule:
89
+ return __import__("pymysql")
90
+
91
+ @langhelpers.memoized_property
92
+ def _send_false_to_ping(self) -> bool:
93
+ """determine if pymysql has deprecated, changed the default of,
94
+ or removed the 'reconnect' argument of connection.ping().
95
+
96
+ See #10492 and
97
+ https://github.com/PyMySQL/mysqlclient/discussions/651#discussioncomment-7308971
98
+ for background.
99
+
100
+ """ # noqa: E501
101
+
102
+ try:
103
+ Connection = __import__(
104
+ "pymysql.connections"
105
+ ).connections.Connection
106
+ except (ImportError, AttributeError):
107
+ return True
108
+ else:
109
+ insp = langhelpers.get_callable_argspec(Connection.ping)
110
+ try:
111
+ reconnect_arg = insp.args[1]
112
+ except IndexError:
113
+ return False
114
+ else:
115
+ return reconnect_arg == "reconnect" and (
116
+ not insp.defaults or insp.defaults[0] is not False
117
+ )
118
+
119
+ def do_ping(self, dbapi_connection: DBAPIConnection) -> Literal[True]:
120
+ if self._send_false_to_ping:
121
+ dbapi_connection.ping(False)
122
+ else:
123
+ dbapi_connection.ping()
124
+
125
+ return True
126
+
127
+ def create_connect_args(
128
+ self, url: URL, _translate_args: Optional[Dict[str, Any]] = None
129
+ ) -> ConnectArgsType:
130
+ if _translate_args is None:
131
+ _translate_args = dict(username="user")
132
+ return super().create_connect_args(
133
+ url, _translate_args=_translate_args
134
+ )
135
+
136
+ def is_disconnect(
137
+ self,
138
+ e: DBAPIModule.Error,
139
+ connection: Optional[Union[PoolProxiedConnection, DBAPIConnection]],
140
+ cursor: Optional[DBAPICursor],
141
+ ) -> bool:
142
+ if super().is_disconnect(e, connection, cursor):
143
+ return True
144
+ elif isinstance(e, self.loaded_dbapi.Error):
145
+ str_e = str(e).lower()
146
+ return (
147
+ "already closed" in str_e or "connection was killed" in str_e
148
+ )
149
+ else:
150
+ return False
151
+
152
+ def _extract_error_code(self, exception: BaseException) -> Any:
153
+ if isinstance(exception.args[0], Exception):
154
+ exception = exception.args[0]
155
+ return exception.args[0]
156
+
157
+
158
+ dialect = MySQLDialect_pymysql
loan-advisor-agent/.venv/Lib/site-packages/sqlalchemy/dialects/mysql/pyodbc.py ADDED
@@ -0,0 +1,157 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # dialects/mysql/pyodbc.py
2
+ # Copyright (C) 2005-2026 the SQLAlchemy authors and contributors
3
+ # <see AUTHORS file>
4
+ #
5
+ # This module is part of SQLAlchemy and is released under
6
+ # the MIT License: https://www.opensource.org/licenses/mit-license.php
7
+
8
+
9
+ r"""
10
+
11
+ .. dialect:: mysql+pyodbc
12
+ :name: PyODBC
13
+ :dbapi: pyodbc
14
+ :connectstring: mysql+pyodbc://<username>:<password>@<dsnname>
15
+ :url: https://pypi.org/project/pyodbc/
16
+
17
+ .. note::
18
+
19
+ The PyODBC for MySQL dialect is **not tested as part of
20
+ SQLAlchemy's continuous integration**.
21
+ The recommended MySQL dialects are mysqlclient and PyMySQL.
22
+ However, if you want to use the mysql+pyodbc dialect and require
23
+ full support for ``utf8mb4`` characters (including supplementary
24
+ characters like emoji) be sure to use a current release of
25
+ MySQL Connector/ODBC and specify the "ANSI" (**not** "Unicode")
26
+ version of the driver in your DSN or connection string.
27
+
28
+ Pass through exact pyodbc connection string::
29
+
30
+ import urllib
31
+
32
+ connection_string = (
33
+ "DRIVER=MySQL ODBC 8.0 ANSI Driver;"
34
+ "SERVER=localhost;"
35
+ "PORT=3307;"
36
+ "DATABASE=mydb;"
37
+ "UID=root;"
38
+ "PWD=(whatever);"
39
+ "charset=utf8mb4;"
40
+ )
41
+ params = urllib.parse.quote_plus(connection_string)
42
+ connection_uri = "mysql+pyodbc:///?odbc_connect=%s" % params
43
+
44
+ """ # noqa
45
+ from __future__ import annotations
46
+
47
+ import datetime
48
+ import re
49
+ from typing import Any
50
+ from typing import Callable
51
+ from typing import Optional
52
+ from typing import Tuple
53
+ from typing import TYPE_CHECKING
54
+ from typing import Union
55
+
56
+ from .base import MySQLDialect
57
+ from .base import MySQLExecutionContext
58
+ from .types import TIME
59
+ from ... import exc
60
+ from ... import util
61
+ from ...connectors.pyodbc import PyODBCConnector
62
+ from ...sql.sqltypes import Time
63
+
64
+ if TYPE_CHECKING:
65
+ from ...engine import Connection
66
+ from ...engine.interfaces import DBAPIConnection
67
+ from ...engine.interfaces import Dialect
68
+ from ...sql.type_api import _ResultProcessorType
69
+
70
+
71
+ class _pyodbcTIME(TIME):
72
+ def result_processor(
73
+ self, dialect: Dialect, coltype: object
74
+ ) -> _ResultProcessorType[datetime.time]:
75
+ def process(value: Any) -> Union[datetime.time, None]:
76
+ # pyodbc returns a datetime.time object; no need to convert
77
+ return value # type: ignore[no-any-return]
78
+
79
+ return process
80
+
81
+
82
+ class MySQLExecutionContext_pyodbc(MySQLExecutionContext):
83
+ def get_lastrowid(self) -> int:
84
+ cursor = self.create_cursor()
85
+ cursor.execute("SELECT LAST_INSERT_ID()")
86
+ lastrowid = cursor.fetchone()[0] # type: ignore[index]
87
+ cursor.close()
88
+ return lastrowid # type: ignore[no-any-return]
89
+
90
+
91
+ class MySQLDialect_pyodbc(PyODBCConnector, MySQLDialect):
92
+ supports_statement_cache = True
93
+ colspecs = util.update_copy(MySQLDialect.colspecs, {Time: _pyodbcTIME})
94
+ supports_unicode_statements = True
95
+ execution_ctx_cls = MySQLExecutionContext_pyodbc
96
+
97
+ pyodbc_driver_name = "MySQL"
98
+
99
+ def _detect_charset(self, connection: Connection) -> str:
100
+ """Sniff out the character set in use for connection results."""
101
+
102
+ # Prefer 'character_set_results' for the current connection over the
103
+ # value in the driver. SET NAMES or individual variable SETs will
104
+ # change the charset without updating the driver's view of the world.
105
+ #
106
+ # If it's decided that issuing that sort of SQL leaves you SOL, then
107
+ # this can prefer the driver value.
108
+
109
+ # set this to None as _fetch_setting attempts to use it (None is OK)
110
+ self._connection_charset = None
111
+ try:
112
+ value = self._fetch_setting(connection, "character_set_client")
113
+ if value:
114
+ return value
115
+ except exc.DBAPIError:
116
+ pass
117
+
118
+ util.warn(
119
+ "Could not detect the connection character set. "
120
+ "Assuming latin1."
121
+ )
122
+ return "latin1"
123
+
124
+ def _get_server_version_info(
125
+ self, connection: Connection
126
+ ) -> Tuple[int, ...]:
127
+ return MySQLDialect._get_server_version_info(self, connection)
128
+
129
+ def _extract_error_code(self, exception: BaseException) -> Optional[int]:
130
+ m = re.compile(r"\((\d+)\)").search(str(exception.args))
131
+ if m is None:
132
+ return None
133
+ c: Optional[str] = m.group(1)
134
+ if c:
135
+ return int(c)
136
+ else:
137
+ return None
138
+
139
+ def on_connect(self) -> Callable[[DBAPIConnection], None]:
140
+ super_ = super().on_connect()
141
+
142
+ def on_connect(conn: DBAPIConnection) -> None:
143
+ if super_ is not None:
144
+ super_(conn)
145
+
146
+ # declare Unicode encoding for pyodbc as per
147
+ # https://github.com/mkleehammer/pyodbc/wiki/Unicode
148
+ pyodbc_SQL_CHAR = 1 # pyodbc.SQL_CHAR
149
+ pyodbc_SQL_WCHAR = -8 # pyodbc.SQL_WCHAR
150
+ conn.setdecoding(pyodbc_SQL_CHAR, encoding="utf-8")
151
+ conn.setdecoding(pyodbc_SQL_WCHAR, encoding="utf-8")
152
+ conn.setencoding(encoding="utf-8")
153
+
154
+ return on_connect
155
+
156
+
157
+ dialect = MySQLDialect_pyodbc
loan-advisor-agent/.venv/Lib/site-packages/sqlalchemy/dialects/mysql/reflection.py ADDED
@@ -0,0 +1,727 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # dialects/mysql/reflection.py
2
+ # Copyright (C) 2005-2026 the SQLAlchemy authors and contributors
3
+ # <see AUTHORS file>
4
+ #
5
+ # This module is part of SQLAlchemy and is released under
6
+ # the MIT License: https://www.opensource.org/licenses/mit-license.php
7
+ from __future__ import annotations
8
+
9
+ import re
10
+ from typing import Any
11
+ from typing import Callable
12
+ from typing import Dict
13
+ from typing import List
14
+ from typing import Optional
15
+ from typing import overload
16
+ from typing import Sequence
17
+ from typing import Tuple
18
+ from typing import TYPE_CHECKING
19
+ from typing import Union
20
+
21
+ from .enumerated import ENUM
22
+ from .enumerated import SET
23
+ from .types import DATETIME
24
+ from .types import TIME
25
+ from .types import TIMESTAMP
26
+ from ... import types as sqltypes
27
+ from ... import util
28
+ from ...util.typing import Literal
29
+
30
+ if TYPE_CHECKING:
31
+ from .base import MySQLDialect
32
+ from .base import MySQLIdentifierPreparer
33
+ from ...engine.interfaces import ReflectedColumn
34
+
35
+
36
+ class ReflectedState:
37
+ """Stores raw information about a SHOW CREATE TABLE statement."""
38
+
39
+ charset: Optional[str]
40
+
41
+ def __init__(self) -> None:
42
+ self.columns: List[ReflectedColumn] = []
43
+ self.table_options: Dict[str, str] = {}
44
+ self.table_name: Optional[str] = None
45
+ self.keys: List[Dict[str, Any]] = []
46
+ self.fk_constraints: List[Dict[str, Any]] = []
47
+ self.ck_constraints: List[Dict[str, Any]] = []
48
+
49
+
50
+ class MySQLTableDefinitionParser:
51
+ """Parses the results of a SHOW CREATE TABLE statement."""
52
+
53
+ def __init__(
54
+ self, dialect: MySQLDialect, preparer: MySQLIdentifierPreparer
55
+ ):
56
+ self.dialect = dialect
57
+ self.preparer = preparer
58
+ self._prep_regexes()
59
+
60
+ def parse(
61
+ self, show_create: str, charset: Optional[str]
62
+ ) -> ReflectedState:
63
+ state = ReflectedState()
64
+ state.charset = charset
65
+ for line in re.split(r"\r?\n", show_create):
66
+ if line.startswith(" " + self.preparer.initial_quote):
67
+ self._parse_column(line, state)
68
+ # a regular table options line
69
+ elif line.startswith(") "):
70
+ self._parse_table_options(line, state)
71
+ # an ANSI-mode table options line
72
+ elif line == ")":
73
+ pass
74
+ elif line.startswith("CREATE "):
75
+ self._parse_table_name(line, state)
76
+ elif "PARTITION" in line:
77
+ self._parse_partition_options(line, state)
78
+ # Not present in real reflection, but may be if
79
+ # loading from a file.
80
+ elif not line:
81
+ pass
82
+ else:
83
+ type_, spec = self._parse_constraints(line)
84
+ if type_ is None:
85
+ util.warn("Unknown schema content: %r" % line)
86
+ elif type_ == "key":
87
+ state.keys.append(spec) # type: ignore[arg-type]
88
+ elif type_ == "fk_constraint":
89
+ state.fk_constraints.append(spec) # type: ignore[arg-type]
90
+ elif type_ == "ck_constraint":
91
+ state.ck_constraints.append(spec) # type: ignore[arg-type]
92
+ else:
93
+ pass
94
+ return state
95
+
96
+ def _check_view(self, sql: str) -> bool:
97
+ return bool(self._re_is_view.match(sql))
98
+
99
+ def _parse_constraints(self, line: str) -> Union[
100
+ Tuple[None, str],
101
+ Tuple[Literal["partition"], str],
102
+ Tuple[
103
+ Literal["ck_constraint", "fk_constraint", "key"], Dict[str, str]
104
+ ],
105
+ ]:
106
+ """Parse a KEY or CONSTRAINT line.
107
+
108
+ :param line: A line of SHOW CREATE TABLE output
109
+ """
110
+
111
+ # KEY
112
+ m = self._re_key.match(line)
113
+ if m:
114
+ spec = m.groupdict()
115
+ # convert columns into name, length pairs
116
+ # NOTE: we may want to consider SHOW INDEX as the
117
+ # format of indexes in MySQL becomes more complex
118
+ spec["columns"] = self._parse_keyexprs(spec["columns"])
119
+ if spec["version_sql"]:
120
+ m2 = self._re_key_version_sql.match(spec["version_sql"])
121
+ if m2 and m2.groupdict()["parser"]:
122
+ spec["parser"] = m2.groupdict()["parser"]
123
+ if spec["parser"]:
124
+ spec["parser"] = self.preparer.unformat_identifiers(
125
+ spec["parser"]
126
+ )[0]
127
+ return "key", spec
128
+
129
+ # FOREIGN KEY CONSTRAINT
130
+ m = self._re_fk_constraint.match(line)
131
+ if m:
132
+ spec = m.groupdict()
133
+ spec["table"] = self.preparer.unformat_identifiers(spec["table"])
134
+ spec["local"] = [c[0] for c in self._parse_keyexprs(spec["local"])]
135
+ spec["foreign"] = [
136
+ c[0] for c in self._parse_keyexprs(spec["foreign"])
137
+ ]
138
+ return "fk_constraint", spec
139
+
140
+ # CHECK constraint
141
+ m = self._re_ck_constraint.match(line)
142
+ if m:
143
+ spec = m.groupdict()
144
+ return "ck_constraint", spec
145
+
146
+ # PARTITION and SUBPARTITION
147
+ m = self._re_partition.match(line)
148
+ if m:
149
+ # Punt!
150
+ return "partition", line
151
+
152
+ # No match.
153
+ return (None, line)
154
+
155
+ def _parse_table_name(self, line: str, state: ReflectedState) -> None:
156
+ """Extract the table name.
157
+
158
+ :param line: The first line of SHOW CREATE TABLE
159
+ """
160
+
161
+ regex, cleanup = self._pr_name
162
+ m = regex.match(line)
163
+ if m:
164
+ state.table_name = cleanup(m.group("name"))
165
+
166
+ def _parse_table_options(self, line: str, state: ReflectedState) -> None:
167
+ """Build a dictionary of all reflected table-level options.
168
+
169
+ :param line: The final line of SHOW CREATE TABLE output.
170
+ """
171
+
172
+ options = {}
173
+
174
+ if line and line != ")":
175
+ rest_of_line = line
176
+ for regex, cleanup in self._pr_options:
177
+ m = regex.search(rest_of_line)
178
+ if not m:
179
+ continue
180
+ directive, value = m.group("directive"), m.group("val")
181
+ if cleanup:
182
+ value = cleanup(value)
183
+ options[directive.lower()] = value
184
+ rest_of_line = regex.sub("", rest_of_line)
185
+
186
+ for nope in ("auto_increment", "data directory", "index directory"):
187
+ options.pop(nope, None)
188
+
189
+ for opt, val in options.items():
190
+ state.table_options["%s_%s" % (self.dialect.name, opt)] = val
191
+
192
+ def _parse_partition_options(
193
+ self, line: str, state: ReflectedState
194
+ ) -> None:
195
+ options = {}
196
+ new_line = line[:]
197
+
198
+ while new_line.startswith("(") or new_line.startswith(" "):
199
+ new_line = new_line[1:]
200
+
201
+ for regex, cleanup in self._pr_options:
202
+ m = regex.search(new_line)
203
+ if not m or "PARTITION" not in regex.pattern:
204
+ continue
205
+
206
+ directive = m.group("directive")
207
+ directive = directive.lower()
208
+ is_subpartition = directive == "subpartition"
209
+
210
+ if directive == "partition" or is_subpartition:
211
+ new_line = new_line.replace(") */", "")
212
+ new_line = new_line.replace(",", "")
213
+ if is_subpartition and new_line.endswith(")"):
214
+ new_line = new_line[:-1]
215
+ if self.dialect.name == "mariadb" and new_line.endswith(")"):
216
+ if (
217
+ "MAXVALUE" in new_line
218
+ or "MINVALUE" in new_line
219
+ or "ENGINE" in new_line
220
+ ):
221
+ # final line of MariaDB partition endswith ")"
222
+ new_line = new_line[:-1]
223
+
224
+ defs = "%s_%s_definitions" % (self.dialect.name, directive)
225
+ options[defs] = new_line
226
+
227
+ else:
228
+ directive = directive.replace(" ", "_")
229
+ value = m.group("val")
230
+ if cleanup:
231
+ value = cleanup(value)
232
+ options[directive] = value
233
+ break
234
+
235
+ for opt, val in options.items():
236
+ part_def = "%s_partition_definitions" % (self.dialect.name)
237
+ subpart_def = "%s_subpartition_definitions" % (self.dialect.name)
238
+ if opt == part_def or opt == subpart_def:
239
+ # builds a string of definitions
240
+ if opt not in state.table_options:
241
+ state.table_options[opt] = val
242
+ else:
243
+ state.table_options[opt] = "%s, %s" % (
244
+ state.table_options[opt],
245
+ val,
246
+ )
247
+ else:
248
+ state.table_options["%s_%s" % (self.dialect.name, opt)] = val
249
+
250
+ def _parse_column(self, line: str, state: ReflectedState) -> None:
251
+ """Extract column details.
252
+
253
+ Falls back to a 'minimal support' variant if full parse fails.
254
+
255
+ :param line: Any column-bearing line from SHOW CREATE TABLE
256
+ """
257
+
258
+ spec = None
259
+ m = self._re_column.match(line)
260
+ if m:
261
+ spec = m.groupdict()
262
+ spec["full"] = True
263
+ else:
264
+ m = self._re_column_loose.match(line)
265
+ if m:
266
+ spec = m.groupdict()
267
+ spec["full"] = False
268
+ if not spec:
269
+ util.warn("Unknown column definition %r" % line)
270
+ return
271
+ if not spec["full"]:
272
+ util.warn("Incomplete reflection of column definition %r" % line)
273
+
274
+ name, type_, args = spec["name"], spec["coltype"], spec["arg"]
275
+
276
+ try:
277
+ col_type = self.dialect.ischema_names[type_]
278
+ except KeyError:
279
+ util.warn(
280
+ "Did not recognize type '%s' of column '%s'" % (type_, name)
281
+ )
282
+ col_type = sqltypes.NullType
283
+
284
+ # Column type positional arguments eg. varchar(32)
285
+ if args is None or args == "":
286
+ type_args = []
287
+ elif args[0] == "'" and args[-1] == "'":
288
+ type_args = self._re_csv_str.findall(args)
289
+ else:
290
+ type_args = [int(v) for v in self._re_csv_int.findall(args)]
291
+
292
+ # Column type keyword options
293
+ type_kw = {}
294
+
295
+ if issubclass(col_type, (DATETIME, TIME, TIMESTAMP)):
296
+ if type_args:
297
+ type_kw["fsp"] = type_args.pop(0)
298
+
299
+ for kw in ("unsigned", "zerofill"):
300
+ if spec.get(kw, False):
301
+ type_kw[kw] = True
302
+ for kw in ("charset", "collate"):
303
+ if spec.get(kw, False):
304
+ type_kw[kw] = spec[kw]
305
+ if issubclass(col_type, (ENUM, SET)):
306
+ type_args = _strip_values(type_args)
307
+
308
+ if issubclass(col_type, SET) and "" in type_args:
309
+ type_kw["retrieve_as_bitwise"] = True
310
+
311
+ type_instance = col_type(*type_args, **type_kw)
312
+
313
+ col_kw: Dict[str, Any] = {}
314
+
315
+ # NOT NULL
316
+ col_kw["nullable"] = True
317
+ # this can be "NULL" in the case of TIMESTAMP
318
+ if spec.get("notnull", False) == "NOT NULL":
319
+ col_kw["nullable"] = False
320
+ # For generated columns, the nullability is marked in a different place
321
+ if spec.get("notnull_generated", False) == "NOT NULL":
322
+ col_kw["nullable"] = False
323
+
324
+ # AUTO_INCREMENT
325
+ if spec.get("autoincr", False):
326
+ col_kw["autoincrement"] = True
327
+ elif issubclass(col_type, sqltypes.Integer):
328
+ col_kw["autoincrement"] = False
329
+
330
+ # DEFAULT
331
+ default = spec.get("default", None)
332
+
333
+ if default == "NULL":
334
+ # eliminates the need to deal with this later.
335
+ default = None
336
+
337
+ comment = spec.get("comment", None)
338
+
339
+ if comment is not None:
340
+ comment = cleanup_text(comment)
341
+
342
+ sqltext = spec.get("generated")
343
+ if sqltext is not None:
344
+ computed = dict(sqltext=sqltext)
345
+ persisted = spec.get("persistence")
346
+ if persisted is not None:
347
+ computed["persisted"] = persisted == "STORED"
348
+ col_kw["computed"] = computed
349
+
350
+ col_d = dict(
351
+ name=name, type=type_instance, default=default, comment=comment
352
+ )
353
+ col_d.update(col_kw)
354
+ state.columns.append(col_d) # type: ignore[arg-type]
355
+
356
+ def _describe_to_create(
357
+ self,
358
+ table_name: str,
359
+ columns: Sequence[Tuple[str, str, str, str, str, str]],
360
+ ) -> str:
361
+ """Re-format DESCRIBE output as a SHOW CREATE TABLE string.
362
+
363
+ DESCRIBE is a much simpler reflection and is sufficient for
364
+ reflecting views for runtime use. This method formats DDL
365
+ for columns only- keys are omitted.
366
+
367
+ :param columns: A sequence of DESCRIBE or SHOW COLUMNS 6-tuples.
368
+ SHOW FULL COLUMNS FROM rows must be rearranged for use with
369
+ this function.
370
+ """
371
+
372
+ buffer = []
373
+ for row in columns:
374
+ (name, col_type, nullable, default, extra) = (
375
+ row[i] for i in (0, 1, 2, 4, 5)
376
+ )
377
+
378
+ line = [" "]
379
+ line.append(self.preparer.quote_identifier(name))
380
+ line.append(col_type)
381
+ if not nullable:
382
+ line.append("NOT NULL")
383
+ if default:
384
+ if "auto_increment" in default:
385
+ pass
386
+ elif col_type.startswith("timestamp") and default.startswith(
387
+ "C"
388
+ ):
389
+ line.append("DEFAULT")
390
+ line.append(default)
391
+ elif default == "NULL":
392
+ line.append("DEFAULT")
393
+ line.append(default)
394
+ else:
395
+ line.append("DEFAULT")
396
+ line.append("'%s'" % default.replace("'", "''"))
397
+ if extra:
398
+ line.append(extra)
399
+
400
+ buffer.append(" ".join(line))
401
+
402
+ return "".join(
403
+ [
404
+ (
405
+ "CREATE TABLE %s (\n"
406
+ % self.preparer.quote_identifier(table_name)
407
+ ),
408
+ ",\n".join(buffer),
409
+ "\n) ",
410
+ ]
411
+ )
412
+
413
+ def _parse_keyexprs(
414
+ self, identifiers: str
415
+ ) -> List[Tuple[str, Optional[int], str]]:
416
+ """Unpack '"col"(2),"col" ASC'-ish strings into components."""
417
+
418
+ return [
419
+ (colname, int(length) if length else None, modifiers)
420
+ for colname, length, modifiers in self._re_keyexprs.findall(
421
+ identifiers
422
+ )
423
+ ]
424
+
425
+ def _prep_regexes(self) -> None:
426
+ """Pre-compile regular expressions."""
427
+
428
+ self._pr_options: List[
429
+ Tuple[re.Pattern[Any], Optional[Callable[[str], str]]]
430
+ ] = []
431
+
432
+ _final = self.preparer.final_quote
433
+
434
+ quotes = dict(
435
+ zip(
436
+ ("iq", "fq", "esc_fq"),
437
+ [
438
+ re.escape(s)
439
+ for s in (
440
+ self.preparer.initial_quote,
441
+ _final,
442
+ self.preparer._escape_identifier(_final),
443
+ )
444
+ ],
445
+ )
446
+ )
447
+
448
+ self._pr_name = _pr_compile(
449
+ r"^CREATE (?:\w+ +)?TABLE +"
450
+ r"%(iq)s(?P<name>(?:%(esc_fq)s|[^%(fq)s])+)%(fq)s +\($" % quotes,
451
+ self.preparer._unescape_identifier,
452
+ )
453
+
454
+ self._re_is_view = _re_compile(r"^CREATE(?! TABLE)(\s.*)?\sVIEW")
455
+
456
+ # `col`,`col2`(32),`col3`(15) DESC
457
+ #
458
+ self._re_keyexprs = _re_compile(
459
+ r"(?:"
460
+ r"(?:%(iq)s((?:%(esc_fq)s|[^%(fq)s])+)%(fq)s)"
461
+ r"(?:\((\d+)\))?(?: +(ASC|DESC))?(?=\,|$))+" % quotes
462
+ )
463
+
464
+ # 'foo' or 'foo','bar' or 'fo,o','ba''a''r'
465
+ self._re_csv_str = _re_compile(r"\x27(?:\x27\x27|[^\x27])*\x27")
466
+
467
+ # 123 or 123,456
468
+ self._re_csv_int = _re_compile(r"\d+")
469
+
470
+ # `colname` <type> [type opts]
471
+ # (NOT NULL | NULL)
472
+ # DEFAULT ('value' | CURRENT_TIMESTAMP...)
473
+ # COMMENT 'comment'
474
+ # COLUMN_FORMAT (FIXED|DYNAMIC|DEFAULT)
475
+ # STORAGE (DISK|MEMORY)
476
+ self._re_column = _re_compile(
477
+ r" "
478
+ r"%(iq)s(?P<name>(?:%(esc_fq)s|[^%(fq)s])+)%(fq)s +"
479
+ r"(?P<coltype>\w+)"
480
+ r"(?:\((?P<arg>(?:\d+|\d+,\d+|"
481
+ r"(?:'(?:''|[^'])*',?)+))\))?"
482
+ r"(?: +(?P<unsigned>UNSIGNED))?"
483
+ r"(?: +(?P<zerofill>ZEROFILL))?"
484
+ r"(?: +CHARACTER SET +(?P<charset>[\w_]+))?"
485
+ r"(?: +COLLATE +(?P<collate>[\w_]+))?"
486
+ r"(?: +(?P<notnull>(?:NOT )?NULL))?"
487
+ r"(?: +DEFAULT +(?P<default>"
488
+ r"(?:NULL|'(?:''|[^'])*'|\(.+?\)|[\-\w\.\(\)]+"
489
+ r"(?: +ON UPDATE [\-\w\.\(\)]+)?)"
490
+ r"))?"
491
+ r"(?: +(?:GENERATED ALWAYS)? ?AS +(?P<generated>\("
492
+ r".*\))? ?(?P<persistence>VIRTUAL|STORED)?"
493
+ r"(?: +(?P<notnull_generated>(?:NOT )?NULL))?"
494
+ r")?"
495
+ r"(?: +(?P<autoincr>AUTO_INCREMENT))?"
496
+ r"(?: +COMMENT +'(?P<comment>(?:''|[^'])*)')?"
497
+ r"(?: +COLUMN_FORMAT +(?P<colfmt>\w+))?"
498
+ r"(?: +STORAGE +(?P<storage>\w+))?"
499
+ r"(?: +(?P<extra>.*))?"
500
+ r",?$" % quotes
501
+ )
502
+
503
+ # Fallback, try to parse as little as possible
504
+ self._re_column_loose = _re_compile(
505
+ r" "
506
+ r"%(iq)s(?P<name>(?:%(esc_fq)s|[^%(fq)s])+)%(fq)s +"
507
+ r"(?P<coltype>\w+)"
508
+ r"(?:\((?P<arg>(?:\d+|\d+,\d+|\x27(?:\x27\x27|[^\x27])+\x27))\))?"
509
+ r".*?(?P<notnull>(?:NOT )NULL)?" % quotes
510
+ )
511
+
512
+ # (PRIMARY|UNIQUE|FULLTEXT|SPATIAL) INDEX `name` (USING (BTREE|HASH))?
513
+ # (`col` (ASC|DESC)?, `col` (ASC|DESC)?)
514
+ # KEY_BLOCK_SIZE size | WITH PARSER name /*!50100 WITH PARSER name */
515
+ self._re_key = _re_compile(
516
+ r" "
517
+ r"(?:(?P<type>\S+) )?KEY"
518
+ r"(?: +%(iq)s(?P<name>(?:%(esc_fq)s|[^%(fq)s])+)%(fq)s)?"
519
+ r"(?: +USING +(?P<using_pre>\S+))?"
520
+ r" +\((?P<columns>.+?)\)"
521
+ r"(?: +USING +(?P<using_post>\S+))?"
522
+ r"(?: +KEY_BLOCK_SIZE *[ =]? *(?P<keyblock>\S+))?"
523
+ r"(?: +WITH PARSER +(?P<parser>\S+))?"
524
+ r"(?: +COMMENT +(?P<comment>(\x27\x27|\x27([^\x27])*?\x27)+))?"
525
+ r"(?: +/\*(?P<version_sql>.+)\*/ *)?"
526
+ r",?$" % quotes
527
+ )
528
+
529
+ # https://forums.mysql.com/read.php?20,567102,567111#msg-567111
530
+ # It means if the MySQL version >= \d+, execute what's in the comment
531
+ self._re_key_version_sql = _re_compile(
532
+ r"\!\d+ " r"(?: *WITH PARSER +(?P<parser>\S+) *)?"
533
+ )
534
+
535
+ # CONSTRAINT `name` FOREIGN KEY (`local_col`)
536
+ # REFERENCES `remote` (`remote_col`)
537
+ # MATCH FULL | MATCH PARTIAL | MATCH SIMPLE
538
+ # ON DELETE CASCADE ON UPDATE RESTRICT
539
+ #
540
+ # unique constraints come back as KEYs
541
+ kw = quotes.copy()
542
+ kw["on"] = "RESTRICT|CASCADE|SET NULL|NO ACTION|SET DEFAULT"
543
+ self._re_fk_constraint = _re_compile(
544
+ r" "
545
+ r"CONSTRAINT +"
546
+ r"%(iq)s(?P<name>(?:%(esc_fq)s|[^%(fq)s])+)%(fq)s +"
547
+ r"FOREIGN KEY +"
548
+ r"\((?P<local>[^\)]+?)\) REFERENCES +"
549
+ r"(?P<table>%(iq)s[^%(fq)s]+%(fq)s"
550
+ r"(?:\.%(iq)s[^%(fq)s]+%(fq)s)?) +"
551
+ r"\((?P<foreign>(?:%(iq)s[^%(fq)s]+%(fq)s(?: *, *)?)+)\)"
552
+ r"(?: +(?P<match>MATCH \w+))?"
553
+ r"(?: +ON DELETE (?P<ondelete>%(on)s))?"
554
+ r"(?: +ON UPDATE (?P<onupdate>%(on)s))?" % kw
555
+ )
556
+
557
+ # CONSTRAINT `CONSTRAINT_1` CHECK (`x` > 5)'
558
+ # testing on MariaDB 10.2 shows that the CHECK constraint
559
+ # is returned on a line by itself, so to match without worrying
560
+ # about parenthesis in the expression we go to the end of the line
561
+ self._re_ck_constraint = _re_compile(
562
+ r" "
563
+ r"CONSTRAINT +"
564
+ r"%(iq)s(?P<name>(?:%(esc_fq)s|[^%(fq)s])+)%(fq)s +"
565
+ r"CHECK +"
566
+ r"\((?P<sqltext>.+)\),?" % kw
567
+ )
568
+
569
+ # PARTITION
570
+ #
571
+ # punt!
572
+ self._re_partition = _re_compile(r"(?:.*)(?:SUB)?PARTITION(?:.*)")
573
+
574
+ # Table-level options (COLLATE, ENGINE, etc.)
575
+ # Do the string options first, since they have quoted
576
+ # strings we need to get rid of.
577
+ for option in _options_of_type_string:
578
+ self._add_option_string(option)
579
+
580
+ for option in (
581
+ "ENGINE",
582
+ "TYPE",
583
+ "AUTO_INCREMENT",
584
+ "AVG_ROW_LENGTH",
585
+ "CHARACTER SET",
586
+ "DEFAULT CHARSET",
587
+ "CHECKSUM",
588
+ "COLLATE",
589
+ "DELAY_KEY_WRITE",
590
+ "INSERT_METHOD",
591
+ "MAX_ROWS",
592
+ "MIN_ROWS",
593
+ "PACK_KEYS",
594
+ "ROW_FORMAT",
595
+ "KEY_BLOCK_SIZE",
596
+ "STATS_SAMPLE_PAGES",
597
+ ):
598
+ self._add_option_word(option)
599
+
600
+ for option in (
601
+ "PARTITION BY",
602
+ "SUBPARTITION BY",
603
+ "PARTITIONS",
604
+ "SUBPARTITIONS",
605
+ "PARTITION",
606
+ "SUBPARTITION",
607
+ ):
608
+ self._add_partition_option_word(option)
609
+
610
+ self._add_option_regex("UNION", r"\([^\)]+\)")
611
+ self._add_option_regex("TABLESPACE", r".*? STORAGE DISK")
612
+ self._add_option_regex(
613
+ "RAID_TYPE",
614
+ r"\w+\s+RAID_CHUNKS\s*\=\s*\w+RAID_CHUNKSIZE\s*=\s*\w+",
615
+ )
616
+
617
+ _optional_equals = r"(?:\s*(?:=\s*)|\s+)"
618
+
619
+ def _add_option_string(self, directive: str) -> None:
620
+ regex = r"(?P<directive>%s)%s" r"'(?P<val>(?:[^']|'')*?)'(?!')" % (
621
+ re.escape(directive),
622
+ self._optional_equals,
623
+ )
624
+ self._pr_options.append(_pr_compile(regex, cleanup_text))
625
+
626
+ def _add_option_word(self, directive: str) -> None:
627
+ regex = r"(?P<directive>%s)%s" r"(?P<val>\w+)" % (
628
+ re.escape(directive),
629
+ self._optional_equals,
630
+ )
631
+ self._pr_options.append(_pr_compile(regex))
632
+
633
+ def _add_partition_option_word(self, directive: str) -> None:
634
+ if directive == "PARTITION BY" or directive == "SUBPARTITION BY":
635
+ regex = r"(?<!\S)(?P<directive>%s)%s" r"(?P<val>\w+.*)" % (
636
+ re.escape(directive),
637
+ self._optional_equals,
638
+ )
639
+ elif directive == "SUBPARTITIONS" or directive == "PARTITIONS":
640
+ regex = r"(?<!\S)(?P<directive>%s)%s" r"(?P<val>\d+)" % (
641
+ re.escape(directive),
642
+ self._optional_equals,
643
+ )
644
+ else:
645
+ regex = r"(?<!\S)(?P<directive>%s)(?!\S)" % (re.escape(directive),)
646
+ self._pr_options.append(_pr_compile(regex))
647
+
648
+ def _add_option_regex(self, directive: str, regex: str) -> None:
649
+ regex = r"(?P<directive>%s)%s" r"(?P<val>%s)" % (
650
+ re.escape(directive),
651
+ self._optional_equals,
652
+ regex,
653
+ )
654
+ self._pr_options.append(_pr_compile(regex))
655
+
656
+
657
+ _options_of_type_string = (
658
+ "COMMENT",
659
+ "DATA DIRECTORY",
660
+ "INDEX DIRECTORY",
661
+ "PASSWORD",
662
+ "CONNECTION",
663
+ )
664
+
665
+
666
+ @overload
667
+ def _pr_compile(
668
+ regex: str, cleanup: Callable[[str], str]
669
+ ) -> Tuple[re.Pattern[Any], Callable[[str], str]]: ...
670
+
671
+
672
+ @overload
673
+ def _pr_compile(
674
+ regex: str, cleanup: None = None
675
+ ) -> Tuple[re.Pattern[Any], None]: ...
676
+
677
+
678
+ def _pr_compile(
679
+ regex: str, cleanup: Optional[Callable[[str], str]] = None
680
+ ) -> Tuple[re.Pattern[Any], Optional[Callable[[str], str]]]:
681
+ """Prepare a 2-tuple of compiled regex and callable."""
682
+
683
+ return (_re_compile(regex), cleanup)
684
+
685
+
686
+ def _re_compile(regex: str) -> re.Pattern[Any]:
687
+ """Compile a string to regex, I and UNICODE."""
688
+
689
+ return re.compile(regex, re.I | re.UNICODE)
690
+
691
+
692
+ def _strip_values(values: Sequence[str]) -> List[str]:
693
+ "Strip reflected values quotes"
694
+ strip_values: List[str] = []
695
+ for a in values:
696
+ if a[0:1] == '"' or a[0:1] == "'":
697
+ # strip enclosing quotes and unquote interior
698
+ a = a[1:-1].replace(a[0] * 2, a[0])
699
+ strip_values.append(a)
700
+ return strip_values
701
+
702
+
703
+ def cleanup_text(raw_text: str) -> str:
704
+ if "\\" in raw_text:
705
+ raw_text = re.sub(
706
+ _control_char_regexp,
707
+ lambda s: _control_char_map[s[0]], # type: ignore[index]
708
+ raw_text,
709
+ )
710
+ return raw_text.replace("''", "'")
711
+
712
+
713
+ _control_char_map = {
714
+ "\\\\": "\\",
715
+ "\\0": "\0",
716
+ "\\a": "\a",
717
+ "\\b": "\b",
718
+ "\\t": "\t",
719
+ "\\n": "\n",
720
+ "\\v": "\v",
721
+ "\\f": "\f",
722
+ "\\r": "\r",
723
+ # '\\e':'\e',
724
+ }
725
+ _control_char_regexp = re.compile(
726
+ "|".join(re.escape(k) for k in _control_char_map)
727
+ )
loan-advisor-agent/.venv/Lib/site-packages/sqlalchemy/dialects/mysql/reserved_words.py ADDED
@@ -0,0 +1,570 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # dialects/mysql/reserved_words.py
2
+ # Copyright (C) 2005-2026 the SQLAlchemy authors and contributors
3
+ # <see AUTHORS file>
4
+ #
5
+ # This module is part of SQLAlchemy and is released under
6
+ # the MIT License: https://www.opensource.org/licenses/mit-license.php
7
+
8
+ # generated using:
9
+ # https://gist.github.com/kkirsche/4f31f2153ed7a3248be1ec44ca6ddbc9
10
+ #
11
+ # https://mariadb.com/kb/en/reserved-words/
12
+ # includes: Reserved Words, Oracle Mode (separate set unioned)
13
+ # excludes: Exceptions, Function Names
14
+
15
+ RESERVED_WORDS_MARIADB = {
16
+ "accessible",
17
+ "add",
18
+ "all",
19
+ "alter",
20
+ "analyze",
21
+ "and",
22
+ "as",
23
+ "asc",
24
+ "asensitive",
25
+ "before",
26
+ "between",
27
+ "bigint",
28
+ "binary",
29
+ "blob",
30
+ "both",
31
+ "by",
32
+ "call",
33
+ "cascade",
34
+ "case",
35
+ "change",
36
+ "char",
37
+ "character",
38
+ "check",
39
+ "collate",
40
+ "column",
41
+ "condition",
42
+ "constraint",
43
+ "continue",
44
+ "convert",
45
+ "create",
46
+ "cross",
47
+ "current_date",
48
+ "current_role",
49
+ "current_time",
50
+ "current_timestamp",
51
+ "current_user",
52
+ "cursor",
53
+ "database",
54
+ "databases",
55
+ "day_hour",
56
+ "day_microsecond",
57
+ "day_minute",
58
+ "day_second",
59
+ "dec",
60
+ "decimal",
61
+ "declare",
62
+ "default",
63
+ "delayed",
64
+ "delete",
65
+ "desc",
66
+ "describe",
67
+ "deterministic",
68
+ "distinct",
69
+ "distinctrow",
70
+ "div",
71
+ "do_domain_ids",
72
+ "double",
73
+ "drop",
74
+ "dual",
75
+ "each",
76
+ "else",
77
+ "elseif",
78
+ "enclosed",
79
+ "escaped",
80
+ "except",
81
+ "exists",
82
+ "exit",
83
+ "explain",
84
+ "false",
85
+ "fetch",
86
+ "float",
87
+ "float4",
88
+ "float8",
89
+ "for",
90
+ "force",
91
+ "foreign",
92
+ "from",
93
+ "fulltext",
94
+ "general",
95
+ "grant",
96
+ "group",
97
+ "having",
98
+ "high_priority",
99
+ "hour_microsecond",
100
+ "hour_minute",
101
+ "hour_second",
102
+ "if",
103
+ "ignore",
104
+ "ignore_domain_ids",
105
+ "ignore_server_ids",
106
+ "in",
107
+ "index",
108
+ "infile",
109
+ "inner",
110
+ "inout",
111
+ "insensitive",
112
+ "insert",
113
+ "int",
114
+ "int1",
115
+ "int2",
116
+ "int3",
117
+ "int4",
118
+ "int8",
119
+ "integer",
120
+ "intersect",
121
+ "interval",
122
+ "into",
123
+ "is",
124
+ "iterate",
125
+ "join",
126
+ "key",
127
+ "keys",
128
+ "kill",
129
+ "leading",
130
+ "leave",
131
+ "left",
132
+ "like",
133
+ "limit",
134
+ "linear",
135
+ "lines",
136
+ "load",
137
+ "localtime",
138
+ "localtimestamp",
139
+ "lock",
140
+ "long",
141
+ "longblob",
142
+ "longtext",
143
+ "loop",
144
+ "low_priority",
145
+ "master_heartbeat_period",
146
+ "master_ssl_verify_server_cert",
147
+ "match",
148
+ "maxvalue",
149
+ "mediumblob",
150
+ "mediumint",
151
+ "mediumtext",
152
+ "middleint",
153
+ "minute_microsecond",
154
+ "minute_second",
155
+ "mod",
156
+ "modifies",
157
+ "natural",
158
+ "no_write_to_binlog",
159
+ "not",
160
+ "null",
161
+ "numeric",
162
+ "offset",
163
+ "on",
164
+ "optimize",
165
+ "option",
166
+ "optionally",
167
+ "or",
168
+ "order",
169
+ "out",
170
+ "outer",
171
+ "outfile",
172
+ "over",
173
+ "page_checksum",
174
+ "parse_vcol_expr",
175
+ "partition",
176
+ "position",
177
+ "precision",
178
+ "primary",
179
+ "procedure",
180
+ "purge",
181
+ "range",
182
+ "read",
183
+ "read_write",
184
+ "reads",
185
+ "real",
186
+ "recursive",
187
+ "ref_system_id",
188
+ "references",
189
+ "regexp",
190
+ "release",
191
+ "rename",
192
+ "repeat",
193
+ "replace",
194
+ "require",
195
+ "resignal",
196
+ "restrict",
197
+ "return",
198
+ "returning",
199
+ "revoke",
200
+ "right",
201
+ "rlike",
202
+ "rows",
203
+ "row_number",
204
+ "schema",
205
+ "schemas",
206
+ "second_microsecond",
207
+ "select",
208
+ "sensitive",
209
+ "separator",
210
+ "set",
211
+ "show",
212
+ "signal",
213
+ "slow",
214
+ "smallint",
215
+ "spatial",
216
+ "specific",
217
+ "sql",
218
+ "sql_big_result",
219
+ "sql_calc_found_rows",
220
+ "sql_small_result",
221
+ "sqlexception",
222
+ "sqlstate",
223
+ "sqlwarning",
224
+ "ssl",
225
+ "starting",
226
+ "stats_auto_recalc",
227
+ "stats_persistent",
228
+ "stats_sample_pages",
229
+ "straight_join",
230
+ "table",
231
+ "terminated",
232
+ "then",
233
+ "tinyblob",
234
+ "tinyint",
235
+ "tinytext",
236
+ "to",
237
+ "trailing",
238
+ "trigger",
239
+ "true",
240
+ "undo",
241
+ "union",
242
+ "unique",
243
+ "unlock",
244
+ "unsigned",
245
+ "update",
246
+ "usage",
247
+ "use",
248
+ "using",
249
+ "utc_date",
250
+ "utc_time",
251
+ "utc_timestamp",
252
+ "values",
253
+ "varbinary",
254
+ "varchar",
255
+ "varcharacter",
256
+ "varying",
257
+ "when",
258
+ "where",
259
+ "while",
260
+ "window",
261
+ "with",
262
+ "write",
263
+ "xor",
264
+ "year_month",
265
+ "zerofill",
266
+ }.union(
267
+ {
268
+ "body",
269
+ "elsif",
270
+ "goto",
271
+ "history",
272
+ "others",
273
+ "package",
274
+ "period",
275
+ "raise",
276
+ "rowtype",
277
+ "system",
278
+ "system_time",
279
+ "versioning",
280
+ "without",
281
+ }
282
+ )
283
+
284
+ # https://dev.mysql.com/doc/refman/8.3/en/keywords.html
285
+ # https://dev.mysql.com/doc/refman/8.0/en/keywords.html
286
+ # https://dev.mysql.com/doc/refman/5.7/en/keywords.html
287
+ # https://dev.mysql.com/doc/refman/5.6/en/keywords.html
288
+ # includes: MySQL x.0 Keywords and Reserved Words
289
+ # excludes: MySQL x.0 New Keywords and Reserved Words,
290
+ # MySQL x.0 Removed Keywords and Reserved Words
291
+ RESERVED_WORDS_MYSQL = {
292
+ "accessible",
293
+ "add",
294
+ "admin",
295
+ "all",
296
+ "alter",
297
+ "analyze",
298
+ "and",
299
+ "array",
300
+ "as",
301
+ "asc",
302
+ "asensitive",
303
+ "before",
304
+ "between",
305
+ "bigint",
306
+ "binary",
307
+ "blob",
308
+ "both",
309
+ "by",
310
+ "call",
311
+ "cascade",
312
+ "case",
313
+ "change",
314
+ "char",
315
+ "character",
316
+ "check",
317
+ "collate",
318
+ "column",
319
+ "condition",
320
+ "constraint",
321
+ "continue",
322
+ "convert",
323
+ "create",
324
+ "cross",
325
+ "cube",
326
+ "cume_dist",
327
+ "current_date",
328
+ "current_time",
329
+ "current_timestamp",
330
+ "current_user",
331
+ "cursor",
332
+ "database",
333
+ "databases",
334
+ "day_hour",
335
+ "day_microsecond",
336
+ "day_minute",
337
+ "day_second",
338
+ "dec",
339
+ "decimal",
340
+ "declare",
341
+ "default",
342
+ "delayed",
343
+ "delete",
344
+ "dense_rank",
345
+ "desc",
346
+ "describe",
347
+ "deterministic",
348
+ "distinct",
349
+ "distinctrow",
350
+ "div",
351
+ "double",
352
+ "drop",
353
+ "dual",
354
+ "each",
355
+ "else",
356
+ "elseif",
357
+ "empty",
358
+ "enclosed",
359
+ "escaped",
360
+ "except",
361
+ "exists",
362
+ "exit",
363
+ "explain",
364
+ "false",
365
+ "fetch",
366
+ "first_value",
367
+ "float",
368
+ "float4",
369
+ "float8",
370
+ "for",
371
+ "force",
372
+ "foreign",
373
+ "from",
374
+ "fulltext",
375
+ "function",
376
+ "general",
377
+ "generated",
378
+ "get",
379
+ "get_master_public_key",
380
+ "grant",
381
+ "group",
382
+ "grouping",
383
+ "groups",
384
+ "having",
385
+ "high_priority",
386
+ "hour_microsecond",
387
+ "hour_minute",
388
+ "hour_second",
389
+ "if",
390
+ "ignore",
391
+ "ignore_server_ids",
392
+ "in",
393
+ "index",
394
+ "infile",
395
+ "inner",
396
+ "inout",
397
+ "insensitive",
398
+ "insert",
399
+ "int",
400
+ "int1",
401
+ "int2",
402
+ "int3",
403
+ "int4",
404
+ "int8",
405
+ "integer",
406
+ "intersect",
407
+ "interval",
408
+ "into",
409
+ "io_after_gtids",
410
+ "io_before_gtids",
411
+ "is",
412
+ "iterate",
413
+ "join",
414
+ "json_table",
415
+ "key",
416
+ "keys",
417
+ "kill",
418
+ "lag",
419
+ "last_value",
420
+ "lateral",
421
+ "lead",
422
+ "leading",
423
+ "leave",
424
+ "left",
425
+ "like",
426
+ "limit",
427
+ "linear",
428
+ "lines",
429
+ "load",
430
+ "localtime",
431
+ "localtimestamp",
432
+ "lock",
433
+ "long",
434
+ "longblob",
435
+ "longtext",
436
+ "loop",
437
+ "low_priority",
438
+ "master_bind",
439
+ "master_heartbeat_period",
440
+ "master_ssl_verify_server_cert",
441
+ "match",
442
+ "maxvalue",
443
+ "mediumblob",
444
+ "mediumint",
445
+ "mediumtext",
446
+ "member",
447
+ "middleint",
448
+ "minute_microsecond",
449
+ "minute_second",
450
+ "mod",
451
+ "modifies",
452
+ "natural",
453
+ "no_write_to_binlog",
454
+ "not",
455
+ "nth_value",
456
+ "ntile",
457
+ "null",
458
+ "numeric",
459
+ "of",
460
+ "on",
461
+ "optimize",
462
+ "optimizer_costs",
463
+ "option",
464
+ "optionally",
465
+ "or",
466
+ "order",
467
+ "out",
468
+ "outer",
469
+ "outfile",
470
+ "over",
471
+ "parse_gcol_expr",
472
+ "parallel",
473
+ "partition",
474
+ "percent_rank",
475
+ "persist",
476
+ "persist_only",
477
+ "precision",
478
+ "primary",
479
+ "procedure",
480
+ "purge",
481
+ "qualify",
482
+ "range",
483
+ "rank",
484
+ "read",
485
+ "read_write",
486
+ "reads",
487
+ "real",
488
+ "recursive",
489
+ "references",
490
+ "regexp",
491
+ "release",
492
+ "rename",
493
+ "repeat",
494
+ "replace",
495
+ "require",
496
+ "resignal",
497
+ "restrict",
498
+ "return",
499
+ "revoke",
500
+ "right",
501
+ "rlike",
502
+ "role",
503
+ "row",
504
+ "row_number",
505
+ "rows",
506
+ "schema",
507
+ "schemas",
508
+ "second_microsecond",
509
+ "select",
510
+ "sensitive",
511
+ "separator",
512
+ "set",
513
+ "show",
514
+ "signal",
515
+ "slow",
516
+ "smallint",
517
+ "spatial",
518
+ "specific",
519
+ "sql",
520
+ "sql_after_gtids",
521
+ "sql_before_gtids",
522
+ "sql_big_result",
523
+ "sql_calc_found_rows",
524
+ "sql_small_result",
525
+ "sqlexception",
526
+ "sqlstate",
527
+ "sqlwarning",
528
+ "ssl",
529
+ "starting",
530
+ "stored",
531
+ "straight_join",
532
+ "system",
533
+ "table",
534
+ "terminated",
535
+ "then",
536
+ "tinyblob",
537
+ "tinyint",
538
+ "tinytext",
539
+ "to",
540
+ "trailing",
541
+ "trigger",
542
+ "true",
543
+ "undo",
544
+ "union",
545
+ "unique",
546
+ "unlock",
547
+ "unsigned",
548
+ "update",
549
+ "usage",
550
+ "use",
551
+ "using",
552
+ "utc_date",
553
+ "utc_time",
554
+ "utc_timestamp",
555
+ "values",
556
+ "varbinary",
557
+ "varchar",
558
+ "varcharacter",
559
+ "varying",
560
+ "virtual",
561
+ "when",
562
+ "where",
563
+ "while",
564
+ "window",
565
+ "with",
566
+ "write",
567
+ "xor",
568
+ "year_month",
569
+ "zerofill",
570
+ }
loan-advisor-agent/.venv/Lib/site-packages/sqlalchemy/dialects/mysql/types.py ADDED
@@ -0,0 +1,835 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # dialects/mysql/types.py
2
+ # Copyright (C) 2005-2026 the SQLAlchemy authors and contributors
3
+ # <see AUTHORS file>
4
+ #
5
+ # This module is part of SQLAlchemy and is released under
6
+ # the MIT License: https://www.opensource.org/licenses/mit-license.php
7
+ from __future__ import annotations
8
+
9
+ import datetime
10
+ import decimal
11
+ from typing import Any
12
+ from typing import Iterable
13
+ from typing import Optional
14
+ from typing import TYPE_CHECKING
15
+ from typing import Union
16
+
17
+ from ... import exc
18
+ from ... import util
19
+ from ...sql import sqltypes
20
+
21
+ if TYPE_CHECKING:
22
+ from .base import MySQLDialect
23
+ from ...engine.interfaces import Dialect
24
+ from ...sql.type_api import _BindProcessorType
25
+ from ...sql.type_api import _ResultProcessorType
26
+ from ...sql.type_api import TypeEngine
27
+
28
+
29
+ class _NumericType:
30
+ """Base for MySQL numeric types.
31
+
32
+ This is the base both for NUMERIC as well as INTEGER, hence
33
+ it's a mixin.
34
+
35
+ """
36
+
37
+ def __init__(
38
+ self, unsigned: bool = False, zerofill: bool = False, **kw: Any
39
+ ):
40
+ self.unsigned = unsigned
41
+ self.zerofill = zerofill
42
+ super().__init__(**kw)
43
+
44
+ def __repr__(self) -> str:
45
+ return util.generic_repr(
46
+ self, to_inspect=[_NumericType, sqltypes.Numeric]
47
+ )
48
+
49
+
50
+ class _FloatType(_NumericType, sqltypes.Float[Union[decimal.Decimal, float]]):
51
+ def __init__(
52
+ self,
53
+ precision: Optional[int] = None,
54
+ scale: Optional[int] = None,
55
+ asdecimal: bool = True,
56
+ **kw: Any,
57
+ ):
58
+ if isinstance(self, (REAL, DOUBLE)) and (
59
+ (precision is None and scale is not None)
60
+ or (precision is not None and scale is None)
61
+ ):
62
+ raise exc.ArgumentError(
63
+ "You must specify both precision and scale or omit "
64
+ "both altogether."
65
+ )
66
+ super().__init__(precision=precision, asdecimal=asdecimal, **kw)
67
+ self.scale = scale
68
+
69
+ def __repr__(self) -> str:
70
+ return util.generic_repr(
71
+ self, to_inspect=[_FloatType, _NumericType, sqltypes.Float]
72
+ )
73
+
74
+
75
+ class _IntegerType(_NumericType, sqltypes.Integer):
76
+ def __init__(self, display_width: Optional[int] = None, **kw: Any):
77
+ self.display_width = display_width
78
+ super().__init__(**kw)
79
+
80
+ def __repr__(self) -> str:
81
+ return util.generic_repr(
82
+ self, to_inspect=[_IntegerType, _NumericType, sqltypes.Integer]
83
+ )
84
+
85
+
86
+ class _StringType(sqltypes.String):
87
+ """Base for MySQL string types."""
88
+
89
+ def __init__(
90
+ self,
91
+ charset: Optional[str] = None,
92
+ collation: Optional[str] = None,
93
+ ascii: bool = False, # noqa
94
+ binary: bool = False,
95
+ unicode: bool = False,
96
+ national: bool = False,
97
+ **kw: Any,
98
+ ):
99
+ self.charset = charset
100
+
101
+ # allow collate= or collation=
102
+ kw.setdefault("collation", kw.pop("collate", collation))
103
+
104
+ self.ascii = ascii
105
+ self.unicode = unicode
106
+ self.binary = binary
107
+ self.national = national
108
+ super().__init__(**kw)
109
+
110
+ def __repr__(self) -> str:
111
+ return util.generic_repr(
112
+ self, to_inspect=[_StringType, sqltypes.String]
113
+ )
114
+
115
+
116
+ class _MatchType(
117
+ sqltypes.Float[Union[decimal.Decimal, float]], sqltypes.MatchType
118
+ ):
119
+ def __init__(self, **kw: Any):
120
+ # TODO: float arguments?
121
+ sqltypes.Float.__init__(self) # type: ignore[arg-type]
122
+ sqltypes.MatchType.__init__(self)
123
+
124
+
125
+ class NUMERIC(_NumericType, sqltypes.NUMERIC[Union[decimal.Decimal, float]]):
126
+ """MySQL NUMERIC type."""
127
+
128
+ __visit_name__ = "NUMERIC"
129
+
130
+ def __init__(
131
+ self,
132
+ precision: Optional[int] = None,
133
+ scale: Optional[int] = None,
134
+ asdecimal: bool = True,
135
+ **kw: Any,
136
+ ):
137
+ """Construct a NUMERIC.
138
+
139
+ :param precision: Total digits in this number. If scale and precision
140
+ are both None, values are stored to limits allowed by the server.
141
+
142
+ :param scale: The number of digits after the decimal point.
143
+
144
+ :param unsigned: a boolean, optional.
145
+
146
+ :param zerofill: Optional. If true, values will be stored as strings
147
+ left-padded with zeros. Note that this does not effect the values
148
+ returned by the underlying database API, which continue to be
149
+ numeric.
150
+
151
+ """
152
+ super().__init__(
153
+ precision=precision, scale=scale, asdecimal=asdecimal, **kw
154
+ )
155
+
156
+
157
+ class DECIMAL(_NumericType, sqltypes.DECIMAL[Union[decimal.Decimal, float]]):
158
+ """MySQL DECIMAL type."""
159
+
160
+ __visit_name__ = "DECIMAL"
161
+
162
+ def __init__(
163
+ self,
164
+ precision: Optional[int] = None,
165
+ scale: Optional[int] = None,
166
+ asdecimal: bool = True,
167
+ **kw: Any,
168
+ ):
169
+ """Construct a DECIMAL.
170
+
171
+ :param precision: Total digits in this number. If scale and precision
172
+ are both None, values are stored to limits allowed by the server.
173
+
174
+ :param scale: The number of digits after the decimal point.
175
+
176
+ :param unsigned: a boolean, optional.
177
+
178
+ :param zerofill: Optional. If true, values will be stored as strings
179
+ left-padded with zeros. Note that this does not effect the values
180
+ returned by the underlying database API, which continue to be
181
+ numeric.
182
+
183
+ """
184
+ super().__init__(
185
+ precision=precision, scale=scale, asdecimal=asdecimal, **kw
186
+ )
187
+
188
+
189
+ class DOUBLE(_FloatType, sqltypes.DOUBLE[Union[decimal.Decimal, float]]):
190
+ """MySQL DOUBLE type."""
191
+
192
+ __visit_name__ = "DOUBLE"
193
+
194
+ def __init__(
195
+ self,
196
+ precision: Optional[int] = None,
197
+ scale: Optional[int] = None,
198
+ asdecimal: bool = True,
199
+ **kw: Any,
200
+ ):
201
+ """Construct a DOUBLE.
202
+
203
+ .. note::
204
+
205
+ The :class:`.DOUBLE` type by default converts from float
206
+ to Decimal, using a truncation that defaults to 10 digits.
207
+ Specify either ``scale=n`` or ``decimal_return_scale=n`` in order
208
+ to change this scale, or ``asdecimal=False`` to return values
209
+ directly as Python floating points.
210
+
211
+ :param precision: Total digits in this number. If scale and precision
212
+ are both None, values are stored to limits allowed by the server.
213
+
214
+ :param scale: The number of digits after the decimal point.
215
+
216
+ :param unsigned: a boolean, optional.
217
+
218
+ :param zerofill: Optional. If true, values will be stored as strings
219
+ left-padded with zeros. Note that this does not effect the values
220
+ returned by the underlying database API, which continue to be
221
+ numeric.
222
+
223
+ """
224
+ super().__init__(
225
+ precision=precision, scale=scale, asdecimal=asdecimal, **kw
226
+ )
227
+
228
+
229
+ class REAL(_FloatType, sqltypes.REAL[Union[decimal.Decimal, float]]):
230
+ """MySQL REAL type."""
231
+
232
+ __visit_name__ = "REAL"
233
+
234
+ def __init__(
235
+ self,
236
+ precision: Optional[int] = None,
237
+ scale: Optional[int] = None,
238
+ asdecimal: bool = True,
239
+ **kw: Any,
240
+ ):
241
+ """Construct a REAL.
242
+
243
+ .. note::
244
+
245
+ The :class:`.REAL` type by default converts from float
246
+ to Decimal, using a truncation that defaults to 10 digits.
247
+ Specify either ``scale=n`` or ``decimal_return_scale=n`` in order
248
+ to change this scale, or ``asdecimal=False`` to return values
249
+ directly as Python floating points.
250
+
251
+ :param precision: Total digits in this number. If scale and precision
252
+ are both None, values are stored to limits allowed by the server.
253
+
254
+ :param scale: The number of digits after the decimal point.
255
+
256
+ :param unsigned: a boolean, optional.
257
+
258
+ :param zerofill: Optional. If true, values will be stored as strings
259
+ left-padded with zeros. Note that this does not effect the values
260
+ returned by the underlying database API, which continue to be
261
+ numeric.
262
+
263
+ """
264
+ super().__init__(
265
+ precision=precision, scale=scale, asdecimal=asdecimal, **kw
266
+ )
267
+
268
+
269
+ class FLOAT(_FloatType, sqltypes.FLOAT[Union[decimal.Decimal, float]]):
270
+ """MySQL FLOAT type."""
271
+
272
+ __visit_name__ = "FLOAT"
273
+
274
+ def __init__(
275
+ self,
276
+ precision: Optional[int] = None,
277
+ scale: Optional[int] = None,
278
+ asdecimal: bool = False,
279
+ **kw: Any,
280
+ ):
281
+ """Construct a FLOAT.
282
+
283
+ :param precision: Total digits in this number. If scale and precision
284
+ are both None, values are stored to limits allowed by the server.
285
+
286
+ :param scale: The number of digits after the decimal point.
287
+
288
+ :param unsigned: a boolean, optional.
289
+
290
+ :param zerofill: Optional. If true, values will be stored as strings
291
+ left-padded with zeros. Note that this does not effect the values
292
+ returned by the underlying database API, which continue to be
293
+ numeric.
294
+
295
+ """
296
+ super().__init__(
297
+ precision=precision, scale=scale, asdecimal=asdecimal, **kw
298
+ )
299
+
300
+ def bind_processor(
301
+ self, dialect: Dialect
302
+ ) -> Optional[_BindProcessorType[Union[decimal.Decimal, float]]]:
303
+ return None
304
+
305
+
306
+ class INTEGER(_IntegerType, sqltypes.INTEGER):
307
+ """MySQL INTEGER type."""
308
+
309
+ __visit_name__ = "INTEGER"
310
+
311
+ def __init__(self, display_width: Optional[int] = None, **kw: Any):
312
+ """Construct an INTEGER.
313
+
314
+ :param display_width: Optional, maximum display width for this number.
315
+
316
+ :param unsigned: a boolean, optional.
317
+
318
+ :param zerofill: Optional. If true, values will be stored as strings
319
+ left-padded with zeros. Note that this does not effect the values
320
+ returned by the underlying database API, which continue to be
321
+ numeric.
322
+
323
+ """
324
+ super().__init__(display_width=display_width, **kw)
325
+
326
+
327
+ class BIGINT(_IntegerType, sqltypes.BIGINT):
328
+ """MySQL BIGINTEGER type."""
329
+
330
+ __visit_name__ = "BIGINT"
331
+
332
+ def __init__(self, display_width: Optional[int] = None, **kw: Any):
333
+ """Construct a BIGINTEGER.
334
+
335
+ :param display_width: Optional, maximum display width for this number.
336
+
337
+ :param unsigned: a boolean, optional.
338
+
339
+ :param zerofill: Optional. If true, values will be stored as strings
340
+ left-padded with zeros. Note that this does not effect the values
341
+ returned by the underlying database API, which continue to be
342
+ numeric.
343
+
344
+ """
345
+ super().__init__(display_width=display_width, **kw)
346
+
347
+
348
+ class MEDIUMINT(_IntegerType):
349
+ """MySQL MEDIUMINTEGER type."""
350
+
351
+ __visit_name__ = "MEDIUMINT"
352
+
353
+ def __init__(self, display_width: Optional[int] = None, **kw: Any):
354
+ """Construct a MEDIUMINTEGER
355
+
356
+ :param display_width: Optional, maximum display width for this number.
357
+
358
+ :param unsigned: a boolean, optional.
359
+
360
+ :param zerofill: Optional. If true, values will be stored as strings
361
+ left-padded with zeros. Note that this does not effect the values
362
+ returned by the underlying database API, which continue to be
363
+ numeric.
364
+
365
+ """
366
+ super().__init__(display_width=display_width, **kw)
367
+
368
+
369
+ class TINYINT(_IntegerType):
370
+ """MySQL TINYINT type."""
371
+
372
+ __visit_name__ = "TINYINT"
373
+
374
+ def __init__(self, display_width: Optional[int] = None, **kw: Any):
375
+ """Construct a TINYINT.
376
+
377
+ :param display_width: Optional, maximum display width for this number.
378
+
379
+ :param unsigned: a boolean, optional.
380
+
381
+ :param zerofill: Optional. If true, values will be stored as strings
382
+ left-padded with zeros. Note that this does not effect the values
383
+ returned by the underlying database API, which continue to be
384
+ numeric.
385
+
386
+ """
387
+ super().__init__(display_width=display_width, **kw)
388
+
389
+ def _compare_type_affinity(self, other: TypeEngine[Any]) -> bool:
390
+ return (
391
+ self._type_affinity is other._type_affinity
392
+ or other._type_affinity is sqltypes.Boolean
393
+ )
394
+
395
+
396
+ class SMALLINT(_IntegerType, sqltypes.SMALLINT):
397
+ """MySQL SMALLINTEGER type."""
398
+
399
+ __visit_name__ = "SMALLINT"
400
+
401
+ def __init__(self, display_width: Optional[int] = None, **kw: Any):
402
+ """Construct a SMALLINTEGER.
403
+
404
+ :param display_width: Optional, maximum display width for this number.
405
+
406
+ :param unsigned: a boolean, optional.
407
+
408
+ :param zerofill: Optional. If true, values will be stored as strings
409
+ left-padded with zeros. Note that this does not effect the values
410
+ returned by the underlying database API, which continue to be
411
+ numeric.
412
+
413
+ """
414
+ super().__init__(display_width=display_width, **kw)
415
+
416
+
417
+ class BIT(sqltypes.TypeEngine[Any]):
418
+ """MySQL BIT type.
419
+
420
+ This type is for MySQL 5.0.3 or greater for MyISAM, and 5.0.5 or greater
421
+ for MyISAM, MEMORY, InnoDB and BDB. For older versions, use a
422
+ MSTinyInteger() type.
423
+
424
+ """
425
+
426
+ __visit_name__ = "BIT"
427
+
428
+ def __init__(self, length: Optional[int] = None):
429
+ """Construct a BIT.
430
+
431
+ :param length: Optional, number of bits.
432
+
433
+ """
434
+ self.length = length
435
+
436
+ def result_processor(
437
+ self, dialect: MySQLDialect, coltype: object # type: ignore[override]
438
+ ) -> Optional[_ResultProcessorType[Any]]:
439
+ """Convert a MySQL's 64 bit, variable length binary string to a
440
+ long."""
441
+
442
+ if dialect.supports_native_bit:
443
+ return None
444
+
445
+ def process(value: Optional[Iterable[int]]) -> Optional[int]:
446
+ if value is not None:
447
+ v = 0
448
+ for i in value:
449
+ v = v << 8 | i
450
+ return v
451
+ return value
452
+
453
+ return process
454
+
455
+
456
+ class TIME(sqltypes.TIME):
457
+ """MySQL TIME type."""
458
+
459
+ __visit_name__ = "TIME"
460
+
461
+ def __init__(self, timezone: bool = False, fsp: Optional[int] = None):
462
+ """Construct a MySQL TIME type.
463
+
464
+ :param timezone: not used by the MySQL dialect.
465
+ :param fsp: fractional seconds precision value.
466
+ MySQL 5.6 supports storage of fractional seconds;
467
+ this parameter will be used when emitting DDL
468
+ for the TIME type.
469
+
470
+ .. note::
471
+
472
+ DBAPI driver support for fractional seconds may
473
+ be limited; current support includes
474
+ MySQL Connector/Python.
475
+
476
+ """
477
+ super().__init__(timezone=timezone)
478
+ self.fsp = fsp
479
+
480
+ def result_processor(
481
+ self, dialect: Dialect, coltype: object
482
+ ) -> _ResultProcessorType[datetime.time]:
483
+ time = datetime.time
484
+
485
+ def process(value: Any) -> Optional[datetime.time]:
486
+ # convert from a timedelta value
487
+ if value is not None:
488
+ microseconds = value.microseconds
489
+ seconds = value.seconds
490
+ minutes = seconds // 60
491
+ return time(
492
+ minutes // 60,
493
+ minutes % 60,
494
+ seconds - minutes * 60,
495
+ microsecond=microseconds,
496
+ )
497
+ else:
498
+ return None
499
+
500
+ return process
501
+
502
+
503
+ class TIMESTAMP(sqltypes.TIMESTAMP):
504
+ """MySQL TIMESTAMP type."""
505
+
506
+ __visit_name__ = "TIMESTAMP"
507
+
508
+ def __init__(self, timezone: bool = False, fsp: Optional[int] = None):
509
+ """Construct a MySQL TIMESTAMP type.
510
+
511
+ :param timezone: not used by the MySQL dialect.
512
+ :param fsp: fractional seconds precision value.
513
+ MySQL 5.6.4 supports storage of fractional seconds;
514
+ this parameter will be used when emitting DDL
515
+ for the TIMESTAMP type.
516
+
517
+ .. note::
518
+
519
+ DBAPI driver support for fractional seconds may
520
+ be limited; current support includes
521
+ MySQL Connector/Python.
522
+
523
+ """
524
+ super().__init__(timezone=timezone)
525
+ self.fsp = fsp
526
+
527
+
528
+ class DATETIME(sqltypes.DATETIME):
529
+ """MySQL DATETIME type."""
530
+
531
+ __visit_name__ = "DATETIME"
532
+
533
+ def __init__(self, timezone: bool = False, fsp: Optional[int] = None):
534
+ """Construct a MySQL DATETIME type.
535
+
536
+ :param timezone: not used by the MySQL dialect.
537
+ :param fsp: fractional seconds precision value.
538
+ MySQL 5.6.4 supports storage of fractional seconds;
539
+ this parameter will be used when emitting DDL
540
+ for the DATETIME type.
541
+
542
+ .. note::
543
+
544
+ DBAPI driver support for fractional seconds may
545
+ be limited; current support includes
546
+ MySQL Connector/Python.
547
+
548
+ """
549
+ super().__init__(timezone=timezone)
550
+ self.fsp = fsp
551
+
552
+
553
+ class YEAR(sqltypes.TypeEngine[Any]):
554
+ """MySQL YEAR type, for single byte storage of years 1901-2155."""
555
+
556
+ __visit_name__ = "YEAR"
557
+
558
+ def __init__(self, display_width: Optional[int] = None):
559
+ self.display_width = display_width
560
+
561
+
562
+ class TEXT(_StringType, sqltypes.TEXT):
563
+ """MySQL TEXT type, for character storage encoded up to 2^16 bytes."""
564
+
565
+ __visit_name__ = "TEXT"
566
+
567
+ def __init__(self, length: Optional[int] = None, **kw: Any):
568
+ """Construct a TEXT.
569
+
570
+ :param length: Optional, if provided the server may optimize storage
571
+ by substituting the smallest TEXT type sufficient to store
572
+ ``length`` bytes of characters.
573
+
574
+ :param charset: Optional, a column-level character set for this string
575
+ value. Takes precedence to 'ascii' or 'unicode' short-hand.
576
+
577
+ :param collation: Optional, a column-level collation for this string
578
+ value. Takes precedence to 'binary' short-hand.
579
+
580
+ :param ascii: Defaults to False: short-hand for the ``latin1``
581
+ character set, generates ASCII in schema.
582
+
583
+ :param unicode: Defaults to False: short-hand for the ``ucs2``
584
+ character set, generates UNICODE in schema.
585
+
586
+ :param national: Optional. If true, use the server's configured
587
+ national character set.
588
+
589
+ :param binary: Defaults to False: short-hand, pick the binary
590
+ collation type that matches the column's character set. Generates
591
+ BINARY in schema. This does not affect the type of data stored,
592
+ only the collation of character data.
593
+
594
+ """
595
+ super().__init__(length=length, **kw)
596
+
597
+
598
+ class TINYTEXT(_StringType):
599
+ """MySQL TINYTEXT type, for character storage encoded up to 2^8 bytes."""
600
+
601
+ __visit_name__ = "TINYTEXT"
602
+
603
+ def __init__(self, **kwargs: Any):
604
+ """Construct a TINYTEXT.
605
+
606
+ :param charset: Optional, a column-level character set for this string
607
+ value. Takes precedence to 'ascii' or 'unicode' short-hand.
608
+
609
+ :param collation: Optional, a column-level collation for this string
610
+ value. Takes precedence to 'binary' short-hand.
611
+
612
+ :param ascii: Defaults to False: short-hand for the ``latin1``
613
+ character set, generates ASCII in schema.
614
+
615
+ :param unicode: Defaults to False: short-hand for the ``ucs2``
616
+ character set, generates UNICODE in schema.
617
+
618
+ :param national: Optional. If true, use the server's configured
619
+ national character set.
620
+
621
+ :param binary: Defaults to False: short-hand, pick the binary
622
+ collation type that matches the column's character set. Generates
623
+ BINARY in schema. This does not affect the type of data stored,
624
+ only the collation of character data.
625
+
626
+ """
627
+ super().__init__(**kwargs)
628
+
629
+
630
+ class MEDIUMTEXT(_StringType):
631
+ """MySQL MEDIUMTEXT type, for character storage encoded up
632
+ to 2^24 bytes."""
633
+
634
+ __visit_name__ = "MEDIUMTEXT"
635
+
636
+ def __init__(self, **kwargs: Any):
637
+ """Construct a MEDIUMTEXT.
638
+
639
+ :param charset: Optional, a column-level character set for this string
640
+ value. Takes precedence to 'ascii' or 'unicode' short-hand.
641
+
642
+ :param collation: Optional, a column-level collation for this string
643
+ value. Takes precedence to 'binary' short-hand.
644
+
645
+ :param ascii: Defaults to False: short-hand for the ``latin1``
646
+ character set, generates ASCII in schema.
647
+
648
+ :param unicode: Defaults to False: short-hand for the ``ucs2``
649
+ character set, generates UNICODE in schema.
650
+
651
+ :param national: Optional. If true, use the server's configured
652
+ national character set.
653
+
654
+ :param binary: Defaults to False: short-hand, pick the binary
655
+ collation type that matches the column's character set. Generates
656
+ BINARY in schema. This does not affect the type of data stored,
657
+ only the collation of character data.
658
+
659
+ """
660
+ super().__init__(**kwargs)
661
+
662
+
663
+ class LONGTEXT(_StringType):
664
+ """MySQL LONGTEXT type, for character storage encoded up to 2^32 bytes."""
665
+
666
+ __visit_name__ = "LONGTEXT"
667
+
668
+ def __init__(self, **kwargs: Any):
669
+ """Construct a LONGTEXT.
670
+
671
+ :param charset: Optional, a column-level character set for this string
672
+ value. Takes precedence to 'ascii' or 'unicode' short-hand.
673
+
674
+ :param collation: Optional, a column-level collation for this string
675
+ value. Takes precedence to 'binary' short-hand.
676
+
677
+ :param ascii: Defaults to False: short-hand for the ``latin1``
678
+ character set, generates ASCII in schema.
679
+
680
+ :param unicode: Defaults to False: short-hand for the ``ucs2``
681
+ character set, generates UNICODE in schema.
682
+
683
+ :param national: Optional. If true, use the server's configured
684
+ national character set.
685
+
686
+ :param binary: Defaults to False: short-hand, pick the binary
687
+ collation type that matches the column's character set. Generates
688
+ BINARY in schema. This does not affect the type of data stored,
689
+ only the collation of character data.
690
+
691
+ """
692
+ super().__init__(**kwargs)
693
+
694
+
695
+ class VARCHAR(_StringType, sqltypes.VARCHAR):
696
+ """MySQL VARCHAR type, for variable-length character data."""
697
+
698
+ __visit_name__ = "VARCHAR"
699
+
700
+ def __init__(self, length: Optional[int] = None, **kwargs: Any) -> None:
701
+ """Construct a VARCHAR.
702
+
703
+ :param charset: Optional, a column-level character set for this string
704
+ value. Takes precedence to 'ascii' or 'unicode' short-hand.
705
+
706
+ :param collation: Optional, a column-level collation for this string
707
+ value. Takes precedence to 'binary' short-hand.
708
+
709
+ :param ascii: Defaults to False: short-hand for the ``latin1``
710
+ character set, generates ASCII in schema.
711
+
712
+ :param unicode: Defaults to False: short-hand for the ``ucs2``
713
+ character set, generates UNICODE in schema.
714
+
715
+ :param national: Optional. If true, use the server's configured
716
+ national character set.
717
+
718
+ :param binary: Defaults to False: short-hand, pick the binary
719
+ collation type that matches the column's character set. Generates
720
+ BINARY in schema. This does not affect the type of data stored,
721
+ only the collation of character data.
722
+
723
+ """
724
+ super().__init__(length=length, **kwargs)
725
+
726
+
727
+ class CHAR(_StringType, sqltypes.CHAR):
728
+ """MySQL CHAR type, for fixed-length character data."""
729
+
730
+ __visit_name__ = "CHAR"
731
+
732
+ def __init__(self, length: Optional[int] = None, **kwargs: Any):
733
+ """Construct a CHAR.
734
+
735
+ :param length: Maximum data length, in characters.
736
+
737
+ :param binary: Optional, use the default binary collation for the
738
+ national character set. This does not affect the type of data
739
+ stored, use a BINARY type for binary data.
740
+
741
+ :param collation: Optional, request a particular collation. Must be
742
+ compatible with the national character set.
743
+
744
+ """
745
+ super().__init__(length=length, **kwargs)
746
+
747
+ @classmethod
748
+ def _adapt_string_for_cast(cls, type_: sqltypes.String) -> sqltypes.CHAR:
749
+ # copy the given string type into a CHAR
750
+ # for the purposes of rendering a CAST expression
751
+ type_ = sqltypes.to_instance(type_)
752
+ if isinstance(type_, sqltypes.CHAR):
753
+ return type_
754
+ elif isinstance(type_, _StringType):
755
+ return CHAR(
756
+ length=type_.length,
757
+ charset=type_.charset,
758
+ collation=type_.collation,
759
+ ascii=type_.ascii,
760
+ binary=type_.binary,
761
+ unicode=type_.unicode,
762
+ national=False, # not supported in CAST
763
+ )
764
+ else:
765
+ return CHAR(length=type_.length)
766
+
767
+
768
+ class NVARCHAR(_StringType, sqltypes.NVARCHAR):
769
+ """MySQL NVARCHAR type.
770
+
771
+ For variable-length character data in the server's configured national
772
+ character set.
773
+ """
774
+
775
+ __visit_name__ = "NVARCHAR"
776
+
777
+ def __init__(self, length: Optional[int] = None, **kwargs: Any):
778
+ """Construct an NVARCHAR.
779
+
780
+ :param length: Maximum data length, in characters.
781
+
782
+ :param binary: Optional, use the default binary collation for the
783
+ national character set. This does not affect the type of data
784
+ stored, use a BINARY type for binary data.
785
+
786
+ :param collation: Optional, request a particular collation. Must be
787
+ compatible with the national character set.
788
+
789
+ """
790
+ kwargs["national"] = True
791
+ super().__init__(length=length, **kwargs)
792
+
793
+
794
+ class NCHAR(_StringType, sqltypes.NCHAR):
795
+ """MySQL NCHAR type.
796
+
797
+ For fixed-length character data in the server's configured national
798
+ character set.
799
+ """
800
+
801
+ __visit_name__ = "NCHAR"
802
+
803
+ def __init__(self, length: Optional[int] = None, **kwargs: Any):
804
+ """Construct an NCHAR.
805
+
806
+ :param length: Maximum data length, in characters.
807
+
808
+ :param binary: Optional, use the default binary collation for the
809
+ national character set. This does not affect the type of data
810
+ stored, use a BINARY type for binary data.
811
+
812
+ :param collation: Optional, request a particular collation. Must be
813
+ compatible with the national character set.
814
+
815
+ """
816
+ kwargs["national"] = True
817
+ super().__init__(length=length, **kwargs)
818
+
819
+
820
+ class TINYBLOB(sqltypes._Binary):
821
+ """MySQL TINYBLOB type, for binary data up to 2^8 bytes."""
822
+
823
+ __visit_name__ = "TINYBLOB"
824
+
825
+
826
+ class MEDIUMBLOB(sqltypes._Binary):
827
+ """MySQL MEDIUMBLOB type, for binary data up to 2^24 bytes."""
828
+
829
+ __visit_name__ = "MEDIUMBLOB"
830
+
831
+
832
+ class LONGBLOB(sqltypes._Binary):
833
+ """MySQL LONGBLOB type, for binary data up to 2^32 bytes."""
834
+
835
+ __visit_name__ = "LONGBLOB"
loan-advisor-agent/.venv/Lib/site-packages/sqlalchemy/dialects/oracle/__init__.py ADDED
@@ -0,0 +1,81 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # dialects/oracle/__init__.py
2
+ # Copyright (C) 2005-2026 the SQLAlchemy authors and contributors
3
+ # <see AUTHORS file>
4
+ #
5
+ # This module is part of SQLAlchemy and is released under
6
+ # the MIT License: https://www.opensource.org/licenses/mit-license.php
7
+ # mypy: ignore-errors
8
+ from types import ModuleType
9
+
10
+ from . import base # noqa
11
+ from . import cx_oracle # noqa
12
+ from . import oracledb # noqa
13
+ from .base import BFILE
14
+ from .base import BINARY_DOUBLE
15
+ from .base import BINARY_FLOAT
16
+ from .base import BLOB
17
+ from .base import CHAR
18
+ from .base import CLOB
19
+ from .base import DATE
20
+ from .base import DOUBLE_PRECISION
21
+ from .base import FLOAT
22
+ from .base import INTERVAL
23
+ from .base import LONG
24
+ from .base import NCHAR
25
+ from .base import NCLOB
26
+ from .base import NUMBER
27
+ from .base import NVARCHAR
28
+ from .base import NVARCHAR2
29
+ from .base import RAW
30
+ from .base import REAL
31
+ from .base import ROWID
32
+ from .base import TIMESTAMP
33
+ from .base import VARCHAR
34
+ from .base import VARCHAR2
35
+ from .base import VECTOR
36
+ from .base import VectorIndexConfig
37
+ from .base import VectorIndexType
38
+ from .vector import SparseVector
39
+ from .vector import VectorDistanceType
40
+ from .vector import VectorStorageFormat
41
+ from .vector import VectorStorageType
42
+
43
+ # Alias oracledb also as oracledb_async
44
+ oracledb_async = type(
45
+ "oracledb_async", (ModuleType,), {"dialect": oracledb.dialect_async}
46
+ )
47
+
48
+ base.dialect = dialect = cx_oracle.dialect
49
+
50
+ __all__ = (
51
+ "VARCHAR",
52
+ "NVARCHAR",
53
+ "CHAR",
54
+ "NCHAR",
55
+ "DATE",
56
+ "NUMBER",
57
+ "BLOB",
58
+ "BFILE",
59
+ "CLOB",
60
+ "NCLOB",
61
+ "TIMESTAMP",
62
+ "RAW",
63
+ "FLOAT",
64
+ "DOUBLE_PRECISION",
65
+ "BINARY_DOUBLE",
66
+ "BINARY_FLOAT",
67
+ "LONG",
68
+ "dialect",
69
+ "INTERVAL",
70
+ "VARCHAR2",
71
+ "NVARCHAR2",
72
+ "ROWID",
73
+ "REAL",
74
+ "VECTOR",
75
+ "VectorDistanceType",
76
+ "VectorIndexType",
77
+ "VectorIndexConfig",
78
+ "VectorStorageFormat",
79
+ "VectorStorageType",
80
+ "SparseVector",
81
+ )
loan-advisor-agent/.venv/Lib/site-packages/sqlalchemy/dialects/oracle/base.py ADDED
The diff for this file is too large to render. See raw diff
 
loan-advisor-agent/.venv/Lib/site-packages/sqlalchemy/dialects/oracle/cx_oracle.py ADDED
@@ -0,0 +1,1555 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # dialects/oracle/cx_oracle.py
2
+ # Copyright (C) 2005-2026 the SQLAlchemy authors and contributors
3
+ # <see AUTHORS file>
4
+ #
5
+ # This module is part of SQLAlchemy and is released under
6
+ # the MIT License: https://www.opensource.org/licenses/mit-license.php
7
+ # mypy: ignore-errors
8
+
9
+
10
+ r""".. dialect:: oracle+cx_oracle
11
+ :name: cx-Oracle
12
+ :dbapi: cx_oracle
13
+ :connectstring: oracle+cx_oracle://user:pass@hostname:port[/dbname][?service_name=<service>[&key=value&key=value...]]
14
+ :url: https://oracle.github.io/python-cx_Oracle/
15
+
16
+ Description
17
+ -----------
18
+
19
+ cx_Oracle was the original driver for Oracle Database. It was superseded by
20
+ python-oracledb which should be used instead.
21
+
22
+ DSN vs. Hostname connections
23
+ -----------------------------
24
+
25
+ cx_Oracle provides several methods of indicating the target database. The
26
+ dialect translates from a series of different URL forms.
27
+
28
+ Hostname Connections with Easy Connect Syntax
29
+ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
30
+
31
+ Given a hostname, port and service name of the target database, for example
32
+ from Oracle Database's Easy Connect syntax then connect in SQLAlchemy using the
33
+ ``service_name`` query string parameter::
34
+
35
+ engine = create_engine(
36
+ "oracle+cx_oracle://scott:tiger@hostname:port?service_name=myservice&encoding=UTF-8&nencoding=UTF-8"
37
+ )
38
+
39
+ Note that the default driver value for encoding and nencoding was changed to
40
+ “UTF-8” in cx_Oracle 8.0 so these parameters can be omitted when using that
41
+ version, or later.
42
+
43
+ To use a full Easy Connect string, pass it as the ``dsn`` key value in a
44
+ :paramref:`_sa.create_engine.connect_args` dictionary::
45
+
46
+ import cx_Oracle
47
+
48
+ e = create_engine(
49
+ "oracle+cx_oracle://@",
50
+ connect_args={
51
+ "user": "scott",
52
+ "password": "tiger",
53
+ "dsn": "hostname:port/myservice?transport_connect_timeout=30&expire_time=60",
54
+ },
55
+ )
56
+
57
+ Connections with tnsnames.ora or to Oracle Autonomous Database
58
+ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
59
+
60
+ Alternatively, if no port, database name, or service name is provided, the
61
+ dialect will use an Oracle Database DSN "connection string". This takes the
62
+ "hostname" portion of the URL as the data source name. For example, if the
63
+ ``tnsnames.ora`` file contains a TNS Alias of ``myalias`` as below:
64
+
65
+ .. sourcecode:: text
66
+
67
+ myalias =
68
+ (DESCRIPTION =
69
+ (ADDRESS = (PROTOCOL = TCP)(HOST = mymachine.example.com)(PORT = 1521))
70
+ (CONNECT_DATA =
71
+ (SERVER = DEDICATED)
72
+ (SERVICE_NAME = orclpdb1)
73
+ )
74
+ )
75
+
76
+ The cx_Oracle dialect connects to this database service when ``myalias`` is the
77
+ hostname portion of the URL, without specifying a port, database name or
78
+ ``service_name``::
79
+
80
+ engine = create_engine("oracle+cx_oracle://scott:tiger@myalias")
81
+
82
+ Users of Oracle Autonomous Database should use this syntax. If the database is
83
+ configured for mutural TLS ("mTLS"), then you must also configure the cloud
84
+ wallet as shown in cx_Oracle documentation `Connecting to Autononmous Databases
85
+ <https://cx-oracle.readthedocs.io/en/latest/user_guide/connection_handling.html#autonomousdb>`_.
86
+
87
+ SID Connections
88
+ ^^^^^^^^^^^^^^^
89
+
90
+ To use Oracle Database's obsolete System Identifier connection syntax, the SID
91
+ can be passed in a "database name" portion of the URL::
92
+
93
+ engine = create_engine(
94
+ "oracle+cx_oracle://scott:tiger@hostname:port/dbname"
95
+ )
96
+
97
+ Above, the DSN passed to cx_Oracle is created by ``cx_Oracle.makedsn()`` as
98
+ follows::
99
+
100
+ >>> import cx_Oracle
101
+ >>> cx_Oracle.makedsn("hostname", 1521, sid="dbname")
102
+ '(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=hostname)(PORT=1521))(CONNECT_DATA=(SID=dbname)))'
103
+
104
+ Note that although the SQLAlchemy syntax ``hostname:port/dbname`` looks like
105
+ Oracle's Easy Connect syntax it is different. It uses a SID in place of the
106
+ service name required by Easy Connect. The Easy Connect syntax does not
107
+ support SIDs.
108
+
109
+ Passing cx_Oracle connect arguments
110
+ -----------------------------------
111
+
112
+ Additional connection arguments can usually be passed via the URL query string;
113
+ particular symbols like ``SYSDBA`` are intercepted and converted to the correct
114
+ symbol::
115
+
116
+ e = create_engine(
117
+ "oracle+cx_oracle://user:pass@dsn?encoding=UTF-8&nencoding=UTF-8&mode=SYSDBA&events=true"
118
+ )
119
+
120
+ .. versionchanged:: 1.3 the cx_Oracle dialect now accepts all argument names
121
+ within the URL string itself, to be passed to the cx_Oracle DBAPI. As
122
+ was the case earlier but not correctly documented, the
123
+ :paramref:`_sa.create_engine.connect_args` parameter also accepts all
124
+ cx_Oracle DBAPI connect arguments.
125
+
126
+ To pass arguments directly to ``.connect()`` without using the query
127
+ string, use the :paramref:`_sa.create_engine.connect_args` dictionary.
128
+ Any cx_Oracle parameter value and/or constant may be passed, such as::
129
+
130
+ import cx_Oracle
131
+
132
+ e = create_engine(
133
+ "oracle+cx_oracle://user:pass@dsn",
134
+ connect_args={
135
+ "encoding": "UTF-8",
136
+ "nencoding": "UTF-8",
137
+ "mode": cx_Oracle.SYSDBA,
138
+ "events": True,
139
+ },
140
+ )
141
+
142
+ Note that the default driver value for ``encoding`` and ``nencoding`` was
143
+ changed to "UTF-8" in cx_Oracle 8.0 so these parameters can be omitted when
144
+ using that version, or later.
145
+
146
+ Options consumed by the SQLAlchemy cx_Oracle dialect outside of the driver
147
+ --------------------------------------------------------------------------
148
+
149
+ There are also options that are consumed by the SQLAlchemy cx_oracle dialect
150
+ itself. These options are always passed directly to :func:`_sa.create_engine`
151
+ , such as::
152
+
153
+ e = create_engine(
154
+ "oracle+cx_oracle://user:pass@dsn", coerce_to_decimal=False
155
+ )
156
+
157
+ The parameters accepted by the cx_oracle dialect are as follows:
158
+
159
+ * ``arraysize`` - set the cx_oracle.arraysize value on cursors; defaults
160
+ to ``None``, indicating that the driver default should be used (typically
161
+ the value is 100). This setting controls how many rows are buffered when
162
+ fetching rows, and can have a significant effect on performance when
163
+ modified.
164
+
165
+ .. versionchanged:: 2.0.26 - changed the default value from 50 to None,
166
+ to use the default value of the driver itself.
167
+
168
+ * ``auto_convert_lobs`` - defaults to True; See :ref:`cx_oracle_lob`.
169
+
170
+ * ``coerce_to_decimal`` - see :ref:`cx_oracle_numeric` for detail.
171
+
172
+ * ``encoding_errors`` - see :ref:`cx_oracle_unicode_encoding_errors` for detail.
173
+
174
+ .. _cx_oracle_sessionpool:
175
+
176
+ Using cx_Oracle SessionPool
177
+ ---------------------------
178
+
179
+ The cx_Oracle driver provides its own connection pool implementation that may
180
+ be used in place of SQLAlchemy's pooling functionality. The driver pool
181
+ supports Oracle Database features such dead connection detection, connection
182
+ draining for planned database downtime, support for Oracle Application
183
+ Continuity and Transparent Application Continuity, and gives support for
184
+ Database Resident Connection Pooling (DRCP).
185
+
186
+ Using the driver pool can be achieved by using the
187
+ :paramref:`_sa.create_engine.creator` parameter to provide a function that
188
+ returns a new connection, along with setting
189
+ :paramref:`_sa.create_engine.pool_class` to ``NullPool`` to disable
190
+ SQLAlchemy's pooling::
191
+
192
+ import cx_Oracle
193
+ from sqlalchemy import create_engine
194
+ from sqlalchemy.pool import NullPool
195
+
196
+ pool = cx_Oracle.SessionPool(
197
+ user="scott",
198
+ password="tiger",
199
+ dsn="orclpdb",
200
+ min=1,
201
+ max=4,
202
+ increment=1,
203
+ threaded=True,
204
+ encoding="UTF-8",
205
+ nencoding="UTF-8",
206
+ )
207
+
208
+ engine = create_engine(
209
+ "oracle+cx_oracle://", creator=pool.acquire, poolclass=NullPool
210
+ )
211
+
212
+ The above engine may then be used normally where cx_Oracle's pool handles
213
+ connection pooling::
214
+
215
+ with engine.connect() as conn:
216
+ print(conn.scalar("select 1 from dual"))
217
+
218
+ As well as providing a scalable solution for multi-user applications, the
219
+ cx_Oracle session pool supports some Oracle features such as DRCP and
220
+ `Application Continuity
221
+ <https://cx-oracle.readthedocs.io/en/latest/user_guide/ha.html#application-continuity-ac>`_.
222
+
223
+ Note that the pool creation parameters ``threaded``, ``encoding`` and
224
+ ``nencoding`` were deprecated in later cx_Oracle releases.
225
+
226
+ Using Oracle Database Resident Connection Pooling (DRCP)
227
+ --------------------------------------------------------
228
+
229
+ When using Oracle Database's DRCP, the best practice is to pass a connection
230
+ class and "purity" when acquiring a connection from the SessionPool. Refer to
231
+ the `cx_Oracle DRCP documentation
232
+ <https://cx-oracle.readthedocs.io/en/latest/user_guide/connection_handling.html#database-resident-connection-pooling-drcp>`_.
233
+
234
+ This can be achieved by wrapping ``pool.acquire()``::
235
+
236
+ import cx_Oracle
237
+ from sqlalchemy import create_engine
238
+ from sqlalchemy.pool import NullPool
239
+
240
+ pool = cx_Oracle.SessionPool(
241
+ user="scott",
242
+ password="tiger",
243
+ dsn="orclpdb",
244
+ min=2,
245
+ max=5,
246
+ increment=1,
247
+ threaded=True,
248
+ encoding="UTF-8",
249
+ nencoding="UTF-8",
250
+ )
251
+
252
+
253
+ def creator():
254
+ return pool.acquire(
255
+ cclass="MYCLASS", purity=cx_Oracle.ATTR_PURITY_SELF
256
+ )
257
+
258
+
259
+ engine = create_engine(
260
+ "oracle+cx_oracle://", creator=creator, poolclass=NullPool
261
+ )
262
+
263
+ The above engine may then be used normally where cx_Oracle handles session
264
+ pooling and Oracle Database additionally uses DRCP::
265
+
266
+ with engine.connect() as conn:
267
+ print(conn.scalar("select 1 from dual"))
268
+
269
+ .. _cx_oracle_unicode:
270
+
271
+ Unicode
272
+ -------
273
+
274
+ As is the case for all DBAPIs under Python 3, all strings are inherently
275
+ Unicode strings. In all cases however, the driver requires an explicit
276
+ encoding configuration.
277
+
278
+ Ensuring the Correct Client Encoding
279
+ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
280
+
281
+ The long accepted standard for establishing client encoding for nearly all
282
+ Oracle Database related software is via the `NLS_LANG
283
+ <https://www.oracle.com/database/technologies/faq-nls-lang.html>`_ environment
284
+ variable. Older versions of cx_Oracle use this environment variable as the
285
+ source of its encoding configuration. The format of this variable is
286
+ Territory_Country.CharacterSet; a typical value would be
287
+ ``AMERICAN_AMERICA.AL32UTF8``. cx_Oracle version 8 and later use the character
288
+ set "UTF-8" by default, and ignore the character set component of NLS_LANG.
289
+
290
+ The cx_Oracle driver also supported a programmatic alternative which is to pass
291
+ the ``encoding`` and ``nencoding`` parameters directly to its ``.connect()``
292
+ function. These can be present in the URL as follows::
293
+
294
+ engine = create_engine(
295
+ "oracle+cx_oracle://scott:tiger@tnsalias?encoding=UTF-8&nencoding=UTF-8"
296
+ )
297
+
298
+ For the meaning of the ``encoding`` and ``nencoding`` parameters, please
299
+ consult
300
+ `Characters Sets and National Language Support (NLS) <https://cx-oracle.readthedocs.io/en/latest/user_guide/globalization.html#globalization>`_.
301
+
302
+ .. seealso::
303
+
304
+ `Characters Sets and National Language Support (NLS) <https://cx-oracle.readthedocs.io/en/latest/user_guide/globalization.html#globalization>`_
305
+ - in the cx_Oracle documentation.
306
+
307
+
308
+ Unicode-specific Column datatypes
309
+ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
310
+
311
+ The Core expression language handles unicode data by use of the
312
+ :class:`.Unicode` and :class:`.UnicodeText` datatypes. These types correspond
313
+ to the VARCHAR2 and CLOB Oracle Database datatypes by default. When using
314
+ these datatypes with Unicode data, it is expected that the database is
315
+ configured with a Unicode-aware character set, as well as that the ``NLS_LANG``
316
+ environment variable is set appropriately (this applies to older versions of
317
+ cx_Oracle), so that the VARCHAR2 and CLOB datatypes can accommodate the data.
318
+
319
+ In the case that Oracle Database is not configured with a Unicode character
320
+ set, the two options are to use the :class:`_types.NCHAR` and
321
+ :class:`_oracle.NCLOB` datatypes explicitly, or to pass the flag
322
+ ``use_nchar_for_unicode=True`` to :func:`_sa.create_engine`, which will cause
323
+ the SQLAlchemy dialect to use NCHAR/NCLOB for the :class:`.Unicode` /
324
+ :class:`.UnicodeText` datatypes instead of VARCHAR/CLOB.
325
+
326
+ .. versionchanged:: 1.3 The :class:`.Unicode` and :class:`.UnicodeText`
327
+ datatypes now correspond to the ``VARCHAR2`` and ``CLOB`` Oracle Database
328
+ datatypes unless the ``use_nchar_for_unicode=True`` is passed to the dialect
329
+ when :func:`_sa.create_engine` is called.
330
+
331
+
332
+ .. _cx_oracle_unicode_encoding_errors:
333
+
334
+ Encoding Errors
335
+ ^^^^^^^^^^^^^^^
336
+
337
+ For the unusual case that data in Oracle Database is present with a broken
338
+ encoding, the dialect accepts a parameter ``encoding_errors`` which will be
339
+ passed to Unicode decoding functions in order to affect how decoding errors are
340
+ handled. The value is ultimately consumed by the Python `decode
341
+ <https://docs.python.org/3/library/stdtypes.html#bytes.decode>`_ function, and
342
+ is passed both via cx_Oracle's ``encodingErrors`` parameter consumed by
343
+ ``Cursor.var()``, as well as SQLAlchemy's own decoding function, as the
344
+ cx_Oracle dialect makes use of both under different circumstances.
345
+
346
+ .. versionadded:: 1.3.11
347
+
348
+
349
+ .. _cx_oracle_setinputsizes:
350
+
351
+ Fine grained control over cx_Oracle data binding performance with setinputsizes
352
+ -------------------------------------------------------------------------------
353
+
354
+ The cx_Oracle DBAPI has a deep and fundamental reliance upon the usage of the
355
+ DBAPI ``setinputsizes()`` call. The purpose of this call is to establish the
356
+ datatypes that are bound to a SQL statement for Python values being passed as
357
+ parameters. While virtually no other DBAPI assigns any use to the
358
+ ``setinputsizes()`` call, the cx_Oracle DBAPI relies upon it heavily in its
359
+ interactions with the Oracle Database client interface, and in some scenarios
360
+ it is not possible for SQLAlchemy to know exactly how data should be bound, as
361
+ some settings can cause profoundly different performance characteristics, while
362
+ altering the type coercion behavior at the same time.
363
+
364
+ Users of the cx_Oracle dialect are **strongly encouraged** to read through
365
+ cx_Oracle's list of built-in datatype symbols at
366
+ https://cx-oracle.readthedocs.io/en/latest/api_manual/module.html#database-types.
367
+ Note that in some cases, significant performance degradation can occur when
368
+ using these types vs. not, in particular when specifying ``cx_Oracle.CLOB``.
369
+
370
+ On the SQLAlchemy side, the :meth:`.DialectEvents.do_setinputsizes` event can
371
+ be used both for runtime visibility (e.g. logging) of the setinputsizes step as
372
+ well as to fully control how ``setinputsizes()`` is used on a per-statement
373
+ basis.
374
+
375
+ .. versionadded:: 1.2.9 Added :meth:`.DialectEvents.setinputsizes`
376
+
377
+
378
+ Example 1 - logging all setinputsizes calls
379
+ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
380
+
381
+ The following example illustrates how to log the intermediary values from a
382
+ SQLAlchemy perspective before they are converted to the raw ``setinputsizes()``
383
+ parameter dictionary. The keys of the dictionary are :class:`.BindParameter`
384
+ objects which have a ``.key`` and a ``.type`` attribute::
385
+
386
+ from sqlalchemy import create_engine, event
387
+
388
+ engine = create_engine("oracle+cx_oracle://scott:tiger@host/xe")
389
+
390
+
391
+ @event.listens_for(engine, "do_setinputsizes")
392
+ def _log_setinputsizes(inputsizes, cursor, statement, parameters, context):
393
+ for bindparam, dbapitype in inputsizes.items():
394
+ log.info(
395
+ "Bound parameter name: %s SQLAlchemy type: %r DBAPI object: %s",
396
+ bindparam.key,
397
+ bindparam.type,
398
+ dbapitype,
399
+ )
400
+
401
+ Example 2 - remove all bindings to CLOB
402
+ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
403
+
404
+ The ``CLOB`` datatype in cx_Oracle incurs a significant performance overhead,
405
+ however is set by default for the ``Text`` type within the SQLAlchemy 1.2
406
+ series. This setting can be modified as follows::
407
+
408
+ from sqlalchemy import create_engine, event
409
+ from cx_Oracle import CLOB
410
+
411
+ engine = create_engine("oracle+cx_oracle://scott:tiger@host/xe")
412
+
413
+
414
+ @event.listens_for(engine, "do_setinputsizes")
415
+ def _remove_clob(inputsizes, cursor, statement, parameters, context):
416
+ for bindparam, dbapitype in list(inputsizes.items()):
417
+ if dbapitype is CLOB:
418
+ del inputsizes[bindparam]
419
+
420
+ .. _cx_oracle_lob:
421
+
422
+ LOB Datatypes
423
+ --------------
424
+
425
+ LOB datatypes refer to the "large object" datatypes such as CLOB, NCLOB and
426
+ BLOB. Modern versions of cx_Oracle is optimized for these datatypes to be
427
+ delivered as a single buffer. As such, SQLAlchemy makes use of these newer type
428
+ handlers by default.
429
+
430
+ To disable the use of newer type handlers and deliver LOB objects as classic
431
+ buffered objects with a ``read()`` method, the parameter
432
+ ``auto_convert_lobs=False`` may be passed to :func:`_sa.create_engine`,
433
+ which takes place only engine-wide.
434
+
435
+ .. _cx_oracle_returning:
436
+
437
+ RETURNING Support
438
+ -----------------
439
+
440
+ The cx_Oracle dialect implements RETURNING using OUT parameters.
441
+ The dialect supports RETURNING fully.
442
+
443
+ Two Phase Transactions Not Supported
444
+ ------------------------------------
445
+
446
+ Two phase transactions are **not supported** under cx_Oracle due to poor driver
447
+ support. The newer :ref:`oracledb` dialect however **does** support two phase
448
+ transactions.
449
+
450
+ .. _cx_oracle_numeric:
451
+
452
+ Precision Numerics
453
+ ------------------
454
+
455
+ SQLAlchemy's numeric types can handle receiving and returning values as Python
456
+ ``Decimal`` objects or float objects. When a :class:`.Numeric` object, or a
457
+ subclass such as :class:`.Float`, :class:`_oracle.DOUBLE_PRECISION` etc. is in
458
+ use, the :paramref:`.Numeric.asdecimal` flag determines if values should be
459
+ coerced to ``Decimal`` upon return, or returned as float objects. To make
460
+ matters more complicated under Oracle Database, the ``NUMBER`` type can also
461
+ represent integer values if the "scale" is zero, so the Oracle
462
+ Database-specific :class:`_oracle.NUMBER` type takes this into account as well.
463
+
464
+ The cx_Oracle dialect makes extensive use of connection- and cursor-level
465
+ "outputtypehandler" callables in order to coerce numeric values as requested.
466
+ These callables are specific to the specific flavor of :class:`.Numeric` in
467
+ use, as well as if no SQLAlchemy typing objects are present. There are
468
+ observed scenarios where Oracle Database may send incomplete or ambiguous
469
+ information about the numeric types being returned, such as a query where the
470
+ numeric types are buried under multiple levels of subquery. The type handlers
471
+ do their best to make the right decision in all cases, deferring to the
472
+ underlying cx_Oracle DBAPI for all those cases where the driver can make the
473
+ best decision.
474
+
475
+ When no typing objects are present, as when executing plain SQL strings, a
476
+ default "outputtypehandler" is present which will generally return numeric
477
+ values which specify precision and scale as Python ``Decimal`` objects. To
478
+ disable this coercion to decimal for performance reasons, pass the flag
479
+ ``coerce_to_decimal=False`` to :func:`_sa.create_engine`::
480
+
481
+ engine = create_engine("oracle+cx_oracle://dsn", coerce_to_decimal=False)
482
+
483
+ The ``coerce_to_decimal`` flag only impacts the results of plain string
484
+ SQL statements that are not otherwise associated with a :class:`.Numeric`
485
+ SQLAlchemy type (or a subclass of such).
486
+
487
+ .. versionchanged:: 1.2 The numeric handling system for cx_Oracle has been
488
+ reworked to take advantage of newer cx_Oracle features as well
489
+ as better integration of outputtypehandlers.
490
+
491
+ """ # noqa
492
+ from __future__ import annotations
493
+
494
+ import decimal
495
+ import random
496
+ import re
497
+
498
+ from . import base as oracle
499
+ from .base import OracleCompiler
500
+ from .base import OracleDialect
501
+ from .base import OracleExecutionContext
502
+ from .types import _OracleDateLiteralRender
503
+ from ... import exc
504
+ from ... import util
505
+ from ...engine import cursor as _cursor
506
+ from ...engine import interfaces
507
+ from ...engine import processors
508
+ from ...sql import sqltypes
509
+ from ...sql._typing import is_sql_compiler
510
+
511
+ # source:
512
+ # https://github.com/oracle/python-cx_Oracle/issues/596#issuecomment-999243649
513
+ _CX_ORACLE_MAGIC_LOB_SIZE = 131072
514
+
515
+
516
+ class _OracleInteger(sqltypes.Integer):
517
+ def get_dbapi_type(self, dbapi):
518
+ # see https://github.com/oracle/python-cx_Oracle/issues/
519
+ # 208#issuecomment-409715955
520
+ return int
521
+
522
+ def _cx_oracle_var(self, dialect, cursor, arraysize=None):
523
+ cx_Oracle = dialect.dbapi
524
+ return cursor.var(
525
+ cx_Oracle.STRING,
526
+ 255,
527
+ arraysize=arraysize if arraysize is not None else cursor.arraysize,
528
+ outconverter=int,
529
+ )
530
+
531
+ def _cx_oracle_outputtypehandler(self, dialect):
532
+ def handler(cursor, name, default_type, size, precision, scale):
533
+ return self._cx_oracle_var(dialect, cursor)
534
+
535
+ return handler
536
+
537
+
538
+ class _OracleNumeric(sqltypes.Numeric):
539
+ is_number = False
540
+
541
+ def bind_processor(self, dialect):
542
+ if self.scale == 0:
543
+ return None
544
+ elif self.asdecimal:
545
+ processor = processors.to_decimal_processor_factory(
546
+ decimal.Decimal, self._effective_decimal_return_scale
547
+ )
548
+
549
+ def process(value):
550
+ if isinstance(value, (int, float)):
551
+ return processor(value)
552
+ elif value is not None and value.is_infinite():
553
+ return float(value)
554
+ else:
555
+ return value
556
+
557
+ return process
558
+ else:
559
+ return processors.to_float
560
+
561
+ def result_processor(self, dialect, coltype):
562
+ return None
563
+
564
+ def _cx_oracle_outputtypehandler(self, dialect):
565
+ cx_Oracle = dialect.dbapi
566
+
567
+ def handler(cursor, name, default_type, size, precision, scale):
568
+ outconverter = None
569
+
570
+ if precision:
571
+ if self.asdecimal:
572
+ if default_type == cx_Oracle.NATIVE_FLOAT:
573
+ # receiving float and doing Decimal after the fact
574
+ # allows for float("inf") to be handled
575
+ type_ = default_type
576
+ outconverter = decimal.Decimal
577
+ else:
578
+ type_ = decimal.Decimal
579
+ else:
580
+ if self.is_number and scale == 0:
581
+ # integer. cx_Oracle is observed to handle the widest
582
+ # variety of ints when no directives are passed,
583
+ # from 5.2 to 7.0. See [ticket:4457]
584
+ return None
585
+ else:
586
+ type_ = cx_Oracle.NATIVE_FLOAT
587
+
588
+ else:
589
+ if self.asdecimal:
590
+ if default_type == cx_Oracle.NATIVE_FLOAT:
591
+ type_ = default_type
592
+ outconverter = decimal.Decimal
593
+ else:
594
+ type_ = decimal.Decimal
595
+ else:
596
+ if self.is_number and scale == 0:
597
+ # integer. cx_Oracle is observed to handle the widest
598
+ # variety of ints when no directives are passed,
599
+ # from 5.2 to 7.0. See [ticket:4457]
600
+ return None
601
+ else:
602
+ type_ = cx_Oracle.NATIVE_FLOAT
603
+
604
+ return cursor.var(
605
+ type_,
606
+ 255,
607
+ arraysize=cursor.arraysize,
608
+ outconverter=outconverter,
609
+ )
610
+
611
+ return handler
612
+
613
+
614
+ class _OracleUUID(sqltypes.Uuid):
615
+ def get_dbapi_type(self, dbapi):
616
+ return dbapi.STRING
617
+
618
+
619
+ class _OracleBinaryFloat(_OracleNumeric):
620
+ def get_dbapi_type(self, dbapi):
621
+ return dbapi.NATIVE_FLOAT
622
+
623
+
624
+ class _OracleBINARY_FLOAT(_OracleBinaryFloat, oracle.BINARY_FLOAT):
625
+ pass
626
+
627
+
628
+ class _OracleBINARY_DOUBLE(_OracleBinaryFloat, oracle.BINARY_DOUBLE):
629
+ pass
630
+
631
+
632
+ class _OracleNUMBER(_OracleNumeric):
633
+ is_number = True
634
+
635
+
636
+ class _CXOracleDate(oracle._OracleDate):
637
+ def bind_processor(self, dialect):
638
+ return None
639
+
640
+ def result_processor(self, dialect, coltype):
641
+ def process(value):
642
+ if value is not None:
643
+ return value.date()
644
+ else:
645
+ return value
646
+
647
+ return process
648
+
649
+
650
+ class _CXOracleTIMESTAMP(_OracleDateLiteralRender, sqltypes.TIMESTAMP):
651
+ def literal_processor(self, dialect):
652
+ return self._literal_processor_datetime(dialect)
653
+
654
+
655
+ class _LOBDataType:
656
+ pass
657
+
658
+
659
+ # TODO: the names used across CHAR / VARCHAR / NCHAR / NVARCHAR
660
+ # here are inconsistent and not very good
661
+ class _OracleChar(sqltypes.CHAR):
662
+ def get_dbapi_type(self, dbapi):
663
+ return dbapi.FIXED_CHAR
664
+
665
+
666
+ class _OracleNChar(sqltypes.NCHAR):
667
+ def get_dbapi_type(self, dbapi):
668
+ return dbapi.FIXED_NCHAR
669
+
670
+
671
+ class _OracleUnicodeStringNCHAR(oracle.NVARCHAR2):
672
+ def get_dbapi_type(self, dbapi):
673
+ return dbapi.NCHAR
674
+
675
+
676
+ class _OracleUnicodeStringCHAR(sqltypes.Unicode):
677
+ def get_dbapi_type(self, dbapi):
678
+ return dbapi.LONG_STRING
679
+
680
+
681
+ class _OracleUnicodeTextNCLOB(_LOBDataType, oracle.NCLOB):
682
+ def get_dbapi_type(self, dbapi):
683
+ # previously, this was dbapi.NCLOB.
684
+ # DB_TYPE_NVARCHAR will instead be passed to setinputsizes()
685
+ # when this datatype is used.
686
+ return dbapi.DB_TYPE_NVARCHAR
687
+
688
+
689
+ class _OracleUnicodeTextCLOB(_LOBDataType, sqltypes.UnicodeText):
690
+ def get_dbapi_type(self, dbapi):
691
+ # previously, this was dbapi.CLOB.
692
+ # DB_TYPE_NVARCHAR will instead be passed to setinputsizes()
693
+ # when this datatype is used.
694
+ return dbapi.DB_TYPE_NVARCHAR
695
+
696
+
697
+ class _OracleText(_LOBDataType, sqltypes.Text):
698
+ def get_dbapi_type(self, dbapi):
699
+ # previously, this was dbapi.CLOB.
700
+ # DB_TYPE_NVARCHAR will instead be passed to setinputsizes()
701
+ # when this datatype is used.
702
+ return dbapi.DB_TYPE_NVARCHAR
703
+
704
+
705
+ class _OracleLong(_LOBDataType, oracle.LONG):
706
+ def get_dbapi_type(self, dbapi):
707
+ return dbapi.LONG_STRING
708
+
709
+
710
+ class _OracleString(sqltypes.String):
711
+ pass
712
+
713
+
714
+ class _OracleEnum(sqltypes.Enum):
715
+ def bind_processor(self, dialect):
716
+ enum_proc = sqltypes.Enum.bind_processor(self, dialect)
717
+
718
+ def process(value):
719
+ raw_str = enum_proc(value)
720
+ return raw_str
721
+
722
+ return process
723
+
724
+
725
+ class _OracleBinary(_LOBDataType, sqltypes.LargeBinary):
726
+ def get_dbapi_type(self, dbapi):
727
+ # previously, this was dbapi.BLOB.
728
+ # DB_TYPE_RAW will instead be passed to setinputsizes()
729
+ # when this datatype is used.
730
+ return dbapi.DB_TYPE_RAW
731
+
732
+ def bind_processor(self, dialect):
733
+ return None
734
+
735
+ def result_processor(self, dialect, coltype):
736
+ if not dialect.auto_convert_lobs:
737
+ return None
738
+ else:
739
+ return super().result_processor(dialect, coltype)
740
+
741
+
742
+ class _OracleInterval(oracle.INTERVAL):
743
+ def get_dbapi_type(self, dbapi):
744
+ return dbapi.INTERVAL
745
+
746
+
747
+ class _OracleRaw(oracle.RAW):
748
+ pass
749
+
750
+
751
+ class _OracleRowid(oracle.ROWID):
752
+ def get_dbapi_type(self, dbapi):
753
+ return dbapi.ROWID
754
+
755
+
756
+ class OracleCompiler_cx_oracle(OracleCompiler):
757
+ _oracle_cx_sql_compiler = True
758
+
759
+ _oracle_returning = False
760
+
761
+ # Oracle bind names can't start with digits or underscores.
762
+ # currently we rely upon Oracle-specific quoting of bind names in most
763
+ # cases. however for expanding params, the escape chars are used.
764
+ # see #8708
765
+ bindname_escape_characters = util.immutabledict(
766
+ {
767
+ "%": "P",
768
+ "(": "A",
769
+ ")": "Z",
770
+ ":": "C",
771
+ ".": "C",
772
+ "[": "C",
773
+ "]": "C",
774
+ " ": "C",
775
+ "\\": "C",
776
+ "/": "C",
777
+ "?": "C",
778
+ }
779
+ )
780
+
781
+ def bindparam_string(self, name, **kw):
782
+ quote = getattr(name, "quote", None)
783
+ if (
784
+ quote is True
785
+ or quote is not False
786
+ and self.preparer._bindparam_requires_quotes(name)
787
+ # bind param quoting for Oracle doesn't work with post_compile
788
+ # params. For those, the default bindparam_string will escape
789
+ # special chars, and the appending of a number "_1" etc. will
790
+ # take care of reserved words
791
+ and not kw.get("post_compile", False)
792
+ ):
793
+ # interesting to note about expanding parameters - since the
794
+ # new parameters take the form <paramname>_<int>, at least if
795
+ # they are originally formed from reserved words, they no longer
796
+ # need quoting :). names that include illegal characters
797
+ # won't work however.
798
+ quoted_name = '"%s"' % name
799
+ kw["escaped_from"] = name
800
+ name = quoted_name
801
+ return OracleCompiler.bindparam_string(self, name, **kw)
802
+
803
+ # TODO: we could likely do away with quoting altogether for
804
+ # Oracle parameters and use the custom escaping here
805
+ escaped_from = kw.get("escaped_from", None)
806
+ if not escaped_from:
807
+ if self._bind_translate_re.search(name):
808
+ # not quite the translate use case as we want to
809
+ # also get a quick boolean if we even found
810
+ # unusual characters in the name
811
+ new_name = self._bind_translate_re.sub(
812
+ lambda m: self._bind_translate_chars[m.group(0)],
813
+ name,
814
+ )
815
+ if new_name[0].isdigit() or new_name[0] == "_":
816
+ new_name = "D" + new_name
817
+ kw["escaped_from"] = name
818
+ name = new_name
819
+ elif name[0].isdigit() or name[0] == "_":
820
+ new_name = "D" + name
821
+ kw["escaped_from"] = name
822
+ name = new_name
823
+
824
+ return OracleCompiler.bindparam_string(self, name, **kw)
825
+
826
+
827
+ class OracleExecutionContext_cx_oracle(OracleExecutionContext):
828
+ out_parameters = None
829
+
830
+ def _generate_out_parameter_vars(self):
831
+ # check for has_out_parameters or RETURNING, create cx_Oracle.var
832
+ # objects if so
833
+ if self.compiled.has_out_parameters or self.compiled._oracle_returning:
834
+ out_parameters = self.out_parameters
835
+ assert out_parameters is not None
836
+
837
+ len_params = len(self.parameters)
838
+
839
+ quoted_bind_names = self.compiled.escaped_bind_names
840
+ for bindparam in self.compiled.binds.values():
841
+ if bindparam.isoutparam:
842
+ name = self.compiled.bind_names[bindparam]
843
+ type_impl = bindparam.type.dialect_impl(self.dialect)
844
+
845
+ if hasattr(type_impl, "_cx_oracle_var"):
846
+ out_parameters[name] = type_impl._cx_oracle_var(
847
+ self.dialect, self.cursor, arraysize=len_params
848
+ )
849
+ else:
850
+ dbtype = type_impl.get_dbapi_type(self.dialect.dbapi)
851
+
852
+ cx_Oracle = self.dialect.dbapi
853
+
854
+ assert cx_Oracle is not None
855
+
856
+ if dbtype is None:
857
+ raise exc.InvalidRequestError(
858
+ "Cannot create out parameter for "
859
+ "parameter "
860
+ "%r - its type %r is not supported by"
861
+ " cx_oracle" % (bindparam.key, bindparam.type)
862
+ )
863
+
864
+ # note this is an OUT parameter. Using
865
+ # non-LOB datavalues with large unicode-holding
866
+ # values causes the failure (both cx_Oracle and
867
+ # oracledb):
868
+ # ORA-22835: Buffer too small for CLOB to CHAR or
869
+ # BLOB to RAW conversion (actual: 16507,
870
+ # maximum: 4000)
871
+ # [SQL: INSERT INTO long_text (x, y, z) VALUES
872
+ # (:x, :y, :z) RETURNING long_text.x, long_text.y,
873
+ # long_text.z INTO :ret_0, :ret_1, :ret_2]
874
+ # so even for DB_TYPE_NVARCHAR we convert to a LOB
875
+
876
+ if isinstance(type_impl, _LOBDataType):
877
+ if dbtype == cx_Oracle.DB_TYPE_NVARCHAR:
878
+ dbtype = cx_Oracle.NCLOB
879
+ elif dbtype == cx_Oracle.DB_TYPE_RAW:
880
+ dbtype = cx_Oracle.BLOB
881
+ # other LOB types go in directly
882
+
883
+ out_parameters[name] = self.cursor.var(
884
+ dbtype,
885
+ # this is fine also in oracledb_async since
886
+ # the driver will await the read coroutine
887
+ outconverter=lambda value: value.read(),
888
+ arraysize=len_params,
889
+ )
890
+ elif (
891
+ isinstance(type_impl, _OracleNumeric)
892
+ and type_impl.asdecimal
893
+ ):
894
+ out_parameters[name] = self.cursor.var(
895
+ decimal.Decimal,
896
+ arraysize=len_params,
897
+ )
898
+
899
+ else:
900
+ out_parameters[name] = self.cursor.var(
901
+ dbtype, arraysize=len_params
902
+ )
903
+
904
+ for param in self.parameters:
905
+ param[quoted_bind_names.get(name, name)] = (
906
+ out_parameters[name]
907
+ )
908
+
909
+ def _generate_cursor_outputtype_handler(self):
910
+ output_handlers = {}
911
+
912
+ for keyname, name, objects, type_ in self.compiled._result_columns:
913
+ handler = type_._cached_custom_processor(
914
+ self.dialect,
915
+ "cx_oracle_outputtypehandler",
916
+ self._get_cx_oracle_type_handler,
917
+ )
918
+
919
+ if handler:
920
+ denormalized_name = self.dialect.denormalize_name(keyname)
921
+ output_handlers[denormalized_name] = handler
922
+
923
+ if output_handlers:
924
+ default_handler = self._dbapi_connection.outputtypehandler
925
+
926
+ def output_type_handler(
927
+ cursor, name, default_type, size, precision, scale
928
+ ):
929
+ if name in output_handlers:
930
+ return output_handlers[name](
931
+ cursor, name, default_type, size, precision, scale
932
+ )
933
+ else:
934
+ return default_handler(
935
+ cursor, name, default_type, size, precision, scale
936
+ )
937
+
938
+ self.cursor.outputtypehandler = output_type_handler
939
+
940
+ def _get_cx_oracle_type_handler(self, impl):
941
+ if hasattr(impl, "_cx_oracle_outputtypehandler"):
942
+ return impl._cx_oracle_outputtypehandler(self.dialect)
943
+ else:
944
+ return None
945
+
946
+ def pre_exec(self):
947
+ super().pre_exec()
948
+ if not getattr(self.compiled, "_oracle_cx_sql_compiler", False):
949
+ return
950
+
951
+ self.out_parameters = {}
952
+
953
+ self._generate_out_parameter_vars()
954
+
955
+ self._generate_cursor_outputtype_handler()
956
+
957
+ def post_exec(self):
958
+ if (
959
+ self.compiled
960
+ and is_sql_compiler(self.compiled)
961
+ and self.compiled._oracle_returning
962
+ ):
963
+ initial_buffer = self.fetchall_for_returning(
964
+ self.cursor, _internal=True
965
+ )
966
+
967
+ fetch_strategy = _cursor.FullyBufferedCursorFetchStrategy(
968
+ self.cursor,
969
+ [
970
+ (entry.keyname, None)
971
+ for entry in self.compiled._result_columns
972
+ ],
973
+ initial_buffer=initial_buffer,
974
+ )
975
+
976
+ self.cursor_fetch_strategy = fetch_strategy
977
+
978
+ def create_cursor(self):
979
+ c = self._dbapi_connection.cursor()
980
+ if self.dialect.arraysize:
981
+ c.arraysize = self.dialect.arraysize
982
+
983
+ return c
984
+
985
+ def fetchall_for_returning(self, cursor, *, _internal=False):
986
+ compiled = self.compiled
987
+ if (
988
+ not _internal
989
+ and compiled is None
990
+ or not is_sql_compiler(compiled)
991
+ or not compiled._oracle_returning
992
+ ):
993
+ raise NotImplementedError(
994
+ "execution context was not prepared for Oracle RETURNING"
995
+ )
996
+
997
+ # create a fake cursor result from the out parameters. unlike
998
+ # get_out_parameter_values(), the result-row handlers here will be
999
+ # applied at the Result level
1000
+
1001
+ numcols = len(self.out_parameters)
1002
+
1003
+ # [stmt_result for stmt_result in outparam.values] == each
1004
+ # statement in executemany
1005
+ # [val for val in stmt_result] == each row for a particular
1006
+ # statement
1007
+ return list(
1008
+ zip(
1009
+ *[
1010
+ [
1011
+ val
1012
+ for stmt_result in self.out_parameters[
1013
+ f"ret_{j}"
1014
+ ].values
1015
+ for val in (stmt_result or ())
1016
+ ]
1017
+ for j in range(numcols)
1018
+ ]
1019
+ )
1020
+ )
1021
+
1022
+ def get_out_parameter_values(self, out_param_names):
1023
+ # this method should not be called when the compiler has
1024
+ # RETURNING as we've turned the has_out_parameters flag set to
1025
+ # False.
1026
+ assert not self.compiled.returning
1027
+
1028
+ return [
1029
+ self.dialect._paramval(self.out_parameters[name])
1030
+ for name in out_param_names
1031
+ ]
1032
+
1033
+
1034
+ class OracleDialect_cx_oracle(OracleDialect):
1035
+ supports_statement_cache = True
1036
+ execution_ctx_cls = OracleExecutionContext_cx_oracle
1037
+ statement_compiler = OracleCompiler_cx_oracle
1038
+
1039
+ supports_sane_rowcount = True
1040
+ supports_sane_multi_rowcount = True
1041
+
1042
+ insert_executemany_returning = True
1043
+ insert_executemany_returning_sort_by_parameter_order = True
1044
+ update_executemany_returning = True
1045
+ delete_executemany_returning = True
1046
+
1047
+ bind_typing = interfaces.BindTyping.SETINPUTSIZES
1048
+
1049
+ driver = "cx_oracle"
1050
+
1051
+ colspecs = util.update_copy(
1052
+ OracleDialect.colspecs,
1053
+ {
1054
+ sqltypes.TIMESTAMP: _CXOracleTIMESTAMP,
1055
+ sqltypes.Numeric: _OracleNumeric,
1056
+ sqltypes.Float: _OracleNumeric,
1057
+ oracle.BINARY_FLOAT: _OracleBINARY_FLOAT,
1058
+ oracle.BINARY_DOUBLE: _OracleBINARY_DOUBLE,
1059
+ sqltypes.Integer: _OracleInteger,
1060
+ oracle.NUMBER: _OracleNUMBER,
1061
+ sqltypes.Date: _CXOracleDate,
1062
+ sqltypes.LargeBinary: _OracleBinary,
1063
+ sqltypes.Boolean: oracle._OracleBoolean,
1064
+ sqltypes.Interval: _OracleInterval,
1065
+ oracle.INTERVAL: _OracleInterval,
1066
+ sqltypes.Text: _OracleText,
1067
+ sqltypes.String: _OracleString,
1068
+ sqltypes.UnicodeText: _OracleUnicodeTextCLOB,
1069
+ sqltypes.CHAR: _OracleChar,
1070
+ sqltypes.NCHAR: _OracleNChar,
1071
+ sqltypes.Enum: _OracleEnum,
1072
+ oracle.LONG: _OracleLong,
1073
+ oracle.RAW: _OracleRaw,
1074
+ sqltypes.Unicode: _OracleUnicodeStringCHAR,
1075
+ sqltypes.NVARCHAR: _OracleUnicodeStringNCHAR,
1076
+ sqltypes.Uuid: _OracleUUID,
1077
+ oracle.NCLOB: _OracleUnicodeTextNCLOB,
1078
+ oracle.ROWID: _OracleRowid,
1079
+ },
1080
+ )
1081
+
1082
+ execute_sequence_format = list
1083
+
1084
+ _cx_oracle_threaded = None
1085
+
1086
+ _cursor_var_unicode_kwargs = util.immutabledict()
1087
+
1088
+ @util.deprecated_params(
1089
+ threaded=(
1090
+ "1.3",
1091
+ "The 'threaded' parameter to the cx_oracle/oracledb dialect "
1092
+ "is deprecated as a dialect-level argument, and will be removed "
1093
+ "in a future release. As of version 1.3, it defaults to False "
1094
+ "rather than True. The 'threaded' option can be passed to "
1095
+ "cx_Oracle directly in the URL query string passed to "
1096
+ ":func:`_sa.create_engine`.",
1097
+ )
1098
+ )
1099
+ def __init__(
1100
+ self,
1101
+ auto_convert_lobs=True,
1102
+ coerce_to_decimal=True,
1103
+ arraysize=None,
1104
+ encoding_errors=None,
1105
+ threaded=None,
1106
+ **kwargs,
1107
+ ):
1108
+ OracleDialect.__init__(self, **kwargs)
1109
+ self.arraysize = arraysize
1110
+ self.encoding_errors = encoding_errors
1111
+ if encoding_errors:
1112
+ self._cursor_var_unicode_kwargs = {
1113
+ "encodingErrors": encoding_errors
1114
+ }
1115
+ if threaded is not None:
1116
+ self._cx_oracle_threaded = threaded
1117
+ self.auto_convert_lobs = auto_convert_lobs
1118
+ self.coerce_to_decimal = coerce_to_decimal
1119
+ if self._use_nchar_for_unicode:
1120
+ self.colspecs = self.colspecs.copy()
1121
+ self.colspecs[sqltypes.Unicode] = _OracleUnicodeStringNCHAR
1122
+ self.colspecs[sqltypes.UnicodeText] = _OracleUnicodeTextNCLOB
1123
+
1124
+ dbapi_module = self.dbapi
1125
+ self._load_version(dbapi_module)
1126
+
1127
+ if dbapi_module is not None:
1128
+ # these constants will first be seen in SQLAlchemy datatypes
1129
+ # coming from the get_dbapi_type() method. We then
1130
+ # will place the following types into setinputsizes() calls
1131
+ # on each statement. Oracle constants that are not in this
1132
+ # list will not be put into setinputsizes().
1133
+ self.include_set_input_sizes = {
1134
+ dbapi_module.DATETIME,
1135
+ dbapi_module.DB_TYPE_NVARCHAR, # used for CLOB, NCLOB
1136
+ dbapi_module.DB_TYPE_RAW, # used for BLOB
1137
+ dbapi_module.NCLOB, # not currently used except for OUT param
1138
+ dbapi_module.CLOB, # not currently used except for OUT param
1139
+ dbapi_module.LOB, # not currently used
1140
+ dbapi_module.BLOB, # not currently used except for OUT param
1141
+ dbapi_module.NCHAR,
1142
+ dbapi_module.FIXED_NCHAR,
1143
+ dbapi_module.FIXED_CHAR,
1144
+ dbapi_module.TIMESTAMP,
1145
+ int, # _OracleInteger,
1146
+ # _OracleBINARY_FLOAT, _OracleBINARY_DOUBLE,
1147
+ dbapi_module.NATIVE_FLOAT,
1148
+ }
1149
+
1150
+ self._paramval = lambda value: value.getvalue()
1151
+
1152
+ def _load_version(self, dbapi_module):
1153
+ version = (0, 0, 0)
1154
+ if dbapi_module is not None:
1155
+ m = re.match(r"(\d+)\.(\d+)(?:\.(\d+))?", dbapi_module.version)
1156
+ if m:
1157
+ version = tuple(
1158
+ int(x) for x in m.group(1, 2, 3) if x is not None
1159
+ )
1160
+ self.cx_oracle_ver = version
1161
+ if self.cx_oracle_ver < (8,) and self.cx_oracle_ver > (0, 0, 0):
1162
+ raise exc.InvalidRequestError(
1163
+ "cx_Oracle version 8 and above are supported"
1164
+ )
1165
+
1166
+ @classmethod
1167
+ def import_dbapi(cls):
1168
+ import cx_Oracle
1169
+
1170
+ return cx_Oracle
1171
+
1172
+ def initialize(self, connection):
1173
+ super().initialize(connection)
1174
+ self._detect_decimal_char(connection)
1175
+
1176
+ def get_isolation_level(self, dbapi_connection):
1177
+ # sources:
1178
+
1179
+ # general idea of transaction id, have to start one, etc.
1180
+ # https://stackoverflow.com/questions/10711204/how-to-check-isoloation-level
1181
+
1182
+ # how to decode xid cols from v$transaction to match
1183
+ # https://asktom.oracle.com/pls/apex/f?p=100:11:0::::P11_QUESTION_ID:9532779900346079444
1184
+
1185
+ # Oracle tuple comparison without using IN:
1186
+ # https://www.sql-workbench.eu/comparison/tuple_comparison.html
1187
+
1188
+ with dbapi_connection.cursor() as cursor:
1189
+ # this is the only way to ensure a transaction is started without
1190
+ # actually running DML. There's no way to see the configured
1191
+ # isolation level without getting it from v$transaction which
1192
+ # means transaction has to be started.
1193
+ outval = cursor.var(str)
1194
+ cursor.execute(
1195
+ """
1196
+ begin
1197
+ :trans_id := dbms_transaction.local_transaction_id( TRUE );
1198
+ end;
1199
+ """,
1200
+ {"trans_id": outval},
1201
+ )
1202
+ trans_id = outval.getvalue()
1203
+ xidusn, xidslot, xidsqn = trans_id.split(".", 2)
1204
+
1205
+ cursor.execute(
1206
+ "SELECT CASE BITAND(t.flag, POWER(2, 28)) "
1207
+ "WHEN 0 THEN 'READ COMMITTED' "
1208
+ "ELSE 'SERIALIZABLE' END AS isolation_level "
1209
+ "FROM v$transaction t WHERE "
1210
+ "(t.xidusn, t.xidslot, t.xidsqn) = "
1211
+ "((:xidusn, :xidslot, :xidsqn))",
1212
+ {"xidusn": xidusn, "xidslot": xidslot, "xidsqn": xidsqn},
1213
+ )
1214
+ row = cursor.fetchone()
1215
+ if row is None:
1216
+ raise exc.InvalidRequestError(
1217
+ "could not retrieve isolation level"
1218
+ )
1219
+ result = row[0]
1220
+
1221
+ return result
1222
+
1223
+ def get_isolation_level_values(self, dbapi_connection):
1224
+ return super().get_isolation_level_values(dbapi_connection) + [
1225
+ "AUTOCOMMIT"
1226
+ ]
1227
+
1228
+ def set_isolation_level(self, dbapi_connection, level):
1229
+ if level == "AUTOCOMMIT":
1230
+ dbapi_connection.autocommit = True
1231
+ else:
1232
+ dbapi_connection.autocommit = False
1233
+ dbapi_connection.rollback()
1234
+ with dbapi_connection.cursor() as cursor:
1235
+ cursor.execute(f"ALTER SESSION SET ISOLATION_LEVEL={level}")
1236
+
1237
+ def detect_autocommit_setting(self, dbapi_conn) -> bool:
1238
+ return bool(dbapi_conn.autocommit)
1239
+
1240
+ def _detect_decimal_char(self, connection):
1241
+ # we have the option to change this setting upon connect,
1242
+ # or just look at what it is upon connect and convert.
1243
+ # to minimize the chance of interference with changes to
1244
+ # NLS_TERRITORY or formatting behavior of the DB, we opt
1245
+ # to just look at it
1246
+
1247
+ dbapi_connection = connection.connection
1248
+
1249
+ with dbapi_connection.cursor() as cursor:
1250
+ # issue #8744
1251
+ # nls_session_parameters is not available in some Oracle
1252
+ # modes like "mount mode". But then, v$nls_parameters is not
1253
+ # available if the connection doesn't have SYSDBA priv.
1254
+ #
1255
+ # simplify the whole thing and just use the method that we were
1256
+ # doing in the test suite already, selecting a number
1257
+
1258
+ def output_type_handler(
1259
+ cursor, name, defaultType, size, precision, scale
1260
+ ):
1261
+ return cursor.var(
1262
+ self.dbapi.STRING, 255, arraysize=cursor.arraysize
1263
+ )
1264
+
1265
+ cursor.outputtypehandler = output_type_handler
1266
+ cursor.execute("SELECT 1.1 FROM DUAL")
1267
+ value = cursor.fetchone()[0]
1268
+
1269
+ decimal_char = value.lstrip("0")[1]
1270
+ assert not decimal_char[0].isdigit()
1271
+
1272
+ self._decimal_char = decimal_char
1273
+
1274
+ if self._decimal_char != ".":
1275
+ _detect_decimal = self._detect_decimal
1276
+ _to_decimal = self._to_decimal
1277
+
1278
+ self._detect_decimal = lambda value: _detect_decimal(
1279
+ value.replace(self._decimal_char, ".")
1280
+ )
1281
+ self._to_decimal = lambda value: _to_decimal(
1282
+ value.replace(self._decimal_char, ".")
1283
+ )
1284
+
1285
+ def _detect_decimal(self, value):
1286
+ if "." in value:
1287
+ return self._to_decimal(value)
1288
+ else:
1289
+ return int(value)
1290
+
1291
+ _to_decimal = decimal.Decimal
1292
+
1293
+ def _generate_connection_outputtype_handler(self):
1294
+ """establish the default outputtypehandler established at the
1295
+ connection level.
1296
+
1297
+ """
1298
+
1299
+ dialect = self
1300
+ cx_Oracle = dialect.dbapi
1301
+
1302
+ number_handler = _OracleNUMBER(
1303
+ asdecimal=True
1304
+ )._cx_oracle_outputtypehandler(dialect)
1305
+ float_handler = _OracleNUMBER(
1306
+ asdecimal=False
1307
+ )._cx_oracle_outputtypehandler(dialect)
1308
+
1309
+ def output_type_handler(
1310
+ cursor, name, default_type, size, precision, scale
1311
+ ):
1312
+ if (
1313
+ default_type == cx_Oracle.NUMBER
1314
+ and default_type is not cx_Oracle.NATIVE_FLOAT
1315
+ ):
1316
+ if not dialect.coerce_to_decimal:
1317
+ return None
1318
+ elif precision == 0 and scale in (0, -127):
1319
+ # ambiguous type, this occurs when selecting
1320
+ # numbers from deep subqueries
1321
+ return cursor.var(
1322
+ cx_Oracle.STRING,
1323
+ 255,
1324
+ outconverter=dialect._detect_decimal,
1325
+ arraysize=cursor.arraysize,
1326
+ )
1327
+ elif precision and scale > 0:
1328
+ return number_handler(
1329
+ cursor, name, default_type, size, precision, scale
1330
+ )
1331
+ else:
1332
+ return float_handler(
1333
+ cursor, name, default_type, size, precision, scale
1334
+ )
1335
+
1336
+ # if unicode options were specified, add a decoder, otherwise
1337
+ # cx_Oracle should return Unicode
1338
+ elif (
1339
+ dialect._cursor_var_unicode_kwargs
1340
+ and default_type
1341
+ in (
1342
+ cx_Oracle.STRING,
1343
+ cx_Oracle.FIXED_CHAR,
1344
+ )
1345
+ and default_type is not cx_Oracle.CLOB
1346
+ and default_type is not cx_Oracle.NCLOB
1347
+ ):
1348
+ return cursor.var(
1349
+ str,
1350
+ size,
1351
+ cursor.arraysize,
1352
+ **dialect._cursor_var_unicode_kwargs,
1353
+ )
1354
+
1355
+ elif dialect.auto_convert_lobs and default_type in (
1356
+ cx_Oracle.CLOB,
1357
+ cx_Oracle.NCLOB,
1358
+ ):
1359
+ typ = (
1360
+ cx_Oracle.DB_TYPE_VARCHAR
1361
+ if default_type is cx_Oracle.CLOB
1362
+ else cx_Oracle.DB_TYPE_NVARCHAR
1363
+ )
1364
+ return cursor.var(
1365
+ typ,
1366
+ _CX_ORACLE_MAGIC_LOB_SIZE,
1367
+ cursor.arraysize,
1368
+ **dialect._cursor_var_unicode_kwargs,
1369
+ )
1370
+
1371
+ elif dialect.auto_convert_lobs and default_type in (
1372
+ cx_Oracle.BLOB,
1373
+ ):
1374
+ return cursor.var(
1375
+ cx_Oracle.DB_TYPE_RAW,
1376
+ _CX_ORACLE_MAGIC_LOB_SIZE,
1377
+ cursor.arraysize,
1378
+ )
1379
+
1380
+ return output_type_handler
1381
+
1382
+ def on_connect(self):
1383
+ output_type_handler = self._generate_connection_outputtype_handler()
1384
+
1385
+ def on_connect(conn):
1386
+ conn.outputtypehandler = output_type_handler
1387
+
1388
+ return on_connect
1389
+
1390
+ def create_connect_args(self, url):
1391
+ opts = dict(url.query)
1392
+
1393
+ for opt in ("use_ansi", "auto_convert_lobs"):
1394
+ if opt in opts:
1395
+ util.warn_deprecated(
1396
+ f"{self.driver} dialect option {opt!r} should only be "
1397
+ "passed to create_engine directly, not within the URL "
1398
+ "string",
1399
+ version="1.3",
1400
+ )
1401
+ util.coerce_kw_type(opts, opt, bool)
1402
+ setattr(self, opt, opts.pop(opt))
1403
+
1404
+ database = url.database
1405
+ service_name = opts.pop("service_name", None)
1406
+ if database or service_name:
1407
+ # if we have a database, then we have a remote host
1408
+ port = url.port
1409
+ if port:
1410
+ port = int(port)
1411
+ else:
1412
+ port = 1521
1413
+
1414
+ if database and service_name:
1415
+ raise exc.InvalidRequestError(
1416
+ '"service_name" option shouldn\'t '
1417
+ 'be used with a "database" part of the url'
1418
+ )
1419
+ if database:
1420
+ makedsn_kwargs = {"sid": database}
1421
+ if service_name:
1422
+ makedsn_kwargs = {"service_name": service_name}
1423
+
1424
+ dsn = self.dbapi.makedsn(url.host, port, **makedsn_kwargs)
1425
+ else:
1426
+ # we have a local tnsname
1427
+ dsn = url.host
1428
+
1429
+ if dsn is not None:
1430
+ opts["dsn"] = dsn
1431
+ if url.password is not None:
1432
+ opts["password"] = url.password
1433
+ if url.username is not None:
1434
+ opts["user"] = url.username
1435
+
1436
+ if self._cx_oracle_threaded is not None:
1437
+ opts.setdefault("threaded", self._cx_oracle_threaded)
1438
+
1439
+ def convert_cx_oracle_constant(value):
1440
+ if isinstance(value, str):
1441
+ try:
1442
+ int_val = int(value)
1443
+ except ValueError:
1444
+ value = value.upper()
1445
+ return getattr(self.dbapi, value)
1446
+ else:
1447
+ return int_val
1448
+ else:
1449
+ return value
1450
+
1451
+ util.coerce_kw_type(opts, "mode", convert_cx_oracle_constant)
1452
+ util.coerce_kw_type(opts, "threaded", bool)
1453
+ util.coerce_kw_type(opts, "events", bool)
1454
+ util.coerce_kw_type(opts, "purity", convert_cx_oracle_constant)
1455
+ return ([], opts)
1456
+
1457
+ def _get_server_version_info(self, connection):
1458
+ return tuple(int(x) for x in connection.connection.version.split("."))
1459
+
1460
+ def is_disconnect(self, e, connection, cursor):
1461
+ (error,) = e.args
1462
+ if isinstance(
1463
+ e, (self.dbapi.InterfaceError, self.dbapi.DatabaseError)
1464
+ ) and "not connected" in str(e):
1465
+ return True
1466
+
1467
+ if hasattr(error, "code") and error.code in {
1468
+ 28,
1469
+ 3114,
1470
+ 3113,
1471
+ 3135,
1472
+ 1033,
1473
+ 2396,
1474
+ }:
1475
+ # ORA-00028: your session has been killed
1476
+ # ORA-03114: not connected to ORACLE
1477
+ # ORA-03113: end-of-file on communication channel
1478
+ # ORA-03135: connection lost contact
1479
+ # ORA-01033: ORACLE initialization or shutdown in progress
1480
+ # ORA-02396: exceeded maximum idle time, please connect again
1481
+ # TODO: Others ?
1482
+ return True
1483
+
1484
+ if re.match(r"^(?:DPI-1010|DPI-1080|DPY-1001|DPY-4011)", str(e)):
1485
+ # DPI-1010: not connected
1486
+ # DPI-1080: connection was closed by ORA-3113
1487
+ # python-oracledb's DPY-1001: not connected to database
1488
+ # python-oracledb's DPY-4011: the database or network closed the
1489
+ # connection
1490
+ # TODO: others?
1491
+ return True
1492
+
1493
+ return False
1494
+
1495
+ def create_xid(self):
1496
+ id_ = random.randint(0, 2**128)
1497
+ return (0x1234, "%032x" % id_, "%032x" % 9)
1498
+
1499
+ def do_executemany(self, cursor, statement, parameters, context=None):
1500
+ if isinstance(parameters, tuple):
1501
+ parameters = list(parameters)
1502
+ cursor.executemany(statement, parameters)
1503
+
1504
+ def do_begin_twophase(self, connection, xid):
1505
+ connection.connection.begin(*xid)
1506
+ connection.connection.info["cx_oracle_xid"] = xid
1507
+
1508
+ def do_prepare_twophase(self, connection, xid):
1509
+ result = connection.connection.prepare()
1510
+ connection.info["cx_oracle_prepared"] = result
1511
+
1512
+ def do_rollback_twophase(
1513
+ self, connection, xid, is_prepared=True, recover=False
1514
+ ):
1515
+ self.do_rollback(connection.connection)
1516
+ # TODO: need to end XA state here
1517
+
1518
+ def do_commit_twophase(
1519
+ self, connection, xid, is_prepared=True, recover=False
1520
+ ):
1521
+ if not is_prepared:
1522
+ self.do_commit(connection.connection)
1523
+ else:
1524
+ if recover:
1525
+ raise NotImplementedError(
1526
+ "2pc recovery not implemented for cx_Oracle"
1527
+ )
1528
+ oci_prepared = connection.info["cx_oracle_prepared"]
1529
+ if oci_prepared:
1530
+ self.do_commit(connection.connection)
1531
+ # TODO: need to end XA state here
1532
+
1533
+ def do_set_input_sizes(self, cursor, list_of_tuples, context):
1534
+ if self.positional:
1535
+ # not usually used, here to support if someone is modifying
1536
+ # the dialect to use positional style
1537
+ cursor.setinputsizes(
1538
+ *[dbtype for key, dbtype, sqltype in list_of_tuples]
1539
+ )
1540
+ else:
1541
+ collection = (
1542
+ (key, dbtype)
1543
+ for key, dbtype, sqltype in list_of_tuples
1544
+ if dbtype
1545
+ )
1546
+
1547
+ cursor.setinputsizes(**{key: dbtype for key, dbtype in collection})
1548
+
1549
+ def do_recover_twophase(self, connection):
1550
+ raise NotImplementedError(
1551
+ "recover two phase query for cx_Oracle not implemented"
1552
+ )
1553
+
1554
+
1555
+ dialect = OracleDialect_cx_oracle