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

The following examples show how to use net.sf.jsqlparser.schema.Table. 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: DataPermissionHelper   Source File: FromItemVisitorImpl.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void visit(Table table) {
    String tableName = table.getName();
    //关键点:解析到需要进行数据权限控制的表时进行拼装,可以从当前线程获取表数据
    //需要进行的数据权限控制的表数据
    Map<String, IdsAndColumn> tables = DPHelper.getLocalDataPermissions().getTables();
    if (tables.containsKey(tableName)) {
        IdsAndColumn idsAndColumn = tables.get(tableName);
        List<String> ids = idsAndColumn.getIds();
        List<String> columns = idsAndColumn.getColumns();

        SubSelect subSelect = new SubSelect();
        String subSql = SqlSpliceUtils.spliceIdAndColumn(tableName, ids, columns);
        try {
            subSelect.setSelectBody(((Select) (CCJSqlParserUtil.parse(subSql))).getSelectBody());
        } catch (JSQLParserException e) {
            logger.error("数据权限sql解析异常");
        }
        //TODO:采用随机别名不能避免重名
        subSelect.setAlias(table.getAlias() != null ? table.getAlias() : new Alias("DP" + UUID.randomUUID()
                .toString().replace("-", "")));
        this.subSelect = subSelect;
    }
}
 
Example 2
Source Project: spanner-jdbc   Source File: AbstractCloudSpannerStatement.java    License: MIT License 6 votes vote down vote up
/**
 * Determines whether the given sql statement must be executed in a single use read context. This
 * must be done for queries against the information schema. This method sets the
 * <code>forceSingleUseReadContext</code> to true if necessary.
 * 
 * @param select The sql statement to be examined.
 */
protected void determineForceSingleUseReadContext(Select select) {
  if (select.getSelectBody() != null) {
    select.getSelectBody().accept(new SelectVisitorAdapter() {
      @Override
      public void visit(PlainSelect plainSelect) {
        if (plainSelect.getFromItem() != null) {
          plainSelect.getFromItem().accept(new FromItemVisitorAdapter() {
            @Override
            public void visit(Table table) {
              if (table.getSchemaName() != null
                  && table.getSchemaName().equalsIgnoreCase("INFORMATION_SCHEMA")) {
                setForceSingleUseReadContext(true);
              }
            }
          });
        }
      }

    });
  }
}
 
Example 3
Source Project: evosql   Source File: TablesNamesFinder.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void visit(Update update) {
    for (Table table : update.getTables()) {
        tables.add(table.getName());
    }
    if (update.getExpressions() != null) {
        for (Expression expression : update.getExpressions()) {
            expression.accept(this);
        }
    }

    if (update.getFromItem() != null) {
        update.getFromItem().accept(this);
    }

    if (update.getJoins() != null) {
        for (Join join : update.getJoins()) {
            join.getRightItem().accept(this);
        }
    }

    if (update.getWhere() != null) {
        update.getWhere().accept(this);
    }
}
 
Example 4
Source Project: ddal   Source 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 5
Source Project: ddal   Source File: JSQLParserAdapter.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void visit(Table table) {
    String tbName = table.getName();

    ShardRouteConfig routeConfig = shardRouter.getRouteConfig(table.getSchemaName(), tbName);
    if (routeConfig != null) {
        TableWrapper tab = new TableWrapper(table, routeConfig);
        FrameContext frameContext = this.getStack().peek();
        StatementType statementType = frameContext.getStatementType();
        if (statementType == StatementType.SELECT) {
            addRoutedTableIntoContext(tab, routeConfig, true);
        } else {
            addRoutedTableIntoContext(tab, routeConfig, false);
        }
    }
}
 
