Get imported keys.

@param tableDef   table definition
@param tableName  table name
@param catalog    catalog
@param connection connection
@return resultset resultset
@throws ParseException exception
162237
private static ResultSet getImportedKeys(String tableDef, String tableName, String catalog,
      MariaDbConnection connection) throws ParseException {
    String[] columnNames = {
        "PKTABLE_CAT", "PKTABLE_SCHEM", "PKTABLE_NAME",
        "PKCOLUMN_NAME", "FKTABLE_CAT", "FKTABLE_SCHEM",
        "FKTABLE_NAME", "FKCOLUMN_NAME", "KEY_SEQ",
        "UPDATE_RULE", "DELETE_RULE", "FK_NAME",
        "PK_NAME", "DEFERRABILITY"
    };
    ColumnType[] columnTypes = {
        ColumnType.VARCHAR, ColumnType.NULL, ColumnType.VARCHAR,
        ColumnType.VARCHAR, ColumnType.VARCHAR, ColumnType.NULL,
        ColumnType.VARCHAR, ColumnType.VARCHAR, ColumnType.SMALLINT,
        ColumnType.SMALLINT, ColumnType.SMALLINT, ColumnType.VARCHAR,
        ColumnType.NULL, ColumnType.SMALLINT};

    String[] parts = tableDef.split("\n");

    List<String[]> data = new ArrayList<>();

    for (String part : parts) {
      part = part.trim();
      if (!part.startsWith("CONSTRAINT") && !part.contains("FOREIGN KEY")) {
        continue;
      }
      char[] partChar = part.toCharArray();

      Identifier constraintName = new Identifier();

      int pos = skipKeyword(partChar, 0, "CONSTRAINT");
      pos = parseIdentifier(partChar, pos, constraintName);
      pos = skipKeyword(partChar, pos, "FOREIGN KEY");
      List<Identifier> foreignKeyCols = new ArrayList<>();
      pos = parseIdentifierList(partChar, pos, foreignKeyCols);
      pos = skipKeyword(partChar, pos, "REFERENCES");
      Identifier pkTable = new Identifier();
      pos = parseIdentifier(partChar, pos, pkTable);
      List<Identifier> primaryKeyCols = new ArrayList<>();
      parseIdentifierList(partChar, pos, primaryKeyCols);
      if (primaryKeyCols.size() != foreignKeyCols.size()) {
        throw new ParseException(tableDef, 0);
      }
      int onUpdateReferenceAction = DatabaseMetaData.importedKeyRestrict;
      int onDeleteReferenceAction = DatabaseMetaData.importedKeyRestrict;

      for (String referenceAction : new String[]{"RESTRICT", "CASCADE", "SET NULL", "NO ACTION"}) {
        if (part.contains("ON UPDATE " + referenceAction)) {
          onUpdateReferenceAction = getImportedKeyAction(referenceAction);
        }
        if (part.contains("ON DELETE " + referenceAction)) {
          onDeleteReferenceAction = getImportedKeyAction(referenceAction);
        }
      }

      for (int i = 0; i < primaryKeyCols.size(); i++) {

        String[] row = new String[columnNames.length];
        row[0] = pkTable.schema;
        if (row[0] == null) {
          row[0] = catalog;
        }
        row[1] = null;
        row[2] = pkTable.name;
        row[3] = primaryKeyCols.get(i).name;
        row[4] = catalog;
        row[5] = null;
        row[6] = tableName;
        row[7] = foreignKeyCols.get(i).name;
        row[8] = Integer.toString(i + 1);
        row[9] = Integer.toString(onUpdateReferenceAction);
        row[10] = Integer.toString(onDeleteReferenceAction);
        row[11] = constraintName.name;
        row[12] = null;
        row[13] = Integer.toString(DatabaseMetaData.importedKeyNotDeferrable);
        data.add(row);
      }
    }
    String[][] arr = data.toArray(new String[0][]);

    /* Sort array by PKTABLE_CAT, PKTABLE_NAME, and KEY_SEQ.*/
    Arrays.sort(arr, (row1, row2) -> {
      int result = row1[0].compareTo(row2[0]);   //PKTABLE_CAT
      if (result == 0) {
        result = row1[2].compareTo(row2[2]);   //PKTABLE_NAME
        if (result == 0) {
          result = row1[8].length() - row2[8].length();  // KEY_SEQ
          if (result == 0) {
            result = row1[8].compareTo(row2[8]);
          }
        }
      }
      return result;
    });
    return SelectResultSet.createResultSet(columnNames, columnTypes, arr, connection.getProtocol());
  }
