Execute the callable, selecting and marking the new winning revision.

@param db the database to execute the callable against
@throws DocumentStoreException
513309
@Override
    public Void call(SQLDatabase db) throws DocumentStoreException {

         /*
         Pick winner and mark the appropriate revision with the 'current' flag set
         - There can only be one winner in a tree (or set of trees - if there is no common root)
           at any one time, so if there is a new winner, we only have to mark the old winner as
           no longer 'current'. This is the 'previousWinner' object
         - The new winner is determined by:
           * consider only non-deleted leafs
           * sort according to the CouchDB sorting algorithm: highest rev wins, if there is a tie
             then do a lexicographical compare of the revision ID strings
           * we do a reverse sort (highest first) and pick the 1st and mark it 'current'
           * special case: if all leafs are deleted, then apply sorting and selection criteria
             above to all leafs
         */

        // first get all non-deleted leafs
        SortedMap<String, Long> leafs = new TreeMap<String, Long>(Collections.reverseOrder(new
                GenerationComparator()));

        Cursor cursor = null;
        try {
            cursor = db.rawQuery(GET_NON_DELETED_LEAFS, new String[]{Long.toString(docNumericId)});
            while (cursor.moveToNext()) {
                leafs.put(cursor.getString(0), cursor.getLong(1));
            }
        } catch (SQLException sqe) {
            throw new DocumentStoreException("Exception thrown whilst trying to fetch non-deleted " +
                    "leaf nodes.", sqe);
        } finally {
            DatabaseUtils.closeCursorQuietly(cursor);
        }

        // this is a corner case - all leaf nodes are deleted
        // re-get with the same query but without the revs.delete clause
        if (leafs.size() == 0) {
            try {
                cursor = db.rawQuery(GET_ALL_LEAFS, new String[]{Long.toString(docNumericId)});
                while (cursor.moveToNext()) {
                    leafs.put(cursor.getString(0), cursor.getLong(1));
                }
            } catch (SQLException sqe) {
                throw new DocumentStoreException("Exception thrown whilst trying to fetch all leaf " +
                        "nodes.", sqe);
            } finally {
                DatabaseUtils.closeCursorQuietly(cursor);
            }
        }

        // new winner will be at the top of the list
        long newWinnerSeq = leafs.get(leafs.firstKey());
        // set current=1 for winning sequence
        ContentValues currentTrue = new ContentValues();
        currentTrue.put("current", 1);
        db.update("revs", currentTrue,
                "sequence=?", new String[]{Long.toString(newWinnerSeq)});
        // set current=0 for all other leaf sequences with this doc_id
        ContentValues currentFalse = new ContentValues();
        currentFalse.put("current", 0);
        db.update("revs", currentFalse,
                "sequence!=? AND doc_id=? AND sequence NOT IN " +
                        "(SELECT DISTINCT parent FROM revs revs_inner WHERE parent NOT NULL AND revs_inner.doc_id=revs.doc_id)",
                new String[]{Long.toString(newWinnerSeq), Long.toString(docNumericId)});
        return null;
    }
8635
public static ODatabaseDocument castToODatabaseDocument(ODatabase<?> db)
	{
		while(db!=null && !(db instanceof ODatabaseDocument))
		{
			if(db instanceof ODatabaseInternal<?>)
			{
				db = ((ODatabaseInternal<?>)db).getUnderlying();
			}
		}
		return (ODatabaseDocument)db;
	}
642588
public void doAdd(Rec record) throws DBException
    {
        try   {
            m_objLastModBookmark = m_tableRemote.add(this.getDataSource(), record.getOpenMode());
        } catch (RemoteException ex) {
            throw new DBException(ex.getMessage());
        }
    }
1018019
private void executeStatement(String statement) throws SQLException {

        Statement stmt = null;

        try {
            stmt = m_con.createStatement();
            stmt.execute(statement);
        } finally {
            if (stmt != null) {
                stmt.close();
            }
        }
    }
298670
public void runResultHandlers(ResultHierarchy hier, Database db) {
    // Run result handlers
    for(ResultHandler resulthandler : resulthandlers) {
      Thread.currentThread().setName(resulthandler.toString());
      resulthandler.processNewResult(hier, db);
    }
  }
