Search in sources :

Example 1 with FieldType

use of io.cdap.cdap.spi.data.table.field.FieldType in project cdap by caskdata.

the class SystemAppTestBaseTest method testTableOperations.

@Test
public void testTableOperations() throws Exception {
    StructuredTableAdmin tableAdmin = getStructuredTableAdmin();
    StructuredTableId id = new StructuredTableId("t0");
    Assert.assertFalse(tableAdmin.exists(id));
    String keyCol = "key";
    String valCol = "val";
    tableAdmin.create(new StructuredTableSpecification.Builder().withId(id).withFields(new FieldType(keyCol, FieldType.Type.STRING), new FieldType(valCol, FieldType.Type.STRING)).withPrimaryKeys(keyCol).build());
    try {
        TransactionRunner transactionRunner = getTransactionRunner();
        String key = "k0";
        String val = "v0";
        transactionRunner.run(context -> {
            StructuredTable table = context.getTable(id);
            List<Field<?>> fields = new ArrayList<>();
            fields.add(Fields.stringField(keyCol, key));
            Optional<StructuredRow> row = table.read(fields);
            Assert.assertFalse(row.isPresent());
            fields.add(Fields.stringField(valCol, val));
            table.upsert(fields);
        });
        transactionRunner.run(context -> {
            StructuredTable table = context.getTable(id);
            List<Field<?>> keyField = Collections.singletonList(Fields.stringField(keyCol, key));
            Optional<StructuredRow> row = table.read(keyField);
            Assert.assertTrue(row.isPresent());
            Assert.assertEquals(val, row.get().getString(valCol));
        });
    } finally {
        tableAdmin.drop(id);
    }
}
Also used : StructuredTable(io.cdap.cdap.spi.data.StructuredTable) StructuredTableAdmin(io.cdap.cdap.spi.data.StructuredTableAdmin) ArrayList(java.util.ArrayList) StructuredRow(io.cdap.cdap.spi.data.StructuredRow) FieldType(io.cdap.cdap.spi.data.table.field.FieldType) Field(io.cdap.cdap.spi.data.table.field.Field) TransactionRunner(io.cdap.cdap.spi.data.transaction.TransactionRunner) StructuredTableId(io.cdap.cdap.spi.data.table.StructuredTableId) StructuredTableSpecification(io.cdap.cdap.spi.data.table.StructuredTableSpecification) Test(org.junit.Test)

Example 2 with FieldType

use of io.cdap.cdap.spi.data.table.field.FieldType in project cdap by caskdata.

the class DraftStore method doSort.

/**
 * Helper method to apply the sorting onto a list of rows. Sorting needs to take place at the store-level so it can
 * leverage the StructuredRow to enable sorting on any field.
 *
 * @param rows list of {@link StructuredRow} to be sorted
 * @param sortRequest {@link SortRequest} describing the sort to be performed
 * @return a sorted list of {@link StructuredRow}
 */
private List<StructuredRow> doSort(List<StructuredRow> rows, @Nullable SortRequest sortRequest) {
    if (sortRequest == null) {
        return rows;
    }
    String sortField = sortRequest.getFieldName();
    FieldType field = TABLE_SPEC.getFieldTypes().stream().filter(f -> f.getName().equals(sortField)).findFirst().orElse(null);
    if (field == null) {
        throw new IllegalArgumentException(String.format("Invalid value '%s' for sortBy. This field does not exist in the Drafts table.", sortField));
    }
    FieldType.Type fieldType = field.getType();
    Comparator<StructuredRow> comparator;
    switch(fieldType) {
        case STRING:
            comparator = Comparator.<StructuredRow, String>comparing(o -> o.getString(sortField));
            break;
        case INTEGER:
            comparator = Comparator.<StructuredRow, Integer>comparing(o -> o.getInteger(sortField));
            break;
        case LONG:
            comparator = Comparator.<StructuredRow, Long>comparing(o -> o.getLong(sortField));
            break;
        case FLOAT:
            comparator = Comparator.<StructuredRow, Float>comparing(o -> o.getFloat(sortField));
            break;
        case DOUBLE:
            comparator = Comparator.<StructuredRow, Double>comparing(o -> o.getDouble(sortField));
            break;
        case BYTES:
            comparator = Comparator.comparing(o -> o.getBytes(sortField), Bytes.BYTES_COMPARATOR);
            break;
        default:
            throw new UnsupportedOperationException(String.format("Cannot sort field '%s' because type '%s' is not supported.", sortField, fieldType.toString()));
    }
    if (sortRequest.getOrder() != SortRequest.SortOrder.ASC) {
        comparator = comparator.reversed();
    }
    rows.sort(comparator);
    return rows;
}
Also used : TransactionRunners(io.cdap.cdap.spi.data.transaction.TransactionRunners) StructuredRow(io.cdap.cdap.spi.data.StructuredRow) Bytes(io.cdap.cdap.api.common.Bytes) Fields(io.cdap.cdap.spi.data.table.field.Fields) ArrayList(java.util.ArrayList) StructuredTableId(io.cdap.cdap.spi.data.table.StructuredTableId) Gson(com.google.gson.Gson) ArtifactSummary(io.cdap.cdap.api.artifact.ArtifactSummary) ETLConfig(io.cdap.cdap.etl.proto.v2.ETLConfig) Field(io.cdap.cdap.spi.data.table.field.Field) StructuredTableSpecification(io.cdap.cdap.spi.data.table.StructuredTableSpecification) Nullable(javax.annotation.Nullable) InvalidFieldException(io.cdap.cdap.spi.data.InvalidFieldException) StudioUtil(io.cdap.cdap.datapipeline.service.StudioUtil) ETLBatchConfig(io.cdap.cdap.etl.proto.v2.ETLBatchConfig) NamespaceSummary(io.cdap.cdap.api.NamespaceSummary) FieldType(io.cdap.cdap.spi.data.table.field.FieldType) CloseableIterator(io.cdap.cdap.api.dataset.lib.CloseableIterator) Collectors(java.util.stream.Collectors) DataStreamsConfig(io.cdap.cdap.etl.proto.v2.DataStreamsConfig) TableNotFoundException(io.cdap.cdap.spi.data.TableNotFoundException) List(java.util.List) StructuredTable(io.cdap.cdap.spi.data.StructuredTable) Range(io.cdap.cdap.spi.data.table.field.Range) TransactionRunner(io.cdap.cdap.spi.data.transaction.TransactionRunner) Optional(java.util.Optional) Comparator(java.util.Comparator) Collections(java.util.Collections) StructuredRow(io.cdap.cdap.spi.data.StructuredRow) FieldType(io.cdap.cdap.spi.data.table.field.FieldType)

