Returns true for Oracle adapter (since Oracle requires primary key
 values to be pre-fetched before insert).
 @see #next_sequence_value
 @override
340483
def prefetch_primary_key?(table_name = nil)
      return true if table_name.nil?
      do_not_prefetch_hash = @@do_not_prefetch_primary_key
      do_not_prefetch = do_not_prefetch_hash[ table_name = table_name.to_s ]
      if do_not_prefetch.nil?
        owner, desc_table_name, db_link = @connection.describe(table_name, default_owner)
        do_not_prefetch_hash[table_name] = do_not_prefetch =
          ! has_primary_key?(table_name, owner, desc_table_name, db_link) ||
          has_primary_key_trigger?(table_name, owner, desc_table_name, db_link)
      end
      ! do_not_prefetch
    end
1052105
public void checkOrRepairSequence(final int partition, final long nextSequence, final boolean viaAntiEntropy) {
        assert nextSequence > 0;

        MetaDataContainer metaData = getMetaDataContainer(partition);
        while (true) {
            final long currentSequence = metaData.getSequence();
            if (currentSequence >= nextSequence) {
                break;
            }
            if (metaData.casSequence(currentSequence, nextSequence)) {
                final long sequenceDiff = nextSequence - currentSequence;
                if (viaAntiEntropy || sequenceDiff > 1L) {
                    // we have found at least one missing sequence between current and next sequences. if miss is detected by
                    // anti-entropy, number of missed sequences will be `miss = next - current`, otherwise it means miss is
                    // detected by observing received invalidation event sequence numbers and number of missed sequences will be
                    // `miss = next - current - 1`.
                    final long missCount = viaAntiEntropy ? sequenceDiff : sequenceDiff - 1;
                    final long totalMissCount = metaData.addAndGetMissedSequenceCount(missCount);

                    if (logger.isFinestEnabled()) {
                        logger.finest(format("%s:[map=%s,partition=%d,currentSequence=%d,nextSequence=%d,totalMissCount=%d]",
                                "Invalid sequence", name, partition, currentSequence, nextSequence, totalMissCount));
                    }
                }
                break;
            }
        }
    }
689234
protected boolean _load ()
    {
        java.sql.ResultSet rs = null;
        try
        {
            
            // This synchronization is necessary for Oracle JDBC drivers 8.1.7, 9.0.1, 9.2.0.1
            // The documentation says synchronization is done within the driver, but they
            // must have overlooked something. Without the lock we'd get mysterious error
            // messages.            
            synchronized(getDbMeta())
            {
            
                getDbMetaTreeModel().setStatusBarMessage("Reading schemas for catalog " 
                    + this.getAttribute(ATT_CATALOG_NAME));
                rs = getDbMeta().getSchemas();
                final java.util.ArrayList alNew = new java.util.ArrayList();
                int count = 0;
                while (rs.next())
                {
                    getDbMetaTreeModel().setStatusBarMessage("Creating schema " + getCatalogName() + "." + rs.getString("TABLE_SCHEM"));
                    alNew.add(new DBMetaSchemaNode(getDbMeta(),
                                                   getDbMetaTreeModel(),
                                                   DBMetaCatalogNode.this, 
                                                   rs.getString("TABLE_SCHEM")));
                    count++;
                }
                if (count == 0) 
                    alNew.add(new DBMetaSchemaNode(getDbMeta(), 
                                                   getDbMetaTreeModel(),
                                                   DBMetaCatalogNode.this, null));
                alChildren = alNew;            
                javax.swing.SwingUtilities.invokeLater(new Runnable()
                {
                    public void run()
                    {
                        getDbMetaTreeModel().nodeStructureChanged(DBMetaCatalogNode.this);
                    }
                });
                rs.close();
            }
        }
        catch (java.sql.SQLException sqlEx)
        {
            getDbMetaTreeModel().reportSqlError("Error retrieving schemas", sqlEx);
            try
            {
                if (rs != null) rs.close ();
            }
            catch (java.sql.SQLException sqlEx2)
            {
                this.getDbMetaTreeModel().reportSqlError("Error retrieving schemas", sqlEx2);
            }                        
            return false;
        }
        return true;
    }
