hyb
2025-11-07 cadac0a99d87c53805a07f3b4ca7fd11e524fe4a
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
Ë
WñúhšEã ó —dZddlZddlZddlZddlZddlZddlmZddlm    Z    m
Z
m Z m Z m Z mZmZmZddlZddlZddlmZddlmZddlmZddlmZd    Zd
Zd d d dddœZd    Z dee!de!fd„Z"edede e#e$e%e%ffd„«Z&    d1dede%deddfd„Z'de%fd„Z(d2de
e%ge)fde*de%fd„Z+de    dee%e e    ffd„Z,dedejZfd „Z.ded!e%d"e%dejZfd#„Z/ded!e%d"e%de)fd$„Z0ded!e%d"e%ddfd%„Z1    d1ded!e%d"e%d&ejZd'e e%e%fddf d(„Z2ded!e%d&ejZdee%e%ffd)„Z3d*e%de%fd+„Z4dede%fd,„Z5ded!e%d"e%de)fd-„Z6    d3d.eeejZejnejpfd/e%deejZfd0„Z9y)4a.General utilities for AI features in MySQL Connector/Python.
 
Includes helpers for:
- defensive dict copying
- temporary table lifecycle management
- SQL execution and result conversions
- DataFrame to/from SQL table utilities
- schema/table/column name validation
- array-like to DataFrame conversion
éN)Úcontextmanager)ÚAnyÚCallableÚDictÚIteratorÚListÚOptionalÚTupleÚUnion)Úatomic_transaction)ÚMySQLConnectionAbstract)ÚMySQLCursorAbstract)ÚParamsSequenceOrDictTypeÚmysql_aié ÚBIGINTÚDOUBLEÚLONGTEXTÚBOOLEANÚDATETIME)Úint64Úfloat64ÚobjectÚboolzdatetime64[ns]ÚoptionsÚreturncó4—|€iStj|«S)z›
    Make a defensive copy of a dictionary, or return an empty dict if None.
 
    Args:
        options: param dict or None
 
    Returns:
        dict
    )ÚcopyÚdeepcopy)rs úGH:\Change_password\venv_build\Lib\site-packages\mysql/ai/utils/utils.pyÚ    copy_dictr!Is€ð€Øˆ    ä =‰=˜Ó !Ð!óÚ db_connectionc    #óK—g}    |–—t|«5}|D]\}}t|||«Œ    ddd«y#1swYyxYw#t|«5}|D]\}}t|||«Œ    ddd«w#1swYwxYwxYw­w)a
    Context manager to track and automatically clean up temporary SQL tables.
 
    Args:
        db_connection: Database connection object used to create and delete tables.
 
    Returns:
        None
 
    Raises:
        DatabaseError:
            If a database connection issue occurs.
            If an operational error occurs during execution.
 
    Yields:
        temporary_tables: List of (schema_name, table_name) tuples created during the
            context. All tables in this list are deleted on context exit.
    N)r Údelete_sql_table)r#Útemporary_tablesÚcursorÚ schema_nameÚ
table_names     r Útemporary_sql_tablesr*Ys£èø€ð,/1ÐðBØÒä   Ó .ð    B°&Ø+;ò BÑ' ˜ZÜ  ¨°jÕAñ B÷    B÷    Bñ    BûÔ   Ó .ð    B°&Ø+;ò BÑ' ˜ZÜ  ¨°jÕAñ B÷    B÷    Bñ    BÿsF‚B†AŠ B•7®    B·A¼BÁ A=ÁA1Á(    A=Á1A: Á6A=Á=Br'ÚqueryÚparamscó0—|j||xsd«y)aB
    Execute an SQL query with optional parameters using the given cursor.
 
    Args:
        cursor: MySQLCursorAbstract object to execute the query.
        query: SQL query string to execute.
        params: Optional sequence or dict providing parameters for the query.
 
    Raises:
        DatabaseError:
            If the provided SQL query/params are invalid
            If the query is valid but the sql raises as an exception
            If a database connection issue occurs.
            If an operational error occurs during execution.
 
    Returns:
        None
    ©N)Úexecute)r'r+r,s   r Ú execute_sqlr0xs€ð* ‡NN5˜&š, BÕ'r"cóv—tj}djtj|t
