Beispiel #1
0
 def _connect(self):
     """ establish the connections
     
     establish a connection to local server and shotgun
     """
     try:
         self.src = connectors.DatabaseModificator()
     except Exception, error:  #IGNORE:W0703
         debug.error("Unable to _connect to database server. " +
                     unicode(error))
         return False
Beispiel #2
0
def deleteEntity( myObj ):
    """delete an entity in couchdb and shotgun"""
    src = connectors.DatabaseModificator()
    src.changeInDB( myObj, "__retired", True )

    _createChangeEvent( src, "deletion",
                        corr_entity = myObj.getPgObj() )

    if myObj.getType() == "Task":
        pEntity = myObj.entity
        src.changeInDB( pEntity, "tasks", myObj.getSgObj(), doRemove = True )

    src.con.commit()
Beispiel #3
0
def removeCreatedChangeEvents():
    """
    method to get rid of change events that where created during unit and integration tests
    see tests_elefant.baseTest
    """
    global CREATED_CHANGE_EVENTS

#    debug.debug( CREATED_CHANGE_EVENTS )

    src = connectors.DatabaseModificator()
    cur = src.con.cursor()
    cur.execute( "DELETE FROM \"ChangeEventsToShotgun\" WHERE id = ANY(%s) AND task != %s", ( CREATED_CHANGE_EVENTS,
                                                                                              "deletion", ) )

    CREATED_CHANGE_EVENTS = []
Beispiel #4
0
def createEntity( myObj ):
    """
    create entity in local database and add corresponding change-events for shotgun-sync
    
    @return: local entity ID
    """


    src = connectors.DatabaseModificator()
    newID = src.add( myObj )

    object.__setattr__( myObj, "local_id", newID )

    _createChangeEvent( src, "creation",
                        corr_entity = myObj.getPgObj()
                        )
Beispiel #5
0
def getObject( entityType, local_id = None, remote_id = None, includeRetireds = False ):
    """ return entity of a specific type with given IDs

    :py:class:`shotgun_replica.entities.Task`

    :param entityType: either a entities-class or a string (ex. "CustomEntity22")
    :type entityType: class or str
    :param local_id: the local id of the object
    :param remote_id: the remote id (shotgun) of the object
    :param includeRetireds: include retired (deleted) objects
    
    :rtype: object or None if object not available
    """
    classObj = entityType

    if type( entityType ) == str or type( entityType ) == unicode:
        classObj = connectors.getClassOfType( entityType )
        if not classObj:
            return None

    tableName = classObj._type

    dbc = connectors.DatabaseModificator()

    filters = []

    if remote_id != None and remote_id != UNKNOWN_SHOTGUN_ID:
        filters.append( "id=%d" % remote_id )
    if local_id != None and local_id != UNKNOWN_SHOTGUN_ID:
        filters.append( "__local_id=%d" % local_id )

    if len( filters ) == 0:
        return None

    if includeRetireds:
        sqlFilter = " OR ".join( filters )
    else:
        sqlFilter = "NOT __retired AND " + " OR ".join( filters )

    resultList = dbc.getListOfEntities( tableName, sqlFilter, limit = "1" )

    if len( resultList ) == 1:
        return resultList[0]
    else:
        return None
Beispiel #6
0
def getObjects( entityType, filters = None, filterValues = None, orderby = None,
               limit = None, includeRetireds = False ):
    """ return objects of a specific type
    
    :param entityType: either a entities-class or a string (ex. "CustomEntity22")
    :type entityType: class or str
    :param filters: string with SQL-style filters (example "sg_link=%s")
    :param filterValues: list with variables that are passed to the sql-statement for %x-style variables
    :param orderby: SQL-ish order-by-string
    :param limit:  SQL-ish limit-string
    :param includeRetireds: include retired (deleted) objects
    
    :rtype: array with matching entities
    """

    if type( entityType ) == str or type( entityType ) == unicode:
        tableName = entityType
    else:
        tableName = entityType._type

    dbc = connectors.DatabaseModificator()
    pgFilterValues = []
    if filterValues != None:
        for filterValue in filterValues:
            pgFilterValues.append( connectors.getPgObj( filterValue ) )

    if not includeRetireds:
        if filters == None:
            filters = "NOT __retired"
        else:
            filters = "NOT __retired AND ( " + filters + " )"

    resultList = dbc.getListOfEntities( tableName,
                                       filters,
                                       variables = pgFilterValues,
                                       order = orderby,
                                       limit = limit )
    return resultList
