Java Code Examples for net.sf.jsqlparser.schema.Column

The following examples show how to use net.sf.jsqlparser.schema.Column. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source Project: ddal   Author: hellojavaer   File: JSQLParserAdapter.java    License: Apache License 2.0 7 votes vote down vote up
@Override
public void visit(InExpression inExpression) {
    if (inExpression.isNot()) {
        visit0(inExpression);
        return;
    }
    Column column = (Column) inExpression.getLeftExpression();
    if (inExpression.getRightItemsList() instanceof ExpressionList) {
        TableWrapper tab = getTableFromContext(column);
        if (tab == null) {
            visit0(inExpression);
            return;
        }
        ExpressionList itemsList = (ExpressionList) inExpression.getRightItemsList();
        List<Expression> list = itemsList.getExpressions();
        if (list == null || list.isEmpty()) {
            visit0(inExpression);
        }
        for (Expression exp : list) {
            routeTable(tab, column, exp);
        }
    } else {
        visit0(inExpression);
        return;
    }
}
 
Example #2
Source Project: spanner-jdbc   Author: olavloite   File: CloudSpannerResultSetMetaData.java    License: MIT License 6 votes vote down vote up
@Override
public int isNullable(int column) throws SQLException {
  Column col = getColumn(column);
  if (col != null && col.getTable() != null) {
    String schema = Strings.isNullOrEmpty(col.getTable().getSchemaName()) ? ""
        : CloudSpannerDriver.unquoteIdentifier(col.getTable().getSchemaName());
    String tableName = CloudSpannerDriver.unquoteIdentifier(col.getTable().getName());
    String colName = CloudSpannerDriver.unquoteIdentifier(col.getColumnName());
    try (java.sql.ResultSet rs =
        statement.getConnection().getMetaData().getColumns("", schema, tableName, colName)) {
      if (rs.next()) {
        return rs.getInt("NULLABLE");
      }
    }
  }
  return columnNullableUnknown;
}
 
Example #3
Source Project: spanner-jdbc   Author: olavloite   File: CloudSpannerPreparedStatement.java    License: MIT License 6 votes vote down vote up
private void setWhereParameters(Expression where,
    com.google.cloud.spanner.Statement.Builder builder) {
  if (where != null) {
    where.accept(new ExpressionVisitorAdapter() {
      private String currentCol = null;

      @Override
      public void visit(Column col) {
        currentCol = unquoteIdentifier(col.getFullyQualifiedName());
      }

      @Override
      public void visit(JdbcParameter parameter) {
        parameter.accept(new ValueBinderExpressionVisitorAdapter<>(getParameterStore(),
            builder.bind("p" + parameter.getIndex()), currentCol));
        currentCol = null;
      }

      @Override
      public void visit(SubSelect subSelect) {
        setSelectParameters(subSelect.getSelectBody(), builder);
      }

    });
  }
}
 
Example #4
Source Project: spanner-jdbc   Author: olavloite   File: CloudSpannerPreparedStatement.java    License: MIT License 6 votes vote down vote up
private Mutation createUpdateMutation(Update update, boolean generateParameterMetaData)
    throws SQLException {
  if (update.getTables().isEmpty())
    throw new CloudSpannerSQLException("No table found in update statement",
        Code.INVALID_ARGUMENT);
  if (update.getTables().size() > 1)
    throw new CloudSpannerSQLException(
        "Update statements for multiple tables at once are not supported", Code.INVALID_ARGUMENT);
  String table = unquoteIdentifier(update.getTables().get(0).getFullyQualifiedName());
  getParameterStore().setTable(table);
  List<Expression> expressions = update.getExpressions();
  WriteBuilder builder = Mutation.newUpdateBuilder(table);
  int index = 0;
  for (Column col : update.getColumns()) {
    String columnName = unquoteIdentifier(col.getFullyQualifiedName());
    expressions.get(index).accept(new ValueBinderExpressionVisitorAdapter<>(getParameterStore(),
        builder.set(columnName), columnName));
    index++;
  }
  visitUpdateWhereClause(update.getWhere(), builder, generateParameterMetaData);

  return builder.build();
}
 