1193131
@Override
	public Record nextRecord(Record record) {
		try {
			resultSet.next();
			ResultSetMetaData rsmd = resultSet.getMetaData();
			int column_count = rsmd.getColumnCount();
			record.setNumFields(column_count);

			for (int pos = 0; pos < column_count; pos++) {
				int type = rsmd.getColumnType(pos + 1);
				retrieveTypeAndFillRecord(pos, type, record);
			}
			return record;
		} catch (SQLException e) {
			throw new IllegalArgumentException("Couldn't read data:\t" + e.getMessage());
		} catch (NotTransformableSQLFieldException e) {
			throw new IllegalArgumentException("Couldn't read data because of unknown column sql-type:\t"
				+ e.getMessage());
		} catch (NullPointerException e) {
			throw new IllegalArgumentException("Couldn't access resultSet:\t" + e.getMessage());
		}
	}
134672
private boolean isMoreToReadBeforeReadingRecord(
      final SequenceOffsetType recordSequenceNumber,
      final SequenceOffsetType endSequenceNumber
  )
  {
    final int compareToEnd = createSequenceNumber(recordSequenceNumber)
        .compareTo(createSequenceNumber(endSequenceNumber));

    return isEndOffsetExclusive() ? compareToEnd < 0 : compareToEnd <= 0;
  }
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();
	}
564002
def before_insert(mapper, conn, target):
        """"""

        # from identity import ObjectNumber
        # assert not target.fk_vid or not ObjectNumber.parse(target.fk_vid).revision

        if target.sequence_id is None:
            from ambry.orm.exc import DatabaseError
            raise DatabaseError('Must have sequence_id before insertion')

        # Check that the id column is always sequence id 1
        assert (target.name == 'id') == (target.sequence_id == 1), (target.name, target.sequence_id)

        Column.before_update(mapper, conn, target)
1112907
public boolean next(Long key, Row value) throws IOException
    {
        if (nextKeyValue())
        {
            ((WrappedRow)value).setRow(getCurrentValue());
            return true;
        }
        return false;
    }
1345895
public boolean nextIsNull(long currentRow) throws IOException {
    if (present != null) {
      seekToPresentRow(currentRow);
      valuePresent = present.next() == 1;
      if (valuePresent) {
        // Adjust numNonNulls so we know how many non-null values we'll need to skip if skip is
        // called
        numNonNulls++;
      } else {
        if (currentRow == previousRow + 1) {
          // if currentRow = previousRow + 1, and the value is null this is equivalent to going to the
          // next row.  if there's a series of nulls this prevents us from calling skipRows when
          // the next non-null value is fetched
          previousRow++;
        }
      }
    }

    return !valuePresent;
  }