353026
public final List<Connection> getConnections(final ConnectionMode connectionMode, final String dataSourceName, final int connectionSize) throws SQLException {
        DataSource dataSource = getDataSourceMap().get(dataSourceName);
        Preconditions.checkState(null != dataSource, "Missing the data source name: '%s'", dataSourceName);
        Collection<Connection> connections;
        synchronized (cachedConnections) {
            connections = cachedConnections.get(dataSourceName);
        }
        List<Connection> result;
        if (connections.size() >= connectionSize) {
            result = new ArrayList<>(connections).subList(0, connectionSize);
        } else if (!connections.isEmpty()) {
            result = new ArrayList<>(connectionSize);
            result.addAll(connections);
            List<Connection> newConnections = createConnections(dataSourceName, connectionMode, dataSource, connectionSize - connections.size());
            result.addAll(newConnections);
            synchronized (cachedConnections) {
                cachedConnections.putAll(dataSourceName, newConnections);
            }
        } else {
            result = new ArrayList<>(createConnections(dataSourceName, connectionMode, dataSource, connectionSize));
            synchronized (cachedConnections) {
                cachedConnections.putAll(dataSourceName, result);
            }
        }
        return result;
    }
1185511
public Set<String> getTable(String sql) {
		Set<String> tableSet = new HashSet<String>();
		
		try {
			Statement statement = parserManager.parse(new StringReader(sql));
			
			if (statement instanceof Select) {
				tableSet = new SelectParser().parse((Select)statement);
			} else if (statement instanceof Delete) {
				tableSet = new DeleteParser().parse((Delete)statement);
			} else if (statement instanceof Insert) {
				tableSet = new InsertParser().parse((Insert)statement);
			} else if (statement instanceof Update) {
				tableSet = new UpdateParser().parse((Update)statement);
			} else if (statement instanceof CreateTable) {
				tableSet = new CreateTableParser().parse((CreateTable)statement);
			} else if (statement instanceof CreateView) {
				tableSet = new CreateViewParser().parse((CreateView)statement);
			} else if (statement instanceof Alter) {
				tableSet = new AlterParser().parse((Alter)statement);
			} else if (statement instanceof Drop) {
				tableSet = new DropParser().parse((Drop)statement);
			}
		} catch (Exception e) {
			logger.debug(String.format("SQL Parse Exception: exception=%s, sql=%s", e.getMessage(), sql));
		} catch (Error e) {
			logger.debug(String.format("SQL Parse Exception: exception=%s, sql=%s", e.getMessage(), sql));
		}
		
		Set<String> resultSet = new HashSet<String>();
		for (String tableName : tableSet) {
			if (StringUtils.isNotEmpty(tableName)) {
				if (tableName.startsWith("`")) {
					tableName = tableName.substring(1);
				}
				if (tableName.endsWith("`")) {
					tableName = tableName.substring(0, tableName.length() - 1);
				}
				resultSet.add(tableName.toUpperCase());
			}
		}
		
		return resultSet;
	}
91012
public static int getColumnType (Connection conn, String table,
                                     String column)
        throws SQLException
    {
        ResultSet rs = getColumnMetaData(conn, table, column);
        try {
            return rs.getInt("DATA_TYPE");
        } finally {
            rs.close();
        }
    }
225022
@Override
    public ResultSet getTables(String catalog, String schemaPattern, String tableNamePattern, String[] types) throws SQLException
    {
        checkClosed();
        this.sysCatalog.setString(1, "TABLES");
        JDBC4ResultSet res = (JDBC4ResultSet) this.sysCatalog.executeQuery();
        VoltTable vtable = res.getVoltTable().clone(0);

        List<String> typeStrings = null;
        if (types != null) {
            typeStrings = Arrays.asList(types);
        }

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

        Pattern table_pattern = computeJavaPattern(tableNamePattern);

        // Filter tables based on type and pattern
        while (res.next()) {
            if (typeStrings == null || typeStrings.contains(res.getString("TABLE_TYPE"))) {
                Matcher table_matcher = table_pattern.matcher(res.getString("TABLE_NAME"));
                if (table_matcher.matches())
                {
                    vtable.addRow(res.getRowData());
                }
            }
        }

        return new JDBC4ResultSet(this.sysCatalog, vtable);
    }