¬««S)z•
    Generate a random uppercase string of fixed length for table names.
 
    Returns:
        Random string of length RANDOM_TABLE_NAME_LENGTH.
    Ú)Úk)ÚstringÚascii_uppercaseÚjoinÚrandomÚchoicesÚRANDOM_TABLE_NAME_LENGTH)Úchar_sets r Ú    _get_namer;s*€ô×%Ñ%€HØ 7‰7”6—>‘> (Ô.FÔGÓ HÐHr"Ú    conditionÚ    max_callscód—t|«D]}|t«x}«sŒ|cStd«‚)a¨
    Generate a random string name that satisfies a given condition.
 
    Args:
        condition: Callable that takes a generated name and returns True if it is valid.
        max_calls: Maximum number of attempts before giving up (default 100).
 
    Returns:
        A random string that fulfills the provided condition.
 
    Raises:
        RuntimeError: If the maximum number of attempts is reached without success.
    z<Reached max tries without successfully finding a unique name)Úranger;Ú RuntimeError)r<r=Ú_Únames    r Úget_random_namerC›s:€ô9Ó òˆÙ œY›[Ð(TÕ )ØŠKðô ÐUÓ
VÐVr"ÚvaluecóŽ—t|ttf«r+t|«dk(rddgfSdt    j
|«gfSd|gfS)a.
    Convert a Python value into its SQL-compatible string representation and parameters.
 
    Args:
        value: The value to format.
 
    Returns:
        Tuple containing:
            - A string for substitution into a SQL query.
            - A list of parameters to be bound into the query.
    rz%sNzCAST(%s as JSON))Ú