765691
public void doOpen() throws DBException
    {
        try   {
    // FROM is automatic, since the remote BaseRecord is exactly the same as this one
    // ORDER BY
            KeyArea keyArea = this.getRecord().getKeyArea(-1);  // Current index
            String strKeyArea = null;
            boolean bDirection = DBConstants.ASCENDING;
            if (true)
            {
                strKeyArea = keyArea.getKeyName();
                bDirection = keyArea.getKeyField(DBConstants.MAIN_KEY_FIELD).getKeyOrder();
            }
            m_bDirectionCurrent = bDirection;
    // Open mode
            int iOpenMode = this.getRecord().getOpenMode();
    // SELECT (fields to select)
            String strFields = null;
            if (true) // All selected?
            {
                strFields = this.getRecord().getSQLFields(DBConstants.SQL_SELECT_TYPE, true);
                if (strFields.equals(" *"))
                    strFields = null; // Select all
            }
    // WHERE XYZ >=
            Object objInitialKey = null;
            if (true)
            {
                BaseBuffer buffer = new VectorBuffer(null);
                this.getRecord().handleInitialKey();
                if (keyArea.isModified(DBConstants.START_SELECT_KEY))
                {   // Anything set?
                    keyArea.setupKeyBuffer(buffer, DBConstants.START_SELECT_KEY, false);
                    objInitialKey = buffer.getPhysicalData();
                    buffer.addNextString(Integer.toString(keyArea.lastModified(DBConstants.START_SELECT_KEY, false))); // Largest modified field.
                }
            }
    // WHERE XYZ <=
            Object objEndKey = null;
            if (true)
            {
                BaseBuffer buffer = new VectorBuffer(null);
                this.getRecord().handleEndKey();
                if (keyArea.isModified(DBConstants.END_SELECT_KEY))
                {   // Anything set?
                    keyArea.setupKeyBuffer(buffer, DBConstants.END_SELECT_KEY, false);
                    objEndKey = buffer.getPhysicalData();
                    buffer.addNextString(Integer.toString(keyArea.lastModified(DBConstants.END_SELECT_KEY, false))); // Largest modified field.
                }
            }
    // WHERE XYZ
            byte[] byBehaviorData = null;
            boolean bDirty = false;
            if (this.getRecord().getListener() != null)
            {
                ByteArrayOutputStream baOut = new ByteArrayOutputStream();
                ObjectOutputStream daOut = new ObjectOutputStream(baOut);
                FileListener listener = (FileListener)this.getRecord().getListener();
                while (listener != null)
                {
                    if ((listener.getMasterSlaveFlag() & FileListener.RUN_IN_SLAVE) != 0) // Should exist in a SERVER environment
                        if ((listener.getMasterSlaveFlag() & FileListener.DONT_REPLICATE_TO_SLAVE) == 0) // Yes, replicate to the SERVER environment
                            if (listener.isEnabledListener()) // Yes, only replicate enabled listeners.
                    { // There should be a copy of this on the server
                        bDirty = true;
                        daOut.writeUTF(listener.getClass().getName());
                        listener.initRemoteStub(daOut);
                    }
                    listener = (FileListener)listener.getNextListener();
                }
                daOut.flush();
                if (bDirty)
                    byBehaviorData = baOut.toByteArray();
                daOut.close();
                baOut.close();
            }

            this.checkCacheMode(Boolean.TRUE);      // Make sure the cache is set up correctly for this type of query (typically needed)

            synchronized (this.getSyncObject())
            {   // In case this is called from another task
                m_tableRemote.open(strKeyArea, iOpenMode, bDirection, strFields, objInitialKey, objEndKey, byBehaviorData);
            }
        } catch (Exception ex) {
            throw DatabaseException.toDatabaseException(ex);
        }
    }
758075
@Override
    public boolean execute( String sql ) throws SQLException {
        notClosed();
        warning = null;
        moreResults = 0;
        try {
            // Convert the supplied SQL into JCR-SQL2 ...
            String jcrSql2 = connection.nativeSQL(sql);
            // Create the query ...
            final QueryResult jcrResults = getJcrRepositoryDelegate().execute(jcrSql2, this.sqlLanguage);
            results = new JcrResultSet(this, jcrResults, null);
            moreResults = 1;
        } catch (RepositoryException e) {
            throw new SQLException(e.getLocalizedMessage(), e);
        }
        return true; // always a ResultSet
    }
904989
public synchronized void updateDocumentInfo(Document docvo) throws SQLException {
        if (cache_document==CACHE_OFF) {
            edadb.updateDocumentInfo(docvo);
        } else if (cache_document==CACHE_ONLY) {
            Document docvo0 = documentCache.get(docvo.getDocumentId());
            docvo0.setDocumentType(docvo.getDocumentType());
            docvo0.setOwnerId(docvo.getOwnerId());
            docvo0.setOwnerType(docvo.getOwnerType());
        } else {
            edadb.updateDocumentInfo(docvo);
            Document docvo0 = documentCache.get(docvo.getDocumentId());
            if (docvo0!=docvo) {
                docvo0.setDocumentType(docvo.getDocumentType());
                docvo0.setOwnerId(docvo.getOwnerId());
                docvo0.setOwnerType(docvo.getOwnerType());
            }
        }
    }
1109701
public void execute(Runnable statements)
	{
		try (HibernateTransaction tx = start().withAutoRollback())
		{
			statements.run();

			// Success, perform a TX commit
			tx.commit();
		}
	}
