Why Gemfury? Push, build, and install  RubyGems npm packages Python packages Maven artifacts PHP packages Go Modules Debian packages RPM packages NuGet packages

Repository URL to install this package:

Details    
idna / lib / python2.7 / site-packages / oslo_db / sqlalchemy / update_match.pyc
Size: Mime:
ó
x“EYc@s/ddlZddlmZddlmZddlmZddlmZddlmZdddddd„Z
ddd	„Zddd
„Zd„Z
d„Zd
„Zd„Zd„Zd„Zd„Zd„ZedgƒZdefd„ƒYZdefd„ƒYZdefd„ƒYZdS(iÿÿÿÿN(tinspect(torm(tsql(ttypes(tutilsicCs˜|dkri}nt|ƒ}|j}	g|jD]}
|
d^q4|	jgksbtdƒ‚t|d|d|gƒ}|j|ƒ}|r¡||ƒ}n||j|j	f}d}
xxt
|ƒD]Z}y|j||ƒ}
Wn:tk
rü‚qÊt
k
r"|r$||ƒr$Pq$qÊXPqÊWt
d|ƒ‚|
dkrY|jj|ƒ}
ntj|ƒ}|d||<t|j|jƒ||
ƒ}|S(sÅEmit an UPDATE statement matching the given specimen.

    E.g.::

        with enginefacade.writer() as session:
            specimen = MyInstance(
                uuid='ccea54f',
                interface_id='ad33fea',
                vm_state='SOME_VM_STATE',
            )

            values = {
                'vm_state': 'SOME_NEW_VM_STATE'
            }

            base_query = model_query(
                context, models.Instance,
                project_only=True, session=session)

            hostname_query = model_query(
                    context, models.Instance, session=session,
                    read_deleted='no').
                filter(func.lower(models.Instance.hostname) == 'SOMEHOSTNAME')

            surrogate_key = ('uuid', )

            def process_query(query):
                return query.where(~exists(hostname_query))

            def handle_failure(query):
                try:
                    instance = base_query.one()
                except NoResultFound:
                    raise exception.InstanceNotFound(instance_id=instance_uuid)

                if session.query(hostname_query.exists()).scalar():
                    raise exception.InstanceExists(
                        name=values['hostname'].lower())

                # try again
                return False

            persistent_instance = base_query.update_on_match(
                specimen,
                surrogate_key,
                values=values,
                process_query=process_query,
                handle_failure=handle_failure
            )

    The UPDATE statement is constructed against the given specimen
    using those values which are present to construct a WHERE clause.
    If the specimen contains additional values to be ignored, the
    ``include_only`` parameter may be passed which indicates a sequence
    of attributes to use when constructing the WHERE.

    The UPDATE is performed against an ORM Query, which is created from
    the given ``Session``, or alternatively by passing the ```query``
    parameter referring to an existing query.

    Before the query is invoked, it is also passed through the callable
    sent as ``process_query``, if present.  This hook allows additional
    criteria to be added to the query after it is created but before
    invocation.

    The function will then invoke the UPDATE statement and check for
    "success" one or more times, up to a maximum of that passed as
    ``attempts``.

    The initial check for "success" from the UPDATE statement is that the
    number of rows returned matches 1.  If zero rows are matched, then
    the UPDATE statement is assumed to have "failed", and the failure handling
    phase begins.

    The failure handling phase involves invoking the given ``handle_failure``
    function, if any.  This handler can perform additional queries to attempt
    to figure out why the UPDATE didn't match any rows.  The handler,
    upon detection of the exact failure condition, should throw an exception
    to exit; if it doesn't, it has the option of returning True or False,
    where False means the error was not handled, and True means that there
    was not in fact an error, and the function should return successfully.

    If the failure handler is not present, or returns False after ``attempts``
    number of attempts, then the function overall raises CantUpdateException.
    If the handler returns True, then the function returns with no error.

    The return value of the function is a persistent version of the given
    specimen; this may be the specimen itself, if no matching object were
    already present in the session; otherwise, the existing object is
    returned, with the state of the specimen merged into it.  The returned
    persistent object will have the given values populated into the object.

    The object is is returned as "persistent", meaning that it is
    associated with the given
    Session and has an identity key (that is, a real primary key
    value).

    In order to produce this identity key, a strategy must be used to
    determine it as efficiently and safely as possible:

    1. If the given specimen already contained its primary key attributes
       fully populated, then these attributes were used as criteria in the
       UPDATE, so we have the primary key value; it is populated directly.

    2. If the target backend supports RETURNING, then when the update() query
       is performed with a RETURNING clause so that the matching primary key
       is returned atomically.  This currently includes Postgresql, Oracle
       and others (notably not MySQL or SQLite).

    3. If the target backend is MySQL, and the given model uses a
       single-column, AUTO_INCREMENT integer primary key value (as is
       the case for Nova), MySQL's recommended approach of making use
       of ``LAST_INSERT_ID(expr)`` is used to atomically acquire the
       matching primary key value within the scope of the UPDATE
       statement, then it fetched immediately following by using
       ``SELECT LAST_INSERT_ID()``.
       http://dev.mysql.com/doc/refman/5.0/en/information-       functions.html#function_last-insert-id

    4. Otherwise, for composite keys on MySQL or other backends such
       as SQLite, the row as UPDATED must be re-fetched in order to
       acquire the primary key value.  The ``surrogate_key``
       parameter is used for this in order to re-fetch the row; this
       is a column name with a known, unique value where
       the object can be fetched.


    ttypes#Query does not match given specimentinclude_onlytexcludes!Zero rows matched for %d attemptsiN(tNoneRtmappertcolumn_descriptionstclass_tAssertionErrortmanufacture_entity_criteriatfiltertattrstloaded_valuetrangetupdate_returning_pktMultiRowsMatchedt
NoRowsMatchedtprimary_key_from_instancetcopytmanufacture_persistent_objecttsessiont	__class__(tquerytspeciment
surrogate_keytvaluestattemptsRt
process_querythandle_failuretentityR	tdesctcriteriatsurrogate_key_argtpk_valuetattempttpersistent_obj((sT/home/tvault/.virtenv/lib/python2.7/site-packages/oslo_db/sqlalchemy/update_match.pytupdate_on_matchs<‹		

cCs8t|ƒ}|j}x0|jƒD]"\}}tjj|||ƒq"Wg|jD]}|j|ƒj^qR}	|dk	rµx6t
|	|ƒD]"\}
}tjj||
|ƒqŒWnx9|	D]1}
|j|
jtjj
kr¼tdƒ‚q¼q¼Wtj|ƒ|j|jkr!|j|ƒ|S|j|dtƒSdS(s¿Make an ORM-mapped object persistent in a Session without SQL.

    The persistent object is returned.

    If a matching object is already present in the given session, the specimen
    is merged into it and the persistent object returned.  Otherwise, the
    specimen itself is made persistent and is returned.

    The object must contain a full primary key, or provide it via the values or
    primary_key parameters.  The object is peristed to the Session in a "clean"
    state with no pending changes.

    :param session: A Session object.

    :param specimen: a mapped object which is typically transient.

    :param values: a dictionary of values to be applied to the specimen,
     in addition to the state that's already on it.  The attributes will be
     set such that no history is created; the object remains clean.

    :param primary_key: optional tuple-based primary key.  This will also
     be applied to the instance if present.


    s full primary key must be presenttloadN(RR	titemsRt
attributestset_committed_valuetprimary_keytget_property_by_columntkeyRtzipRRtNO_VALUEt
ValueErrortmake_transient_to_detachedtidentity_maptaddtmergetFalse(RRRR-tstateR	tktvtcoltpk_attrsR/tvalue((sT/home/tvault/.virtenv/lib/python2.7/site-packages/oslo_db/sqlalchemy/update_match.pyRÑs(	%	


cst|ƒ}ˆdk	r$tˆƒntƒ‰t‡fd†|jDƒƒ‰|r€t‡fd†tˆƒj|ƒDƒƒ‰nt|jˆƒS(s‘Given a mapped instance, produce a WHERE clause.

    The attributes set upon the instance will be combined to produce
    a SQL expression using the mapped SQL expressions as the base
    of comparison.

    Values on the instance may be set as tuples in which case the
    criteria will produce an IN clause.  None is also acceptable as a
    scalar or tuple entry, which will produce IS NULL that is properly
    joined with an OR against an IN expression if appropriate.

    :param entity: a mapped entity.

    :param include_only: optional sequence of keys to limit which
     keys are included.

    :param exclude: sequence of keys to exclude

    c3sE|];}|jtjjk	r|jˆkr|j|jfVqdS(N(RRR+R1R/(t.0tattr(R(sT/home/tvault/.virtenv/lib/python2.7/site-packages/oslo_db/sqlalchemy/update_match.pys	<genexpr>%sc3s|]}|ˆ|fVqdS(N((R>R9(texisting(sT/home/tvault/.virtenv/lib/python2.7/site-packages/oslo_db/sqlalchemy/update_match.pys	<genexpr>,sN(RRtsettdictRtintersectiontmanufacture_criteriaR	(R!RRR8((RR@sT/home/tvault/.virtenv/lib/python2.7/site-packages/oslo_db/sqlalchemy/update_match.pyR
s!cCs}t|ƒ}t|ƒ}g|jjƒD]}||kr(|^q(}tjg|D]#}t|j|j||ƒ^qSŒS(sRGiven a mapper/class and a namespace of values, produce a WHERE clause.

    The class should be a mapped class and the entries in the dictionary
    correspond to mapped attribute names on the class.

    A value may also be a tuple in which case that particular attribute
    will be compared to a tuple using IN.   The scalar value or
    tuple can also contain None which translates to an IS NULL, that is
    properly joined with OR against an IN expression if appropriate.

    :param cls: a mapped class, or actual :class:`.Mapper` object.

    :param values: dictionary of values.

    (RRAtcolumn_attrstkeysRtand_t	_sql_critt
expression(tmappedRR	t
value_keysR9RFR/((sT/home/tvault/.virtenv/lib/python2.7/site-packages/oslo_db/sqlalchemy/update_match.pyRD3s.cCs¬tj|ddƒ}t|ƒdkrX|ddkrG|tjƒkS||dkSnPtj|ƒr›tj|tjƒkt	|t
|ƒjtƒƒƒS|j|ƒSdS(sÐProduce an equality expression against the given value.

    This takes into account a value that is actually a collection
    of values, as well as a value of None or collection that contains
    None.

    tdefaultiiN(N(
Rtto_listRtlenRtnullt	_none_setRCtor_RHRAt
differencetin_(RIR=R((sT/home/tvault/.virtenv/lib/python2.7/site-packages/oslo_db/sqlalchemy/update_match.pyRHOs	cCsµ|jdd}t|ƒj}|j}|jd|ƒ}|jjrPt}nR|jjdkrœt	|j
ƒdkrœt|j
djt
jƒrœt}nt}|||||ƒS(sòPerform an UPDATE, returning the primary key of the matched row.

    The primary key is returned using a selection of strategies:

    * if the database supports RETURNING, RETURNING is used to retrieve
      the primary key values inline.

    * If the database is MySQL and the entity is mapped to a single integer
      primary key column, MySQL's last_insert_id() function is used
      inline within the UPDATE and then upon a second SELECT to get the
      value.

    * Otherwise, a "refetch" strategy is used, where a given "surrogate"
      key value (typically a UUID column on the entity) is used to run
      a new SELECT against that UUID.   This UUID is also placed into
      the UPDATE query to ensure the row matches.

    :param query: a Query object with existing criterion, against a single
     entity.

    :param values: a dictionary of values to be updated on the row.

    :param surrogate_key: a tuple of (attrname, value), referring to a
     UNIQUE attribute that will also match the row.  This attribute is used
     to retrieve the row via a SELECT when no optimized strategy exists.

    :return: the primary key, returned as a tuple.
     Is only returned if rows matched is one.  Otherwise, CantUpdateException
     is raised.

    iRR	tmysqli(R
RR	Rt
connectiontdialecttimplicit_returningt_pk_strategy_returningtnameRNR-t
isinstanceRtsqltypestIntegert!_pk_strategy_mysql_last_insert_idt_pk_strategy_refetch(RRRR!R	Rtbindtpk_strategy((sT/home/tvault/.virtenv/lib/python2.7/site-packages/oslo_db/sqlalchemy/update_match.pyRgs!			cCs?|dkr|S|dkr/td|ƒ‚ntdƒ‚dS(Nis%d rows matched; expected onesNo rows matched the UPDATE(RR(trows_updated((sT/home/tvault/.virtenv/lib/python2.7/site-packages/oslo_db/sqlalchemy/update_match.pyt_assert_single_rowšs
c
Cs~|\}}|j|j}|j||kƒj|dtƒ}t|ƒ|jj|jŒj||kƒ}|j	ƒ}	|	S(Ntsynchronize_session(
RRIRtupdateR7RbRRR-tone(
RR	RRtsurrogate_key_nametsurrogate_key_valuetsurrogate_key_coltrowcounttfetch_queryR-((sT/home/tvault/.virtenv/lib/python2.7/site-packages/oslo_db/sqlalchemy/update_match.pyR^£s
	cCs|\}}|j|j}t|||ƒ}|j||kƒ}|j|jŒ}|jj|ƒ}|j}	t	|	ƒt
|jƒƒ}
|
S(N(RRIt_update_stmt_from_querytwheret	returningR-RtexecuteRiRbttupletfirst(RR	RRRfRgRhtupdate_stmttresultRiR-((sT/home/tvault/.virtenv/lib/python2.7/site-packages/oslo_db/sqlalchemy/update_match.pyRX¹s	
cCs¹|\}}|j|j}|jd}t|||ƒ}|j||kƒ}|jitjj|ƒ|6ƒ}|j	j
|ƒ}	|	j}
t|
ƒ|j	j
tjjƒƒf}|S(Ni(RRIR-RkRlRRtfunctlast_insert_idRRnRiRbtscalar(RR	RRRfRgRhtsurrogate_pk_colRqRrRiR-((sT/home/tvault/.virtenv/lib/python2.7/site-packages/oslo_db/sqlalchemy/update_match.pyR]Ës
	
csit‡fd†|jƒDƒƒ}|jtƒ}|jƒ}|jjd}tj||j	|ƒ}|S(Nc3s(|]\}}ˆj||fVqdS(N(RE(R>R/R=(R	(sT/home/tvault/.virtenv/lib/python2.7/site-packages/oslo_db/sqlalchemy/update_match.pys	<genexpr>ãsi(
RBR*tenable_eagerloadsR7t_compile_contextt	statementtfromsRRdtwhereclause(R	RRt
upd_valuestcontextt
primary_tableRq((R	sT/home/tvault/.virtenv/lib/python2.7/site-packages/oslo_db/sqlalchemy/update_match.pyRkás		tCantUpdateExceptioncBseZRS((t__name__t
__module__(((sT/home/tvault/.virtenv/lib/python2.7/site-packages/oslo_db/sqlalchemy/update_match.pyRósRcBseZRS((R€R(((sT/home/tvault/.virtenv/lib/python2.7/site-packages/oslo_db/sqlalchemy/update_match.pyR÷sRcBseZRS((R€R(((sT/home/tvault/.virtenv/lib/python2.7/site-packages/oslo_db/sqlalchemy/update_match.pyRûs(Rt
sqlalchemyRRRRR[toslo_db.sqlalchemyRRR(RR
RDRHRRbR^RXR]Rkt	frozensetRPt	ExceptionRRR(((sT/home/tvault/.virtenv/lib/python2.7/site-packages/oslo_db/sqlalchemy/update_match.pyt<module>
s0³:'			3