/*
This is to work around an issue reading from ORC transactional data sets that contain only deltas. These contain
synthesised column names that are not usable to us.
778958
private Path getSplitPath(FileSplit inputSplit, JobConf conf) throws IOException {
    Path path = inputSplit.getPath();
    if (inputSplit instanceof OrcSplit) {
      OrcSplit orcSplit = (OrcSplit) inputSplit;
      List<Long> deltas = orcSplit.getDeltas();
      if (!orcSplit.hasBase() && deltas.size() >= 2) {
        throw new IOException("Cannot read valid StructTypeInfo from delta only file: " + path);
      }
    }
    LOG.debug("Input split path: {}", path);
    return path;
  }
427330
static SQLTransform getLanguageTransform(TypeName type) {
		String typeName = type.toString();

		if (Integer.class.getCanonicalName().equals(typeName)) {
			return new IntegerSQLTransform(true);
		}
		if (Boolean.class.getCanonicalName().equals(typeName)) {
			return new BooleanSQLTransform(true);
		}
		if (Long.class.getCanonicalName().equals(typeName)) {
			return new LongSQLTransform(true);
		}
		if (Double.class.getCanonicalName().equals(typeName)) {
			return new DoubleSQLTransform(true);
		}
		if (Float.class.getCanonicalName().equals(typeName)) {
			return new FloatSQLTransform(true);
		}
		if (Short.class.getCanonicalName().equals(typeName)) {
			return new ShortSQLTransform(true);
		}
		if (Byte.class.getCanonicalName().equals(typeName)) {
			return new ByteSQLTransform(true);
		}
		if (Character.class.getCanonicalName().equals(typeName)) {
			return new CharacterSQLTransform(true);
		}
		if (String.class.getCanonicalName().equals(typeName)) {
			return new StringSQLTransform();
		}
		return null;
	}
1152151
private void readTableData(List<SynchroTable> tables, InputStream is) throws IOException
   {
      for (SynchroTable table : tables)
      {
         if (REQUIRED_TABLES.contains(table.getName()))
         {
            readTable(is, table);
         }
      }
   }
297081
@Override
    public ResultSet getColumns(String catalog, String schemaPattern, String tableNamePattern, String columnNamePattern) throws SQLException
    {
        checkClosed();
        this.sysCatalog.setString(1, "COLUMNS");
        JDBC4ResultSet res = (JDBC4ResultSet) this.sysCatalog.executeQuery();
        VoltTable vtable = res.getVoltTable().clone(0);

        // If no pattern is specified, default to matching any/all.
        if (tableNamePattern == null || tableNamePattern.length() == 0)
        {
            tableNamePattern = "%";
        }
        Pattern table_pattern = computeJavaPattern(tableNamePattern);

        if (columnNamePattern == null || columnNamePattern.length() == 0)
        {
            columnNamePattern = "%";
        }
        Pattern column_pattern = computeJavaPattern(columnNamePattern);

        // Filter columns based on table name and column name
        while (res.next()) {
            Matcher table_matcher = table_pattern.matcher(res.getString("TABLE_NAME"));
            if (table_matcher.matches())
            {
                Matcher column_matcher = column_pattern.matcher(res.getString("COLUMN_NAME"));
                if (column_matcher.matches())
                {
                    vtable.addRow(res.getRowData());
                }
            }
        }

        return new JDBC4ResultSet(this.sysCatalog, vtable);
    }
1191029
private Iterator<Map.Entry<DeltaClusteringKey, Change>> decodeChangesFromCql(final Iterator<Row> iter) {
        return Iterators.transform(iter, row ->
                Maps.immutableEntry(new DeltaClusteringKey(getChangeId(row), _daoUtils.getNumDeltaBlocks(getValue(row))), _changeEncoder.decodeChange(getChangeId(row), getValue(row))));
    }
852573
private List<OrcDataOutput> bufferStripeData(long stripeStartOffset, FlushReason flushReason)
            throws IOException
    {
        if (stripeRowCount == 0) {
            verify(flushReason == CLOSED, "An empty stripe is not allowed");
            // column writers must be closed or the reset call will fail
            columnWriters.forEach(ColumnWriter::close);
            return ImmutableList.of();
        }

        if (rowGroupRowCount > 0) {
            finishRowGroup();
        }

        // convert any dictionary encoded column with a low compression ratio to direct
        dictionaryCompressionOptimizer.finalOptimize(bufferedBytes);

        columnWriters.forEach(ColumnWriter::close);

        List<OrcDataOutput> outputData = new ArrayList<>();
        List<Stream> allStreams = new ArrayList<>(columnWriters.size() * 3);

        // get index streams
        long indexLength = 0;
        for (ColumnWriter columnWriter : columnWriters) {
            for (StreamDataOutput indexStream : columnWriter.getIndexStreams(metadataWriter)) {
                // The ordering is critical because the stream only contain a length with no offset.
                outputData.add(indexStream);
                allStreams.add(indexStream.getStream());
                indexLength += indexStream.size();
            }
        }

        // data streams (sorted by size)
        long dataLength = 0;
        List<StreamDataOutput> dataStreams = new ArrayList<>(columnWriters.size() * 2);
        for (ColumnWriter columnWriter : columnWriters) {
            List<StreamDataOutput> streams = columnWriter.getDataStreams();
            dataStreams.addAll(streams);
            dataLength += streams.stream()
                    .mapToLong(StreamDataOutput::size)
                    .sum();
        }
        Collections.sort(dataStreams);

        // add data streams
        for (StreamDataOutput dataStream : dataStreams) {
            // The ordering is critical because the stream only contain a length with no offset.
            outputData.add(dataStream);
            allStreams.add(dataStream.getStream());
        }

        Map<Integer, ColumnEncoding> columnEncodings = new HashMap<>();
        columnWriters.forEach(columnWriter -> columnEncodings.putAll(columnWriter.getColumnEncodings()));

        Map<Integer, ColumnStatistics> columnStatistics = new HashMap<>();
        columnWriters.forEach(columnWriter -> columnStatistics.putAll(columnWriter.getColumnStripeStatistics()));

        // the 0th column is a struct column for the whole row
        columnEncodings.put(0, new ColumnEncoding(DIRECT, 0));
        columnStatistics.put(0, new ColumnStatistics((long) stripeRowCount, 0, null, null, null, null, null, null, null, null));

        // add footer
        StripeFooter stripeFooter = new StripeFooter(allStreams, toDenseList(columnEncodings, orcTypes.size()));
        Slice footer = metadataWriter.writeStripeFooter(stripeFooter);
        outputData.add(createDataOutput(footer));

        // create final stripe statistics
        StripeStatistics statistics = new StripeStatistics(toDenseList(columnStatistics, orcTypes.size()));
        recordValidation(validation -> validation.addStripeStatistics(stripeStartOffset, statistics));
        StripeInformation stripeInformation = new StripeInformation(stripeRowCount, stripeStartOffset, indexLength, dataLength, footer.length());
        ClosedStripe closedStripe = new ClosedStripe(stripeInformation, statistics);
        closedStripes.add(closedStripe);
        closedStripesRetainedBytes += closedStripe.getRetainedSizeInBytes();
        recordValidation(validation -> validation.addStripe(stripeInformation.getNumberOfRows()));
        stats.recordStripeWritten(flushReason, stripeInformation.getTotalLength(), stripeInformation.getNumberOfRows(), dictionaryCompressionOptimizer.getDictionaryMemoryBytes());

        return outputData;
    }
152163
@Override
    void getTableNamesForWrite(OrderedHashSet set) {

        /* A VoltDB Extension.
         * Base table could be null for views.
         */
        if (baseTable==null || baseTable.isTemp()) {
            return;
        }

        set.add(baseTable.getName());

        for (int i = 0; i < baseTable.fkPath.length; i++) {
            set.add(baseTable.fkPath[i].getMain().getName());
        }

        getTriggerTableNames(set, true);
    }