1198233
public List<Connection> getConnections(final ConnectionMode connectionMode, final String dataSourceName, final int connectionSize) throws SQLException {
        if (stateHandler.isInTransaction()) {
            return getConnectionsWithTransaction(connectionMode, dataSourceName, connectionSize);
        } else {
            return getConnectionsWithoutTransaction(connectionMode, dataSourceName, connectionSize);
        }
    }
766480
protected String[] getKeysFromResultSet()
            throws SQLException {

        String[] keys = super.getKeysFromResultSet();

        // check schemaProperty mapping names for more accurate column->field mapping
        SchemaProperty[] props = _schemaType.getElementProperties();
        for (int i = 0; i < props.length; i++) {

            int col = -1;
            try {
                col = _resultSet.findColumn(props[i].getName().getLocalPart());
            } catch (SQLException x) {
            }

            if (col > 0) {
                keys[col] = props[i].getJavaPropertyName().toUpperCase();
            }
        }
        return keys;
    }
750036
protected List<String> getTableNames(final Connection connection) throws SQLException {
        ResultSet resultSet = null;

        try {
            final List<String> tables = new ArrayList<String>();

            resultSet = connection.getMetaData().getTables(null, null, "%", new String[] { "TABLE" });

            while (resultSet.next()) {
                tables.add(resultSet.getString("TABLE_NAME"));
            }
            return tables;
        } finally {
            if (resultSet != null) {
                resultSet.close();
            }
        }

    }
1243814
private static List<RelationID> getTableList(Connection conn, RelationListProvider relationListProvider, QuotedIDFactory idfac) throws SQLException {

		// Obtain the relational objects (i.e., tables and views)
		List<RelationID> relationIds = new LinkedList<>();
		try (Statement stmt = conn.createStatement();
				ResultSet rs = stmt.executeQuery(relationListProvider.getQuery())) {
			while (rs.next())
				relationIds.add(relationListProvider.getTableID(rs));
		}
		return relationIds;
	}
1301024
@Override
    public ResultSet getVersionColumns(String catalog, String schema, String table) throws SQLException
    {
        checkClosed();
        throw SQLError.noSupport();
    }
106307
private void addIndex(IndexDescriptorDef indexDescDef, TableDef tableDef)
    {
        IndexDef indexDef = tableDef.getIndex(indexDescDef.getName());

        if (indexDef == null)
        {
            indexDef = new IndexDef(indexDescDef.getName(),
                                    indexDescDef.getBooleanProperty(PropertyHelper.OJB_PROPERTY_UNIQUE, false));
            tableDef.addIndex(indexDef);
        }

        try
        {
            String             fieldNames = indexDescDef.getProperty(PropertyHelper.OJB_PROPERTY_FIELDS);
            ArrayList          fields     = ((ClassDescriptorDef)indexDescDef.getOwner()).getFields(fieldNames);
            FieldDescriptorDef fieldDef;

            for (Iterator it = fields.iterator(); it.hasNext();)
            {
                fieldDef = (FieldDescriptorDef)it.next();
                indexDef.addColumn(fieldDef.getProperty(PropertyHelper.OJB_PROPERTY_COLUMN));
            }
        }
        catch (NoSuchFieldException ex)
        {
            // won't happen if we already checked the constraints
        }
    }
355212
public List<T> query(ConnectionSource connectionSource, PreparedStmt<T> preparedStmt, ObjectCache objectCache)
			throws SQLException {
		SelectIterator<T, ID> iterator = buildIterator(/* no dao specified because no removes */null, connectionSource,
				preparedStmt, objectCache, DatabaseConnection.DEFAULT_RESULT_FLAGS);
		try {
			List<T> results = new ArrayList<T>();
			while (iterator.hasNextThrow()) {
				results.add(iterator.nextThrow());
			}
			logger.debug("query of '{}' returned {} results", preparedStmt.getStatement(), results.size());
			return results;
		} finally {
			IOUtils.closeThrowSqlException(iterator, "iterator");
		}
	}