isinstanceÚdictÚlistÚlenÚjsonÚdumps)rDs r Úformat_value_sqlrL³sL€ô%œ$¤˜Ô&Ü ˆu‹:˜Š?ؘ$˜<Ð Ø!¤D§J¡J¨uÓ$5Ð#6Ð6Ð6Ø %ˆ=Ðr"có°—dttdttfd„}dtdtfd„}i}t    |j
«D]\}}|ddk(r|||<Œ|||<Œ|j «}g}|D]?}t|«}    t    |«D]\}}
|||
«|    |<Œ|j|    «ŒAtj||j¬«S)a³
    Convert the results of a cursor's last executed query to a pandas DataFrame.
 
    Args:
        cursor: MySQLCursorAbstract with a completed query.
 
    Returns:
        DataFrame with data from the cursor.
 
    Raises:
        DatabaseError:
            If a database connection issue occurs.
            If an operational error occurs during execution.
            If a compatible SELECT query wasn't the last statement ran
    Úelemrcó4—|tj|«SdS©N)rJÚloads©rNs r Ú_json_processorz+sql_response_to_df.<locals>._json_processor×s€Ø#'Ð#3Œtz‰z˜$ÓÐ=¸Ð=r"có—|SrPr.rRs r Ú_default_processorz.sql_response_to_df.<locals>._default_processorÚs€Øˆ r"ééõ)Úcolumns) r    ÚstrrGrÚ    enumerateÚ descriptionÚfetchallrHÚappendÚpdÚ    DataFrameÚ column_names) r'rSrUÚidx_to_processorÚidxÚcolÚrowsÚprocessed_rowsÚrowÚ processed_rowrNs            r Úsql_response_to_dfrhÆsû€ð">œh¤s™mð>´¼±ó>ð¤ð¬óðÐܘf×0Ñ0Ó1ò7‰ˆˆSØ ˆq‰6SŠ=à$3Ð ˜SÒ !à$6Ð ˜SÒ !ð 7ð ?‰?Ó €Dð€NØò-ˆÜ˜S›    ˆ ä" 3›ò    =‰IˆCØ!6Ð!1°#Ñ!6°tÓ!<ˆM˜#Ò ð    =ð    ×јmÕ,ð -ô <‰<˜°×0CÑ0CÔ DÐDr"r(r)cóh—t|«t|«t|d|›d|›«t|«S)aD
    Load the entire contents of a SQL table into a pandas DataFrame.
 
    Args:
        cursor: MySQLCursorAbstract to execute the query.
        schema_name: Name of the schema containing the table.
        table_name: Name of the table to fetch.
 
    Returns:
        DataFrame containing all rows from the specified table.
 
    Raises:
        DatabaseError:
            If the table does not exist
            If a database connection issue occurs.
            If an operational error occurs during execution.
        ValueError: If the schema or table name is not valid
    zSELECT * FROM ú.)Ú validate_namer0rh©r'r(r)s   r Úsql_table_to_dfrmôs6€ô*+Ôܐ*Ô䐘.¨¨ °Q°z°lÐCÔDÜ ˜fÓ %Ð%r"cóz—t|«t|«|jd||f«|j«duS)aó
    Check whether a table exists in a specific schema.
 
    Args:
        cursor: MySQLCursorAbstract object to execute the query.
        schema_name: Name of the database schema.
        table_name: Name of the table.
 
    Returns:
        True if the table exists, False otherwise.
 
    Raises:
        DatabaseError:
            If a database connection issue occurs.
            If an operational error occurs during execution.
        ValueError: If the schema or table name is not valid
    z…
        SELECT 1
        FROM information_schema.tables
        WHERE table_schema = %s AND table_name = %s
        LIMIT 1
        N©rkr/Úfetchonerls   r Ú table_existsrqsC€ô(+Ôܐ*Ôà
‡NNð     ð
jÐ!ôð ?‰?Ó  DÐ (Ð(r"cóT—t|«t|«t|d|›d|›«y)aÌ
    Drop a table from the SQL database if it exists.
 
    Args:
        cursor: MySQLCursorAbstract to execute the drop command.
        schema_name: Name of the schema.
        table_name: Name of the table to delete.
 
    Returns:
        None
 
    Raises:
        DatabaseError:
            If a database connection issue occurs.
            If an operational error occurs during execution.
        ValueError: If the schema or table name is not valid
    zDROP TABLE IF EXISTS rjN)rkr0rls   r r%r%6s,€ô(+Ôܐ*ÔäÐ/° ¨}¸A¸j¸\ÐJÕKr"ÚdfÚcol_name_to_placeholder_stringc    ó‚—|€i}t|«t|«|jD]}tt|««Œ|›d|›}|jD]å}gg}    }t    ||j«D]i\}
}t |
d«r|
j «n|
}
||vr||t|
«g} } nt|
«\} } |j| «|    j| «Œkdj|jDcgc] }t|«‘Œc}«} dj|«}d|›d| ›d|›d}t|||    ¬    «Œçycc}w)
aõ
    Insert all rows from a pandas DataFrame into an existing SQL table.
 
    Args:
        cursor: MySQLCursorAbstract for execution.
        schema_name: Name of the database schema.
        table_name: Table to insert new rows into.
        df: DataFrame containing the rows to insert.
        col_name_to_placeholder_string:
            Optional mapping of column names to custom SQL value/placeholder
            strings.
 
    Returns:
        None
 
    Raises:
        DatabaseError:
            If the rows could not be inserted into the table, e.g., a type or shape issue
            If a database connection issue occurs.
            If an operational error occurs during execution.
        ValueError: If the schema or table name is not valid
    NrjÚitemú, z INSERT INTO ú (z
) VALUES (ú))r,) rkrXrYÚvaluesÚzipÚhasattrrvrLr]Úextendr6r0)r'r(r)rsrtrcÚqualified_table_namerfÚ placeholdersr,rNÚelem_placeholderÚ elem_paramsÚcols_sqlÚplaceholders_sqlÚ
insert_sqls                r Úextend_sql_tabler…Psa€ð:&Ð-Ø)+Ð&ä+Ôܐ*ÔØz‰zò ˆÜ”c˜#“hÕð ð*˜]¨!¨J¨<Ð8Ððy‰yò7ˆØ! 2fˆ ܘS "§*¡*Ó-ò     '‰IˆD#Ü")¨$°Ô"74—9‘9”;¸TˆDàÐ4Ñ4Ø0NÈsÑ0Sܘ“IðV +Ñ ô1AÀÓ0FÑ-Р +à × Ñ Р0Ô 1Ø M‰M˜+Õ &ð     'ð—9‘9°"·*±*Ö=¨3œc #hÒ=Ó>ˆØŸ9™9 \Ó2ÐàÐ/Ð0ð1؈z˜Ð$4Ð#5°Qð 8ð    ô    F˜J¨vÖ6ñ+7ùò>sÃ5D<
cóp‡‡—tˆˆfd„«}‰›d|›}t‰«t|«|jD]}tt|««Œg}|jj «D]N\}}t jt|«d«}tt|««|j|›d|›«ŒPdj|«}    td„|jD««}
|
r|    dz }    d|›d    |    ›d
} t‰| «    t‰‰||«||fS#t$rt‰‰|«‚wxYw) a
    Create a new SQL table with a random name, and populate it with data from a DataFrame.
 
    If an 'id' column is defined in the dataframe, it will be used as the primary key.
 
    Args:
        cursor: MySQLCursorAbstract for executing SQL.
        schema_name: Schema in which to create the table.
        df: DataFrame containing the data to be inserted.
 
    Returns:
        Tuple (qualified_table_name, table_name): The schema-qualified and
        unqualified table names.
 
    Raises:
        RuntimeError: If a random available table name could not be found.
        ValueError: If any schema, table, or a column name is invalid.
        DatabaseError:
            If a database connection issue occurs.
            If an operational error occurs during execution.
    có •—t‰‰|« SrP)rq)r)r'r(s €€r ú<lambda>z#sql_table_from_df.<locals>.<lambda>©sø€œ|¨F°KÀÓLÐL€r"rjrú rwc3óBK—|]}|j«dk(–—Œy­w)ÚidN)Úlower)Ú.0rcs  r ú    <genexpr>z$sql_table_from_df.<locals>.<genexpr>»sèø€Ò?¨SS—Y‘Y“[ DÕ(Ñ?ùs‚z, PRIMARY KEY (id)z CREATE TABLE rxry)rCrkrXrYÚdtypesÚitemsÚPD_TO_SQL_DTYPE_MAPPINGÚgetr]r6Úanyr0r…Ú    Exceptionr%) r'r(rsr)r~rcÚ columns_sqlÚdtypeÚsql_typeÚ columns_strÚ