717086
def _set_noconvert_columns(self):
        
        names = self.orig_names
        if self.usecols_dtype == 'integer':
            # A set of integers will be converted to a list in
            # the correct order every single time.
            usecols = list(self.usecols)
            usecols.sort()
        elif (callable(self.usecols) or
                self.usecols_dtype not in ('empty', None)):
            # The names attribute should have the correct columns
            # in the proper order for indexing with parse_dates.
            usecols = self.names[:]
        else:
            # Usecols is empty.
            usecols = None

        def _set(x):
            if usecols is not None and is_integer(x):
                x = usecols[x]

            if not is_integer(x):
                x = names.index(x)

            self._reader.set_noconvert(x)

        if isinstance(self.parse_dates, list):
            for val in self.parse_dates:
                if isinstance(val, list):
                    for k in val:
                        _set(k)
                else:
                    _set(val)

        elif isinstance(self.parse_dates, dict):
            for val in self.parse_dates.values():
                if isinstance(val, list):
                    for k in val:
                        _set(k)
                else:
                    _set(val)

        elif self.parse_dates:
            if isinstance(self.index_col, list):
                for k in self.index_col:
                    _set(k)
            elif self.index_col is not None:
                _set(self.index_col)
922043
@Override
    public ResultSet getImportedKeys(String catalog, String schema, String table) throws SQLException
    {
        checkClosed();
        VoltTable vtable = new VoltTable(
                new ColumnInfo("PKTABLE_CAT", VoltType.STRING),
                new ColumnInfo("PKTABLE_SCHEM", VoltType.STRING),
                new ColumnInfo("PKTABLE_NAME", VoltType.STRING),
                new ColumnInfo("PKCOLUMN_NAME", VoltType.STRING),
                new ColumnInfo("FKTABLE_CAT", VoltType.STRING),
                new ColumnInfo("FKTABLE_SCHEM", VoltType.STRING),
                new ColumnInfo("FKTABLE_NAME", VoltType.STRING),
                new ColumnInfo("FKCOLUMN_NAME", VoltType.STRING),
                new ColumnInfo("KEY_SEQ", VoltType.SMALLINT),
                new ColumnInfo("UPDATE_RULE", VoltType.SMALLINT),
                new ColumnInfo("DELETE_RULE", VoltType.SMALLINT),
                new ColumnInfo("FK_NAME", VoltType.STRING),
                new ColumnInfo("PK_NAME", VoltType.STRING),
                new ColumnInfo("DEFERRABILITY", VoltType.SMALLINT)
        );
        //NB: @SystemCatalog(?) will need additional support if we want to
        // populate the table.
        JDBC4ResultSet res = new JDBC4ResultSet(this.sysCatalog, vtable);
        return res;
    }
