We are lock-happy here but SQL performance is not currently an issue daemon-side.
778887
def locked_execute(self, sql, parameters = None, cursorClass = DictCursor, quiet = False):
		'''''' 
		return self.execute(sql, parameters, cursorClass, quiet = quiet, locked = True)
978571
def flushdb(self, async_op=False):
        
        if async_op:
            fut = self.execute(b'FLUSHDB', b'ASYNC')
        else:
            fut = self.execute(b'FLUSHDB')
        return wait_ok(fut)
542367
function updateSqliteStats(unit){
	if (count_writes === 1){
		start_time = Date.now();
		prev_time = Date.now();
	}
	if (count_writes % 100 !== 0)
		return;
	var STATS_CHUNK_SIZE = 1000;
	if (count_writes % STATS_CHUNK_SIZE === 0){
		var total_time = (Date.now() - start_time)/1000;
		var recent_time = (Date.now() - prev_time)/1000;
		var recent_tps = STATS_CHUNK_SIZE/recent_time;
		var avg_tps = count_writes/total_time;
		prev_time = Date.now();
	//	console.error(count_writes+" units done in "+total_time+" s, recent "+recent_tps+" tps, avg "+avg_tps+" tps, unit "+unit);
	}
	if (conf.storage !== 'sqlite' || bDbTooBig)
		return;
	db.query("SELECT MAX(rowid) AS count_units FROM units", function(rows){
		var count_units = rows[0].count_units;
		if (count_units > 500000){ // the db is too big
			bDbTooBig = true;
			return;
		}
		readCountOfAnalyzedUnits(function(count_analyzed_units){
			console.log('count analyzed units: '+count_analyzed_units);
			if (count_units < 2*count_analyzed_units)
				return;
			count_units_in_prev_analyze = count_units;
			console.log("will update sqlite stats");
			db.query("ANALYZE", function(){
				db.query("ANALYZE sqlite_master", function(){
					console.log("sqlite stats updated");
				});
			});
		});
	});
}
1013917
@Override
    public ResultSet executeQuery(String sql) throws SQLException {
        boolean isOk = false;

        try {
            final ResultSet result = wrap(internalStmt.executeQuery(sql));
            isOk = true;
            return result;
        } finally {
            poolableConn.updateLastSQLExecutionTime(isOk);
        }
    }
1125963
private void upgradeLockIfNeeded()
    {
        // using clone to avoid ConcurentModificationException
        Iterator iter = ((List) mvOrderOfIds.clone()).iterator();
        TransactionImpl tx = getTransaction();
        ObjectEnvelope mod;
        while(iter.hasNext())
        {
            mod = (ObjectEnvelope) mhtObjectEnvelopes.get(iter.next());
            // ignore transient objects
            if(!mod.getModificationState().isTransient())
            {
                /*
                now we check if all modified objects has a write lock. On insert of new
                objects we don't need a write lock.
                */
                if(!mod.needsInsert())
                {
                    if((mod.needsDelete() || mod.needsUpdate()
                            || mod.hasChanged(tx.getBroker())))
                    {
                        needsCommit = true;
                        // mark object dirty
                        mod.setModificationState(mod.getModificationState().markDirty());
                        ClassDescriptor cld = mod.getClassDescriptor();
                        // if the object isn't already locked, we will do it now
                        if(!mod.isWriteLocked())
                        {
                            tx.doSingleLock(cld, mod.getObject(), mod.getIdentity(), Transaction.WRITE);
                        }
                    }
                }
                else
                {
                    needsCommit = true;
                }
            }
        }
    }
1090869
def save_performance(db, job_id, records):
    
    # NB: rec['counts'] is a numpy.uint64 which is not automatically converted
    # into an int in Ubuntu 12.04, so we convert it manually below
    rows = [(job_id, rec['operation'], rec['time_sec'], rec['memory_mb'],
             int(rec['counts'])) for rec in records]
    db.insert('performance',
              'job_id operation time_sec memory_mb counts'.split(), rows)
563508
def fetch(self, sql, *args, **kwargs):
        
        with self.locked() as conn:
            return conn.query(sql, *args, **kwargs).fetch()
965359
function updateSqliteStats(){
	if (count_writes % 100 !== 0)
		return;
	db.query("SELECT MAX(rowid) AS count_units FROM units", function(rows){
		var count_units = rows[0].count_units;
		if (count_units > 500000) // the db is too big, anaylze will lock db for long time,skip it from now on.
			return;
		readCountOfAnalyzedUnits(function(count_analyzed_units){
			console.log('count analyzed units: '+count_analyzed_units);
			if (count_units < 2*count_analyzed_units)
				return;
			count_units_in_prev_analyze = count_units;
			console.log("will update sqlite stats");
			db.query("ANALYZE", function(){
				db.query("ANALYZE sqlite_master", function(){
					console.log("sqlite stats updated");
				});
			});
		});
	});
}
497017
def _compile_lock(self, query, value):
        
        if isinstance(value, basestring):
            return value

        if value is True:
            return 'FOR UPDATE'
        elif value is False:
            return 'LOCK IN SHARE MODE'
