mysqlx-connector-python 8.3.0__py2.py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
mysqlx/crud.py ADDED
@@ -0,0 +1,776 @@
1
+ # Copyright (c) 2016, 2023, Oracle and/or its affiliates.
2
+ #
3
+ # This program is free software; you can redistribute it and/or modify
4
+ # it under the terms of the GNU General Public License, version 2.0, as
5
+ # published by the Free Software Foundation.
6
+ #
7
+ # This program is also distributed with certain software (including
8
+ # but not limited to OpenSSL) that is licensed under separate terms,
9
+ # as designated in a particular file or component or in included license
10
+ # documentation. The authors of MySQL hereby grant you an
11
+ # additional permission to link the program and your derivative works
12
+ # with the separately licensed software that they have included with
13
+ # MySQL.
14
+ #
15
+ # Without limiting anything contained in the foregoing, this file,
16
+ # which is part of MySQL Connector/Python, is also subject to the
17
+ # Universal FOSS Exception, version 1.0, a copy of which can be found at
18
+ # http://oss.oracle.com/licenses/universal-foss-exception.
19
+ #
20
+ # This program is distributed in the hope that it will be useful, but
21
+ # WITHOUT ANY WARRANTY; without even the implied warranty of
22
+ # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
23
+ # See the GNU General Public License, version 2.0, for more details.
24
+ #
25
+ # You should have received a copy of the GNU General Public License
26
+ # along with this program; if not, write to the Free Software Foundation, Inc.,
27
+ # 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
28
+
29
+ """Implementation of the CRUD database objects."""
30
+
31
+ from __future__ import annotations
32
+
33
+ import json
34
+ import warnings
35
+
36
+ from typing import TYPE_CHECKING, Any, Dict, List, Optional, Union
37
+
38
+ from .dbdoc import DbDoc
39
+ from .errorcode import (
40
+ ER_NO_SUCH_TABLE,
41
+ ER_TABLE_EXISTS_ERROR,
42
+ ER_X_CMD_NUM_ARGUMENTS,
43
+ ER_X_INVALID_ADMIN_COMMAND,
44
+ )
45
+ from .errors import NotSupportedError, OperationalError, ProgrammingError
46
+ from .helpers import deprecated, escape, quote_identifier
47
+ from .statement import (
48
+ AddStatement,
49
+ CreateCollectionIndexStatement,
50
+ DeleteStatement,
51
+ FindStatement,
52
+ InsertStatement,
53
+ ModifyStatement,
54
+ RemoveStatement,
55
+ SelectStatement,
56
+ UpdateStatement,
57
+ )
58
+ from .types import ConnectionType, SchemaType, SessionType, StrOrBytes
59
+
60
+ if TYPE_CHECKING:
61
+ from .result import Result
62
+
63
+ _COUNT_VIEWS_QUERY = (
64
+ "SELECT COUNT(*) FROM information_schema.views "
65
+ "WHERE table_schema = '{0}' AND table_name = '{1}'"
66
+ )
67
+ _COUNT_TABLES_QUERY = (
68
+ "SELECT COUNT(*) FROM information_schema.tables "
69
+ "WHERE table_schema = '{0}' AND table_name = '{1}'"
70
+ )
71
+ _COUNT_SCHEMAS_QUERY = (
72
+ "SELECT COUNT(*) FROM information_schema.schemata WHERE schema_name = '{0}'"
73
+ )
74
+ _COUNT_QUERY = "SELECT COUNT(*) FROM {0}.{1}"
75
+ _DROP_TABLE_QUERY = "DROP TABLE IF EXISTS {0}.{1}"
76
+
77
+
78
+ class DatabaseObject:
79
+ """Provides base functionality for database objects.
80
+
81
+ Args:
82
+ schema (mysqlx.Schema): The Schema object.
83
+ name (str): The database object name.
84
+ """
85
+
86
+ def __init__(self, schema: SchemaType, name: StrOrBytes) -> None:
87
+ self._schema: SchemaType = schema
88
+ self._name: str = name.decode() if isinstance(name, bytes) else name
89
+ self._session: SessionType = self._schema.get_session()
90
+ self._connection: ConnectionType = self._session.get_connection()
91
+
92
+ @property
93
+ def session(self) -> SessionType:
94
+ """:class:`mysqlx.Session`: The Session object."""
95
+ return self._session
96
+
97
+ @property
98
+ def schema(self) -> SchemaType:
99
+ """:class:`mysqlx.Schema`: The Schema object."""
100
+ return self._schema
101
+
102
+ @property
103
+ def name(self) -> str:
104
+ """str: The name of this database object."""
105
+ return self._name
106
+
107
+ def get_connection(self) -> ConnectionType:
108
+ """Returns the underlying connection.
109
+
110
+ Returns:
111
+ mysqlx.connection.Connection: The connection object.
112
+ """
113
+ return self._connection
114
+
115
+ def get_session(self) -> SessionType:
116
+ """Returns the session of this database object.
117
+
118
+ Returns:
119
+ mysqlx.Session: The Session object.
120
+ """
121
+ return self._session
122
+
123
+ def get_schema(self) -> SchemaType:
124
+ """Returns the Schema object of this database object.
125
+
126
+ Returns:
127
+ mysqlx.Schema: The Schema object.
128
+ """
129
+ return self._schema
130
+
131
+ def get_name(self) -> str:
132
+ """Returns the name of this database object.
133
+
134
+ Returns:
135
+ str: The name of this database object.
136
+ """
137
+ return self._name
138
+
139
+ def exists_in_database(self) -> Any:
140
+ """Verifies if this object exists in the database.
141
+
142
+ Returns:
143
+ bool: `True` if object exists in database.
144
+
145
+ Raises:
146
+ NotImplementedError: This method must be implemented.
147
+ """
148
+ raise NotImplementedError
149
+
150
+ @deprecated("8.0.12", "Use 'exists_in_database()' method instead")
151
+ def am_i_real(self) -> Any:
152
+ """Verifies if this object exists in the database.
153
+
154
+ Returns:
155
+ bool: `True` if object exists in database.
156
+
157
+ Raises:
158
+ NotImplementedError: This method must be implemented.
159
+
160
+ .. deprecated:: 8.0.12
161
+ Use ``exists_in_database()`` method instead.
162
+ """
163
+ return self.exists_in_database()
164
+
165
+ @deprecated("8.0.12", "Use 'get_name()' method instead")
166
+ def who_am_i(self) -> str:
167
+ """Returns the name of this database object.
168
+
169
+ Returns:
170
+ str: The name of this database object.
171
+
172
+ .. deprecated:: 8.0.12
173
+ Use ``get_name()`` method instead.
174
+ """
175
+ return self.get_name()
176
+
177
+
178
+ class Schema(DatabaseObject):
179
+ """A client-side representation of a database schema. Provides access to
180
+ the schema contents.
181
+
182
+ Args:
183
+ session (mysqlx.XSession): Session object.
184
+ name (str): The Schema name.
185
+ """
186
+
187
+ def __init__(self, session: SessionType, name: str) -> None:
188
+ self._session: SessionType = session
189
+ super().__init__(self, name)
190
+
191
+ def exists_in_database(self) -> bool:
192
+ """Verifies if this object exists in the database.
193
+
194
+ Returns:
195
+ bool: `True` if object exists in database.
196
+ """
197
+ sql = _COUNT_SCHEMAS_QUERY.format(escape(self._name))
198
+ return self._connection.execute_sql_scalar(sql) == 1
199
+
200
+ def get_collections(self) -> List[Collection]:
201
+ """Returns a list of collections for this schema.
202
+
203
+ Returns:
204
+ `list`: List of Collection objects.
205
+ """
206
+ rows = self._connection.get_row_result("list_objects", {"schema": self._name})
207
+ rows.fetch_all()
208
+ collections = []
209
+ for row in rows:
210
+ if row["type"] != "COLLECTION":
211
+ continue
212
+ try:
213
+ collection = Collection(self, row["TABLE_NAME"])
214
+ except ValueError:
215
+ collection = Collection(self, row["name"])
216
+ collections.append(collection)
217
+ return collections
218
+
219
+ def get_collection_as_table(
220
+ self, name: str, check_existence: bool = False
221
+ ) -> Table:
222
+ """Returns a a table object for the given collection
223
+
224
+ Returns:
225
+ mysqlx.Table: Table object.
226
+
227
+ """
228
+ return self.get_table(name, check_existence)
229
+
230
+ def get_tables(self) -> List[Table]:
231
+ """Returns a list of tables for this schema.
232
+
233
+ Returns:
234
+ `list`: List of Table objects.
235
+ """
236
+ rows = self._connection.get_row_result("list_objects", {"schema": self._name})
237
+ rows.fetch_all()
238
+ tables = []
239
+ object_types = (
240
+ "TABLE",
241
+ "VIEW",
242
+ )
243
+ for row in rows:
244
+ if row["type"] in object_types:
245
+ try:
246
+ table = Table(self, row["TABLE_NAME"])
247
+ except ValueError:
248
+ table = Table(self, row["name"])
249
+ tables.append(table)
250
+ return tables
251
+
252
+ def get_table(self, name: str, check_existence: bool = False) -> Table:
253
+ """Returns the table of the given name for this schema.
254
+
255
+ Returns:
256
+ mysqlx.Table: Table object.
257
+ """
258
+ table = Table(self, name)
259
+ if check_existence:
260
+ if not table.exists_in_database():
261
+ raise ProgrammingError("Table does not exist")
262
+ return table
263
+
264
+ def get_view(self, name: str, check_existence: bool = False) -> View:
265
+ """Returns the view of the given name for this schema.
266
+
267
+ Returns:
268
+ mysqlx.View: View object.
269
+ """
270
+ view = View(self, name)
271
+ if check_existence:
272
+ if not view.exists_in_database():
273
+ raise ProgrammingError("View does not exist")
274
+ return view
275
+
276
+ def get_collection(self, name: str, check_existence: bool = False) -> Collection:
277
+ """Returns the collection of the given name for this schema.
278
+
279
+ Returns:
280
+ mysqlx.Collection: Collection object.
281
+ """
282
+ collection = Collection(self, name)
283
+ if check_existence:
284
+ if not collection.exists_in_database():
285
+ raise ProgrammingError("Collection does not exist")
286
+ return collection
287
+
288
+ def drop_collection(self, name: str) -> None:
289
+ """Drops a collection.
290
+
291
+ Args:
292
+ name (str): The name of the collection to be dropped.
293
+ """
294
+ self._connection.execute_nonquery(
295
+ "sql",
296
+ _DROP_TABLE_QUERY.format(
297
+ quote_identifier(self._name), quote_identifier(name)
298
+ ),
299
+ False,
300
+ )
301
+
302
+ def create_collection(
303
+ self,
304
+ name: str,
305
+ reuse_existing: bool = False,
306
+ validation: Optional[Dict[str, Union[str, Dict]]] = None,
307
+ **kwargs: Any,
308
+ ) -> Collection:
309
+ """Creates in the current schema a new collection with the specified
310
+ name and retrieves an object representing the new collection created.
311
+
312
+ Args:
313
+ name (str): The name of the collection.
314
+ reuse_existing (bool): `True` to reuse an existing collection.
315
+ validation (Optional[dict]): A dict, containing the keys `level`
316
+ with the validation level and `schema`
317
+ with a dict or a string representation
318
+ of a JSON schema specification.
319
+
320
+ Returns:
321
+ mysqlx.Collection: Collection object.
322
+
323
+ Raises:
324
+ :class:`mysqlx.ProgrammingError`: If ``reuse_existing`` is False
325
+ and collection exists or the
326
+ collection name is invalid.
327
+ :class:`mysqlx.NotSupportedError`: If schema validation is not
328
+ supported by the server.
329
+
330
+ .. versionchanged:: 8.0.21
331
+ """
332
+ if not name:
333
+ raise ProgrammingError("Collection name is invalid")
334
+
335
+ if "reuse" in kwargs:
336
+ warnings.warn(
337
+ "'reuse' is deprecated since 8.0.21. "
338
+ "Please use 'reuse_existing' instead",
339
+ DeprecationWarning,
340
+ )
341
+ reuse_existing = kwargs["reuse"]
342
+
343
+ collection = Collection(self, name)
344
+ fields: Dict[str, Any] = {"schema": self._name, "name": name}
345
+
346
+ if validation is not None:
347
+ if not isinstance(validation, dict) or not validation:
348
+ raise ProgrammingError("Invalid value for 'validation'")
349
+
350
+ valid_options = ("level", "schema")
351
+ for option in validation:
352
+ if option not in valid_options:
353
+ raise ProgrammingError(f"Invalid option in 'validation': {option}")
354
+
355
+ options = []
356
+
357
+ if "level" in validation:
358
+ level = validation["level"]
359
+ if not isinstance(level, str):
360
+ raise ProgrammingError("Invalid value for 'level'")
361
+ options.append(("level", level))
362
+
363
+ if "schema" in validation:
364
+ schema = validation["schema"]
365
+ if not isinstance(schema, (str, dict)):
366
+ raise ProgrammingError("Invalid value for 'schema'")
367
+ options.append(
368
+ (
369
+ "schema",
370
+ json.dumps(schema) if isinstance(schema, dict) else schema,
371
+ )
372
+ )
373
+
374
+ fields["options"] = ("validation", options)
375
+
376
+ try:
377
+ self._connection.execute_nonquery(
378
+ "mysqlx", "create_collection", True, fields
379
+ )
380
+ except OperationalError as err:
381
+ if err.errno == ER_X_CMD_NUM_ARGUMENTS:
382
+ raise NotSupportedError(
383
+ "Your MySQL server does not support the requested "
384
+ "operation. Please update to MySQL 8.0.19 or a later "
385
+ "version"
386
+ ) from err
387
+ if err.errno == ER_TABLE_EXISTS_ERROR:
388
+ if not reuse_existing:
389
+ raise ProgrammingError(
390
+ f"Collection '{name}' already exists"
391
+ ) from err
392
+ else:
393
+ raise ProgrammingError(err.msg, err.errno) from err
394
+
395
+ return collection
396
+
397
+ def modify_collection(
398
+ self, name: str, validation: Optional[Dict[str, Union[str, Dict]]] = None
399
+ ) -> None:
400
+ """Modifies a collection using a JSON schema validation.
401
+
402
+ Args:
403
+ name (str): The name of the collection.
404
+ validation (Optional[dict]): A dict, containing the keys `level`
405
+ with the validation level and `schema`
406
+ with a dict or a string representation
407
+ of a JSON schema specification.
408
+
409
+ Raises:
410
+ :class:`mysqlx.ProgrammingError`: If the collection name or
411
+ validation is invalid.
412
+ :class:`mysqlx.NotSupportedError`: If schema validation is not
413
+ supported by the server.
414
+
415
+ .. versionadded:: 8.0.21
416
+ """
417
+ if not name:
418
+ raise ProgrammingError("Collection name is invalid")
419
+
420
+ if not isinstance(validation, dict) or not validation:
421
+ raise ProgrammingError("Invalid value for 'validation'")
422
+
423
+ valid_options = ("level", "schema")
424
+ for option in validation:
425
+ if option not in valid_options:
426
+ raise ProgrammingError(f"Invalid option in 'validation': {option}")
427
+ options = []
428
+
429
+ if "level" in validation:
430
+ level = validation["level"]
431
+ if not isinstance(level, str):
432
+ raise ProgrammingError("Invalid value for 'level'")
433
+ options.append(("level", level))
434
+
435
+ if "schema" in validation:
436
+ schema = validation["schema"]
437
+ if not isinstance(schema, (str, dict)):
438
+ raise ProgrammingError("Invalid value for 'schema'")
439
+ options.append(
440
+ (
441
+ "schema",
442
+ json.dumps(schema) if isinstance(schema, dict) else schema,
443
+ )
444
+ )
445
+
446
+ fields = {
447
+ "schema": self._name,
448
+ "name": name,
449
+ "options": ("validation", options),
450
+ }
451
+
452
+ try:
453
+ self._connection.execute_nonquery(
454
+ "mysqlx", "modify_collection_options", True, fields
455
+ )
456
+ except OperationalError as err:
457
+ if err.errno == ER_X_INVALID_ADMIN_COMMAND:
458
+ raise NotSupportedError(
459
+ "Your MySQL server does not support the requested "
460
+ "operation. Please update to MySQL 8.0.19 or a later "
461
+ "version"
462
+ ) from err
463
+ raise ProgrammingError(err.msg, err.errno) from err
464
+
465
+
466
+ class Collection(DatabaseObject):
467
+ """Represents a collection of documents on a schema.
468
+
469
+ Args:
470
+ schema (mysqlx.Schema): The Schema object.
471
+ name (str): The collection name.
472
+ """
473
+
474
+ def exists_in_database(self) -> bool:
475
+ """Verifies if this object exists in the database.
476
+
477
+ Returns:
478
+ bool: `True` if object exists in database.
479
+ """
480
+ sql = _COUNT_TABLES_QUERY.format(escape(self._schema.name), escape(self._name))
481
+ return self._connection.execute_sql_scalar(sql) == 1
482
+
483
+ def find(self, condition: Optional[str] = None) -> FindStatement:
484
+ """Retrieves documents from a collection.
485
+
486
+ Args:
487
+ condition (Optional[str]): The string with the filter expression of
488
+ the documents to be retrieved.
489
+ """
490
+ stmt = FindStatement(self, condition)
491
+ stmt.stmt_id = self._connection.get_next_statement_id()
492
+ return stmt
493
+
494
+ def add(self, *values: DbDoc) -> AddStatement:
495
+ """Adds a list of documents to a collection.
496
+
497
+ Args:
498
+ *values: The document list to be added into the collection.
499
+
500
+ Returns:
501
+ mysqlx.AddStatement: AddStatement object.
502
+ """
503
+ return AddStatement(self).add(*values)
504
+
505
+ def remove(self, condition: str) -> RemoveStatement:
506
+ """Removes documents based on the ``condition``.
507
+
508
+ Args:
509
+ condition (str): The string with the filter expression of the
510
+ documents to be removed.
511
+
512
+ Returns:
513
+ mysqlx.RemoveStatement: RemoveStatement object.
514
+
515
+ .. versionchanged:: 8.0.12
516
+ The ``condition`` parameter is now mandatory.
517
+ """
518
+ stmt = RemoveStatement(self, condition)
519
+ stmt.stmt_id = self._connection.get_next_statement_id()
520
+ return stmt
521
+
522
+ def modify(self, condition: str) -> ModifyStatement:
523
+ """Modifies documents based on the ``condition``.
524
+
525
+ Args:
526
+ condition (str): The string with the filter expression of the
527
+ documents to be modified.
528
+
529
+ Returns:
530
+ mysqlx.ModifyStatement: ModifyStatement object.
531
+
532
+ .. versionchanged:: 8.0.12
533
+ The ``condition`` parameter is now mandatory.
534
+ """
535
+ stmt = ModifyStatement(self, condition)
536
+ stmt.stmt_id = self._connection.get_next_statement_id()
537
+ return stmt
538
+
539
+ def count(self) -> int:
540
+ """Counts the documents in the collection.
541
+
542
+ Returns:
543
+ int: The total of documents in the collection.
544
+ """
545
+ sql = _COUNT_QUERY.format(
546
+ quote_identifier(self._schema.name), quote_identifier(self._name)
547
+ )
548
+ try:
549
+ res = self._connection.execute_sql_scalar(sql)
550
+ except OperationalError as err:
551
+ if err.errno == ER_NO_SUCH_TABLE:
552
+ raise OperationalError(
553
+ f"Collection '{self._name}' does not exist in schema "
554
+ f"'{self._schema.name}'"
555
+ ) from err
556
+ raise
557
+ return res
558
+
559
+ def create_index(
560
+ self, index_name: str, fields_desc: Dict[str, Any]
561
+ ) -> CreateCollectionIndexStatement:
562
+ """Creates a collection index.
563
+
564
+ Args:
565
+ index_name (str): Index name.
566
+ fields_desc (dict): A dictionary containing the fields members that
567
+ constraints the index to be created. It must
568
+ have the form as shown in the following::
569
+
570
+ {"fields": [{"field": member_path,
571
+ "type": member_type,
572
+ "required": member_required,
573
+ "array": array,
574
+ "collation": collation,
575
+ "options": options,
576
+ "srid": srid},
577
+ # {... more members,
578
+ # repeated as many times
579
+ # as needed}
580
+ ],
581
+ "type": type}
582
+ """
583
+ return CreateCollectionIndexStatement(self, index_name, fields_desc)
584
+
585
+ def drop_index(self, index_name: str) -> None:
586
+ """Drops a collection index.
587
+
588
+ Args:
589
+ index_name (str): Index name.
590
+ """
591
+ self._connection.execute_nonquery(
592
+ "mysqlx",
593
+ "drop_collection_index",
594
+ False,
595
+ {
596
+ "schema": self._schema.name,
597
+ "collection": self._name,
598
+ "name": index_name,
599
+ },
600
+ )
601
+
602
+ def replace_one(self, doc_id: str, doc: Union[Dict, DbDoc]) -> "Result":
603
+ """Replaces the Document matching the document ID with a new document
604
+ provided.
605
+
606
+ Args:
607
+ doc_id (str): Document ID
608
+ doc (:class:`mysqlx.DbDoc` or `dict`): New Document
609
+ """
610
+ if "_id" in doc and doc["_id"] != doc_id:
611
+ raise ProgrammingError(
612
+ "Replacement document has an _id that is different than the "
613
+ "matched document"
614
+ )
615
+ return self.modify("_id = :id").set("$", doc).bind("id", doc_id).execute()
616
+
617
+ def add_or_replace_one(self, doc_id: str, doc: Union[Dict, DbDoc]) -> "Result":
618
+ """Upserts the Document matching the document ID with a new document
619
+ provided.
620
+
621
+ Args:
622
+ doc_id (str): Document ID
623
+ doc (:class:`mysqlx.DbDoc` or dict): New Document
624
+ """
625
+ if "_id" in doc and doc["_id"] != doc_id:
626
+ raise ProgrammingError(
627
+ "Replacement document has an _id that is different than the "
628
+ "matched document"
629
+ )
630
+ if not isinstance(doc, DbDoc):
631
+ doc = DbDoc(doc)
632
+ return self.add(doc.copy(doc_id)).upsert(True).execute()
633
+
634
+ def get_one(self, doc_id: str) -> DbDoc:
635
+ """Returns a Document matching the Document ID.
636
+
637
+ Args:
638
+ doc_id (str): Document ID
639
+
640
+ Returns:
641
+ mysqlx.DbDoc: The Document matching the Document ID.
642
+ """
643
+ result = self.find("_id = :id").bind("id", doc_id).execute()
644
+ doc = result.fetch_one()
645
+ self._connection.fetch_active_result()
646
+ return doc
647
+
648
+ def remove_one(self, doc_id: str) -> "Result":
649
+ """Removes a Document matching the Document ID.
650
+
651
+ Args:
652
+ doc_id (str): Document ID
653
+
654
+ Returns:
655
+ mysqlx.Result: Result object.
656
+ """
657
+ return self.remove("_id = :id").bind("id", doc_id).execute()
658
+
659
+
660
+ class Table(DatabaseObject):
661
+ """Represents a database table on a schema.
662
+
663
+ Provides access to the table through standard INSERT/SELECT/UPDATE/DELETE
664
+ statements.
665
+
666
+ Args:
667
+ schema (mysqlx.Schema): The Schema object.
668
+ name (str): The table name.
669
+ """
670
+
671
+ def exists_in_database(self) -> bool:
672
+ """Verifies if this object exists in the database.
673
+
674
+ Returns:
675
+ bool: `True` if object exists in database.
676
+ """
677
+ sql = _COUNT_TABLES_QUERY.format(escape(self._schema.name), escape(self._name))
678
+ return self._connection.execute_sql_scalar(sql) == 1
679
+
680
+ def select(self, *fields: str) -> SelectStatement:
681
+ """Creates a new :class:`mysqlx.SelectStatement` object.
682
+
683
+ Args:
684
+ *fields: The fields to be retrieved.
685
+
686
+ Returns:
687
+ mysqlx.SelectStatement: SelectStatement object
688
+ """
689
+ stmt = SelectStatement(self, *fields)
690
+ stmt.stmt_id = self._connection.get_next_statement_id()
691
+ return stmt
692
+
693
+ def insert(self, *fields: Any) -> InsertStatement:
694
+ """Creates a new :class:`mysqlx.InsertStatement` object.
695
+
696
+ Args:
697
+ *fields: The fields to be inserted.
698
+
699
+ Returns:
700
+ mysqlx.InsertStatement: InsertStatement object
701
+ """
702
+ stmt = InsertStatement(self, *fields)
703
+ stmt.stmt_id = self._connection.get_next_statement_id()
704
+ return stmt
705
+
706
+ def update(self) -> UpdateStatement:
707
+ """Creates a new :class:`mysqlx.UpdateStatement` object.
708
+
709
+ Returns:
710
+ mysqlx.UpdateStatement: UpdateStatement object
711
+ """
712
+ stmt = UpdateStatement(self)
713
+ stmt.stmt_id = self._connection.get_next_statement_id()
714
+ return stmt
715
+
716
+ def delete(self) -> DeleteStatement:
717
+ """Creates a new :class:`mysqlx.DeleteStatement` object.
718
+
719
+ Returns:
720
+ mysqlx.DeleteStatement: DeleteStatement object
721
+
722
+ .. versionchanged:: 8.0.12
723
+ The ``condition`` parameter was removed.
724
+ """
725
+ stmt = DeleteStatement(self)
726
+ stmt.stmt_id = self._connection.get_next_statement_id()
727
+ return stmt
728
+
729
+ def count(self) -> int:
730
+ """Counts the rows in the table.
731
+
732
+ Returns:
733
+ int: The total of rows in the table.
734
+ """
735
+ sql = _COUNT_QUERY.format(
736
+ quote_identifier(self._schema.name), quote_identifier(self._name)
737
+ )
738
+ try:
739
+ res = self._connection.execute_sql_scalar(sql)
740
+ except OperationalError as err:
741
+ if err.errno == ER_NO_SUCH_TABLE:
742
+ raise OperationalError(
743
+ f"Table '{self._name}' does not exist in schema "
744
+ f"'{self._schema.name}'"
745
+ ) from err
746
+ raise
747
+ return res
748
+
749
+ def is_view(self) -> bool:
750
+ """Determine if the underlying object is a view or not.
751
+
752
+ Returns:
753
+ bool: `True` if the underlying object is a view.
754
+ """
755
+ sql = _COUNT_VIEWS_QUERY.format(escape(self._schema.name), escape(self._name))
756
+ return self._connection.execute_sql_scalar(sql) == 1
757
+
758
+
759
+ class View(Table):
760
+ """Represents a database view on a schema.
761
+
762
+ Provides a mechanism for creating, alter and drop views.
763
+
764
+ Args:
765
+ schema (mysqlx.Schema): The Schema object.
766
+ name (str): The table name.
767
+ """
768
+
769
+ def exists_in_database(self) -> bool:
770
+ """Verifies if this object exists in the database.
771
+
772
+ Returns:
773
+ bool: `True` if object exists in database.
774
+ """
775
+ sql = _COUNT_VIEWS_QUERY.format(escape(self._schema.name), escape(self._name))
776
+ return self._connection.execute_sql_scalar(sql) == 1