605902
private Delta<E> toDelta(difflib.Delta<E> delta) throws DiffException
    {
        Delta<E> newDelta;

        switch (delta.getType()) {
            case CHANGE:
                newDelta = new ChangeDelta<E>(delta.getOriginal(), delta.getRevised());
                break;
            case DELETE:
                newDelta = new DeleteDelta<E>(delta.getOriginal(), delta.getRevised());
                break;
            case INSERT:
                newDelta = new InsertDelta<E>(delta.getOriginal(), delta.getRevised());
                break;
            default:
                throw new DiffException(String.format("Failed to convert [%s] info [%s]. Unknown type [%s]", delta
                    .getClass().getName(), Delta.class.getName(), delta.getType().toString()));
        }

        return newDelta;
    }
467232
private void processAlterColumnType(Table table, ColumnSchema oldCol,
                                        boolean fullDefinition) {

        ColumnSchema newCol;

        if (oldCol.isGenerated()) {
            throw Error.error(ErrorCode.X_42561);
        }

        if (fullDefinition) {
            HsqlArrayList list = new HsqlArrayList();
            Constraint    c    = table.getPrimaryConstraint();

            if (c == null) {
                c = new Constraint(null, true, null, Constraint.TEMP);
            }

            list.add(c);

            newCol = readColumnDefinitionOrNull(table, oldCol.getName(), list);

            if (newCol == null) {
                throw Error.error(ErrorCode.X_42000);
            }

            if (oldCol.isIdentity() && newCol.isIdentity()) {
                throw Error.error(ErrorCode.X_42525);
            }

            if (list.size() > 1) {
                // A VoltDB extension to support establishing or preserving the NOT NULL
                // attribute of an altered column.
                if (voltDBacceptNotNullConstraint(list)) {
                    newCol.setNullable(false);
                } else
                // End of VoltDB extension
                throw Error.error(ErrorCode.X_42524);
            }
        } else {
            Type type = readTypeDefinition(true);

            if (oldCol.isIdentity()) {
                if (!type.isIntegralType()) {
                    throw Error.error(ErrorCode.X_42561);
                }
            }

            newCol = oldCol.duplicate();

            newCol.setType(type);
        }

        TableWorks tw = new TableWorks(session, table);

        tw.retypeColumn(oldCol, newCol);
    }
