0
# Constants and Enumerations
1
2
MySQL-specific constants for field types, flags, character sets, client capabilities, and configuration options that provide standardized access to MySQL protocol values.
3
4
## Field Type Constants
5
6
### FieldType
7
8
```python { .api }
9
class FieldType:
10
"""
11
MySQL field type constants for column type identification.
12
Used in cursor descriptions and type checking.
13
"""
14
15
# Numeric types
16
DECIMAL: int = 0 # DECIMAL or NUMERIC
17
TINY: int = 1 # TINYINT (-128 to 127 or 0 to 255)
18
SHORT: int = 2 # SMALLINT (-32768 to 32767 or 0 to 65535)
19
LONG: int = 3 # INTEGER (-2147483648 to 2147483647 or 0 to 4294967295)
20
FLOAT: int = 4 # FLOAT (single precision)
21
DOUBLE: int = 5 # DOUBLE (double precision)
22
LONGLONG: int = 8 # BIGINT (-9223372036854775808 to 9223372036854775807)
23
INT24: int = 9 # MEDIUMINT (-8388608 to 8388607 or 0 to 16777215)
24
NEWDECIMAL: int = 246 # Precision math DECIMAL or NUMERIC
25
BIT: int = 16 # BIT field type
26
27
# Date and time types
28
DATE: int = 10 # DATE (YYYY-MM-DD)
29
TIME: int = 11 # TIME (HH:MM:SS)
30
DATETIME: int = 12 # DATETIME (YYYY-MM-DD HH:MM:SS)
31
YEAR: int = 13 # YEAR (YYYY)
32
TIMESTAMP: int = 7 # TIMESTAMP (YYYY-MM-DD HH:MM:SS)
33
NEWDATE: int = 14 # Internal DATE type
34
35
# String and text types
36
VARCHAR: int = 15 # Variable-length string
37
STRING: int = 254 # Fixed-length string (CHAR)
38
VAR_STRING: int = 253 # Variable-length string
39
40
# Binary and blob types
41
TINY_BLOB: int = 249 # TINYBLOB (up to 255 bytes)
42
MEDIUM_BLOB: int = 250 # MEDIUMBLOB (up to 16MB)
43
LONG_BLOB: int = 251 # LONGBLOB (up to 4GB)
44
BLOB: int = 252 # BLOB (up to 64KB)
45
46
# Special types
47
SET: int = 248 # SET (multiple choice from predefined list)
48
ENUM: int = 247 # ENUM (single choice from predefined list)
49
GEOMETRY: int = 255 # Spatial data type
50
JSON: int = 245 # JSON data type (MySQL 5.7+)
51
NULL: int = 6 # NULL type
52
53
@classmethod
54
def get_string_types(cls) -> List[int]:
55
"""Get the list of all string types."""
56
pass
57
58
@classmethod
59
def get_binary_types(cls) -> List[int]:
60
"""Get the list of all binary types."""
61
pass
62
63
@classmethod
64
def get_number_types(cls) -> List[int]:
65
"""Get the list of all number types."""
66
pass
67
68
@classmethod
69
def get_timestamp_types(cls) -> List[int]:
70
"""Get the list of all timestamp types."""
71
pass
72
```
73
74
## Field Flag Constants
75
76
### FieldFlag
77
78
```python { .api }
79
class FieldFlag:
80
"""
81
MySQL field flag constants for column attributes.
82
Used to identify column properties and constraints.
83
"""
84
85
# Column constraints
86
NOT_NULL: int = 1 # Column cannot be NULL
87
PRI_KEY: int = 2 # Column is part of primary key
88
UNIQUE_KEY: int = 4 # Column is part of unique key
89
MULTIPLE_KEY: int = 8 # Column is part of non-unique key
90
91
# Data characteristics
92
BLOB: int = 16 # Column is a BLOB or TEXT
93
UNSIGNED: int = 32 # Numeric column is UNSIGNED
94
ZEROFILL: int = 64 # Numeric column uses ZEROFILL
95
BINARY: int = 128 # Column uses BINARY collation
96
97
# Special attributes
98
ENUM: int = 256 # Column is an ENUM
99
AUTO_INCREMENT: int = 512 # Column has AUTO_INCREMENT
100
TIMESTAMP: int = 1024 # Column is a TIMESTAMP
101
SET: int = 2048 # Column is a SET
102
NO_DEFAULT_VALUE: int = 4096 # Column has no default value
103
ON_UPDATE_NOW: int = 8192 # Column updates to CURRENT_TIMESTAMP
104
PART_KEY: int = 16384 # Column is part of some key
105
GROUP: int = 32768 # Column is part of GROUP BY
106
UNIQUE: int = 65536 # Column is unique
107
BINCMP: int = 131072 # Column uses binary comparison
108
```
109
110
## Client and Server Flags
111
112
### ClientFlag
113
114
```python { .api }
115
class ClientFlag:
116
"""
117
MySQL client capability flags for connection negotiation.
118
Indicates client capabilities to the MySQL server.
119
"""
120
121
LONG_PASSWD: int = 1 # Use improved version of old password hashing
122
FOUND_ROWS: int = 2 # Return found rows instead of affected rows
123
LONG_FLAG: int = 4 # Get all column flags
124
CONNECT_WITH_DB: int = 8 # Database name in connection packet
125
NO_SCHEMA: int = 16 # Don't allow database.table.column
126
COMPRESS: int = 32 # Use compression protocol
127
ODBC: int = 64 # ODBC client
128
LOCAL_FILES: int = 128 # Can use LOAD DATA LOCAL INFILE
129
IGNORE_SPACE: int = 256 # Ignore spaces before '('
130
PROTOCOL_41: int = 512 # New 4.1 protocol
131
INTERACTIVE: int = 1024 # Interactive client
132
SSL: int = 2048 # Use SSL encryption
133
IGNORE_SIGPIPE: int = 4096 # Ignore SIGPIPE
134
TRANSACTIONS: int = 8192 # Client knows about transactions
135
RESERVED: int = 16384 # Reserved for future use
136
SECURE_CONNECTION: int = 32768 # New 4.1 authentication
137
MULTI_STATEMENTS: int = 65536 # Enable multi-statement support
138
MULTI_RESULTS: int = 131072 # Enable multi-result support
139
PS_MULTI_RESULTS: int = 262144 # Multi-results in prepared statements
140
PLUGIN_AUTH: int = 524288 # Client supports plugin authentication
141
CONNECT_ATTRS: int = 1048576 # Client supports connection attributes
142
PLUGIN_AUTH_LENENC_CLIENT_DATA: int = 2097152 # Length encoded client data
143
CAN_HANDLE_EXPIRED_PASSWORDS: int = 4194304 # Handle expired passwords
144
SESSION_TRACK: int = 8388608 # Session tracking capability
145
DEPRECATE_EOF: int = 16777216 # Client expects OK packet instead of EOF
146
```
147
148
### ServerFlag
149
150
```python { .api }
151
class ServerFlag:
152
"""
153
MySQL server status flags indicating server state.
154
Returned in response packets to indicate server status.
155
"""
156
157
SERVER_STATUS_IN_TRANS: int = 1 # Transaction is active
158
SERVER_STATUS_AUTOCOMMIT: int = 2 # Autocommit is enabled
159
SERVER_MORE_RESULTS_EXISTS: int = 8 # More results exist (multi-statement)
160
SERVER_QUERY_NO_GOOD_INDEX_USED: int = 16 # No good index was used
161
SERVER_QUERY_NO_INDEX_USED: int = 32 # No index was used
162
SERVER_STATUS_CURSOR_EXISTS: int = 64 # Cursor exists (prepared statements)
163
SERVER_STATUS_LAST_ROW_SENT: int = 128 # Last row of result sent
164
SERVER_STATUS_DB_DROPPED: int = 256 # Database was dropped
165
SERVER_STATUS_NO_BACKSLASH_ESCAPES: int = 512 # NO_BACKSLASH_ESCAPES mode
166
SERVER_STATUS_METADATA_CHANGED: int = 1024 # Metadata changed
167
SERVER_QUERY_WAS_SLOW: int = 2048 # Query was slow
168
SERVER_PS_OUT_PARAMS: int = 4096 # Prepared statement has OUT parameters
169
SERVER_STATUS_IN_TRANS_READONLY: int = 8192 # In read-only transaction
170
SERVER_SESSION_STATE_CHANGED: int = 16384 # Session state changed
171
```
172
173
### ServerCmd
174
175
```python { .api }
176
class ServerCmd:
177
"""
178
MySQL server command constants for client-server protocol.
179
Used in low-level protocol communication.
180
"""
181
182
SLEEP: int = 0 # Internal server thread state
183
QUIT: int = 1 # Close connection
184
INIT_DB: int = 2 # Change default database
185
QUERY: int = 3 # Execute SQL statement
186
FIELD_LIST: int = 4 # Get column definitions
187
CREATE_DB: int = 5 # Create database
188
DROP_DB: int = 6 # Drop database
189
REFRESH: int = 7 # Refresh/flush tables and logs
190
SHUTDOWN: int = 8 # Shutdown server
191
STATISTICS: int = 9 # Get server statistics
192
PROCESS_INFO: int = 10 # Get process list
193
CONNECT: int = 11 # Internal server thread state
194
PROCESS_KILL: int = 12 # Kill server process
195
DEBUG: int = 13 # Get debug information
196
PING: int = 14 # Ping server
197
TIME: int = 15 # Internal server thread state
198
DELAYED_INSERT: int = 16 # Internal server thread state
199
CHANGE_USER: int = 17 # Change user authentication
200
BINLOG_DUMP: int = 18 # Binary log dump (replication)
201
TABLE_DUMP: int = 19 # Table dump
202
CONNECT_OUT: int = 20 # Internal server thread state
203
REGISTER_SLAVE: int = 21 # Register as replication slave
204
STMT_PREPARE: int = 22 # Prepare statement
205
STMT_EXECUTE: int = 23 # Execute prepared statement
206
STMT_SEND_LONG_DATA: int = 24 # Send long data for prepared statement
207
STMT_CLOSE: int = 25 # Close prepared statement
208
STMT_RESET: int = 26 # Reset prepared statement
209
SET_OPTION: int = 27 # Set connection option
210
STMT_FETCH: int = 28 # Fetch from prepared statement cursor
211
DAEMON: int = 29 # Internal server thread state
212
BINLOG_DUMP_GTID: int = 30 # Binary log dump with GTID
213
RESET_CONNECTION: int = 31 # Reset connection state
214
```
215
216
## Character Set and Collation
217
218
### CharacterSet
219
220
```python { .api }
221
class CharacterSet:
222
"""
223
MySQL character set utilities and constants.
224
Provides character set information and conversion utilities.
225
"""
226
227
# Common character sets
228
LATIN1_SWEDISH_CI: int = 8 # latin1_swedish_ci (default for latin1)
229
UTF8_GENERAL_CI: int = 33 # utf8_general_ci (default for utf8)
230
UTF8_UNICODE_CI: int = 192 # utf8_unicode_ci
231
UTF8MB4_GENERAL_CI: int = 45 # utf8mb4_general_ci (default for utf8mb4)
232
UTF8MB4_UNICODE_CI: int = 224 # utf8mb4_unicode_ci
233
UTF8MB4_0900_AI_CI: int = 255 # utf8mb4_0900_ai_ci (MySQL 8.0 default)
234
BINARY: int = 63 # binary
235
236
@classmethod
237
def get_info(cls, charset_id: int) -> Dict[str, Union[str, int]]:
238
"""
239
Get character set information by ID.
240
241
Args:
242
charset_id: MySQL character set ID
243
244
Returns:
245
Dictionary with charset info (name, collation, etc.)
246
"""
247
pass
248
249
@classmethod
250
def get_default_collation(cls, charset: str) -> Tuple[int, str]:
251
"""
252
Get default collation for character set.
253
254
Args:
255
charset: Character set name
256
257
Returns:
258
Tuple of (collation_id, collation_name)
259
"""
260
pass
261
262
@classmethod
263
def get_charset_info(cls, charset: str) -> Dict[str, Any]:
264
"""
265
Get comprehensive character set information.
266
267
Args:
268
charset: Character set name
269
270
Returns:
271
Dictionary with detailed charset information
272
"""
273
pass
274
```
275
276
### RefreshOption
277
278
```python { .api }
279
class RefreshOption:
280
"""
281
MySQL refresh option constants for FLUSH operations.
282
Used with CMD_REFRESH command and FLUSH statements.
283
"""
284
285
GRANT: int = 1 # Reload grant tables
286
LOG: int = 2 # Flush logs
287
TABLES: int = 4 # Close all open tables
288
HOSTS: int = 8 # Flush host cache
289
STATUS: int = 16 # Reset status variables
290
THREADS: int = 32 # Flush thread cache
291
SLAVE: int = 64 # Reset replica (slave) info
292
MASTER: int = 128 # Remove binary logs listed in index
293
ERROR_LOG: int = 256 # Flush error log
294
ENGINE_LOG: int = 512 # Flush engine logs
295
BINARY_LOG: int = 1024 # Flush binary log
296
RELAY_LOG: int = 2048 # Flush relay log
297
GENERAL_LOG: int = 4096 # Flush general log
298
SLOW_LOG: int = 8192 # Flush slow query log
299
```
300
301
## SSL/TLS Constants
302
303
### SSL Configuration
304
305
```python { .api }
306
# SSL mode constants
307
SSL_DISABLED: int = 0 # SSL connections disabled
308
SSL_PREFERRED: int = 1 # SSL preferred but not required
309
SSL_REQUIRED: int = 2 # SSL required
310
SSL_VERIFY_CA: int = 3 # SSL required with CA verification
311
SSL_VERIFY_IDENTITY: int = 4 # SSL required with full verification
312
313
# TLS version constants
314
TLS_VERSIONS: Dict[str, str] = {
315
'TLSv1': 'TLSv1',
316
'TLSv1.1': 'TLSv1.1',
317
'TLSv1.2': 'TLSv1.2',
318
'TLSv1.3': 'TLSv1.3'
319
}
320
```
321
322
### TLS Cipher Suites
323
324
```python { .api }
325
# TLS cipher suite definitions from mysql.connector.tls_ciphers
326
TLS_CIPHER_SUITES: Dict[str, List[str]] = {
327
'TLSv1.2': [
328
'ECDHE-RSA-AES128-GCM-SHA256',
329
'ECDHE-RSA-AES256-GCM-SHA384',
330
'ECDHE-ECDSA-AES128-GCM-SHA256',
331
'ECDHE-ECDSA-AES256-GCM-SHA384',
332
'DHE-RSA-AES128-GCM-SHA256',
333
'DHE-RSA-AES256-GCM-SHA384',
334
# ... additional cipher suites
335
],
336
'TLSv1.3': [
337
'TLS_AES_256_GCM_SHA384',
338
'TLS_CHACHA20_POLY1305_SHA256',
339
'TLS_AES_128_GCM_SHA256',
340
# ... additional TLS 1.3 cipher suites
341
]
342
}
343
```
344
345
## Default Configuration
346
347
```python { .api }
348
# Default connection configuration values
349
DEFAULT_CONFIGURATION: Dict[str, Any] = {
350
'host': 'localhost',
351
'port': 3306,
352
'user': '',
353
'password': '',
354
'database': '',
355
'charset': 'utf8mb4',
356
'collation': 'utf8mb4_general_ci',
357
'use_unicode': True,
358
'autocommit': False,
359
'time_zone': None,
360
'sql_mode': None,
361
'connect_timeout': 10,
362
'read_timeout': None,
363
'write_timeout': None,
364
'client_flags': 0,
365
'compress': False,
366
'buffered': False,
367
'raw': False,
368
'consume_results': False,
369
'ssl_disabled': False,
370
'ssl_verify_cert': False,
371
'ssl_verify_identity': False,
372
'force_ipv6': False,
373
'use_pure': None,
374
'auth_plugin': None,
375
'pool_name': None,
376
'pool_size': 5,
377
'pool_reset_session': True,
378
'pool_timeout': 0,
379
'allow_local_infile': True,
380
'allow_local_infile_in_path': None,
381
'get_warnings': False,
382
'raise_on_warnings': False,
383
'prepared': False,
384
'converter_class': None,
385
'converter_str_fallback': False,
386
'failover': [],
387
'option_files': None,
388
'option_groups': ['client', 'mysql_connector_python'],
389
}
390
```
391
392
## Usage Examples
393
394
### Field Type Checking
395
396
```python
397
import mysql.connector
398
from mysql.connector.constants import FieldType
399
400
connection = mysql.connector.connect(
401
host='localhost',
402
user='myuser',
403
password='mypassword',
404
database='mydatabase'
405
)
406
407
cursor = connection.cursor()
408
cursor.execute("DESCRIBE users")
409
410
# Check field types in table structure
411
for row in cursor:
412
field_name = row[0]
413
field_type = row[1]
414
415
# Parse field type (simplified example)
416
if 'int' in field_type.lower():
417
print(f"{field_name}: Integer type")
418
elif 'varchar' in field_type.lower():
419
print(f"{field_name}: Variable string type")
420
elif 'datetime' in field_type.lower():
421
print(f"{field_name}: Datetime type")
422
elif 'text' in field_type.lower():
423
print(f"{field_name}: Text type")
424
425
cursor.close()
426
connection.close()
427
```
428
429
### Field Flag Analysis
430
431
```python
432
import mysql.connector
433
from mysql.connector.constants import FieldFlag
434
435
connection = mysql.connector.connect(
436
host='localhost',
437
user='myuser',
438
password='mypassword',
439
database='mydatabase'
440
)
441
442
cursor = connection.cursor()
443
cursor.execute("SELECT * FROM users LIMIT 1")
444
445
# Analyze field flags from cursor description
446
for i, column_desc in enumerate(cursor.description):
447
name, type_code, display_size, internal_size, precision, scale, null_ok = column_desc
448
449
# Note: Field flags would be available in extended cursor descriptions
450
# This is a conceptual example
451
print(f"Column {name}:")
452
print(f" Type: {type_code}")
453
print(f" Nullable: {null_ok}")
454
print(f" Display size: {display_size}")
455
456
cursor.close()
457
connection.close()
458
```
459
460
### Client Capability Configuration
461
462
```python
463
import mysql.connector
464
from mysql.connector.constants import ClientFlag
465
466
# Configure specific client capabilities
467
client_flags = (
468
ClientFlag.FOUND_ROWS | # Return found rows, not affected rows
469
ClientFlag.LONG_FLAG | # Get all column flags
470
ClientFlag.CONNECT_WITH_DB | # Send database name in connection
471
ClientFlag.COMPRESS | # Use compression
472
ClientFlag.LOCAL_FILES | # Allow LOAD DATA LOCAL INFILE
473
ClientFlag.MULTI_STATEMENTS | # Enable multi-statement support
474
ClientFlag.MULTI_RESULTS | # Enable multi-result support
475
ClientFlag.SSL # Use SSL encryption
476
)
477
478
connection = mysql.connector.connect(
479
host='localhost',
480
user='myuser',
481
password='mypassword',
482
database='mydatabase',
483
client_flags=client_flags
484
)
485
486
# Connection now uses specified client capabilities
487
print(f"Connected with client flags: {client_flags}")
488
connection.close()
489
```
490
491
### Character Set Configuration
492
493
```python
494
import mysql.connector
495
from mysql.connector.constants import CharacterSet
496
497
# Get character set information
498
charset_info = CharacterSet.get_charset_info('utf8mb4')
499
print(f"Character set info: {charset_info}")
500
501
# Get default collation
502
collation_id, collation_name = CharacterSet.get_default_collation('utf8mb4')
503
print(f"Default collation: {collation_name} (ID: {collation_id})")
504
505
# Connect with specific character set
506
connection = mysql.connector.connect(
507
host='localhost',
508
user='myuser',
509
password='mypassword',
510
database='mydatabase',
511
charset='utf8mb4',
512
collation='utf8mb4_unicode_ci'
513
)
514
515
print(f"Connection charset: {connection.charset}")
516
print(f"Connection collation: {connection.collation}")
517
518
connection.close()
519
```
520
521
### Server Status Monitoring
522
523
```python
524
import mysql.connector
525
from mysql.connector.constants import ServerFlag
526
527
connection = mysql.connector.connect(
528
host='localhost',
529
user='myuser',
530
password='mypassword',
531
database='mydatabase'
532
)
533
534
cursor = connection.cursor()
535
536
# Execute query and check server status
537
cursor.execute("SELECT COUNT(*) FROM users")
538
result = cursor.fetchone()
539
540
# Note: Server status flags would be available in result metadata
541
# This is a conceptual example of how you might check transaction status
542
if connection.in_transaction:
543
print("Currently in a transaction")
544
else:
545
print("Not in a transaction")
546
547
if connection.autocommit:
548
print("Autocommit is enabled")
549
else:
550
print("Autocommit is disabled")
551
552
cursor.close()
553
connection.close()
554
```
555
556
### Using Refresh Options
557
558
```python
559
import mysql.connector
560
from mysql.connector.constants import RefreshOption
561
562
connection = mysql.connector.connect(
563
host='localhost',
564
user='myuser',
565
password='mypassword',
566
database='mydatabase'
567
)
568
569
# Flush various server caches (requires appropriate privileges)
570
refresh_options = RefreshOption.TABLES | RefreshOption.STATUS
571
572
try:
573
# Send refresh command (low-level protocol operation)
574
result = connection.cmd_refresh(refresh_options)
575
print("Server caches refreshed successfully")
576
except mysql.connector.Error as err:
577
print(f"Refresh failed: {err}")
578
579
connection.close()
580
```
581
582
### SSL/TLS Configuration with Constants
583
584
```python
585
import mysql.connector
586
587
# SSL configuration using constants
588
ssl_config = {
589
'ssl_disabled': False,
590
'ssl_verify_cert': True,
591
'ssl_verify_identity': True,
592
'ssl_cert': '/path/to/client-cert.pem',
593
'ssl_key': '/path/to/client-key.pem',
594
'ssl_ca': '/path/to/ca-cert.pem',
595
'tls_versions': ['TLSv1.2', 'TLSv1.3'],
596
'tls_ciphersuites': [
597
'TLS_AES_256_GCM_SHA384',
598
'TLS_CHACHA20_POLY1305_SHA256'
599
]
600
}
601
602
try:
603
connection = mysql.connector.connect(
604
host='mysql.example.com',
605
user='myuser',
606
password='mypassword',
607
database='mydatabase',
608
**ssl_config
609
)
610
611
print("Secure SSL/TLS connection established")
612
connection.close()
613
614
except mysql.connector.Error as err:
615
print(f"SSL connection failed: {err}")
616
```