Example #5
Source Project: spanner-jdbc   Author: olavloite   File: CloudSpannerPreparedStatement.java    License: MIT License 6 votes vote down vote up
private void visitDeleteWhereClause(Expression where, DeleteKeyBuilder keyBuilder,
    boolean generateParameterMetaData) throws SQLException {
  if (where != null) {
    DMLWhereClauseVisitor whereClauseVisitor = new DMLWhereClauseVisitor(getParameterStore()) {

      @Override
      protected void visitExpression(Column col, Expression expression) {
        String columnName = unquoteIdentifier(col.getFullyQualifiedName());
        keyBuilder.set(columnName);
        expression.accept(
            new KeyBuilderExpressionVisitorAdapter(getParameterStore(), columnName, keyBuilder));
      }

    };
    where.accept(whereClauseVisitor);
    if (!generateParameterMetaData && !whereClauseVisitor.isValid()) {
      throw new CloudSpannerSQLException(INVALID_WHERE_CLAUSE_DELETE_MESSAGE,
          Code.INVALID_ARGUMENT);
    }
  }
}
 
Example #6
Source Project: spanner-jdbc   Author: olavloite   File: CloudSpannerPreparedStatement.java    License: MIT License 6 votes vote down vote up
private boolean isSingleRowWhereClause(TableKeyMetaData table, Expression where) {
  if (where != null) {
    SingleRowWhereClauseValidator validator = new SingleRowWhereClauseValidator(table);
    DMLWhereClauseVisitor whereClauseVisitor = new DMLWhereClauseVisitor(getParameterStore()) {

      @Override
      protected void visitExpression(Column col, Expression expression) {
        String columnName = unquoteIdentifier(col.getFullyQualifiedName());
        validator.set(columnName);
        expression.accept(new SingleRowWhereClauseValidatorExpressionVisitorAdapter(
            getParameterStore(), validator));
      }

    };
    where.accept(whereClauseVisitor);
    return whereClauseVisitor.isValid() && validator.isValid();
  }
  return false;
}
 
Example #7
Source Project: spanner-jdbc   Author: olavloite   File: CloudSpannerPreparedStatement.java    License: MIT License 6 votes vote down vote up
private void visitUpdateWhereClause(Expression where, WriteBuilder builder,
    boolean generateParameterMetaData) throws SQLException {
  if (where != null) {
    DMLWhereClauseVisitor whereClauseVisitor = new DMLWhereClauseVisitor(getParameterStore()) {

      @Override
      protected void visitExpression(Column col, Expression expression) {
        String columnName = unquoteIdentifier(col.getFullyQualifiedName());
        expression.accept(new ValueBinderExpressionVisitorAdapter<>(getParameterStore(),
            builder.set(columnName), columnName));
      }

    };
    where.accept(whereClauseVisitor);
    if (!generateParameterMetaData && !whereClauseVisitor.isValid()) {
      throw new CloudSpannerSQLException(INVALID_WHERE_CLAUSE_UPDATE_MESSAGE,
          Code.INVALID_ARGUMENT);
    }
  } else {
    throw new SQLException(INVALID_WHERE_CLAUSE_UPDATE_MESSAGE);
  }
}
 
Example #8
Source Project: FastSQL   Author: fast-sql   File: CountSqlParser.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 将sql转换为count查询
 *
 */
public void sqlToCount(Select select, String name) {
    SelectBody selectBody = select.getSelectBody();
    // 是否能简化count查询
    List<SelectItem> COUNT_ITEM = new ArrayList<SelectItem>();
    COUNT_ITEM.add(new SelectExpressionItem(new Column("count(" + name + ")")));
    if (selectBody instanceof PlainSelect && isSimpleCount((PlainSelect) selectBody)) {
        ((PlainSelect) selectBody).setSelectItems(COUNT_ITEM);
    } else {
        PlainSelect plainSelect = new PlainSelect();
        SubSelect subSelect = new SubSelect();
        subSelect.setSelectBody(selectBody);
        subSelect.setAlias(TABLE_ALIAS);
        plainSelect.setFromItem(subSelect);
        plainSelect.setSelectItems(COUNT_ITEM);
        select.setSelectBody(plainSelect);
    }
}
 