has_id_colÚcreate_table_sqls ``          r Úsql_table_from_dfr›sJù€ô0!ÜLó€Jð*˜]¨!¨J¨<Ð8Ðä+Ôܐ*ÔØz‰zò ˆÜ”c˜#“hÕð ð€KØ—i‘i—o‘oÓ'ò0‰
ˆˆUä*×.Ñ.¬s°5«z¸:ÓFˆÜ”c˜#“hÔØ×јc˜U ! H :Ð.Õ/ð    0ð —)‘)˜KÓ(€KäÑ?°B·J±JÔ?Ó?€JÙØÐ+Ñ+ˆ ð'Ð';Ð&<¸B¸{¸mÈ1ÐMÐܐÐ(Ô)ð䘠¨j¸"Ô=ð
  Ð +Ð+øô     ò䘠¨jÔ9Ø ðús Ä DÄD5rBcón—t|t«rtjd|«st    d|›«‚|S)a
    Validate that the string is a legal SQL identifier (letters, digits, underscores).
 
    Args:
        name: Name (schema, table, or column) to validate.
 
    Returns:
        The validated name.
 
    Raises:
        ValueError: If the name does not meet format requirements.
    z^[A-Za-z0-9_]+$zUnsupported name format )rFrYÚreÚmatchÚ
ValueError)rBs r rkrkÍs4€ô tœSÔ !¤b§h¡hÐ/AÀ4Ô&HÜÐ3°D°6Ð:Ó;Ð;à €Kr"có¦—|j}|€+t}t|«5}d|›}t||«ddd«t    |«|S#1swYŒxYw)aµ
    Retrieve the name of the currently selected schema, or set and ensure the default schema.
 
    Args:
        db_connection: MySQL connector database connection object.
 
    Returns:
        Name of the schema (database in use).
 
    Raises:
        ValueError: If the schema name is not valid
        DatabaseError:
            If a database connection issue occurs.
            If an operational error occurs during execution.
    NzCREATE DATABASE IF NOT EXISTS )ÚdatabaseÚDEFAULT_SCHEMAr r0rk)r#Úschemar'Úcreate_database_stmts    r Ú source_schemar¥ás_€ð × #Ñ #€FØ €~Üˆä   Ó .ð    6°&Ø%CÀFÀ8Ð#LÐ  Ü ˜Р4Ô 5÷    6ô&Ôà €M÷     6ð    6ús  AÁAcó‚—t|«t|«|jd|›d|›d«|j«duS)a+
    Determine if a given SQL table is empty.
 
    Args:
        cursor: MySQLCursorAbstract with access to the database.
        schema_name: Name of the schema containing the table.
        table_name: Name of the table to check.
 
    Returns:
        True if the table has no rows, False otherwise.
 
    Raises:
        DatabaseError:
            If the table does not exist
            If a database connection issue occurs.
            If an operational error occurs during execution.
        ValueError: If the schema or table name is not valid
    zSELECT 1 FROM rjz LIMIT 1Nrorls   r Úis_table_emptyr§þsA€ô*+Ôܐ*Ôà