1030949
@Override
  protected void updateEntity(DbEntityOperation operation) {

    final DbEntity dbEntity = operation.getEntity();

    String updateStatement = dbSqlSessionFactory.getUpdateStatement(dbEntity);
    ensureNotNull("no update statement for " + dbEntity.getClass() + " in the ibatis mapping files", "updateStatement", updateStatement);

    LOG.executeDatabaseOperation("UPDATE", dbEntity);

    if (Context.getProcessEngineConfiguration().isJdbcBatchProcessing()) {
      // execute update
      executeUpdate(updateStatement, dbEntity);
    } else {
      // execute update
      int numOfRowsUpdated = executeUpdate(updateStatement, dbEntity);

      if (dbEntity instanceof HasDbRevision) {
        if (numOfRowsUpdated != 1) {
          // failed with optimistic locking
          operation.setFailed(true);
          return;
        } else {
          // increment revision of our copy
          HasDbRevision versionedObject = (HasDbRevision) dbEntity;
          versionedObject.setRevision(versionedObject.getRevisionNext());
        }
      }
    }

    // perform post update action
    entityUpdated(dbEntity);
  }
97399
private void createOrOpenBDBDbs() throws Exception {
		// configuration for the mapping dbs
		DatabaseConfig dbConfig = new DatabaseConfig();
		dbConfig.setAllowCreate(true); // db will be created if it does not exist
		dbConfig.setReadOnly(readOnly);
		dbConfig.setTransactional(transactional);
		// create/open mapping dbs using config
		iidToIdDB = dbEnv.openDatabase(null, "idToName", dbConfig);

		// if countSizeOnLoad is true, the id-name mappings are counted and the loadCounter is initialized
		if (countSizeOnLoad) {
			System.out.println(new Date() + " counting index size started ");
			int idToNameMappings = (int) iidToIdDB.count();
			loadCounter = Math.min(idToNameMappings, maxNumVectors);
			System.out.println(new Date() + " counting index size ended ");
			System.out.println("Index size: " + loadCounter);
		}

		idToIidDB = dbEnv.openDatabase(null, "nameToId", dbConfig);

		if (useGeolocation) {// create/open geolocation db using config
			iidToGeolocationDB = dbEnv.openDatabase(null, "idToGeolocation", dbConfig);
		}

		if (useMetaData) {
			StoreConfig storeConfig = new StoreConfig(); // configuration of the entity store
			storeConfig.setAllowCreate(true); // store will be created if it does not exist
			storeConfig.setReadOnly(readOnly);
			storeConfig.setTransactional(transactional);
			iidToMetadataDB = new EntityStore(dbEnv, "idToMetadata", storeConfig);
			// int nameToMetadataMappings = (int) nameToMetadataBDB.getPrimaryIndex(String.class,
			// MediaFeedData.class).count(); // counting the size of an EntityStore
		}
	}
650434
private void execute(String sql) throws SQLException {
        Statement statement = connection.createStatement();
        try {
            statement.executeUpdate(substitute(sql));
        } finally {
            DbUtils.closeQuietly(statement);
        }
    }
1065524
@Override
    public void execute() throws MojoExecutionException, MojoFailureException {
        super.execute();

        // scan classes and build graph
        try {
            processClasspaths();
        } catch (Exception e) {
            throw new MojoExecutionException("Error processing entity classes", e);
        }
    }
750356
public void doSet(Record record) throws DBException
    {
        try   {
            m_pTable.set(this);
        } catch (DBException ex)    {
            throw DatabaseException.toDatabaseException(ex);
        }
    }
1155009
public void open() throws DBException
    {
        super.open();
        this.getRecord().setEditMode(DBConstants.EDIT_NONE);    // Being careful
        Iterator<BaseTable> iterator = this.getTables();
        while (iterator.hasNext())
        {
            BaseTable table = iterator.next();
            if ((table != null) && (table != this.getNextTable()))
            {
                this.syncRecordToBase(table.getRecord(), this.getRecord(), true); // Note: I am syncing the base to the alt here
                table.open();
            }
        }
    }
357721
private void returnDocumentBuilderToPool(DocumentBuilder db) {
        try {
            db.reset();
            documentBuilderPool.offerFirst(db);
        } catch (UnsupportedOperationException e) {
            // document builders that don't support reset() can't be pooled
        }
    }
921224
public static SelectionResult ensureSelectionResult(final Database db) {
    List<SelectionResult> selections = ResultUtil.filterResults(db.getHierarchy(), db, SelectionResult.class);
    if(!selections.isEmpty()) {
      return selections.get(0);
    }
    SelectionResult sel = new SelectionResult();
    ResultUtil.addChildResult(db, sel);
    return sel;
  }