Example 3 with FieldType

use of io.cdap.cdap.spi.data.table.field.FieldType in project cdap by caskdata.

the class SpannerStructuredTableAdmin method loadSchema.

private StructuredTableSchema loadSchema(StructuredTableId tableId) throws TableNotFoundException {
    // Query the information_schema to reconstruct the StructuredTableSchema
    // See https://cloud.google.com/spanner/docs/information-schema for details
    Statement schemaStatement = Statement.newBuilder("SELECT C.column_name, C.spanner_type, I.index_type, I.ordinal_position FROM information_schema.columns C " + "LEFT JOIN information_schema.index_columns I " + "ON C.column_name = I.column_name AND C.table_name = I.table_name " + "WHERE C.table_name = @table_name ORDER BY C.ordinal_position").bind("table_name").to(tableId.getName()).build();
    List<FieldType> fields = new ArrayList<>();
    List<String> primaryKeys = new ArrayList<>();
    List<String> indexes = new ArrayList<>();
    try (ReadOnlyTransaction tx = databaseClient.readOnlyTransaction()) {
        try (ResultSet resultSet = tx.executeQuery(schemaStatement)) {
            while (resultSet.next()) {
                Struct row = resultSet.getCurrentRowAsStruct();
                String columnName = row.getString("column_name");
                String indexType = row.isNull("index_type") ? null : row.getString("index_type");
                // If a field is not a primary nor an index, the ordinal_position will be NULL in the index_columns table.
                boolean isIndex = !row.isNull("ordinal_position");
                fields.add(new FieldType(columnName, fromSpannerType(row.getString("spanner_type"))));
                if ("PRIMARY_KEY".equalsIgnoreCase(indexType)) {
                    primaryKeys.add(columnName);
                } else if ("INDEX".equalsIgnoreCase(indexType) && isIndex) {
                    indexes.add(columnName);
                }
            }
        }
    }
    if (fields.isEmpty()) {
        throw new TableNotFoundException(tableId);
    }
    return new StructuredTableSchema(tableId, fields, primaryKeys, indexes);
}
Also used : StructuredTableSchema(io.cdap.cdap.spi.data.table.StructuredTableSchema) TableNotFoundException(io.cdap.cdap.spi.data.TableNotFoundException) Statement(com.google.cloud.spanner.Statement) ArrayList(java.util.ArrayList) ReadOnlyTransaction(com.google.cloud.spanner.ReadOnlyTransaction) ResultSet(com.google.cloud.spanner.ResultSet) FieldType(io.cdap.cdap.spi.data.table.field.FieldType) Struct(com.google.cloud.spanner.Struct)

Aggregations

FieldType (io.cdap.cdap.spi.data.table.field.FieldType)3 ArrayList (java.util.ArrayList)3 StructuredRow (io.cdap.cdap.spi.data.StructuredRow)2 StructuredTable (io.cdap.cdap.spi.data.StructuredTable)2 TableNotFoundException (io.cdap.cdap.spi.data.TableNotFoundException)2 StructuredTableId (io.cdap.cdap.spi.data.table.StructuredTableId)2 StructuredTableSpecification (io.cdap.cdap.spi.data.table.StructuredTableSpecification)2 Field (io.cdap.cdap.spi.data.table.field.Field)2 TransactionRunner (io.cdap.cdap.spi.data.transaction.TransactionRunner)2 ReadOnlyTransaction (com.google.cloud.spanner.ReadOnlyTransaction)1 ResultSet (com.google.cloud.spanner.ResultSet)1 Statement (com.google.cloud.spanner.Statement)1 Struct (com.google.cloud.spanner.Struct)1 Gson (com.google.gson.Gson)1 NamespaceSummary (io.cdap.cdap.api.NamespaceSummary)1 ArtifactSummary (io.cdap.cdap.api.artifact.ArtifactSummary)1 Bytes (io.cdap.cdap.api.common.Bytes)1 CloseableIterator (io.cdap.cdap.api.dataset.lib.CloseableIterator)1 StudioUtil (io.cdap.cdap.datapipeline.service.StudioUtil)1 DataStreamsConfig (io.cdap.cdap.etl.proto.v2.DataStreamsConfig)1