Example #9
Source Project: evosql   Author: SERG-Delft   File: UsedColumnExtractorVisitor.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void visit(SelectExpressionItem arg0) {
	if (currentState.stateSource != null) {
		String columnName = null;
		if (arg0.getAlias() != null)
			columnName = arg0.getAlias().getName();
		else if (arg0.getExpression() instanceof Column) {
			columnName = ((Column)arg0.getExpression()).getColumnName();
		}
		// Strip quotes
		if (columnName != null)
			columnName = columnName.replaceAll("^\"|\"$", "");
		currentState.columnSource = new ColumnSource(currentState.stateSource, columnName);
	}
	
	arg0.getExpression().accept(this);
	
	// Get ColumnSource and store in the current state source
	if (currentState.stateSource != null) {
		currentState.stateSource.add(currentState.columnSource);
		currentState.columnSource = null;
	}
}
 
Example #10
Source Project: ddal   Author: hellojavaer   File: JSQLParserAdapter.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void visit(Insert insert) {
    this.getStack().push(new FrameContext(StatementType.INSERT));
    visit0(insert);
    // route table
    List<Column> columns = insert.getColumns();
    if (columns != null) {
        ItemsList itemsList = insert.getItemsList();
        if (itemsList instanceof ExpressionList) {
            procInsertColumns(columns, (ExpressionList) itemsList);
        } else if (itemsList instanceof MultiExpressionList) {
            for (ExpressionList expressionList : ((MultiExpressionList) itemsList).getExprList()) {
                procInsertColumns(columns, expressionList);
            }
        } else {
            throw new UnsupportedSQLExpressionException(insert.toString());
        }
    }
    afterVisitBaseStatement();
}
 
Example #11
Source Project: foxtrot   Author: Flipkart   File: QueryTranslator.java    License: Apache License 2.0 6 votes vote down vote up
private ColumnData setupColumn(Expression expression) {
    if(expression instanceof Function) {
        Function function = (Function)expression;
        if(function.getName()
                .equalsIgnoreCase("temporal")) {
            List parameters = function.getParameters()
                    .getExpressions();
            if(parameters.size() != 1 || !(parameters.get(0) instanceof Column)) {
                throw new FqlParsingException("temporal function must have a fieldname as parameter");
            }
            return ColumnData.temporal(((Column)parameters.get(0)).getFullyQualifiedName());
        }
        throw new FqlParsingException("Only the function 'temporal' is supported in where clause");
    }
    if(expression instanceof Column) {
        return new ColumnData(((Column)expression).getFullyQualifiedName());
    }
    throw new FqlParsingException("Only the function 'temporal([fieldname)' and fieldname is supported in where clause");
}
 
Example #12
Source Project: ddal   Author: hellojavaer   File: JSQLParserAdapter.java    License: Apache License 2.0 6 votes vote down vote up
private void routeTable(TableWrapper tab, Column column, Object sdValue) {
    if (tab == null) {//
        return;
    }
    if (tab == AMBIGUOUS_TABLE) {
        throw new RuntimeException("Shard value '" + column.toString() + "' in where clause is ambiguous. Sql is ["
                                   + sql + "]");
    }
    ShardRouteInfo routeInfo = getRouteInfo(tab, sdValue);
    // 当没有设置别名,但分表字段使用了表前缀时,别前缀需要根据路由结果进行重写;
    // 这里之所有没有采用将table取名的方式是因为update/delete/insert不全支持别名;
    // 由于select都是支持别名的,所有都会被添加别名,因此不会执行下面的操作;
    Table columnTable = column.getTable();
    if (tab.getAlias() == null && columnTable != null && columnTable.getName() != null
        && columnTable.getName().length() > 0) {
        if (columnTable.getSchemaName() != null) {
            columnTable.setSchemaName(routeInfo.getScName());
        }
        columnTable.setName(routeInfo.getTbName());
    }
    route0(tab, routeInfo);
}
 