Beispiel #7
0
def changeEntity( myObj, changes ):
    """change entity in local database and add corresponding change-events for shotgun-sync"""

#    myObj.reload()

    src = connectors.DatabaseModificator()
    src.changeInDB( myObj, changes = changes )

    for ( key, value ) in changes.iteritems():
        if type( value ) == datetime.datetime:
            changes[key] = value.strftime( "%Y-%m-%d %H:%M:%S" )
        if type( value ) == datetime.date:
            changes[key] = value.strftime( "%Y-%m-%d" )
        elif type( value ) == datetime.timedelta:
            changes[key] = float( value.days ) * 24 + float( value.seconds ) / 3600
        elif type( value ) == connectors.PostgresEntityType:
            changes[key] = value.getShortDict()
        elif isinstance( value, base_entity.ShotgunBaseEntity ):
            changes[key] = value.getShortDict()
        elif type( value ) == type( [] ):
            changes[key] = []
            for entry in value:
                if isinstance( entry, base_entity.ShotgunBaseEntity ) or type( entry ) == connectors.PostgresEntityType:
                    changes[key].append( entry.getShortDict() )
                else:
                    changes[key].append( entry )




            attributeName = key
            fieldValues = value
            entityType = myObj.getType()

            connEntityName = entityNaming.getConnectionEntityName( entityType, attributeName )

            if connEntityName != None:

                reverseAttribute = entityNaming.getReverseAttributeName( entityType, attributeName )
                linkedEntityType = myObj.shotgun_fields[attributeName]["properties"]["valid_types"]["value"][0]
                baseEntityType = entityType

                ( baseAttrName, linkedAttrName ) = entityNaming.getConnectionEntityAttrName( baseEntityType,
                                                                                         linkedEntityType,
                                                                                         connEntityName )

                basePgObj = myObj.getPgObj()

                # get connections
                filters = "%s=%s" % ( baseAttrName,
                                      "%s"
                                      )
                filterValues = [ basePgObj ]
                connections = factories.getObjects( connEntityName,
                                                    filters,
                                                    filterValues )

                # create new connection entities
                for linkedDict in changes[key]:
                    linkedPostgresObj = getPgObj( linkedDict )
                    fieldNames = [ baseAttrName, linkedAttrName ]
                    fieldValues = [ basePgObj, linkedPostgresObj ]

                    # check if existing first
                    connectionExists = False
                    for i in range( len( connections ) ):
                        connection = connections[i]
                        if connection.getRawField( linkedAttrName ) == linkedPostgresObj:
                            connections.remove( connection )
                            connectionExists = True
                            break

                    if not connectionExists:
                        debug.debug( dict( zip( fieldNames, fieldValues ) ), prefix = "OOOOOOOOO" )
                        src._addToDatabase( connEntityName, fieldValues, fieldNames )

                    # setting reverse attribute as well
                    linkedObj = factories.getObject( linkedDict["type"],
                                                     local_id = linkedDict["__local_id"],
                                                     remote_id = linkedDict["id"] )
                    retValues = linkedObj.getRawField( reverseAttribute )

                    if retValues == None:
                        retValues = []

                    if basePgObj not in retValues:
                        retValues.append( basePgObj )
                        src.changeInDB( linkedObj, reverseAttribute, retValues )


                # delete unused connection entities

                for connection in connections:
                    linkedObj = connection.getField( linkedAttrName )
                    retValues = linkedObj.getRawField( reverseAttribute )

                    retValues.remove( basePgObj )
                    src.changeInDB( linkedObj, reverseAttribute, retValues )
                    src.delete( connection )


    _createChangeEvent( src, "change",
                        corr_entity = myObj.getPgObj(),
                        changed_values = json.dumps( changes )
                        )

    return myObj