/*
@param tableName
@param dataTable
compares two tables: pattern table and the result from remote database
by default: order by id
542364
@Then("^I check that table '(.+?)' is iqual to$")
    public void comparetable(String tableName, DataTable dataTable) throws Exception {
        Statement myStatement = null;
        java.sql.ResultSet rs = null;

        //from postgres table
        List<String> sqlTable = new ArrayList<String>();
        List<String> sqlTableAux = new ArrayList<String>();
        //from Cucumber Datatable
        List<String> tablePattern = new ArrayList<String>();
        //comparison is by lists of string
        tablePattern = dataTable.asList(String.class);


        Connection myConnection = this.commonspec.getConnection();
        String query = "SELECT * FROM " + tableName + " order by " + "id" + ";";
        try {
            myStatement = myConnection.createStatement();
            rs = myStatement.executeQuery(query);

            //takes column names and culumn count
            ResultSetMetaData resultSetMetaData = rs.getMetaData();
            int count = resultSetMetaData.getColumnCount();
            for (int i = 1; i <= count; i++) {
                sqlTable.add(resultSetMetaData.getColumnName(i).toString());
            }

            //takes column names and culumn count
            while (rs.next()) {
                for (int i = 1; i <= count; i++) {
                    //aux list without column names
                    sqlTableAux.add(rs.getObject(i).toString());
                }
            }
            sqlTable.addAll(sqlTableAux);

            assertThat(sqlTable).as("Not equal elements!").isEqualTo(tablePattern);
            rs.close();
            myStatement.close();
        } catch (Exception e) {
            e.printStackTrace();
            assertThat(rs).as("There are no table " + tableName).isNotNull();
        }
    }
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;
    }
1155791
public boolean remove(String table, String cellName) {

        if (cellName == null) {
            throw new DeepGenericException(new IllegalArgumentException(
                    "cell name parameter cannot be null"));
        }

        List<Cell> localCells = getCellsByTable(table);

        for (Cell currentCell : localCells) {
            if (currentCell.getCellName().equals(cellName)) {
                return localCells.remove(currentCell);
            }
        }

        return false;
    }
713381
public static int columnIndex(CSTable table, String name) {
        for (int i = 1; i <= table.getColumnCount(); i++) {
            if (table.getColumnName(i).equals(name)) {
                return i;
            }
        }
        return -1;
    }
53633
@Given("^I insert in keyspace '(.+?)' and table '(.+?)' with:$")
    public void insertData(String keyspace, String table, DataTable datatable) {
        try {
            commonspec.getCassandraClient().useKeyspace(keyspace);
            int attrLength = datatable.getPickleRows().get(0).getCells().size();
            Map<String, Object> fields = new HashMap<String, Object>();
            for (int e = 1; e < datatable.getPickleRows().size(); e++) {
                for (int i = 0; i < attrLength; i++) {
                    fields.put(datatable.getPickleRows().get(0).getCells().get(i).getValue(), datatable.getPickleRows().get(e).getCells().get(i).getValue());

                }
                commonspec.getCassandraClient().insertData(keyspace + "." + table, fields);

            }
        } catch (Exception e) {
            commonspec.getLogger().debug("Exception captured");
            commonspec.getLogger().debug(e.toString());
            commonspec.getExceptions().add(e);
        }
    }
271950
public boolean deleteById(String tableName, Object idValue) {
		return deleteByIds(tableName, config.dialect.getDefaultPrimaryKey(), idValue);
	}
986309
public VoltTable sortByAverage(String tableName)
    {
        List<ProcProfRow> sorted = new ArrayList<ProcProfRow>(m_table);
        Collections.sort(sorted, new Comparator<ProcProfRow>() {
            @Override
            public int compare(ProcProfRow lhs, ProcProfRow rhs) {
                return compareByAvg(rhs, lhs);  // sort desc
            }
        });

        long sumOfAverage = 0L;
        for (ProcProfRow row : sorted) {
            sumOfAverage += (row.avg * row.invocations);
        }

        VoltTable result = TableShorthand.tableFromShorthand(
                tableName + "(TIMESTAMP:BIGINT, PROCEDURE:VARCHAR, WEIGHTED_PERC:BIGINT, INVOCATIONS:BIGINT," +
                "AVG:BIGINT, MIN:BIGINT, MAX:BIGINT, ABORTS:BIGINT, FAILURES:BIGINT)");
        for (ProcProfRow row : sorted ) {
            result.addRow(row.timestamp, row.procedure, calculatePercent(row.avg * row.invocations, sumOfAverage),
                    row.invocations, row.avg, row.min, row.max, row.aborts, row.failures);
        }

        return result;
    }
74248
public boolean isShardingColumn(final String columnName, final String tableName) {
        for (TableRule each : tableRules) {
            if (each.getLogicTable().equalsIgnoreCase(tableName) && isShardingColumn(each, columnName)) {
                return true;
            }
        }
        return false;
    }
955000
public TableResult listTableDataSchema(
      String datasetName, String tableName, Schema schema, String field) {
    // [START ]
    TableResult tableData = bigquery.listTableData(datasetName, tableName, schema);
    for (FieldValueList row : tableData.iterateAll()) {
      row.get(field);
    }
    // [END ]
    return tableData;
  }
1286784
public static boolean columnExist(CSTable table, String name) {
        for (int i = 1; i <= table.getColumnCount(); i++) {
            if (table.getColumnName(i).startsWith(name)) {
                return true;
            }
        }
        return false;
    }
1325211
public boolean hasTableOrColumnCaseSensitive(String table, String column) {

        boolean result = false;
        ResultSet set = null;

        try {
            if (CmsStringUtil.isNotEmptyOrWhitespaceOnly(column)) {
                // Check if the column is given
                set = m_con.getMetaData().getColumns(null, null, table, column);
                if (set.next()) {
                    String colname = set.getString("COLUMN_NAME");
                    if (colname.equalsIgnoreCase(column)) {
                        result = true; // The column is available
                    }
                }
            } else if (CmsStringUtil.isNotEmptyOrWhitespaceOnly(table)) {
                // Check the table
                set = m_con.getMetaData().getTables(null, null, table, null);
                if (set.next()) {
                    String tablename = set.getString("TABLE_NAME");
                    if (tablename.equalsIgnoreCase(table)) {
                        result = true;
                    }
                }
            }
        } catch (SQLException e) {
            e.printStackTrace();
            result = false;
        } finally {
            try {
                if (set != null) {
                    set.close();
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        return result;
    }
1211948
@Override
    protected void compareData(ITable expectedTable, ITable actualTable, ComparisonColumn[] comparisonCols, FailureHandler failureHandler) throws DataSetException {
        logger.debug("compareData(expectedTable={}, actualTable={}, "
                        + "comparisonCols={}, failureHandler={}) - start",
                new Object[]{expectedTable, actualTable, comparisonCols,
                        failureHandler});

        if (expectedTable == null) {
            throw new NullPointerException(
                    "The parameter 'expectedTable' must not be null");
        }
        if (actualTable == null) {
            throw new NullPointerException(
                    "The parameter 'actualTable' must not be null");
        }
        if (comparisonCols == null) {
            throw new NullPointerException(
                    "The parameter 'comparisonCols' must not be null");
        }
        if (failureHandler == null) {
            throw new NullPointerException(
                    "The parameter 'failureHandler' must not be null");
        }

        // iterate over all rows
        for (int i = 0; i < expectedTable.getRowCount(); i++) {
            // iterate over all columns of the current row
            for (int j = 0; j < comparisonCols.length; j++) {
                ComparisonColumn compareColumn = comparisonCols[j];

                String columnName = compareColumn.getColumnName();
                DataType dataType = compareColumn.getDataType();

                Object expectedValue = expectedTable.getValue(i, columnName);
                Object actualValue = actualTable.getValue(i, columnName);

                // Compare the values
                if (skipCompare(columnName, expectedValue, actualValue)) {
                    if (logger.isTraceEnabled()) {
                        logger.trace("ignoring comparison " + expectedValue + "=" +
                                actualValue + " on column " + columnName);
                    }
                    continue;
                }

                if(expectedValue != null && expectedValue.toString().startsWith("regex:")){
                    if(!regexMatches(expectedValue.toString(),actualValue.toString())){
                        Difference diff = new Difference(
                                expectedTable, actualTable,
                                i, columnName,
                                expectedValue, actualValue);

                        // Handle the difference (throw error immediately or something else)
                        failureHandler.handle(diff);
                    }
                }
                else if (dataType.compare(expectedValue, actualValue) != 0) {

                    Difference diff = new Difference(
                            expectedTable, actualTable,
                            i, columnName,
                            expectedValue, actualValue);

                    // Handle the difference (throw error immediately or something else)
                    failureHandler.handle(diff);
                }
            }
        }
    }
713304
@Then("^a Cassandra keyspace '(.+?)' contains a table '(.+?)'$")
    public void assertTableExistsOnCassandraKeyspace(String keyspace, String tableName) {
        assertThat(commonspec.getCassandraClient().getTables(keyspace)).as("The table " + tableName + "exists on cassandra").contains(tableName);
    }
1122393
public Job copyTableId(String dataset, String tableName) throws BigQueryException {
    // [START bigquery_copy_table]
    TableId destinationId = TableId.of(dataset, tableName);
    JobOption options = JobOption.fields(JobField.STATUS, JobField.USER_EMAIL);
    Job job = table.copy(destinationId, options);
    // Wait for the job to complete.
    try {
      Job completedJob =
          job.waitFor(
              RetryOption.initialRetryDelay(Duration.ofSeconds(1)),
              RetryOption.totalTimeout(Duration.ofMinutes(3)));
      if (completedJob != null && completedJob.getStatus().getError() == null) {
        // Job completed successfully.
      } else {
        // Handle error case.
      }
    } catch (InterruptedException e) {
      // Handle interrupted wait
    }
    // [END bigquery_copy_table]
    return job;
  }
1141892
public boolean deleteTableFromId(String projectId, String datasetName, String tableName) {
    // [START bigquery_delete_table]
    TableId tableId = TableId.of(projectId, datasetName, tableName);
    boolean deleted = bigquery.delete(tableId);
    if (deleted) {
      // the table was deleted
    } else {
      // the table was not found
    }
    // [END bigquery_delete_table]
    return deleted;
  }
48360
@Then("^a Cassandra keyspace '(.+?)' contains a table '(.+?)' with values:$")
    public void assertValuesOfTable(String keyspace, String tableName, DataTable data) throws InterruptedException {
        //  USE of Keyspace
        commonspec.getCassandraClient().useKeyspace(keyspace);
        // Obtain the types and column names of the datatable
        // to return in a hashmap,
        Map<String, String> dataTableColumns = extractColumnNamesAndTypes(data.raw().get(0));
        // check if the table has columns
        String query = "SELECT * FROM " + tableName + " LIMIT 1;";
        com.datastax.driver.core.ResultSet res = commonspec.getCassandraClient().executeQuery(query);
        equalsColumns(res.getColumnDefinitions(), dataTableColumns);
        //receiving the string from the select with the columns
        // that belong to the dataTable
        List<String> selectQueries = giveQueriesList(data, tableName, columnNames(data.raw().get(0)));
        //Check the data  of cassandra with different queries
        int index = 1;
        for (String execQuery : selectQueries) {
            res = commonspec.getCassandraClient().executeQuery(execQuery);
            List<Row> resAsList = res.all();
            assertThat(resAsList.size()).as("The query " + execQuery + " not return any result on Cassandra").isGreaterThan(0);
            assertThat(resAsList.get(0).toString()
                    .substring(VALUE_SUBSTRING)).as("The resultSet is not as expected").isEqualTo(data.raw().get(index).toString().replace("'", ""));
            index++;
        }
    }
851445
private void deleteTable(String tableName) {
        m_logger.info("Deleting table: {}", tableName);
        try {
            m_ddbClient.deleteTable(new DeleteTableRequest(tableName));
            for (int seconds = 0; seconds < 10; seconds++) {
                try {
                    m_ddbClient.describeTable(tableName);
                    Thread.sleep(1000);
                } catch (ResourceNotFoundException e) {
                    break;  // Success
                }   // All other exceptions passed to outer try/catch
            }
        } catch (ResourceNotFoundException e) {
            // Already deleted.
        } catch (Exception e) {
            throw new RuntimeException("Error deleting table: " + tableName, e);
        }
    }