Example #13
Source Project: sql-to-mongo-db-query-converter   Author: vincentrussell   File: OnVisitorMatchLookupBuilder.java    License: Apache License 2.0 6 votes vote down vote up
@Override
  public void visit(Column column) {
if(SqlUtils.isColumn(column)) {
	String columnName;
	if(column.getTable() != null) {
		columnName = SqlUtils.getColumnNameFromColumn(column);
	}
	else {
		columnName = column.getColumnName();
	}
	if(!SqlUtils.isTableAliasOfColumn(column, joinAliasTable) ) {
		if(column.getTable() == null || SqlUtils.isTableAliasOfColumn(column, baseAliasTable)) {//we know let var don't have table inside
			column.setColumnName("$$" + columnName.replace(".", "_").toLowerCase());
		}
		else {
			column.setColumnName("$$" + column.getName(false).replace(".", "_").toLowerCase());
		}
		column.setTable(null);
	}
	else {
		column.setTable(null);
		column.setColumnName("$" + columnName);
	}
}
  }
 
Example #14
Source Project: sql-to-mongo-db-query-converter   Author: vincentrussell   File: QueryConverter.java    License: Apache License 2.0 6 votes vote down vote up
private void validate() throws ParseException {
    List<SelectItem> selectItems = sqlCommandInfoHolder.getSelectItems();
    List<SelectItem> filteredItems = Lists.newArrayList(Iterables.filter(selectItems, new Predicate<SelectItem>() {
        @Override
        public boolean apply(SelectItem selectItem) {
            try {
                if (SelectExpressionItem.class.isInstance(selectItem)
                        && Column.class.isInstance(((SelectExpressionItem) selectItem).getExpression())) {
                    return true;
                }
            } catch (NullPointerException e) {
                return false;
            }
            return false;
        }
    }));

    SqlUtils.isFalse((selectItems.size() >1
            || SqlUtils.isSelectAll(selectItems))
            && sqlCommandInfoHolder.isDistinct(),"cannot run distinct one more than one column");
    SqlUtils.isFalse(sqlCommandInfoHolder.getGoupBys().size() == 0 && selectItems.size()!=filteredItems.size() && !SqlUtils.isSelectAll(selectItems)
            && !SqlUtils.isCountAll(selectItems)&& !sqlCommandInfoHolder.isTotalGroup(),"illegal expression(s) found in select clause.  Only column names supported");
}
 
Example #15
Source Project: sql-to-mongo-db-query-converter   Author: vincentrussell   File: SqlUtils.java    License: Apache License 2.0 6 votes vote down vote up
public static Object getValue(Expression incomingExpression, Expression otherSide,
                              FieldType defaultFieldType,
                              Map<String, FieldType> fieldNameToFieldTypeMapping) throws ParseException {
    FieldType fieldType = otherSide !=null ? firstNonNull(fieldNameToFieldTypeMapping.get(getStringValue(otherSide)),
            defaultFieldType) : FieldType.UNKNOWN;
    if (LongValue.class.isInstance(incomingExpression)) {
        return normalizeValue((((LongValue)incomingExpression).getValue()),fieldType);
    } else if (SignedExpression.class.isInstance(incomingExpression)) {
        return normalizeValue((((SignedExpression)incomingExpression).toString()),fieldType);
    } else if (StringValue.class.isInstance(incomingExpression)) {
        return normalizeValue((((StringValue)incomingExpression).getValue()),fieldType);
    } else if (Column.class.isInstance(incomingExpression)) {
        return normalizeValue(getStringValue(incomingExpression),fieldType);
    } else {
        throw new ParseException("can not parseNaturalLanguageDate: " + incomingExpression.toString());
    }
}
 