Example 6
private void addToSQLHolderMap(FromItem from) throws com.github.vincentrussell.query.mongodb.sql.converter.ParseException, ParseException {
	if (from instanceof Table) {
		Table table = (Table)from;
		fromToSQLHolder.put(table, new SQLTableInfoHolder(table.getName()));
   	}
   	else if(from instanceof SubSelect){
   		SubSelect subselect = (SubSelect) from; 
   		fromToSQLHolder.put(from, SQLCommandInfoHolder.Builder
                   .create(defaultFieldType, fieldNameToFieldTypeMapping)
                   .setPlainSelect((PlainSelect)subselect.getSelectBody())
                   .build());
   	}
   	else {//Not happen SubJoin, not supported previously
   		return;
   	}
}
 
Example 7
Source Project: quetzal   Source File: CTEToNestedQueryConverter.java    License: Eclipse Public License 2.0 6 votes vote down vote up
protected int getNumberNonPlaceHolderFromItem(PlainSelect plainSelect) {
	int ret = 0;
	if (useExplicitJoinSyntax) {
		for (Join join: plainSelect.getJoins()) {
			if (join.getRightItem()!=null) {
				if ( (join.getRightItem() instanceof Table)) {
					String tableName = ((Table) join.getRightItem()).getFullyQualifiedName();
					if (!placeHolderTables.contains(tableName)) {
						ret++;
					}
				} else {
					ret++;
				}
			}
		}
	}
	return ret;
}
 
Example 8
@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 9
Source Project: spanner-jdbc   Source 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 10
Source Project: spanner-jdbc   Source 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 11
Source Project: tx-lcn   Source File: TxcSqlExecuteInterceptor.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void preUpdate(Update update) throws SQLException {
    // 获取线程传递参数
    Connection connection = (Connection) DTXLocalContext.cur().getResource();

    // Update相关数据准备
    List<String> columns = new ArrayList<>(update.getColumns().size());
    List<String> primaryKeys = new ArrayList<>(3);
    List<String> tables = new ArrayList<>(update.getTables().size());
    update.getColumns().forEach(column -> {
        column.setTable(update.getTables().get(0));
        columns.add(column.getFullyQualifiedName());
    });
    for (Table table : update.getTables()) {
        tables.add(table.getName());
        TableStruct tableStruct = globalContext.tableStruct(table.getName(),
                () -> tableStructAnalyser.analyse(connection, table.getName()));
        tableStruct.getPrimaryKeys().forEach(key -> primaryKeys.add(table.getName() + "." + key));
    }

    // 前置准备
    try {
        UpdateImageParams updateImageParams = new UpdateImageParams();
        updateImageParams.setColumns(columns);
        updateImageParams.setPrimaryKeys(primaryKeys);
        updateImageParams.setTables(tables);
        updateImageParams.setWhereSql(update.getWhere() == null ? "1=1" : update.getWhere().toString());
        txcService.resolveUpdateImage(updateImageParams);
    } catch (TxcLogicException e) {
        throw new SQLException(e.getMessage());
    }
}
 
Example 12
Source Project: tx-lcn   Source File: TxcSqlExecuteInterceptor.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void preDelete(Delete delete) throws SQLException {
    // 获取线程传递参数
    Connection connection = (Connection) DTXLocalContext.cur().getResource();

    // 获取Sql Table
    if (delete.getTables().size() == 0) {
        delete.setTables(Collections.singletonList(delete.getTable()));
    }

    // Delete Sql 数据
    List<String> tables = new ArrayList<>(delete.getTables().size());
    List<String> primaryKeys = new ArrayList<>(3);
    List<String> columns = new ArrayList<>();

    for (Table table : delete.getTables()) {
        TableStruct tableStruct = globalContext.tableStruct(table.getName(),
                () -> tableStructAnalyser.analyse(connection, table.getName()));
        tableStruct.getColumns().forEach((k, v) -> columns.add(tableStruct.getTableName() + SqlUtils.DOT + k));
        tableStruct.getPrimaryKeys().forEach(primaryKey -> primaryKeys.add(tableStruct.getTableName() + SqlUtils.DOT + primaryKey));
        tables.add(tableStruct.getTableName());
    }

    // 前置准备
    try {
        DeleteImageParams deleteImageParams = new DeleteImageParams();
        deleteImageParams.setColumns(columns);
        deleteImageParams.setPrimaryKeys(primaryKeys);
        deleteImageParams.setTables(tables);
        deleteImageParams.setSqlWhere(delete.getWhere().toString());
        txcService.resolveDeleteImage(deleteImageParams);
    } catch (TxcLogicException e) {
        throw new SQLException(e.getMessage());
    }
}
 
