U Yzf_ b@sdZddlZddlZddlmZddlmZddlmZm Z m Z m Z ddl m Z mZmZddlmZmZmZdd lmZmZmZmZmZmZmZmZmZd Zd Zd Z d Z!dZ"Gddde#Z$Gddde$Z%Gddde$Z&Gddde$Z'Gddde'Z(dS)z,Implementation of the CRUD database objects.N)DbDoc) STRING_TYPES)ER_NO_SUCH_TABLEER_TABLE_EXISTS_ERRORER_X_CMD_NUM_ARGUMENTSER_X_INVALID_ADMIN_COMMAND)NotSupportedErrorOperationalErrorProgrammingError) deprecatedescapequote_identifier) FindStatement AddStatementRemoveStatementModifyStatementSelectStatementInsertStatementDeleteStatementUpdateStatementCreateCollectionIndexStatementz_SELECT COUNT(*) FROM information_schema.views WHERE table_schema = '{0}' AND table_name = '{1}'z`SELECT COUNT(*) FROM information_schema.tables WHERE table_schema = '{0}' AND table_name = '{1}'zJSELECT COUNT(*) FROM information_schema.schemata WHERE schema_name = '{0}'zSELECT COUNT(*) FROM {0}.{1}zDROP TABLE IF EXISTS {0}.{1}c@seZdZdZddZeddZeddZedd Zd d Z d d Z ddZ ddZ ddZ eddddZeddddZdS)DatabaseObjectzProvides base functionality for database objects. Args: schema (mysqlx.Schema): The Schema object. name (str): The database object name. cCs(||_||_|j|_|j|_dSN)_schema_name get_session_sessionget_connection _connection)selfschemanamer#c/private/var/folders/n9/53xbvtmd7sjg1q1l55xmpg58n4mgng/T/pip-unpacked-wheel-47tvuv7y/mysqlx/crud.py__init__?s zDatabaseObject.__init__cCs|jS)z5:class:`mysqlx.Session`: The Session object. rr r#r#r$sessionEszDatabaseObject.sessioncCs|jS)z3:class:`mysqlx.Schema`: The Schema object. rr'r#r#r$r!KszDatabaseObject.schemacCs|jS)z/str: The name of this database object. rr'r#r#r$r"QszDatabaseObject.namecCs|jS)z~Returns the underlying connection. Returns: mysqlx.connection.Connection: The connection object. )rr'r#r#r$rWszDatabaseObject.get_connectioncCs|jS)zwReturns the session of this database object. Returns: mysqlx.Session: The Session object. r&r'r#r#r$r_szDatabaseObject.get_sessioncCs|jS)z{Returns the Schema object of this database object. Returns: mysqlx.Schema: The Schema object. r)r'r#r#r$ get_schemagszDatabaseObject.get_schemacCs|jS)zwReturns the name of this database object. Returns: str: The name of this database object. r*r'r#r#r$get_nameoszDatabaseObject.get_namecCstdS)zVerifies if this object exists in the database. Returns: bool: `True` if object exists in database. Raises: NotImplementedError: This method must be implemented. N)NotImplementedErrorr'r#r#r$exists_in_databasews z!DatabaseObject.exists_in_databasez8.0.12z)Use 'exists_in_database()' method insteadcCs|S)a+Verifies if this object exists in the database. Returns: bool: `True` if object exists in database. Raises: NotImplementedError: This method must be implemented. .. deprecated:: 8.0.12 Use ``exists_in_database()`` method instead. )r.r'r#r#r$ am_i_reals zDatabaseObject.am_i_realzUse 'get_name()' method insteadcCs|S)zReturns the name of this database object. Returns: str: The name of this database object. .. deprecated:: 8.0.12 Use ``get_name()`` method instead. )r,r'r#r#r$who_am_is zDatabaseObject.who_am_iN)__name__ __module__ __qualname____doc__r%propertyr(r!r"rrr+r,r.r r/r0r#r#r#r$r8s"     rcs|eZdZdZfddZddZddZdd d Zd d Zdd dZ dddZ dddZ ddZ dddZ dddZZS) SchemazA client-side representation of a database schema. Provides access to the schema contents. Args: session (mysqlx.XSession): Session object. name (str): The Schema name. cs||_tt|||dSr)rsuperr6r%)r r(r" __class__r#r$r%szSchema.__init__cCs tt|j}|j|dkSzVerifies if this object exists in the database. Returns: bool: `True` if object exists in database. r)_COUNT_SCHEMAS_QUERYformatr rrexecute_sql_scalarr sqlr#r#r$r.szSchema.exists_in_databasec Cs||jdd|ji}|g}|D]R}|ddkr6q$zt||d}Wn"tk rjt||d}YnX||q$|S)zyReturns a list of collections for this schema. Returns: `list`: List of Collection objects. list_objectsr!typeZ COLLECTION TABLE_NAMEr")rget_row_resultr fetch_all Collection ValueErrorappend)r rows collectionsrow collectionr#r#r$get_collectionss  zSchema.get_collectionsFcCs |||S)zuReturns a a table object for the given collection Returns: mysqlx.Table: Table object. ) get_table)r r"check_existencer#r#r$get_collection_as_tableszSchema.get_collection_as_tablec Cs~|jdd|ji}|g}d}|D]P}|d|kr(zt||d}Wn"tk rlt||d}YnX||q(|S)zoReturns a list of tables for this schema. Returns: `list`: List of Table objects. r@r!)ZTABLEZVIEWrArBr")rrCrrDTablerFrG)r rHZtablesZ object_typesrJtabler#r#r$ get_tabless  zSchema.get_tablescCs"t||}|r|std|S)zwReturns the table of the given name for this schema. Returns: mysqlx.Table: Table object. zTable does not exist)rPr.r )r r"rNrQr#r#r$rMs  zSchema.get_tablecCs"t||}|r|std|S)ztReturns the view of the given name for this schema. Returns: mysqlx.View: View object. zView does not exist)Viewr.r )r r"rNviewr#r#r$get_views  zSchema.get_viewcCs"t||}|r|std|S)zReturns the collection of the given name for this schema. Returns: mysqlx.Collection: Collection object. zCollection does not exist)rEr.r )r r"rNrKr#r#r$get_collections  zSchema.get_collectioncCs&|jdtt|jt|ddS)zmDrops a collection. Args: name (str): The name of the collection to be dropped. r?FN)rexecute_nonquery_DROP_TABLE_QUERYr<rr)r r"r#r#r$drop_collections zSchema.drop_collectionNc Ks|s tdd|kr(tdt|d}t||}|j|d}|dk r t|trV|s^tdd}|D]}||krftd|qfg} d |kr|d } t| t std | d | fd |kr|d } t| t tfstd | d t| trt | n| fd | f|d<z|j ddd|Wnhtk r} zH| jtkrHtd| jtkrj|sxtd|nt| j| jW5d} ~ XYnX|S)aJCreates in the current schema a new collection with the specified name and retrieves an object representing the new collection created. Args: name (str): The name of the collection. reuse_existing (bool): `True` to reuse an existing collection. validation (Optional[dict]): A dict, containing the keys `level` with the validation level and `schema` with a dict or a string representation of a JSON schema specification. Returns: mysqlx.Collection: Collection object. Raises: :class:`mysqlx.ProgrammingError`: If ``reuse_existing`` is False and collection exists or the collection name is invalid. :class:`mysqlx.NotSupportedError`: If schema validation is not supported by the server. .. versionchanged:: 8.0.21 Collection name is invalidZreusezG'reuse' is deprecated since 8.0.21. Please use 'reuse_existing' instead)r!r"NInvalid value for 'validation'levelr!"Invalid option in 'validation': {}r]Invalid value for 'level'r!Invalid value for 'schema' validationoptionsmysqlxcreate_collectionTlYour MySQL server does not support the requested operation. Please update to MySQL 8.0.19 or a later versionzCollection '{}' already exists)r warningswarnDeprecationWarningrEr isinstancedictr<strrGjsondumpsrrWr errnorr rmsg) r r"Zreuse_existingrakwargsrKfields valid_optionsoptionrbr]r!errr#r#r$rdsn         zSchema.create_collectionc Cs6|s tdt|tr|s"tdd}|D]}||kr*td|q*g}d|krz|d}t|tsltd|d|fd|kr|d}t|ttfstd|dt|trt|n|f|j|d |fd }z|j d d d |WnFt k r0} z&| j t krtdt| j| j W5d} ~ XYnXdS)a Modifies a collection using a JSON schema validation. Args: name (str): The name of the collection. validation (Optional[dict]): A dict, containing the keys `level` with the validation level and `schema` with a dict or a string representation of a JSON schema specification. Raises: :class:`mysqlx.ProgrammingError`: If the collection name or validation is invalid. :class:`mysqlx.NotSupportedError`: If schema validation is not supported by the server. .. versionadded:: 8.0.21 rZr[r\r^r]r_r!r`ra)r!r"rbrcZmodify_collection_optionsTreN)r rirjr<rkrGrlrmrrrWr rnrr ro) r r"rarrrsrbr]r!rqrtr#r#r$modify_collectionesX   zSchema.modify_collection)F)F)F)F)FN)N)r1r2r3r4r%r.rLrOrRrMrUrVrYrdru __classcell__r#r#r8r$r6s     Sr6c@sreZdZdZddZdddZddZd d Zd d Zd dZ ddZ ddZ ddZ ddZ ddZddZdS)rEzRepresents a collection of documents on a schema. Args: schema (mysqlx.Schema): The Schema object. name (str): The collection name. cCs*tt|jjt|j}|j|dkSr:_COUNT_TABLES_QUERYr<r rr"rrr=r>r#r#r$r.szCollection.exists_in_databaseNcCst||}|j|_|S)zRetrieves documents from a collection. Args: condition (Optional[str]): The string with the filter expression of the documents to be retrieved. )rrget_next_statement_idstmt_idr conditionstmtr#r#r$finds  zCollection.findcGst|j|S)zAdds a list of documents to a collection. Args: *values: The document list to be added into the collection. Returns: mysqlx.AddStatement: AddStatement object. )radd)r valuesr#r#r$rs zCollection.addcCst||}|j|_|S)apRemoves documents based on the ``condition``. Args: condition (str): The string with the filter expression of the documents to be removed. Returns: mysqlx.RemoveStatement: RemoveStatement object. .. versionchanged:: 8.0.12 The ``condition`` parameter is now mandatory. )rrryrzr{r#r#r$removes  zCollection.removecCst||}|j|_|S)arModifies documents based on the ``condition``. Args: condition (str): The string with the filter expression of the documents to be modified. Returns: mysqlx.ModifyStatement: ModifyStatement object. .. versionchanged:: 8.0.12 The ``condition`` parameter is now mandatory. )rrryrzr{r#r#r$modifys  zCollection.modifyc Csttt|jjt|j}z|j|}WnDtk rn}z&|j t kr\td|j|jjW5d}~XYnX|S)z}Counts the documents in the collection. Returns: int: The total of documents in the collection. z-Collection '{}' does not exist in schema '{}'N _COUNT_QUERYr<rrr"rrr=r rnrr r?resrtr#r#r$counts zCollection.countcCs t|||S)abCreates a collection index. Args: index_name (str): Index name. fields_desc (dict): A dictionary containing the fields members that constraints the index to be created. It must have the form as shown in the following:: {"fields": [{"field": member_path, "type": member_type, "required": member_required, "array": array, "collation": collation, "options": options, "srid": srid}, # {... more members, # repeated as many times # as needed} ], "type": type} )r)r index_nameZ fields_descr#r#r$ create_indexszCollection.create_indexc Cs$|jddd|jj|j|ddS)z[Drops a collection index. Args: index_name (str): Index name. rcZdrop_collection_indexF)r!rKr"N)rrWrr"r)r rr#r#r$ drop_indexs zCollection.drop_indexcCs|dd|d|S)zReplaces the Document matching the document ID with a new document provided. Args: doc_id (str): Document ID doc (:class:`mysqlx.DbDoc` or `dict`): New Document _id = :id$id)rsetbindexecuter doc_iddocr#r#r$ replace_one#szCollection.replace_onecCs,t|tst|}|||dS)zUpserts the Document matching the document ID with a new document provided. Args: doc_id (str): Document ID doc (:class:`mysqlx.DbDoc` or dict): New Document T)rirrcopyZupsertrrr#r#r$add_or_replace_one.s zCollection.add_or_replace_onecCs,|dd|}|}|j|S)zReturns a Document matching the Document ID. Args: doc_id (str): Document ID Returns: mysqlx.DbDoc: The Document matching the Document ID. rr)r~rrZ fetch_onerZfetch_active_result)r rresultrr#r#r$get_one:s  zCollection.get_onecCs|dd|S)zRemoves a Document matching the Document ID. Args: doc_id (str): Document ID Returns: mysqlx.Result: Result object. rr)rrr)r rr#r#r$ remove_oneHs zCollection.remove_one)N)r1r2r3r4r.r~rrrrrrrrrrr#r#r#r$rEs     rEc@sHeZdZdZddZddZddZdd Zd d Zd d Z ddZ dS)rPzRepresents a database table on a schema. Provides access to the table through standard INSERT/SELECT/UPDATE/DELETE statements. Args: schema (mysqlx.Schema): The Schema object. name (str): The table name. cCs*tt|jjt|j}|j|dkSr:rwr>r#r#r$r._szTable.exists_in_databasecGst|f|}|j|_|S)zCreates a new :class:`mysqlx.SelectStatement` object. Args: *fields: The fields to be retrieved. Returns: mysqlx.SelectStatement: SelectStatement object )rrryrzr rqr}r#r#r$selectis  z Table.selectcGst|f|}|j|_|S)zCreates a new :class:`mysqlx.InsertStatement` object. Args: *fields: The fields to be inserted. Returns: mysqlx.InsertStatement: InsertStatement object )rrryrzrr#r#r$insertvs  z Table.insertcCst|}|j|_|S)zCreates a new :class:`mysqlx.UpdateStatement` object. Returns: mysqlx.UpdateStatement: UpdateStatement object )rrryrzr r}r#r#r$updates z Table.updatecCst|}|j|_|S)zCreates a new :class:`mysqlx.DeleteStatement` object. Returns: mysqlx.DeleteStatement: DeleteStatement object .. versionchanged:: 8.0.12 The ``condition`` parameter was removed. )rrryrzrr#r#r$deletes  z Table.deletec Csttt|jjt|j}z|j|}WnDtk rn}z&|j t kr\td|j|jjW5d}~XYnX|S)ziCounts the rows in the table. Returns: int: The total of rows in the table. z(Table '{}' does not exist in schema '{}'Nrrr#r#r$rs z Table.countcCs*tt|jjt|j}|j|dkS)zDetermine if the underlying object is a view or not. Returns: bool: `True` if the underlying object is a view. r_COUNT_VIEWS_QUERYr<r rr"rrr=r>r#r#r$is_viewsz Table.is_viewN) r1r2r3r4r.rrrrrrr#r#r#r$rPTs      rPc@seZdZdZddZdS)rSzRepresents a database view on a schema. Provides a mechanism for creating, alter and drop views. Args: schema (mysqlx.Schema): The Schema object. name (str): The table name. cCs*tt|jjt|j}|j|dkSr:rr>r#r#r$r.szView.exists_in_databaseN)r1r2r3r4r.r#r#r#r$rSs rS))r4rlrfZdbdocrcompatr errorcoderrrrerrorsr r r Zhelpersr r rZ statementrrrrrrrrrrrxr;rrXobjectrr6rErPrSr#r#r#r$s*  ,f1c