595919
def reset_pk_sequence!(table, pk = nil, sequence = nil) #:nodoc:
      unless pk and sequence
        default_pk, default_sequence = pk_and_sequence_for(table)
        pk ||= default_pk
        sequence ||= default_sequence
      end
      if pk
        if sequence
          quoted_sequence = quote_column_name(sequence)

          select_value <<-end_sql, 'Reset sequence'
              SELECT setval('#{quoted_sequence}', (SELECT COALESCE(MAX(#{quote_column_name pk})+(SELECT increment_by FROM #{quoted_sequence}), (SELECT min_value FROM #{quoted_sequence})) FROM #{quote_table_name(table)}), false)
            end_sql
        else
          @logger.warn "#{table} has primary key #{pk} with no default sequence" if @logger
        end
      end
    end
787696
private boolean isRecordAlreadyExistsException(SQLException e)
   {
      // Search in UPPER case
      // MySQL 5.0.x - com.mysql.jdbc.exceptions.MySQLIntegrityConstraintViolationException:
      // Duplicate entry '4f684b34c0a800030018c34f99165791-0' for key 1
      // HSQLDB 8.x - java.sql.SQLException: Violation of unique constraint $$: duplicate value(s) for
      // column(s) $$:
      // JCR_VCAS_PK in statement [INSERT INTO JCR_VCAS (PROPERTY_ID, ORDER_NUM, CAS_ID)
      // VALUES(?,?,?)]         String H2_PK_CONSTRAINT_DETECT_PATTERN = "(.*JdbcSQLException.*violation.*PRIMARY_KEY_.*)";
      // PostgreSQL 8.2.x - org.postgresql.util.PSQLException: ERROR: duplicate key violates unique
      // constraint "jcr_vcas_pk"
      // Oracle 9i x64 (on Fedora 7) - java.sql.SQLException: ORA-00001: unique constraint
      // (EXOADMIN.JCR_VCAS_PK) violated
      // H2 - org.h2.jdbc.JdbcSQLException: Unique index or primary key violation: 
      // "PRIMARY_KEY_4 ON PUBLIC.JCR_VCAS_TEST(PROPERTY_ID, ORDER_NUM)"; 
      //
      String err = e.toString();
      if (dialect.startsWith(DBConstants.DB_DIALECT_MYSQL))
      {
         // for MySQL will search
         return MYSQL_PK_CONSTRAINT_DETECT.matcher(err).find();
      }
      else if (err.toLowerCase().toUpperCase().indexOf(sqlConstraintPK.toLowerCase().toUpperCase()) >= 0)
      {
         // most of supported dbs prints PK name in exception
         return true;
      }
      else if (dialect.startsWith(DBConstants.DB_DIALECT_DB2))
      {
         return DB2_PK_CONSTRAINT_DETECT.matcher(err).find();
      }
      else if (dialect.startsWith(DBConstants.DB_DIALECT_H2))
      {
         return H2_PK_CONSTRAINT_DETECT.matcher(err).find();
      }

      // NOTICE! As an additional check we may ask the database for property currently processed in
      // VCAS
      // and tell true if the property already exists only.

      return false;
   }
727042
protected function query_insert_id ( $tableName, $primaryKey = null )
    {
        $sequenceName = $tableName;
        if ($primaryKey) {
            $sequenceName .= "_$primaryKey";
        }
        $sequenceName .= '_seq';

        $sql = "
            SELECT
                CURRVAL('%s')
                ";
        $args = array($sql, $sequenceName);
        $sql = $this->sql_printf($args);
        if (!($res = pg_query($this->conn, $sql))) {
            return 0;
        }
        $val = pg_fetch_row($res, 0);
        if ($val && isset($val[0])) {
            $val = $val[0];
        }

        pg_free_result($res);
        return $val;
    }
145978
protected boolean orderByColumnsCoverUniqueKeys() {
        // In theory, if EVERY table in the query has a uniqueness constraint
        // (primary key or other unique index) on columns that are all listed in the ORDER BY values,
        // the result is deterministic.
        // This holds regardless of whether the associated index is actually used in the selected plan,
        // so this check is plan-independent.
        //
        // baseTableAliases associates table aliases with the order by
        // expressions which reference them.  Presumably by using
        // table aliases we will map table scans to expressions rather
        // than tables to expressions, and not confuse ourselves with
        // different instances of the same table in self joins.
        HashMap<String, List<AbstractExpression> > baseTableAliases =
                new HashMap<>();
        for (ParsedColInfo col : orderByColumns()) {
            AbstractExpression expr = col.m_expression;
            //
            // Compute the set of tables mentioned in the expression.
            //   1. Search out all the TVEs.
            //   2. Throw the aliases of the tables of each of these into a HashSet.
            //      The table must have an alias.  It might not have a name.
            //   3. If the HashSet has size > 1 we can't use this expression.
            //
            List<TupleValueExpression> baseTVEExpressions =
                    expr.findAllTupleValueSubexpressions();
            Set<String> baseTableNames = new HashSet<>();
            for (TupleValueExpression tve : baseTVEExpressions) {
                String tableAlias = tve.getTableAlias();
                assert(tableAlias != null);
                baseTableNames.add(tableAlias);
            }
            if (baseTableNames.size() != 1) {
                // Table-spanning ORDER BYs -- like ORDER BY A.X + B.Y are not helpful.
                // Neither are (nonsense) constant (table-less) expressions.
                continue;
            }
            // Everything in the baseTVEExpressions table is a column
            // in the same table and has the same alias. So just grab the first one.
            // All we really want is the alias.
            AbstractExpression baseTVE = baseTVEExpressions.get(0);
            String nextTableAlias = ((TupleValueExpression)baseTVE).getTableAlias();
            // This was tested above.  But the assert above may prove to be over cautious
            // and disappear.
            assert(nextTableAlias != null);
            List<AbstractExpression> perTable = baseTableAliases.get(nextTableAlias);
            if (perTable == null) {
                perTable = new ArrayList<>();
                baseTableAliases.put(nextTableAlias, perTable);
            }
            perTable.add(expr);
        }

        if (m_tableAliasMap.size() > baseTableAliases.size()) {
            // FIXME: There are more table aliases in the select list than tables
            //        named in the order by clause.  So, some tables named in the
            //        select list are not explicitly listed in the order by
            //        clause.
            //
            //        This would be one of the tricky cases where the goal would be to prove that the
            //        row with no ORDER BY component came from the right side of a 1-to-1 or many-to-1 join.
            //        like Unique Index nested loop join, etc.
            return false;
        }
        boolean allScansAreDeterministic = true;
        for (Entry<String, List<AbstractExpression>> orderedAlias : baseTableAliases.entrySet()) {
            List<AbstractExpression> orderedAliasExprs = orderedAlias.getValue();
            StmtTableScan tableScan = getStmtTableScanByAlias(orderedAlias.getKey());
            if (tableScan == null) {
                assert(false);
                return false;
            }

            if (tableScan instanceof StmtSubqueryScan) {
                return false; // don't yet handle FROM clause subquery, here.
            }

            Table table = ((StmtTargetTableScan)tableScan).getTargetTable();

            // This table's scans need to be proven deterministic.
            allScansAreDeterministic = false;
            // Search indexes for one that makes the order by deterministic
            for (Index index : table.getIndexes()) {
                // skip non-unique indexes
                if ( ! index.getUnique()) {
                    continue;
                }

                // get the list of expressions for the index
                List<AbstractExpression> indexExpressions = new ArrayList<>();

                String jsonExpr = index.getExpressionsjson();
                // if this is a pure-column index...
                if (jsonExpr.isEmpty()) {
                    for (ColumnRef cref : index.getColumns()) {
                        Column col = cref.getColumn();
                        TupleValueExpression tve = new TupleValueExpression(table.getTypeName(),
                                                                            orderedAlias.getKey(),
                                                                            col.getName(),
                                                                            col.getName(),
                                                                            col.getIndex());
                        indexExpressions.add(tve);
                    }
                }
                // if this is a fancy expression-based index...
                else {
                    try {
                        indexExpressions = AbstractExpression.fromJSONArrayString(jsonExpr, tableScan);
                    }
                    catch (JSONException e) {
                        e.printStackTrace();
                        assert(false);
                        continue;
                    }
                }

                // If the sort covers the index, then it's a unique sort.
                // TODO: The statement's equivalence sets would be handy here to recognize cases like
                //    WHERE B.unique_id = A.b_id
                //    ORDER BY A.unique_id, A.b_id
                if (orderedAliasExprs.containsAll(indexExpressions)) {
                    allScansAreDeterministic = true;
                    break;
                }
            }
            // ALL tables' scans need to have proved deterministic
            if ( ! allScansAreDeterministic) {
                return false;
            }
        }
        return true;
    }
878143
long executeSQL(boolean isFinal) throws VoltAbortException {
        long count = 0;
        VoltTable[] results = voltExecuteSQL(isFinal);
        for (VoltTable result : results) {
            long dmlUpdated = result.asScalarLong();
            if (dmlUpdated == 0) {
                throw new VoltAbortException("Insert failed for tuple.");
            }
            if (dmlUpdated > 1) {
                throw new VoltAbortException("Insert modified more than one tuple.");
            }
            ++count;
        }
        return count;
    }
1209015
@Override
    public SequenceRecord nextSequence() {
        SequenceRecord next = sequenceRecordReader.nextSequence();
        next.setSequenceRecord(transformProcess.executeSequence(next.getSequenceRecord()));
        return next;
    }
315808
final boolean select(int extension, ExplorationStep state) throws WrongFirstParentException {
		if (this.allowExploration(extension, state)) {
			return (this.next == null || this.next.select(extension, state));
		} else {
			PLCMCounters key = this.getCountersKey();
			if (key != null) {
				((PLCM.PLCMThread) Thread.currentThread()).counters[key.ordinal()]++;
			}
			return false;
		}
	}
768604
public M sequence(String sequenceKey, Long initialValue, Boolean increment) {
        SequenceConfig cfg = defaultSequenceConfig();
        if (null != initialValue) {
            cfg.setInitialValue(initialValue);
        }
        if (null != increment) {
            cfg.setDecrement(!increment);
        }
        getSequence(sequenceKey, cfg);
        return THIS();
    }