705410
public static Map<String,String> parseColumns(String sqlStmt) throws Exception {

    // NOTE: While I prefer using a SQL parser here, the presto / calcite / Spark parsers were too complex
    // for this basic task and pulled in unwanted / incompatible dependencies, e.g. presto requires a different
    // version of guava than what Spark supports

    String tmp = sqlStmt.replaceAll("\\s+", " ").trim();

    String lc = tmp.toLowerCase();
    if (!lc.startsWith(SELECT))
      throw new IllegalArgumentException("Expected SQL to start with '"+SELECT+"' but found ["+sqlStmt+"] instead!");

    int fromAt = lc.indexOf(FROM, SELECT.length());
    if (fromAt == -1)
      throw new IllegalArgumentException("No FROM keyword found in SQL: "+sqlStmt);

    String columnList = tmp.substring(SELECT.length(),fromAt).trim();

    // SELECT * not supported yet
    if ("*".equals(columnList))
      return Collections.emptyMap();

    Map<String,String> columns = new HashMap<>();
    for (String pair : columnList.split(",")) {
      pair = pair.trim();

      // trim off distinct indicator
      if (pair.toLowerCase().startsWith(DISTINCT)) {
        pair = pair.substring(DISTINCT.length());
      }

      String col;
      String alias;
      int spaceAt = pair.indexOf(" ");
      if (spaceAt != -1) {
        col = pair.substring(0,spaceAt);
        alias = pair.substring(spaceAt+1);
        if (alias.toLowerCase().startsWith(AS)) {
          alias = alias.substring(AS.length());
        }
      } else {
        col = pair;
        alias = pair;
      }

      columns.put(col.replace("`","").replace("'",""), alias.replace("`","").replace("'",""));
    }
    return columns;
  }