1219201
@Override
    public ResultSet getProcedureColumns(String catalog, String schemaPattern, String procedureNamePattern, String columnNamePattern) throws SQLException
    {
        assert(procedureNamePattern != null && !procedureNamePattern.isEmpty());
        checkClosed();
        this.sysCatalog.setString(1, "PROCEDURECOLUMNS");
        JDBC4ResultSet res = (JDBC4ResultSet) this.sysCatalog.executeQuery();
        VoltTable vtable = res.getVoltTable().clone(0);

        // Filter the results based on procedure name and column name
        while (res.next()) {
            if (res.getString("PROCEDURE_NAME").equals(procedureNamePattern)) {
                if (columnNamePattern == null || columnNamePattern.equals("%") ||
                    res.getString("COLUMN_NAME").equals(columnNamePattern)) {
                    vtable.addRow(res.getRowData());
                }
            }
        }

        return new JDBC4ResultSet(sysCatalog, vtable);
    }
1215646
public List getDataList(DataSource ds, String key, String sql, int start, int count) throws
     Exception {
   Connection c = null;
   Statement stmt = null;
   ResultSet rs = null;
   List items = new ArrayList(count);
   try {
     c = ds.getConnection();
     stmt = c.createStatement();

     DbUtil.testConnection(c);
     if (DbUtil.supportsMaxRows)
       stmt.setMaxRows(count + start + 1);
     rs = stmt.executeQuery(sql);
     if (DbUtil.supportsFetchSize)
       rs.setFetchSize(count);
     if (start >= 0 && rs.absolute(start + 1)) {

       do {
         items.add(rs.getString(1));
       }
       while ( (rs.next()) && (--count > 0));

     }

   } catch (SQLException se) {
     throw new Exception("SQLException: " + se.getMessage());
   } finally {
     if (rs != null)
       rs.close();
     if (stmt != null)
       stmt.close();
     if (c != null)
       c.close();
   }
    return items;
 }
67082
@Override
    public Object getTable(String tableName) {
	logger.debug("OMID Begin of getTable for " + tableName);
        TTable table = tableNameHandleMap.get(tableName);
        if (table != null) {
            logger.debug("OMIDE Found a cached handle for table " + tableName);
            return table;
        }
        try {
            table = new TTable(this.getHbcfg(), tableName);
        } catch (IOException e) {
            logger.error("OMID Error trying to get a TransactionTable of OMID.");
            logger.error(e.getMessage());
        }
        tableNameHandleMap.put(tableName, table);
        logger.debug("OMID Cached a handle of table: " + tableName);
        return table;
    }