‡NN^ K =°°*°¸XÐFÔGØ ?‰?Ó  Ð $Ð$r"ÚarrÚ
col_prefixcóŠ—|€yt|tj«rtj|«St|tj«r|j    «S|j
dk(r|j dd«}t|jd«Dcgc]    }|›d|›‘Œ }}tj||d¬«Scc}w)a$
    Convert input data to a pandas DataFrame if necessary.
 
    Args:
        arr: Input data as a pandas DataFrame, NumPy ndarray, pandas Series, or None.
 
    Returns:
        If the input is None, returns None.
        Otherwise, returns a DataFrame backed by the same underlying data whenever
        possible (except in cases where pandas or NumPy must copy, such as for
        certain views or non-contiguous arrays).
 
    Notes:
        - If an ndarray is passed, column names will be integer indices (0, 1, ...).
        - If a DataFrame is passed, column names and indices are preserved.
        - The returned DataFrame is a shallow copy and shares data with the original
          input when possible; however, copies may still occur for certain input
          types or memory layouts.
    NrVéÿÿÿÿrAF)rXr)    rFr^r_ÚSeriesÚto_frameÚndimÚreshaper?Úshape)r¨r©rbÚ    col_namess    r Ú convert_to_dfr²s¢€ð. €{Øä#”r—|‘|Ô$܏|‰|˜CӠРܐ#”r—y‘yÔ!؏|‰|‹~Ðà
‡xx1‚}؏k‰k˜"˜aÓ ˆÜ27¸¿    ¹    À!¹ Ó2EÖF¨3J<˜q  Ò&ÐF€IÐFä <‰<˜ Y°UÔ ;Ð;ùòGsÂCrP)éd)Úfeature):Ú__doc__rrJr7rr4Ú
contextlibrÚtypingrrrrrr    r
r ÚnumpyÚnpÚpandasr^Úmysql.ai.utils.atomic_cursorr Úmysql.connector.abstractsr Úmysql.connector.cursorrÚmysql.connector.typesrÚVAR_NAME_SPACEr9r‘r¢rGr!rHÚtuplerYr*r0r;rÚintrCrLr_rhrmrqr%r…r›rkr¥r§r¬Úndarrayr²r.r"r ú<module>rÃsäðñ8    ó Û Û Û    Û å%ßN×NÓNãÛå;å=Ý6Ý:à€ØÐðØØØ Ø ñ Ðð€ð
"x ‘~ð "¨$ó "ð ðBØ*ðBà ˆd5˜˜c˜‘?Ñ#Ñ$òBóðBð>QUñ(Ø ð(Ø(+ð(Ø5Mð(à    ó(ð0I3óIñW˜x¨¨¨t¨ Ñ4ðWÀðWÈsóWð0˜Cð E¨#¨t°C©y¨.Ñ$9óð&+EÐ2ð+E°r·|±|ó+Eð\&Ø ð&Ø.1ð&Ø?Bð&à‡\\ó&ð> )Ø ð )Ø.1ð )Ø?Bð )à    ó )ðFLØ ðLØ.1ðLØ?BðLà    óLð>6:ñ =7Ø ð=7àð=7ðð=7ð      ‰ ð    =7ð
%)¨¨c¨¡Nð =7ð 
ó =7ð@:,Ø ð:,Ø.1ð:,Ø79·|±|ð:,à
ˆ3ˆ8_ó:,ðz˜ð óð(Ð!8ð¸Sóð:%Ø ð%Ø.1ð%Ø?Bð%à    ó%ð< ñ#<Ø    %˜Ÿ ™  b§i¡i°·±Ð;Ñ<Ñ    =ð#<àð#<ðˆbl‰lÑô#<r"