Example #16
Source Project: quetzal   Author: Quetzal-RDF   File: CTEToNestedQueryConverter.java    License: Eclipse Public License 2.0 6 votes vote down vote up
@Override
public void visit(Column tableColumn) {
	clear();
	boolean prevIsTopLevel = isTopLevel;
	isTopLevel = false;
	if (tableColumn.getTable()!=null && tableColumn.getTable().getName()!=null) {
		if (tableColumn.getTable().getName().equalsIgnoreCase(leftTable.getAlias()!=null? leftTable.getAlias().getName(): leftTable.getName())) {
			leftTableFound = true;
		}
		if (tableColumn.getTable().getName().equalsIgnoreCase(rightTable.getAlias()!=null? rightTable.getAlias().getName(): rightTable.getName())) {
			rightTableFound = true;
		}
	}
	isTopLevel = prevIsTopLevel;
	defaultTopLevelProcessing(tableColumn);
}
 
Example #17
Source Project: Mybatis-PageHelper   Author: pagehelper   File: CountSqlParser.java    License: MIT License 6 votes vote down vote up
/**
 * 将sql转换为count查询
 *
 * @param select
 */
public void sqlToCount(Select select, String name) {
    SelectBody selectBody = select.getSelectBody();
    // 是否能简化count查询
    List<SelectItem> COUNT_ITEM = new ArrayList<SelectItem>();
    COUNT_ITEM.add(new SelectExpressionItem(new Column("count(" + name +")")));
    if (selectBody instanceof PlainSelect && isSimpleCount((PlainSelect) selectBody)) {
        ((PlainSelect) selectBody).setSelectItems(COUNT_ITEM);
    } else {
        PlainSelect plainSelect = new PlainSelect();
        SubSelect subSelect = new SubSelect();
        subSelect.setSelectBody(selectBody);
        subSelect.setAlias(TABLE_ALIAS);
        plainSelect.setFromItem(subSelect);
        plainSelect.setSelectItems(COUNT_ITEM);
        select.setSelectBody(plainSelect);
    }
}
 
Example #18
Source Project: sqlhelper   Author: fangjinuo   File: JSqlParsers.java    License: GNU Lesser General Public License v3.0 5 votes vote down vote up
public static boolean columnEquals(Column column1, Column column2) {
    if (column1 == null && column2 == null) {
        return true;
    }
    if (column1 == null || column2 == null) {
        return false;
    }
    return column1.getFullyQualifiedName().equalsIgnoreCase(column2.getFullyQualifiedName());
}
 
Example #19
Source Project: sqlhelper   Author: fangjinuo   File: JSqlParsers.java    License: GNU Lesser General Public License v3.0 5 votes vote down vote up
public static boolean expressionEquals(Expression expr1, Expression expr2) {
    if (expr1 == null && expr2 == null) {
        return true;
    }
    if (expr1 == null || expr2 == null) {
        return false;
    }

    if (expr1 instanceof Column && expr2 instanceof Column) {
        return columnEquals((Column) expr1, (Column) expr2);
    }
    return expr1.toString().equalsIgnoreCase(expr2.toString());
}
 
Example #20
Source Project: sqlhelper   Author: fangjinuo   File: ColumnExpressionConverter.java    License: GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
public Column toJSqlParserExpression(ColumnExpression expression) {
    Column column = new Column();
    Database database = null;
    if (Strings.isNotEmpty(expression.getCatalog())) {
        database = new Database(expression.getCatalog());
    }
    String schema = expression.getSchema();
    String tableName = expression.getTable();
    Table table = database == null ? new Table(schema, tableName) : new Table(database, schema, tableName);
    column.setTable(table);
    column.setColumnName(expression.getColumn());
    return column;
}
 