Example 13
Source Project: evosql   Source File: UsedColumnExtractorVisitor.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void visit(Table arg0) {
	// This can only happen in a FROM, source the table
	String tableName = arg0.getName();
	String tableAlias = tableName;
	
	// Handle alias
	if (arg0.getAlias() != null) {
		tableAlias = arg0.getAlias().getName();
	}
	
	sourceTable(tableName, tableAlias);
}
 
Example 14
Source Project: evosql   Source File: TablesNamesFinder.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void visit(Table tableName) {
    String tableWholeName = tableName.getFullyQualifiedName();
    if (!otherItemNames.contains(tableWholeName.toLowerCase())
            && !tables.contains(tableWholeName)) {
        tables.add(tableWholeName);
    }
}
 
Example 15
Source Project: evosql   Source File: SqlSecurerVisitor.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void visit(Column arg0) {
	Table table = arg0.getTable();
	if (table != null) {
		table.accept(this);
	}
	arg0.setColumnName(secureName(arg0.getColumnName()));
}
 
Example 16
Source Project: evosql   Source File: SqlSecurerVisitor.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void visit(Table arg0) {
	if (arg0.getName() == null) return;
	
	arg0.setName(secureName(arg0.getName()));
	
	// Handle alias
	if (arg0.getAlias() != null) {
		arg0.getAlias().setName(secureName(arg0.getAlias().getName()));
	}
}
 
Example 17
Source Project: evosql   Source File: ClassifierVisitor.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void visit(Table arg0) {
	if (!visitedTables.contains(arg0.getName().toUpperCase())) {
		visitedTables.add(arg0.getName().toUpperCase());
		metrics.tables++;
	}
}
 
Example 18
Source Project: evosql   Source File: DetailedClassifierVisitor.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void visit(Table arg0) {
	if (!visitedTables.contains(arg0.getName().toUpperCase())) {
		visitedTables.add(arg0.getName().toUpperCase());
		increment(DetailedClassification.TABLES);
	}
}
 
Example 19
Source Project: evosql   Source File: CryptoVisitor.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void visit(Table arg0) {
	if (arg0.getName() == null) return;
	
	arg0.setName(transform(arg0.getName()));
	
	// Handle alias
	if (arg0.getAlias() != null) {
		arg0.getAlias().setName(transform(arg0.getAlias().getName()));
	}
}
 
Example 20
Source Project: ddal   Source File: JSQLParserAdapter.java    License: Apache License 2.0 5 votes vote down vote up
public TableWrapper(Table table, ShardRouteConfig routeConfig) {
    this.routeConfig = routeConfig;
    if (table != null) {
        this.table = table;
        originalConfig.setDatabase(table.getDatabase());
        originalConfig.setSchemaName(table.getSchemaName());
        originalConfig.setName(table.getName());
        originalConfig.setAlias(table.getAlias());
        originalConfig.setPivot(table.getPivot());
        originalConfig.setASTNode(table.getASTNode());
    }
}
 
Example 21
Source Project: herddb   Source File: TableRef.java    License: Apache License 2.0 5 votes vote down vote up
static TableRef buildFrom(Table fromTable, String defaultTableSpace) {
    String tableSpace = fromTable.getSchemaName();
    String tableName = fromTable.getName();
    String tableAlias = tableName;
    if (fromTable.getAlias() != null && fromTable.getAlias().getName() != null) {
        tableAlias = fromTable.getAlias().getName();
    }
    if (tableSpace == null) {
        tableSpace = defaultTableSpace;
    }
    return new TableRef(tableSpace, tableName, tableAlias);
}
 
