0
# Document Operations (X DevAPI)
1
2
Modern document database operations using MySQL's X DevAPI, supporting JSON document storage, retrieval, and manipulation with a fluent API design.
3
4
## Capabilities
5
6
### Session Management
7
8
Create and manage X Protocol sessions for document and relational operations.
9
10
```python { .api }
11
def get_session(*args, **kwargs):
12
"""
13
Create an X Protocol session with load balancing support.
14
15
Parameters:
16
- *args: Connection string or configuration dict
17
- **kwargs: Connection parameters (host, port, user, password, schema)
18
19
Returns:
20
XSession: X Protocol session with multi-host support
21
22
Raises:
23
InterfaceError: Invalid connection parameters
24
"""
25
26
def get_node_session(*args, **kwargs):
27
"""
28
Create a single-node X Protocol session.
29
30
Parameters:
31
- *args: Connection string or configuration dict
32
- **kwargs: Connection parameters (host, port, user, password, schema)
33
34
Returns:
35
NodeSession: Single-node X Protocol session
36
37
Raises:
38
InterfaceError: Invalid connection parameters or multiple hosts specified
39
"""
40
41
class XSession:
42
"""
43
X Protocol session with load balancing and high availability support.
44
45
Provides document and relational data operations through MySQL X Protocol,
46
supporting automatic failover across multiple MySQL server instances.
47
"""
48
49
def get_schema(self, name):
50
"""
51
Get a schema object.
52
53
Parameters:
54
- name (str): Schema name
55
56
Returns:
57
Schema: Schema object for database operations
58
"""
59
60
def get_schemas(self):
61
"""
62
Get list of available schemas.
63
64
Returns:
65
list[Schema]: List of schema objects
66
"""
67
68
def create_schema(self, name):
69
"""
70
Create a new schema.
71
72
Parameters:
73
- name (str): Schema name to create
74
75
Returns:
76
Schema: Created schema object
77
"""
78
79
def drop_schema(self, name):
80
"""Drop a schema"""
81
82
def sql(self, statement):
83
"""
84
Execute raw SQL statement.
85
86
Parameters:
87
- statement (str): SQL statement to execute
88
89
Returns:
90
SqlStatement: SQL statement object for execution
91
"""
92
93
def close(self):
94
"""Close the session and free resources"""
95
96
class NodeSession(XSession):
97
"""Single-node X Protocol session without load balancing"""
98
```
99
100
**Usage Example:**
101
102
```python
103
import mysqlx
104
105
# Create session with connection string
106
session = mysqlx.get_session('mysqlx://user:password@localhost:33060/mydb')
107
108
# Create session with parameters
109
session = mysqlx.get_session({
110
'host': 'localhost',
111
'port': 33060,
112
'user': 'myuser',
113
'password': 'mypassword',
114
'schema': 'mydb'
115
})
116
117
# Get schema
118
schema = session.get_schema('mydb')
119
120
# Close session
121
session.close()
122
```
123
124
### Schema Operations
125
126
Database schema management and object access.
127
128
```python { .api }
129
class Schema:
130
"""
131
Database schema representation for X DevAPI operations.
132
133
Provides access to collections, tables, and views within a schema,
134
supporting both document and relational data operations.
135
"""
136
137
def get_collections(self):
138
"""
139
Get list of collections in schema.
140
141
Returns:
142
list[Collection]: List of collection objects
143
"""
144
145
def get_collection(self, name):
146
"""
147
Get a collection object.
148
149
Parameters:
150
- name (str): Collection name
151
152
Returns:
153
Collection: Collection object for document operations
154
"""
155
156
def create_collection(self, name, reuse_existing=False):
157
"""
158
Create a new collection.
159
160
Parameters:
161
- name (str): Collection name
162
- reuse_existing (bool): Return existing collection if exists
163
164
Returns:
165
Collection: Created or existing collection object
166
"""
167
168
def drop_collection(self, name):
169
"""Drop a collection"""
170
171
def get_tables(self):
172
"""
173
Get list of tables in schema.
174
175
Returns:
176
list[Table]: List of table objects
177
"""
178
179
def get_table(self, name):
180
"""
181
Get a table object.
182
183
Parameters:
184
- name (str): Table name
185
186
Returns:
187
Table: Table object for relational operations
188
"""
189
190
def get_view(self, name):
191
"""
192
Get a view object.
193
194
Parameters:
195
- name (str): View name
196
197
Returns:
198
View: View object for read operations
199
"""
200
201
@property
202
def name(self):
203
"""Schema name"""
204
205
def exists_in_database(self):
206
"""Check if schema exists in database"""
207
```
208
209
### Collection Operations
210
211
Document collection management and CRUD operations.
212
213
```python { .api }
214
class Collection:
215
"""
216
Document collection for storing and querying JSON documents.
217
218
Provides NoSQL-style operations for document storage, retrieval,
219
and manipulation using MySQL's document store capabilities.
220
"""
221
222
def add(self, *docs):
223
"""
224
Add documents to collection.
225
226
Parameters:
227
- *docs: Documents to add (dict, DbDoc, or JSON strings)
228
229
Returns:
230
AddStatement: Statement for execution
231
"""
232
233
def find(self, condition=None):
234
"""
235
Find documents in collection.
236
237
Parameters:
238
- condition (str): Search condition expression
239
240
Returns:
241
FindStatement: Statement for further refinement and execution
242
"""
243
244
def modify(self, condition):
245
"""
246
Modify documents in collection.
247
248
Parameters:
249
- condition (str): Condition for documents to modify
250
251
Returns:
252
ModifyStatement: Statement for specifying modifications
253
"""
254
255
def remove(self, condition):
256
"""
257
Remove documents from collection.
258
259
Parameters:
260
- condition (str): Condition for documents to remove
261
262
Returns:
263
RemoveStatement: Statement for execution
264
"""
265
266
def create_index(self, name, fields):
267
"""
268
Create an index on collection.
269
270
Parameters:
271
- name (str): Index name
272
- fields (dict): Index field specification
273
274
Returns:
275
CreateCollectionIndexStatement: Statement for execution
276
"""
277
278
def drop_index(self, name):
279
"""
280
Drop an index from collection.
281
282
Parameters:
283
- name (str): Index name to drop
284
285
Returns:
286
DropCollectionIndexStatement: Statement for execution
287
"""
288
289
def count(self):
290
"""
291
Count documents in collection.
292
293
Returns:
294
int: Number of documents
295
"""
296
297
def exists_in_database(self):
298
"""Check if collection exists in database"""
299
300
@property
301
def name(self):
302
"""Collection name"""
303
304
@property
305
def schema(self):
306
"""Parent schema object"""
307
```
308
309
**Usage Example:**
310
311
```python
312
# Get collection
313
collection = schema.get_collection('users')
314
315
# Add documents
316
collection.add({
317
'name': 'John Doe',
318
'email': 'john@example.com',
319
'age': 30,
320
'address': {
321
'city': 'New York',
322
'state': 'NY'
323
}
324
}).execute()
325
326
# Find documents
327
docs = collection.find('age > 25').execute()
328
for doc in docs:
329
print(f"Name: {doc['name']}, Age: {doc['age']}")
330
331
# Modify documents
332
collection.modify('age < 30').set('status', 'young').execute()
333
334
# Remove documents
335
collection.remove('age > 65').execute()
336
```
337
338
### Document Query Operations
339
340
Fluent API for building complex document queries.
341
342
```python { .api }
343
class FindStatement:
344
"""
345
Fluent interface for finding documents in collections.
346
347
Provides chainable methods for building complex queries with filtering,
348
sorting, limiting, and field projection.
349
"""
350
351
def fields(self, *fields):
352
"""
353
Select specific fields to return.
354
355
Parameters:
356
- *fields: Field names or expressions to select
357
358
Returns:
359
FindStatement: Self for method chaining
360
"""
361
362
def group_by(self, *fields):
363
"""
364
Group results by fields.
365
366
Parameters:
367
- *fields: Fields to group by
368
369
Returns:
370
FindStatement: Self for method chaining
371
"""
372
373
def having(self, condition):
374
"""
375
Filter grouped results.
376
377
Parameters:
378
- condition (str): HAVING condition expression
379
380
Returns:
381
FindStatement: Self for method chaining
382
"""
383
384
def sort(self, *sort_criteria):
385
"""
386
Sort results.
387
388
Parameters:
389
- *sort_criteria: Sort expressions ("field ASC", "field DESC")
390
391
Returns:
392
FindStatement: Self for method chaining
393
"""
394
395
def limit(self, count, offset=0):
396
"""
397
Limit number of results.
398
399
Parameters:
400
- count (int): Maximum number of documents
401
- offset (int): Number of documents to skip
402
403
Returns:
404
FindStatement: Self for method chaining
405
"""
406
407
def bind(self, *args, **kwargs):
408
"""
409
Bind values to placeholders.
410
411
Parameters:
412
- *args: Positional parameter values
413
- **kwargs: Named parameter values
414
415
Returns:
416
FindStatement: Self for method chaining
417
"""
418
419
def execute(self):
420
"""
421
Execute the find operation.
422
423
Returns:
424
DocResult: Result object with documents
425
"""
426
427
class AddStatement:
428
"""Statement for adding documents to collection"""
429
430
def execute(self):
431
"""
432
Execute the add operation.
433
434
Returns:
435
Result: Operation result with generated IDs
436
"""
437
438
class ModifyStatement:
439
"""Statement for modifying documents in collection"""
440
441
def set(self, field, value):
442
"""Set field to value"""
443
444
def unset(self, *fields):
445
"""Remove fields from documents"""
446
447
def array_insert(self, field, value):
448
"""Insert value into array field"""
449
450
def array_append(self, field, value):
451
"""Append value to array field"""
452
453
def array_delete(self, field):
454
"""Delete array element"""
455
456
def patch(self, patch_expr):
457
"""Apply JSON patch to documents"""
458
459
def sort(self, *sort_criteria):
460
"""Sort documents before modification"""
461
462
def limit(self, count):
463
"""Limit number of documents to modify"""
464
465
def bind(self, *args, **kwargs):
466
"""Bind parameter values"""
467
468
def execute(self):
469
"""Execute the modify operation"""
470
471
class RemoveStatement:
472
"""Statement for removing documents from collection"""
473
474
def sort(self, *sort_criteria):
475
"""Sort documents before removal"""
476
477
def limit(self, count):
478
"""Limit number of documents to remove"""
479
480
def bind(self, *args, **kwargs):
481
"""Bind parameter values"""
482
483
def execute(self):
484
"""Execute the remove operation"""
485
```
486
487
### Table Operations (Relational)
488
489
Relational table operations through X DevAPI.
490
491
```python { .api }
492
class Table:
493
"""
494
Relational table for SQL-like operations through X DevAPI.
495
496
Provides CRUD operations for relational data using the same
497
fluent interface as document collections.
498
"""
499
500
def select(self, *fields):
501
"""
502
Select data from table.
503
504
Parameters:
505
- *fields: Column names or expressions to select
506
507
Returns:
508
SelectStatement: Statement for building SELECT query
509
"""
510
511
def insert(self, *fields):
512
"""
513
Insert data into table.
514
515
Parameters:
516
- *fields: Column names for insertion
517
518
Returns:
519
InsertStatement: Statement for specifying values
520
"""
521
522
def update(self):
523
"""
524
Update data in table.
525
526
Returns:
527
UpdateStatement: Statement for specifying updates
528
"""
529
530
def delete(self):
531
"""
532
Delete data from table.
533
534
Returns:
535
DeleteStatement: Statement for specifying conditions
536
"""
537
538
def count(self):
539
"""Count rows in table"""
540
541
def exists_in_database(self):
542
"""Check if table exists in database"""
543
544
@property
545
def name(self):
546
"""Table name"""
547
548
class SelectStatement:
549
"""Statement for selecting data from tables"""
550
551
def where(self, condition):
552
"""Filter rows with WHERE condition"""
553
554
def group_by(self, *fields):
555
"""Group results by columns"""
556
557
def having(self, condition):
558
"""Filter grouped results"""
559
560
def order_by(self, *sort_criteria):
561
"""Sort results"""
562
563
def limit(self, count, offset=0):
564
"""Limit number of results"""
565
566
def bind(self, *args, **kwargs):
567
"""Bind parameter values"""
568
569
def execute(self):
570
"""Execute SELECT statement"""
571
572
class InsertStatement:
573
"""Statement for inserting data into tables"""
574
575
def values(self, *values):
576
"""Specify values to insert"""
577
578
def execute(self):
579
"""Execute INSERT statement"""
580
581
class UpdateStatement:
582
"""Statement for updating table data"""
583
584
def set(self, field, value):
585
"""Set column to value"""
586
587
def where(self, condition):
588
"""Filter rows to update"""
589
590
def order_by(self, *sort_criteria):
591
"""Sort rows before update"""
592
593
def limit(self, count):
594
"""Limit number of rows to update"""
595
596
def bind(self, *args, **kwargs):
597
"""Bind parameter values"""
598
599
def execute(self):
600
"""Execute UPDATE statement"""
601
602
class DeleteStatement:
603
"""Statement for deleting table data"""
604
605
def where(self, condition):
606
"""Filter rows to delete"""
607
608
def order_by(self, *sort_criteria):
609
"""Sort rows before deletion"""
610
611
def limit(self, count):
612
"""Limit number of rows to delete"""
613
614
def bind(self, *args, **kwargs):
615
"""Bind parameter values"""
616
617
def execute(self):
618
"""Execute DELETE statement"""
619
```
620
621
**Usage Example:**
622
623
```python
624
# Get table
625
table = schema.get_table('users')
626
627
# Select data
628
result = table.select('id', 'name', 'email').where('age > :age').bind(age=25).execute()
629
for row in result:
630
print(f"ID: {row[0]}, Name: {row[1]}, Email: {row[2]}")
631
632
# Insert data
633
table.insert('name', 'email', 'age').values('John Doe', 'john@example.com', 30).execute()
634
635
# Update data
636
table.update().set('status', 'active').where('age > 18').execute()
637
638
# Delete data
639
table.delete().where('age < 13').execute()
640
```
641
642
### Result Handling
643
644
Result objects returned from X DevAPI operations, providing access to data, metadata, and execution information.
645
646
```python { .api }
647
class Result:
648
"""
649
Base result object for X DevAPI operations.
650
651
Provides common functionality for accessing operation results including
652
affected rows, generated identifiers, and warning information.
653
"""
654
655
def get_affected_items_count(self) -> int:
656
"""Get number of items affected by operation"""
657
658
def get_autoincrement_value(self) -> int:
659
"""Get auto-generated ID from operation"""
660
661
def get_generated_ids(self) -> list:
662
"""Get list of generated document IDs"""
663
664
def get_warnings(self) -> list:
665
"""Get list of warnings from operation"""
666
667
def get_warnings_count(self) -> int:
668
"""Get count of warnings generated"""
669
670
class RowResult(Result):
671
"""
672
Result containing tabular row data from relational operations.
673
674
Provides access to rows, columns, and metadata from SELECT
675
operations on tables and views.
676
"""
677
678
def fetch_one(self) -> Row:
679
"""Fetch next row from result set"""
680
681
def fetch_all(self) -> list[Row]:
682
"""Fetch all remaining rows from result set"""
683
684
def get_columns(self) -> list[ColumnMetaData]:
685
"""Get column metadata for result set"""
686
687
def get_column_names(self) -> list[str]:
688
"""Get list of column names"""
689
690
def get_column_count(self) -> int:
691
"""Get number of columns in result set"""
692
693
def count(self) -> int:
694
"""Get total number of rows in result set"""
695
696
class SqlResult(RowResult):
697
"""
698
Result from SQL statement execution.
699
700
Extends RowResult with SQL-specific functionality and
701
provides access to multiple result sets from stored procedures.
702
"""
703
704
def next_result(self) -> bool:
705
"""Move to next result set if available"""
706
707
def has_data(self) -> bool:
708
"""Check if result contains data rows"""
709
710
class DocResult(Result):
711
"""
712
Result containing document data from collection operations.
713
714
Provides access to JSON documents returned from collection
715
find operations and document modifications.
716
"""
717
718
def fetch_one(self) -> DbDoc:
719
"""Fetch next document from result set"""
720
721
def fetch_all(self) -> list[DbDoc]:
722
"""Fetch all remaining documents from result set"""
723
724
def count(self) -> int:
725
"""Get total number of documents in result set"""
726
727
class Row:
728
"""
729
Row of tabular data from relational operations.
730
731
Provides access to column values by index or name,
732
with automatic type conversion from MySQL data types.
733
"""
734
735
def get_string(self, index: int) -> str:
736
"""Get column value as string"""
737
738
def get_int(self, index: int) -> int:
739
"""Get column value as integer"""
740
741
def get_float(self, index: int) -> float:
742
"""Get column value as float"""
743
744
def __getitem__(self, key):
745
"""Get column value by index or name"""
746
747
class ColumnMetaData:
748
"""
749
Metadata information for result set columns.
750
751
Provides column properties including name, type,
752
length, precision, and other attributes.
753
"""
754
755
def get_column_name(self) -> str:
756
"""Get column name"""
757
758
def get_column_label(self) -> str:
759
"""Get column label/alias"""
760
761
def get_type(self) -> ColumnType:
762
"""Get column data type"""
763
764
def get_length(self) -> int:
765
"""Get column length"""
766
767
def is_number_signed(self) -> bool:
768
"""Check if numeric column is signed"""
769
770
def get_fractional_digits(self) -> int:
771
"""Get number of fractional digits for decimal types"""
772
773
class ColumnType:
774
"""Column data type constants for result metadata"""
775
BIT: int
776
TINYINT: int
777
SMALLINT: int
778
MEDIUMINT: int
779
INT: int
780
BIGINT: int
781
FLOAT: int
782
DOUBLE: int
783
DECIMAL: int
784
DATE: int
785
TIME: int
786
DATETIME: int
787
TIMESTAMP: int
788
CHAR: int
789
VARCHAR: int
790
BINARY: int
791
VARBINARY: int
792
BLOB: int
793
TEXT: int
794
ENUM: int
795
SET: int
796
JSON: int
797
GEOMETRY: int
798
```
799
800
## Types
801
802
```python { .api }
803
SessionConfig = {
804
'host': str,
805
'port': int,
806
'user': str,
807
'password': str,
808
'schema': str,
809
'ssl_mode': str,
810
'ssl_ca': str,
811
'ssl_cert': str,
812
'ssl_key': str,
813
'connect_timeout': int,
814
'compression': str,
815
'auth': str
816
}
817
818
class DbDoc(dict):
819
"""
820
JSON document representation extending dict.
821
822
Provides dictionary interface with additional methods for
823
document manipulation and MySQL-specific functionality.
824
"""
825
826
def copy(self):
827
"""Create a copy of the document"""
828
829
def ensure_id(self):
830
"""Ensure document has _id field"""
831
```