U Yzf_ bã@sdZddlZddlZddlmZddlmZddlmZm Z m Z m Z ddl m Z mZmZddlmZmZmZdd lmZmZmZmZmZmZmZmZmZd Zd Zd Z d Z!dZ"Gdd„de#ƒZ$Gdd„de$ƒZ%Gdd„de$ƒZ&Gdd„de$ƒZ'Gdd„de'ƒZ(dS)z,Implementation of the CRUD database objects.éNé)ÚDbDoc)Ú STRING_TYPES)ÚER_NO_SUCH_TABLEÚER_TABLE_EXISTS_ERRORÚER_X_CMD_NUM_ARGUMENTSÚER_X_INVALID_ADMIN_COMMAND)ÚNotSupportedErrorÚOperationalErrorÚProgrammingError)Ú deprecatedÚescapeÚquote_identifier) Ú FindStatementÚ AddStatementÚRemoveStatementÚModifyStatementÚSelectStatementÚInsertStatementÚDeleteStatementÚUpdateStatementÚCreateCollectionIndexStatementz_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@sˆeZdZdZdd„Zedd„ƒZedd„ƒZedd „ƒZd d „Z d d „Z dd„Z dd„Z dd„Z eddƒdd„ƒZeddƒdd„ƒZdS)ÚDatabaseObjectz¢Provides base functionality for database objects. Args: schema (mysqlx.Schema): The Schema object. name (str): The database object name. cCs(||_||_|j ¡|_|j ¡|_dS©N)Ú_schemaÚ_nameÚ get_sessionÚ_sessionÚget_connectionÚ _connection)ÚselfÚschemaÚname©r#ú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. ©r©r 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_namecCst‚dS)zÓVerifies 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_real‚s zDatabaseObject.am_i_realzUse 'get_name()' method insteadcCs| ¡S)zÅReturns 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_i‘s zDatabaseObject.who_am_iN)Ú__name__Ú __module__Ú __qualname__Ú__doc__r%Úpropertyr(r!r"rrr+r,r.r r/r0r#r#r#r$r8s"     rcs|eZdZdZ‡fdd„Zdd„Zdd„Zdd d „Zd d „Zdd d„Z ddd„Z ddd„Z dd„Z ddd„Z ddd„Z‡ZS) ÚSchemazÆA 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)rÚsuperr6r%)r r(r"©Ú __class__r#r$r%¦szSchema.__init__cCs t t|jƒ¡}|j |¡dkS©z�Verifies if this object exists in the database. Returns: bool: `True` if object exists in database. r)Ú_COUNT_SCHEMAS_QUERYÚformatr rrÚexecute_sql_scalar©r Úsqlr#r#r$r.ªszSchema.exists_in_databasec Cs||j dd|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")rÚget_row_resultrÚ fetch_allÚ CollectionÚ ValueErrorÚappend)r ÚrowsÚ collectionsÚrowÚ collectionr#r#r$Úget_collections³sÿ  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_tableÇszSchema.get_collection_as_tablec Cs~|j dd|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")rrCrrDÚTablerFrG)r rHZtablesZ object_typesrJÚtabler#r#r$Ú get_tablesÐsÿ  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$rMäs  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"rNÚviewr#r#r$Úget_viewðs  zSchema.get_viewcCs"t||ƒ}|r| ¡stdƒ‚|S)z†Returns 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_collectionüs  zSchema.get_collectioncCs&|j dt t|jƒt|ƒ¡d¡dS)zmDrops a collection. Args: name (str): The name of the collection to be dropped. r?FN)rÚexecute_nonqueryÚ_DROP_TABLE_QUERYr<rr)r r"r#r#r$Údrop_collections ÿþzSchema.drop_collectionNc KsŽ|s tdƒ‚d|kr(t dt¡|d}t||ƒ}|j|dœ}|dk �r t|tƒrV|s^tdƒ‚d}|D]}||krftd |¡ƒ‚qfg} d |kr¶|d } t| t ƒs¨td ƒ‚|   d | f¡d |krþ|d } t| t tfƒsÜtd ƒ‚|   d t| tƒröt   | ¡n| f¡d | f|d<z|j  ddd|¡Wnhtk �rˆ} zH| jtk�rHtdƒ‚| jtk�rj|�sxtd |¡ƒ‚nt| j| jƒ‚W5d} ~ 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"NúInvalid value for 'validation'©Úlevelr!ú"Invalid option in 'validation': {}r]úInvalid value for 'level'r!úInvalid value for 'schema'Ú validationÚoptionsÚmysqlxÚcreate_collectionTúlYour MySQL server does not support the requested operation. Please update to MySQL 8.0.19 or a later versionzCollection '{}' already exists)r ÚwarningsÚwarnÚDeprecationWarningrErÚ isinstanceÚdictr<ÚstrrGÚjsonÚdumpsrrWr Úerrnorr rÚmsg) r r"Zreuse_existingraÚkwargsrKÚfieldsÚ valid_optionsÚoptionrbr]r!Úerrr#r#r$rdsnþ   ÿ ÿ ÿÿ ÿ ÿ ÿ zSchema.create_collectionc Cs6|s tdƒ‚t|tƒr|s"tdƒ‚d}|D]}||kr*td |¡ƒ‚q*g}d|krz|d}t|tƒsltdƒ‚| d|f¡d|krÂ|d}t|ttfƒs tdƒ‚| dt|tƒrºt |¡n|f¡|j|d |fd œ}z|j   d d d |¡WnFt k �r0} z&| j t k�rtdƒ‚t| 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$r6žs     Sr6c@sreZdZdZdd„Zddd„Zdd„Zd d „Zd d „Zd d„Z dd„Z dd„Z dd„Z dd„Z dd„Zdd„ZdS)rEz�Represents a collection of documents on a schema. Args: schema (mysqlx.Schema): The Schema object. name (str): The collection name. cCs*t t|jjƒt|jƒ¡}|j |¡dkSr:©Ú_COUNT_TABLES_QUERYr<r rr"rrr=r>r#r#r$r.¬sÿzCollection.exists_in_databaseNcCst||ƒ}|j ¡|_|S)zÔRetrieves documents from a collection. Args: condition (Optional[str]): The string with the filter expression of the documents to be retrieved. )rrÚget_next_statement_idÚstmt_id©r Ú conditionÚstmtr#r#r$Úfind¶s  zCollection.findcGst|ƒj|ŽS)zÑAdds a list of documents to a collection. Args: *values: The document list to be added into the collection. Returns: mysqlx.AddStatement: AddStatement object. )rÚadd)r Úvaluesr#r#r$rÁs 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$ÚremoveÌs  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$ÚmodifyÝs  zCollection.modifyc Cstt t|jjƒt|jƒ¡}z|j |¡}WnDtk rn}z&|j t kr\td |j|jj¡ƒ‚‚W5d}~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 rnr©r r?Úresrtr#r#r$Úcountîsÿ ÿÿ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$|j ddd|jj|j|dœ¡dS)z[Drops a collection index. Args: index_name (str): Index name. rcZdrop_collection_indexF)r!rKr"N)rrWrr"r)r rˆr#r#r$Ú drop_indexs þÿzCollection.drop_indexcCs| d¡ d|¡ d|¡ ¡S)zÒReplaces 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)r‚ÚsetÚbindÚexecute©r Údoc_idÚdocr#r#r$Ú replace_one#sÿzCollection.replace_onecCs,t|tƒst|ƒ}| | |¡¡ d¡ ¡S)zÏUpserts 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)rirrÚcopyZupsertr�r‘r#r#r$Úadd_or_replace_one.s zCollection.add_or_replace_onecCs,| d¡ d|¡ ¡}| ¡}|j ¡|S)z½Returns a Document matching the Document ID. Args: doc_id (str): Document ID Returns: mysqlx.DbDoc: The Document matching the Document ID. r‹r�)r~r�r�Z fetch_onerZfetch_active_result)r r’Úresultr“r#r#r$Úget_one:s  zCollection.get_onecCs| d¡ d|¡ ¡S)z¦Removes a Document matching the Document ID. Args: doc_id (str): Document ID Returns: mysqlx.Result: Result object. r‹r�)r�r�r�)r r’r#r#r$Ú remove_oneHs zCollection.remove_one)N)r1r2r3r4r.r~rr�r‚r‡r‰rŠr”r–r˜r™r#r#r#r$rE¤s     rEc@sHeZdZdZdd„Zdd„Zdd„Zdd „Zd d „Zd d „Z dd„Z dS)rPzîRepresents 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*t t|jjƒt|jƒ¡}|j |¡dkSr:rwr>r#r#r$r._sÿzTable.exists_in_databasecGst|f|žŽ}|j ¡|_|S)zËCreates a new :class:`mysqlx.SelectStatement` object. Args: *fields: The fields to be retrieved. Returns: mysqlx.SelectStatement: SelectStatement object )rrryrz©r rqr}r#r#r$Úselectis  z Table.selectcGst|f|žŽ}|j ¡|_|S)zÊCreates a new :class:`mysqlx.InsertStatement` object. Args: *fields: The fields to be inserted. Returns: mysqlx.InsertStatement: InsertStatement object )rrryrzršr#r#r$Úinsertvs  z Table.insertcCst|ƒ}|j ¡|_|S)z‹Creates a new :class:`mysqlx.UpdateStatement` object. Returns: mysqlx.UpdateStatement: UpdateStatement object )rrryrz©r r}r#r#r$Úupdateƒs z Table.updatecCst|ƒ}|j ¡|_|S)zãCreates a new :class:`mysqlx.DeleteStatement` object. Returns: mysqlx.DeleteStatement: DeleteStatement object .. versionchanged:: 8.0.12 The ``condition`` parameter was removed. )rrryrzr�r#r#r$Údelete�s  z Table.deletec Cstt t|jjƒt|jƒ¡}z|j |¡}WnDtk rn}z&|j t kr\td |j|jj¡ƒ‚‚W5d}~XYnX|S)ziCounts the rows in the table. Returns: int: The total of rows in the table. z(Table '{}' does not exist in schema '{}'Nrƒr…r#r#r$r‡šsÿ ÿÿz Table.countcCs*t t|jjƒt|jƒ¡}|j |¡dkS)zŒDetermine 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_view¬sÿz Table.is_viewN) r1r2r3r4r.r›rœržrŸr‡r¢r#r#r#r$rPTs      rPc@seZdZdZdd„ZdS)rSzÌRepresents 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*t t|jjƒt|jƒ¡}|j |¡dkSr:r r>r#r#r$r.ÁsÿzView.exists_in_databaseN)r1r2r3r4r.r#r#r#r$rS·s rS))r4rlrfZdbdocrÚcompatrÚ errorcoderrrrÚerrorsr r r Zhelpersr r rZ statementrrrrrrrrrr¡rxr;r„rXÚobjectrr6rErPrSr#r#r#r$Ús*  ,f1c