493008
private List<ColumnDef> getKeysMeta(Cassandra.Client client)
            throws Exception
    {
        String query = "SELECT key_aliases, " +
                "       column_aliases, " +
                "       key_validator, " +
                "       comparator, " +
                "       keyspace_name, " +
                "       value_alias, " +
                "       default_validator " +
                "FROM system.schema_columnfamilies " +
                "WHERE keyspace_name = '%s'" +
                "  AND columnfamily_name = '%s' ";

        CqlResult result = client.execute_cql3_query(
                ByteBufferUtil.bytes(String.format(query, keyspace, column_family)),
                Compression.NONE,
                ConsistencyLevel.ONE);

        if (result == null || result.rows == null || result.rows.isEmpty())
            return null;

        Iterator<CqlRow> iteraRow = result.rows.iterator();
        List<ColumnDef> keys = new ArrayList<ColumnDef>();
        if (iteraRow.hasNext())
        {
            CqlRow cqlRow = iteraRow.next();
            String name = ByteBufferUtil.string(cqlRow.columns.get(4).value);
            logger.debug("Found ksDef name: {}", name);
            String keyString = ByteBufferUtil.string(ByteBuffer.wrap(cqlRow.columns.get(0).getValue()));

            logger.debug("partition keys: {}", keyString);
            List<String> keyNames = FBUtilities.fromJsonList(keyString);

            Iterator<String> iterator = keyNames.iterator();
            while (iterator.hasNext())
            {
                ColumnDef cDef = new ColumnDef();
                cDef.name = ByteBufferUtil.bytes(iterator.next());
                keys.add(cDef);
            }
            // classic thrift tables
            if (keys.size() == 0)
            {
                CFMetaData cfm = getCFMetaData(keyspace, column_family, client);
                for (ColumnDefinition def : cfm.partitionKeyColumns())
                {
                    String key = def.name.toString();
                    logger.debug("name: {} ", key);
                    ColumnDef cDef = new ColumnDef();
                    cDef.name = ByteBufferUtil.bytes(key);
                    keys.add(cDef);
                }
                for (ColumnDefinition def : cfm.clusteringColumns())
                {
                    String key = def.name.toString();
                    logger.debug("name: {} ", key);
                    ColumnDef cDef = new ColumnDef();
                    cDef.name = ByteBufferUtil.bytes(key);
                    keys.add(cDef);
                }
            }

            keyString = ByteBufferUtil.string(ByteBuffer.wrap(cqlRow.columns.get(1).getValue()));

            logger.debug("cluster keys: {}", keyString);
            keyNames = FBUtilities.fromJsonList(keyString);

            iterator = keyNames.iterator();
            while (iterator.hasNext())
            {
                ColumnDef cDef = new ColumnDef();
                cDef.name = ByteBufferUtil.bytes(iterator.next());
                keys.add(cDef);
            }

            String validator = ByteBufferUtil.string(ByteBuffer.wrap(cqlRow.columns.get(2).getValue()));
            logger.debug("row key validator: {}", validator);
            AbstractType<?> keyValidator = parseType(validator);

            Iterator<ColumnDef> keyItera = keys.iterator();
            if (keyValidator instanceof CompositeType)
            {
                Iterator<AbstractType<?>> typeItera = ((CompositeType) keyValidator).types.iterator();
                while (typeItera.hasNext())
                    keyItera.next().validation_class = typeItera.next().toString();
            }
            else
                keyItera.next().validation_class = keyValidator.toString();

            validator = ByteBufferUtil.string(ByteBuffer.wrap(cqlRow.columns.get(3).getValue()));
            logger.debug("cluster key validator: {}", validator);

            if (keyItera.hasNext() && validator != null && !validator.isEmpty())
            {
                AbstractType<?> clusterKeyValidator = parseType(validator);

                if (clusterKeyValidator instanceof CompositeType)
                {
                    Iterator<AbstractType<?>> typeItera = ((CompositeType) clusterKeyValidator).types.iterator();
                    while (keyItera.hasNext())
                        keyItera.next().validation_class = typeItera.next().toString();
                }
                else
                    keyItera.next().validation_class = clusterKeyValidator.toString();
            }

            // compact value_alias column
            if (cqlRow.columns.get(5).value != null)
            {
                try
                {
                    String compactValidator = ByteBufferUtil.string(ByteBuffer.wrap(cqlRow.columns.get(6).getValue()));
                    logger.debug("default validator: {}", compactValidator);
                    AbstractType<?> defaultValidator = parseType(compactValidator);

                    ColumnDef cDef = new ColumnDef();
                    cDef.name = cqlRow.columns.get(5).value;
                    cDef.validation_class = defaultValidator.toString();
                    keys.add(cDef);
                    hasCompactValueAlias = true;
                }
                catch (Exception e)
                {
                    // no compact column at value_alias
                }
            }

        }
        return keys;
    }
475139
@Override
  public void findAll(Result<Iterable<byte[]>> result,
                      byte []tableKey,
                      String sql, 
                      Object[] args)
  {
    try {
      TableKraken table = _tableManager.getTable(tableKey);
      
      if (table == null) {
        throw new QueryException(L.l("'{0}' is an unknown table.",
                                     Hex.toShortHex(tableKey)));
      }
      
      QueryBuilderKraken builder = QueryParserKraken.parse(_tableManager, sql);
      
      QueryKraken query = builder.build();
      
      query.findAllLocalKeys(result, args);
    } catch (Throwable e) {
      result.fail(e);
    }
  }