793859
void readColumnConstraints(Table table, ColumnSchema column,
                               HsqlArrayList constraintList) {

        boolean end = false;
        boolean isAutogeneratedName = true;

        while (true) {
            HsqlName constName = null;

            if (token.tokenType == Tokens.CONSTRAINT) {
                read();

                constName = readNewDependentSchemaObjectName(table.getName(),
                        SchemaObject.CONSTRAINT);
                isAutogeneratedName = false;
            }

            // A VoltDB extension to support indexed expressions and the assume unique attribute
            boolean assumeUnique = false; // For VoltDB
            // End of VoltDB extension
            switch (token.tokenType) {

                case Tokens.PRIMARY : {
                    read();
                    readThis(Tokens.KEY);

                    Constraint existingConst =
                        (Constraint) constraintList.get(0);

                    if (existingConst.constType == Constraint.PRIMARY_KEY) {
                        throw Error.error(ErrorCode.X_42532);
                    }

                    OrderedHashSet set = new OrderedHashSet();

                    set.add(column.getName().name);

                    if (constName == null) {
                        constName = database.nameManager.newAutoName("PK",
                                table.getSchemaName(), table.getName(),
                                SchemaObject.CONSTRAINT);
                    }

                    Constraint c = new Constraint(constName, isAutogeneratedName, set,
                                                  Constraint.PRIMARY_KEY);

                    constraintList.set(0, c);
                    column.setPrimaryKey(true);

                    break;
                }
                // A VoltDB extension to support indexed expressions and the assume unique attribute
                case Tokens.ASSUMEUNIQUE :
                    assumeUnique = true;
                    // $FALL-THROUGH$
                // End of VoltDB extension
                case Tokens.UNIQUE : {
                    read();

                    OrderedHashSet set = new OrderedHashSet();

                    set.add(column.getName().name);

                    if (constName == null) {
                        constName = database.nameManager.newAutoName("CT",
                                table.getSchemaName(), table.getName(),
                                SchemaObject.CONSTRAINT);
                    }

                    Constraint c = new Constraint(constName, isAutogeneratedName, set,
                                                  Constraint.UNIQUE);
                    // A VoltDB extension to support indexed expressions and the assume unique attribute
                    c.setAssumeUnique(assumeUnique);
                    // End of VoltDB extension

                    constraintList.add(c);

                    break;
                }
                case Tokens.FOREIGN : {
                    read();
                    readThis(Tokens.KEY);
                }

                // $FALL-THROUGH$
                case Tokens.REFERENCES : {
                    OrderedHashSet set = new OrderedHashSet();

                    set.add(column.getName().name);

                    Constraint c = readFKReferences(table, constName, set);

                    constraintList.add(c);

                    break;
                }
                case Tokens.CHECK : {
                    read();

                    if (constName == null) {
                        constName = database.nameManager.newAutoName("CT",
                                table.getSchemaName(), table.getName(),
                                SchemaObject.CONSTRAINT);
                    }

                    Constraint c = new Constraint(constName, isAutogeneratedName, null,
                                                  Constraint.CHECK);

                    readCheckConstraintCondition(c);

                    OrderedHashSet set = c.getCheckColumnExpressions();

                    for (int i = 0; i < set.size(); i++) {
                        ExpressionColumn e = (ExpressionColumn) set.get(i);

                        if (column.getName().name.equals(e.getColumnName())) {
                            if (e.getSchemaName() != null
                                    && e.getSchemaName()
                                       != table.getSchemaName().name) {
                                throw Error.error(ErrorCode.X_42505);
                            }
                        } else {
                            throw Error.error(ErrorCode.X_42501);
                        }
                    }

                    constraintList.add(c);

                    break;
                }
                case Tokens.NOT : {
                    read();
                    readThis(Tokens.NULL);

                    if (constName == null) {
                        constName = database.nameManager.newAutoName("CT",
                                table.getSchemaName(), table.getName(),
                                SchemaObject.CONSTRAINT);
                    }

                    Constraint c = new Constraint(constName, isAutogeneratedName, null,
                                                  Constraint.CHECK);

                    c.check = new ExpressionLogical(column);

                    constraintList.add(c);

                    break;
                }
                default :
                    end = true;
                    break;
            }

            if (end) {
                break;
            }
        }
    }
769207
private Map<C, Long> readLockColumns(boolean readDataColumns) throws Exception {
        Map<C, Long> result = Maps.newLinkedHashMap();
        // Read all the columns
        if (readDataColumns) {
            columns = new OrderedColumnMap<C>();
            ColumnList<C> lockResult = keyspace
                .prepareQuery(columnFamily)
                    .setConsistencyLevel(consistencyLevel)
                    .getKey(key)
                .execute()
                    .getResult();
    
            for (Column<C> c : lockResult) {
                if (columnStrategy.isLockColumn(c.getName()))
                    result.put(c.getName(), readTimeoutValue(c));
                else 
                    columns.add(c);
            }
        }
        // Read only the lock columns
        else {
            ColumnList<C> lockResult = keyspace
                .prepareQuery(columnFamily)
                    .setConsistencyLevel(consistencyLevel)
                    .getKey(key)
                    .withColumnRange(columnStrategy.getLockColumnRange())
                .execute()
                    .getResult();

            for (Column<C> c : lockResult) {
                result.put(c.getName(), readTimeoutValue(c));
            }

        }
        return result;    
    }