Example #21
Source Project: foxtrot   Author: Flipkart   File: QueryTranslator.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void visit(EqualsTo equalsTo) {
    EqualsFilter equalsFilter = new EqualsFilter();
    String field = ((Column)equalsTo.getLeftExpression()).getFullyQualifiedName();
    equalsFilter.setField(field.replaceAll(Constants.SQL_FIELD_REGEX, ""));
    equalsFilter.setValue(getValueFromExpression(equalsTo.getRightExpression()));
    filters.add(equalsFilter);
}
 
Example #22
Source Project: foxtrot   Author: Flipkart   File: QueryTranslator.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void visit(LikeExpression likeExpression) {
    super.visit(likeExpression);
    ContainsFilter containsFilter = new ContainsFilter();
    containsFilter.setValue(getStringValue(likeExpression.getRightExpression()));
    containsFilter.setField(((Column)likeExpression.getLeftExpression()).getFullyQualifiedName()
                                    .replaceAll(Constants.SQL_FIELD_REGEX, ""));
    filters.add(containsFilter);
}
 
Example #23
Source Project: spanner-jdbc   Author: olavloite   File: CloudSpannerResultSetMetaData.java    License: MIT License 5 votes vote down vote up
private void initColumns(Select select) {
  columns = new ArrayList<>();
  aliases = new ArrayList<>();
  select.getSelectBody().accept(new SelectVisitorAdapter() {
    @Override
    public void visit(PlainSelect plainSelect) {
      for (SelectItem selectItem : plainSelect.getSelectItems()) {
        selectItem.accept(new SelectItemVisitor() {
          private boolean foundColumn = false;

          @Override
          public void visit(SelectExpressionItem selectExpressionItem) {
            selectExpressionItem.getExpression().accept(new ExpressionVisitorAdapter() {
              @Override
              public void visit(Column column) {
                registerColumn(column, selectExpressionItem.getAlias());
                foundColumn = true;
              }
            });
            if (!foundColumn) {
              registerColumn(null, selectExpressionItem.getAlias());
            }
          }

          @Override
          public void visit(AllTableColumns allTableColumns) {
            registerAllTableColumns(allTableColumns.getTable());
          }

          @Override
          public void visit(AllColumns allColumns) {
            for (Table table : tables) {
              registerAllTableColumns(table);
            }
          }
        });
      }
    }
  });
}
 
Example #24
Source Project: spanner-jdbc   Author: olavloite   File: CloudSpannerResultSetMetaData.java    License: MIT License 5 votes vote down vote up
private void registerAllTableColumns(Table table) {
  String schema = Strings.isNullOrEmpty(table.getSchemaName()) ? ""
      : CloudSpannerDriver.unquoteIdentifier(table.getSchemaName());
  String tableName = CloudSpannerDriver.unquoteIdentifier(table.getName());
  try (java.sql.ResultSet rs =
      statement.getConnection().getMetaData().getColumns("", schema, tableName, null)) {
    while (rs.next()) {
      registerColumn(new Column(table, rs.getString("COLUMN_NAME")));
    }
  } catch (SQLException e) {
    throw new ParseException(e);
  }
}
 
Example #25
Source Project: spanner-jdbc   Author: olavloite   File: CloudSpannerResultSetMetaData.java    License: MIT License 5 votes vote down vote up
@Override
public String getColumnName(int column) throws SQLException {
  Column col = getColumn(column);
  if (col != null)
    return col.getColumnName();
  return resultSet.getType().getStructFields().get(column - 1).getName();
}
 
Example #26
Source Project: quetzal   Author: Quetzal-RDF   File: CTEToNestedQueryConverter.java    License: Eclipse Public License 2.0 5 votes vote down vote up
private Expression getExpression(SelectItem item, Table table) {
	SelectExpressionItem rightSelectItem = (SelectExpressionItem) item;
	Expression rightExp = rightSelectItem.getExpression();
	if (rightExp instanceof Column) {
		Column c = (Column) rightExp;
		if (c.getTable() == null) {
			c.setTable(table);
		}
	}
	return rightExp;
}
 