411781
private boolean isLocked(Class entityType, String entityKey) throws LockingException {
        return isLocked(entityType, entityKey, null);
    }
1039446
private void doMacLockRequestWorkaround( final ITransaction transaction, final WebdavRequest req, final WebdavResponse resp )
        throws LockFailedException, IOException
    {
        LockedObject lo;
        final int depth = getDepth( req );
        int lockDuration = getTimeout( transaction, req );
        if ( lockDuration < 0 || lockDuration > MAX_TIMEOUT )
        {
            lockDuration = DEFAULT_TIMEOUT;
        }

        boolean lockSuccess = false;
        lockSuccess = _resourceLocks.exclusiveLock( transaction, _path, _lockOwner, depth, lockDuration );

        if ( lockSuccess )
        {
            // Locks successfully placed - return information about
            lo = _resourceLocks.getLockedObjectByPath( transaction, _path );
            if ( lo != null )
            {
                generateXMLReport( transaction, resp, lo );
            }
            else
            {
                resp.sendError( SC_INTERNAL_SERVER_ERROR );
            }
        }
        else
        {
            // Locking was not successful
            sendLockFailError( transaction, req, resp );
        }
    }
150317
def long_running_queries(self):
        

        if self.is_pg_at_least_nine_two():
            idle = "AND state <> 'idle'"
        else:
            idle = "AND current_query <> '<IDLE>'"

        return self.execute(
            sql.LONG_RUNNING_QUERIES.format(
                pid_column=self.pid_column,
                query_column=self.query_column,
                idle=idle
            )
        )
776689
@GuardedBy("lock")
    protected int computeIndex(long seqno) {
        int diff=(int)(seqno - offset);
        if(diff < 0)
            return diff;
        return diff & (elements_per_row - 1); // same as mod, but (apparently, I'm told) more efficient
    }
972290
function fast_fetch($sql, $resulttype = MYSQLI_ASSOC)
	{
		$recset = $this->query($sql, MYSQLI_USE_RESULT);	//	MYSQLI_USE_RESULT was about 12% faster than MYSQLI_STORE_RESULT
		$result = $recset->fetch_all($resulttype); // MYSQLI_ASSOC || MYSQLI_NUM || MYSQLI_BOTH
		$recset->free();
		return $result;
	}
119211
private List<Metric> checkAlive(final Connection c, final ICommandLine cl) throws BadThresholdException, SQLException {

        List<Metric> metricList = new ArrayList<Metric>();
        Statement stmt = null;
        ResultSet rs = null;
        
        long lStart = System.currentTimeMillis();

        try {
            stmt = c.createStatement();
            rs = stmt.executeQuery(QRY_CHECK_ALIVE);

            if (!rs.next()) {
                // Should never happen...
                throw new SQLException("Unable to execute a 'SELECT SYSDATE FROM DUAL' query");
            }

            long elapsed = (System.currentTimeMillis() - lStart) / 1000L;

            metricList.add(new Metric("conn", "Connection time : " + elapsed + "s", new BigDecimal(elapsed), new BigDecimal(0), null));

            return metricList;

        } finally {
            DBUtils.closeQuietly(rs);
            DBUtils.closeQuietly(stmt);
        }
    }
577731
def ensure_on():
    
    if get_status() == 'not-running':
        if config.dbserver.multi_user:
            sys.exit('Please start the DbServer: '
                     'see the documentation for details')
        # otherwise start the DbServer automatically; NB: I tried to use
        # multiprocessing.Process(target=run_server).start() and apparently
        # it works, but then run-demos.sh hangs after the end of the first
        # calculation, but only if the DbServer is started by oq engine (!?)
        subprocess.Popen([sys.executable, '-m', 'openquake.server.dbserver',
                          '-l', 'INFO'])

        # wait for the dbserver to start
        waiting_seconds = 30
        while get_status() == 'not-running':
            if waiting_seconds == 0:
                sys.exit('The DbServer cannot be started after 30 seconds. '
                         'Please check the configuration')
            time.sleep(1)
            waiting_seconds -= 1
600706
function(transaction, results) {
    if (ydn.db.core.req.CachedWebsqlCursor.DEBUG) {
      goog.global.console.log([sql, results]);
    }
    me.has_pending_request = false;
    me.cursor_ = results;
    me.current_cursor_index_ = 0;
    if (!!me.index_name && goog.isDefAndNotNull(ini_key)) {
      // skip them
      var cmp = ydn.db.cmp(me.getPrimaryKey(), ini_key);
      while (cmp == -1 || (cmp == 0 && exclusive)) {
        me.current_cursor_index_++;
        cmp = ydn.db.cmp(me.getPrimaryKey(), ini_key);
      }
    }
    me.onSuccess(me.getPrimaryKey(), me.getIndexKey(), me.getValue());
  }