Sets {@link Target#getLastTargetQuery()} by native SQL in order to avoid
raising opt lock revision as this update is not mission critical and in
fact only written by {@link ControllerManagement}, i.e. the target
itself.
769113
private void setLastTargetQuery(final String tenant, final long currentTimeMillis, final List<String> chunk) {
        final Map<String, String> paramMapping = Maps.newHashMapWithExpectedSize(chunk.size());

        for (int i = 0; i < chunk.size(); i++) {
            paramMapping.put("cid" + i, chunk.get(i));
        }

        final Query updateQuery = entityManager.createNativeQuery(
                "UPDATE sp_target SET last_target_query = #last_target_query WHERE controller_id IN ("
                        + formatQueryInStatementParams(paramMapping.keySet()) + ") AND tenant = #tenant");

        paramMapping.forEach(updateQuery::setParameter);
        updateQuery.setParameter("last_target_query", currentTimeMillis);
        updateQuery.setParameter("tenant", tenant);

        final int updated = updateQuery.executeUpdate();
        if (updated < chunk.size()) {
            LOG.error("Targets polls could not be applied completely ({} instead of {}).", updated, chunk.size());
        }
    }
550402
public Window getWindow(final String controllerId) {
        final Optional<Target> target = targetManagement.getByControllerID(controllerId);
        if (!target.isPresent()) {
            uINotification.displayWarning(i18n.getMessage("target.not.exists", controllerId));
            return null;
        }
        populateValuesOfTarget(target.get());
        createNewWindow();
        window.setCaption(i18n.getMessage("caption.update", i18n.getMessage("caption.target")));
        window.addStyleName("target-update-window");
        return window;
    }
379418
private Target updateTargetStatus(final JpaTarget toUpdate, final URI address) {
        boolean storeEager = isStoreEager(toUpdate, address);

        if (TargetUpdateStatus.UNKNOWN.equals(toUpdate.getUpdateStatus())) {
            toUpdate.setUpdateStatus(TargetUpdateStatus.REGISTERED);
            storeEager = true;
        }

        if (storeEager || !queue.offer(new TargetPoll(toUpdate))) {
            toUpdate.setAddress(address.toString());
            toUpdate.setLastTargetQuery(System.currentTimeMillis());

            afterCommit.afterCommit(() -> eventPublisher.publishEvent(new TargetPollEvent(toUpdate, bus.getId())));

            return targetRepository.save(toUpdate);
        }

        return toUpdate;
    }
1230026
@Override
    public void setCorrupt(boolean isCorrupt)
    {
        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
            SibTr.entry(tc, "setCorrupt", Boolean.valueOf(isCorrupt));

        _targetDestinationHandler.setCorrupt(isCorrupt);

        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
            SibTr.exit(tc, "setCorrupt");
    }
1068042
private void updateLastSeenEdge(Vertex v) {
    Edge lastSeenEdge = getLastSeenEdge();
    if (lastSeenEdge != null) {
      if (lastSeenEdge.getSourceVertexId() == null) {
        lastSeenEdge.setSourceVertexId(v.getId());
      } else if (lastSeenEdge.getTargetVertexId() == null) {
        lastSeenEdge.setTargetVertexId(v.getId());
      }
    }
  }
849152
protected RemoteStatements updateNextValueQuery(NextValueRequest request) {
		return request.getKey().getMetadata().getType() == IdSourceType.TABLE
				? getTableQuery( request )
				: getSequenceIncrementQuery( request );
	}
154161
private Connection getTargetConnection(Method operation) throws SQLException {
    if (this.target == null) {
      boolean readOnly = MasterSlaveInterceptor.isReadOnly();
      // No target Connection held -> fetch one.
      if (log.isDebugEnabled()) {
        log.debug("Connecting to database for operation '" + operation.getName() + "'");
      }

      // Fetch physical Connection from DataSource.
      DruidDataSource ds = router.determineTargetDataSource(readOnly);
      TraceContext.get().setServerName(router.getConfigName()).setUrl(extractHost(ds.getUrl()));
      this.target = (this.username != null) ? ds.getConnection(this.username, this.password) : ds.getConnection();

      // If we still lack default connection properties, check them now.
      //checkDefaultConnectionProperties(this.target);

      // Apply kept transaction settings, if any.
      if (this.readOnly) {
        this.target.setReadOnly(true);
      }
      if (this.transactionIsolation != null) {
        this.target.setTransactionIsolation(this.transactionIsolation);
      }
      if (this.autoCommit != null && this.autoCommit != this.target.getAutoCommit()) {
        this.target.setAutoCommit(this.autoCommit);
      }
    } else {
      // Target Connection already held -> return it.
      if (log.isDebugEnabled()) {
        log.debug("Using existing database connection for operation '" + operation.getName() + "'");
      }
    }

    return this.target;
  }
372787
private void setLastApplied(long lastApplied) {
    // lastApplied should be either equal to or one greater than this.lastApplied.
    if (lastApplied > this.lastApplied) {
      Assert.arg(lastApplied == this.lastApplied + 1, "lastApplied must be sequential");

      this.lastApplied = lastApplied;

      // Update the index for each session. This will be used to trigger queries that are awaiting the
      // application of specific indexes to the state machine. Setting the session index may cause query
      // callbacks to be called and queries to be evaluated.
      for (ServerSessionContext session : executor.context().sessions().sessions.values()) {
        session.setLastApplied(lastApplied);
      }

      // Take a state machine snapshot if necessary.
      takeSnapshot();

      // Install a state machine snapshot if necessary.
      installSnapshot();
    } else {
      Assert.arg(lastApplied == this.lastApplied, "lastApplied cannot be decreased");
    }
  }
246634
public void preExecute() throws SQLException {
    lastQueryNanos = System.nanoTime();
    //if connection is closed or failed on slave
    if (this.currentProtocol != null && this.currentProtocol.isClosed()) {
      preAutoReconnect();
    }
  }
1051049
private boolean query()
		throws SQLException
	{
		statement = this.connection.createStatement();

		String query = "SELECT PrimaryKey, RevisionCounter,"
				+ " RevisionID, ArticleID, Timestamp, FullRevisionID "
				+ "FROM revisions";

		if (primaryKey > 0) {
			query += " WHERE PrimaryKey > " + primaryKey;
		}

		if (MAX_NUMBER_RESULTS > 0) {
			query += " LIMIT " + MAX_NUMBER_RESULTS;
		}

		result = statement.executeQuery(query);
		return result.next();
	}
908323
private function setLastInsertId(QueryBuilder $query)
    {
        $seq = null;
        if ($query->getConnection()->getDatabasePlatform()->getName() === 'postgresql') {
            $sequences = $query->getConnection()->getSchemaManager()->listSequences();
            $desiredSeq = $query->getQueryPart('from')['table'] . '_id_seq';
            foreach ($sequences as $sequence) {
                if ($desiredSeq === $sequence->getName()) {
                    $seq = $desiredSeq;
                    break;
                }
            }
            if ($seq === null) {
                return;
            }
        }
        $this->lastInsertId = $query->getConnection()->lastInsertId($seq);
    }
28236
public boolean execUpdateByRawSQL(String updateRawSQL) {

    boolean retVal = false;

    log("#execUpdateByRawSQL updateRawSQL=" + updateRawSQL);

    final Connection conn = createConnection();

    try {

      Statement stmt = null;

      // There is a possibility that the error occurs in one single update
      // statement.
      // Therefore, turn the auto commit off.
      conn.setAutoCommit(false);

      stmt = conn.createStatement();
      stmt.executeUpdate(updateRawSQL);

      // finally,commit
      conn.commit();

      retVal = true;

    } catch (SQLException e) {

      loge("#execUpdateByRawSQL", e);
      retVal = false;

    } finally {

      try {
        conn.close();
      } catch (SQLException e) {
        retVal = false;
        loge("#execUpdateByRawSQL", e);
      }
    }
    return retVal;

  }
1006181
public void updateQuery(QueryControllerQuery query) {
		int position = getElementPosition(query.getID());
		queries.set(position, query);
	}
37255
public void fetchRemaining() throws SQLException {
    if (!isEof) {
      lock.lock();
      try {
        lastRowPointer = -1;
        while (!isEof) {
          addStreamingValue();
        }

      } catch (SQLException queryException) {
        throw ExceptionMapper.getException(queryException, null, statement, false);
      } catch (IOException ioe) {
        throw handleIoException(ioe);
      } finally {
        lock.unlock();
      }
      dataFetchTime++;
    }
  }
906891
public static <M extends Model> Updater<M> withUpdater(String sql) {
        return withUpdater(DataSourceManager.getDefaultDataSourceName(), sql);
    }
457231
private boolean targetContainsInstance(GraqlCompute.Statistics.Value query) {
        for (Label attributeType : targetTypeLabels(query)) {
            for (Label type : scopeTypeLabels(query)) {
                Boolean patternExist = tx.stream(Graql.match(
                        Graql.var("x").has(attributeType.getValue(), Graql.var()),
                        Graql.var("x").isa(Graql.type(type.getValue()))
                ), false).iterator().hasNext();
                if (patternExist) return true;
            }
        }
        return false;
        //TODO: should use the following ask query when ask query is even lazier
//        List<Pattern> checkResourceTypes = statisticsResourceTypes.stream()
//                .map(type -> var("x").has(type, var())).collect(Collectors.toList());
//        List<Pattern> checkSubtypes = inTypes.stream()
//                .map(type -> var("x").isa(Graql.label(type))).collect(Collectors.toList());
//
//        return tx.get().graql().infer(false)
//                .match(or(checkResourceTypes), or(checkSubtypes)).get().aggregate(ask()).execute();
    }
334874
protected String getLastQueryParam() {

        String param = parseOptionalStringValue(m_configObject, JSON_KEY_LAST_QUERYPARAM);
        if (param == null) {
            return null != m_baseConfig
            ? m_baseConfig.getGeneralConfig().getLastQueryParam()
            : DEFAULT_LAST_QUERY_PARAM;
        } else {
            return param;
        }
    }