Example 22
Source Project: compass   Source File: TableRenameVisitor.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void visit(Table table) 
{
    String fullyQualifiedName = table.getFullyQualifiedName();
    if (!otherItemNames.contains(fullyQualifiedName.toLowerCase()))
    {
        String oldTableName=table.getName();
        String newTableName=this.tableRenamer.rename(oldTableName);
        table.setName(newTableName);
    }
}
 
Example 23
Source Project: compass   Source File: TableRenameVisitor.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void visit(Update update)
{
    for (Table table : update.getTables())
    {
    	table.accept(this);
    }
    if (update.getExpressions() != null)
    {
        for (Expression expression : update.getExpressions())
        {
            expression.accept(this);
        }
    }

    if (update.getFromItem() != null)
    {
        update.getFromItem().accept(this);
    }

    if (update.getJoins() != null)
    {
        for (Join join : update.getJoins())
        {
            join.getRightItem().accept(this);
        }
    }

    if (update.getWhere() != null)
    {
        update.getWhere().accept(this);
    }
}
 
Example 24
Source Project: DDF   Source File: TableNameReplacer.java    License: Apache License 2.0 5 votes vote down vote up
private DDF handleIndex(String index, List<String> identifierList, Table table)
    throws Exception {
    if (!mIndexPattern.matcher(index).matches()) {
        // Not full uri, no namespace, the index can't match.
        throw new Exception(">>> ERROR: Can't find the required ddf "
            + index);
    }
    String number = index.substring(index.indexOf('{') + 1,
        index.indexOf('}')).trim();
    int idx = Integer.parseInt(number);
    if (idx < 1) {
        throw new Exception("In the SQL command, " +
            "if you use {number} as index, the number should begin from 1");
    }
    if (idx > identifierList.size()) {
        throw new Exception(new ArrayIndexOutOfBoundsException());
    } else {
        String identifier = identifierList.get(idx - 1);

        DDF ddf = null;
        try {
            ddf = this.mDDFManager.getDDFByName(identifier);
        } catch (DDFException e) {
            ddf = this.mDDFManager.getDDF(UUID.fromString(identifier));
        }
        return ddf;
    }
}
 
Example 25
Source Project: foxtrot   Source File: MetaStatementMatcher.java    License: Apache License 2.0 5 votes vote down vote up
public ExtendedSqlStatement parse(final String fql) {
    if(fql.matches(DESC_STATEMENT_MATCH)) {
        final String[] parts = fql.split(DESC_STATEMENT_DELIMITER);
        if(parts.length != 2) {
            throw new FqlParsingException("Could not decode table name from desc statement. Table name format is: [a-zA-Z-_]+");
        }
        return new Describe(new Table(parts[1].toLowerCase()));
    }
    if(fql.matches(SHOWTABLES_STATEMENT_MATCH)) {
        return new ShowTables();
    }
    return null;
}
 
Example 26
Source Project: quetzal   Source 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: mybatis-shard   Source File: SelectSqlConverter.java    License: Eclipse Public License 1.0 5 votes vote down vote up
@Override
public void visit(Table tableName) {
    String tableNameName = tableName.getName();

    if (includePattern.matcher(tableNameName).find()) {

        String newName = convertTableName(tableNameName, suffix);
        tableName.setName(newName);
    }
}
 
Example 28
@Override
public void visit(Table tableName) {
    tableName.setName(tableName.getName());
}
 
Example 29
Source Project: spanner-jdbc   Source File: CloudSpannerResultSetMetaData.java    License: MIT License 4 votes vote down vote up
private void initTable(Table table) {
  tables.add(table);
}
 
Example 30
Source Project: spanner-jdbc   Source File: DeleteWorker.java    License: MIT License 4 votes vote down vote up
@Override
protected Table getTable() {
  return delete.getTable();
}