1309713
private void readConstraint(SchemaObject schemaObject,
                                HsqlArrayList constraintList) {

        HsqlName constName = null;
        boolean isAutogeneratedName = true;

        if (token.tokenType == Tokens.CONSTRAINT) {
            read();

            constName =
                readNewDependentSchemaObjectName(schemaObject.getName(),
                                                 SchemaObject.CONSTRAINT);
            isAutogeneratedName = false;
        }

        // A VoltDB extension to support indexed expressions and the assume unique attribute
        boolean assumeUnique = false; // For VoltDB
        // End of VoltDB extension
        switch (token.tokenType) {

            case Tokens.PRIMARY : {
                if (schemaObject.getName().type != SchemaObject.TABLE) {
                    throw this.unexpectedTokenRequire(Tokens.T_CHECK);
                }

                read();
                readThis(Tokens.KEY);

                Constraint mainConst;

                mainConst = (Constraint) constraintList.get(0);

                if (mainConst.constType == Constraint.PRIMARY_KEY) {
                    throw Error.error(ErrorCode.X_42532);
                }

                if (constName == null) {
                    constName = database.nameManager.newAutoName("PK",
                            schemaObject.getSchemaName(),
                            schemaObject.getName(), SchemaObject.CONSTRAINT);
                }

                OrderedHashSet set = readColumnNames(false);
                Constraint c = new Constraint(constName, isAutogeneratedName, set,
                                              Constraint.PRIMARY_KEY);

                constraintList.set(0, c);

                break;
            }
            // A VoltDB extension to support indexed expressions and the assume unique attribute
            case Tokens.ASSUMEUNIQUE :
                assumeUnique = true;
                // $FALL-THROUGH$
            // End of VoltDB extension
            case Tokens.UNIQUE : {
                if (schemaObject.getName().type != SchemaObject.TABLE) {
                    throw this.unexpectedTokenRequire(Tokens.T_CHECK);
                }

                read();

                // A VoltDB extension to "readColumnNames(false)" to support indexed expressions.
                java.util.List<Expression> indexExprs = XreadExpressions(null);
                OrderedHashSet set = getSimpleColumnNames(indexExprs);
                /* disable 1 line ...
                OrderedHashSet set = readColumnNames(false);
                ... disabled 1 line */
                // End of VoltDB extension

                if (constName == null) {
                    constName = database.nameManager.newAutoName("CT",
                            schemaObject.getSchemaName(),
                            schemaObject.getName(), SchemaObject.CONSTRAINT);
                }

                // A VoltDB extension to support indexed expressions.
                boolean hasNonColumnExprs = false;
                if (set == null) {
                    hasNonColumnExprs = true;
                    set = getBaseColumnNames(indexExprs);
                }
                // End of VoltDB extension
                Constraint c = new Constraint(constName, isAutogeneratedName, set,
                                              Constraint.UNIQUE);
                // A VoltDB extension to support indexed expressions and assume unique attribute.
                c.setAssumeUnique(assumeUnique);
                if (hasNonColumnExprs) {
                    c = c.withExpressions(indexExprs.toArray(new Expression[indexExprs.size()]));
                }
                // End of VoltDB extension

                constraintList.add(c);

                break;
            }
            case Tokens.FOREIGN : {
                if (schemaObject.getName().type != SchemaObject.TABLE) {
                    throw this.unexpectedTokenRequire(Tokens.T_CHECK);
                }

                read();
                readThis(Tokens.KEY);

                OrderedHashSet set = readColumnNames(false);
                Constraint c = readFKReferences((Table) schemaObject,
                                                constName, set);

                constraintList.add(c);

                break;
            }
            case Tokens.CHECK : {
                read();

                if (constName == null) {
                    constName = database.nameManager.newAutoName("CT",
                            schemaObject.getSchemaName(),
                            schemaObject.getName(), SchemaObject.CONSTRAINT);
                }

                Constraint c = new Constraint(constName, isAutogeneratedName, null,
                                              Constraint.CHECK);

                readCheckConstraintCondition(c);
                constraintList.add(c);

                break;
            }
            // A VoltDB extension to support LIMIT PARTITION ROWS
            case Tokens.LIMIT : {
                read();

                for (int i = 0;  i < constraintList.size(); i++) {
                    if (((Constraint)constraintList.get(i)).getConstraintType() == Constraint.LIMIT) {
                        throw Error.error(ErrorCode.X_42524,
                                String.format("Multiple LIMIT PARTITION ROWS constraints on table %s are forbidden.", schemaObject.getName().name));
                    }
                }

                if (constName == null) {
                    constName = database.nameManager.newAutoName("LIMIT",
                            schemaObject.getSchemaName(),
                            schemaObject.getName(), SchemaObject.CONSTRAINT);
                }

                Constraint c = new Constraint(constName, isAutogeneratedName, null, Constraint.LIMIT);
                readLimitConstraintCondition(c);
                constraintList.add(c);

                break;
            }
            // End of VoltDB extension
            default : {
                if (constName != null) {
                    throw Error.error(ErrorCode.X_42581);
                }
            }
        }
    }