Example #27
Source Project: spanner-jdbc   Author: olavloite   File: CloudSpannerResultSetMetaData.java    License: MIT License 5 votes vote down vote up
@Override
public String getTableName(int column) throws SQLException {
  Column col = getColumn(column);
  if (col != null && col.getTable() != null)
    return col.getTable().getName();

  return "";
}
 
Example #28
Source Project: spanner-jdbc   Author: olavloite   File: CloudSpannerResultSetMetaData.java    License: MIT License 5 votes vote down vote up
@Override
public boolean isReadOnly(int column) throws SQLException {
  Column col = getColumn(column);
  if (col == null || col.getTable() == null)
    return true;
  // Primary key columns are only insertable and never updatable, all
  // other columns are insertable and updatable. This however still means
  // that a primary key column is writable.
  return false;
}
 
Example #29
Source Project: spanner-jdbc   Author: olavloite   File: AbstractCloudSpannerStatement.java    License: MIT License 5 votes vote down vote up
/**
 * Transform the given UPDATE-statement into an "INSERT INTO TAB1 (...) SELECT ... FROM TAB1 WHERE
 * ... ON DUPLICATE KEY UPDATE"
 * 
 * @param update The UPDATE-statement
 * @return An SQL-statement equal to the UPDATE-statement but in INSERT form
 * @throws SQLException if a database exception occurs while getting the table meta data or if the
 *         statement tries to update the primary key value
 */
protected String createInsertSelectOnDuplicateKeyUpdateStatement(Update update)
    throws SQLException {
  String tableName = unquoteIdentifier(update.getTables().get(0).getName());
  TableKeyMetaData table = getConnection().getTable(tableName);
  List<String> keyColumns = table.getKeyColumns();
  List<String> updateColumns = update.getColumns().stream().map(Column::getColumnName)
      .map(String::toUpperCase).collect(Collectors.toList());
  List<String> quotedKeyColumns =
      keyColumns.stream().map(this::quoteIdentifier).collect(Collectors.toList());
  List<String> quotedAndQualifiedKeyColumns =
      keyColumns.stream().map(x -> quoteIdentifier(tableName) + "." + quoteIdentifier(x))
          .collect(Collectors.toList());

  List<String> quotedUpdateColumns =
      updateColumns.stream().map(this::quoteIdentifier).collect(Collectors.toList());
  List<String> expressions =
      update.getExpressions().stream().map(Object::toString).collect(Collectors.toList());
  if (updateColumns.stream().anyMatch(keyColumns::contains)) {
    String invalidCols =
        updateColumns.stream().filter(keyColumns::contains).collect(Collectors.joining());
    throw new CloudSpannerSQLException(
        "UPDATE of a primary key value is not allowed, cannot UPDATE the column(s) "
            + invalidCols,
        Code.INVALID_ARGUMENT);
  }

  StringBuilder res = new StringBuilder();
  res.append("INSERT INTO ").append(quoteIdentifier(tableName)).append("\n(");
  res.append(String.join(", ", quotedKeyColumns)).append(", ");
  res.append(String.join(", ", quotedUpdateColumns)).append(")");
  res.append("\nSELECT ").append(String.join(", ", quotedAndQualifiedKeyColumns)).append(", ");
  res.append(String.join(", ", expressions));
  res.append("\nFROM ").append(quoteIdentifier(tableName));
  if (update.getWhere() != null)
    res.append("\n").append("WHERE ").append(update.getWhere().toString());
  res.append("\nON DUPLICATE KEY UPDATE");

  return res.toString();
}
 
Example #30
Source Project: spanner-jdbc   Author: olavloite   File: AbstractSpannerExpressionVisitorAdapter.java    License: MIT License 5 votes vote down vote up
/**
 * Booleans are not recognized by the parser, but are seen as column names.
 * 
 * @param column
 */
@Override
public void visit(Column column) {
  String stringValue = column.getColumnName();
  if (stringValue.equalsIgnoreCase("true") || stringValue.equalsIgnoreCase("false")) {
    setValue(Boolean.valueOf(stringValue), Types.BOOLEAN);
  }
}