352141
public static String RToSqlUdf(List<String> RExps, List<String> selectedColumns, List<Column> existingColumns) {
    List<String> udfs = Lists.newArrayList();
    Map<String, String> newColToDef = new HashMap<String, String>();
    boolean updateOnConflict = (selectedColumns == null || selectedColumns.isEmpty());
    String dupColExp = "%s duplicates another column name";

    if (updateOnConflict) {
      if (existingColumns != null && !existingColumns.isEmpty()) {
        for (Column c : existingColumns) {
          udfs.add(c.getName());
        }
      }
    }
    else {
      for (String c : selectedColumns) {
        udfs.add(c);
      }
    }

    Set<String> newColsInRExp = new HashSet<String>();
    for (String str : RExps) {
      int index = str.indexOf("=") >  str.indexOf("~")
          ? str.indexOf("=")
          : str.indexOf("~");
      String[] udf = new String[2];
      if (index == -1) {
        udf[0] = str;
      } else {
        udf[0] = str.substring(0,index);
        udf[1] = str.substring(index + 1);
      }

      // String[] udf = str.split("[=~](?![^()]*+\\))");
      String newCol = (index != -1) ?
        udf[0].trim().replaceAll("\\W", "") :
        udf[0].trim();
      if (newColsInRExp.contains(newCol)) {
        throw new RuntimeException(String.format(dupColExp, newCol));
      }
      String newDef = (index != -1) ? udf[1].trim() : null;
      if (!udfs.contains(newCol)) {
        udfs.add(newCol);
      }
      else if (!updateOnConflict) {
        throw new RuntimeException(String.format(dupColExp,newCol));
      }

      if (newDef != null && !newDef.isEmpty()) {
        newColToDef.put(newCol.replaceAll("\\W", ""), newDef);
      }
      newColsInRExp.add(newCol);
    }

    String selectStr = "";
    for (String udf : udfs) {
      String exp = newColToDef.containsKey(udf) ?
        String.format("%s as %s", newColToDef.get(udf), udf) :
        String.format("%s", udf);
      selectStr += (exp + ",");
    }

    return selectStr.substring(0, selectStr.length() - 1);
  }
1208272
@Override
    public ResultSet getSchemas() throws SQLException
    {
        checkClosed();
        VoltTable vtable = new VoltTable(
                new ColumnInfo("TABLE_SCHEM", VoltType.STRING),
                new ColumnInfo("TABLE_CATALOG", VoltType.STRING));
        JDBC4ResultSet res = new JDBC4ResultSet(this.sysCatalog, vtable);
        return res;
    }