Search in sources :

Example 1 with Fields

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

the class PostgreSqlStructuredTable method updateInternal.

private void updateInternal(Collection<Field<?>> fields) throws IOException {
    String sqlQuery = getUpdateSqlQuery(fields);
    try (PreparedStatement statement = connection.prepareStatement(sqlQuery)) {
        Map<Boolean, List<Field<?>>> lists = fields.stream().collect(Collectors.partitioningBy(field -> tableSchema.isPrimaryKeyColumn(field.getName())));
        int index = 1;
        // set field values to update
        for (Field<?> field : lists.get(false)) {
            setField(statement, field, index);
            index++;
        }
        // set field values in the WHERE clause
        for (Field<?> field : lists.get(true)) {
            setField(statement, field, index);
            index++;
        }
        LOG.trace("SQL statement: {}", statement);
        statement.executeUpdate();
    } catch (SQLException e) {
        throw new IOException(String.format("Failed to write to table %s with fields %s", tableSchema.getTableId().getName(), fields), e);
    }
}
Also used : IntStream(java.util.stream.IntStream) ConfigModule(io.cdap.cdap.common.guice.ConfigModule) Connection(java.sql.Connection) Inject(com.google.inject.Inject) StructuredRow(io.cdap.cdap.spi.data.StructuredRow) LoggerFactory(org.slf4j.LoggerFactory) FieldValidator(io.cdap.cdap.spi.data.table.field.FieldValidator) Fields(io.cdap.cdap.spi.data.table.field.Fields) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) LinkedHashMap(java.util.LinkedHashMap) SQLException(java.sql.SQLException) ResultSet(java.sql.ResultSet) Map(java.util.Map) Field(io.cdap.cdap.spi.data.table.field.Field) LinkedHashSet(java.util.LinkedHashSet) Nullable(javax.annotation.Nullable) SortOrder(io.cdap.cdap.spi.data.SortOrder) InvalidFieldException(io.cdap.cdap.spi.data.InvalidFieldException) Logger(org.slf4j.Logger) Collection(java.util.Collection) Set(java.util.Set) IOException(java.io.IOException) FieldType(io.cdap.cdap.spi.data.table.field.FieldType) PreparedStatement(java.sql.PreparedStatement) CloseableIterator(io.cdap.cdap.api.dataset.lib.CloseableIterator) Collectors(java.util.stream.Collectors) Injector(com.google.inject.Injector) AbstractCloseableIterator(io.cdap.cdap.api.dataset.lib.AbstractCloseableIterator) List(java.util.List) CConfiguration(io.cdap.cdap.common.conf.CConfiguration) StructuredTable(io.cdap.cdap.spi.data.StructuredTable) Range(io.cdap.cdap.spi.data.table.field.Range) StringJoiner(java.util.StringJoiner) Statement(java.sql.Statement) Guice(com.google.inject.Guice) Optional(java.util.Optional) StructuredTableSchema(io.cdap.cdap.spi.data.table.StructuredTableSchema) Collections(java.util.Collections) ResultSetMetaData(java.sql.ResultSetMetaData) Joiner(com.google.common.base.Joiner) Types(java.sql.Types) SQLException(java.sql.SQLException) PreparedStatement(java.sql.PreparedStatement) ArrayList(java.util.ArrayList) List(java.util.List) IOException(java.io.IOException)

Example 2 with Fields

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

the class StructuredTableConcurrencyTest method testConcurrentUpsert.

@Test
public void testConcurrentUpsert() throws Exception {
    // Concurrently write rows
    int numThreads = 20;
    AtomicInteger idGenerator = new AtomicInteger();
    String strVal = "write-val-";
    runConcurrentOperation("concurrent-upsert", numThreads, () -> TransactionRunners.run(transactionRunner, context -> {
        StructuredTable table = context.getTable(TEST_TABLE);
        int id = idGenerator.getAndIncrement();
        List<Field<?>> fields = Arrays.asList(Fields.intField(KEY, id), Fields.stringField(STRING_COL, strVal + id), Fields.longField(LONG_COL, (long) id));
        table.upsert(fields);
    }));
    // Verify all writes
    AtomicInteger count = new AtomicInteger();
    TransactionRunners.run(transactionRunner, context -> {
        StructuredTable table = context.getTable(TEST_TABLE);
        try (CloseableIterator<StructuredRow> iterator = table.scan(Range.all(), Integer.MAX_VALUE)) {
            while (iterator.hasNext()) {
                StructuredRow row = iterator.next();
                Assert.assertEquals(Integer.valueOf(count.get()), row.getInteger(KEY));
                Assert.assertEquals(strVal + count.get(), row.getString(STRING_COL));
                Assert.assertEquals(Long.valueOf(count.get()), row.getLong(LONG_COL));
                count.incrementAndGet();
            }
        }
    });
    Assert.assertEquals(numThreads, count.get());
}
Also used : Arrays(java.util.Arrays) TransactionRunners(io.cdap.cdap.spi.data.transaction.TransactionRunners) LoggerFactory(org.slf4j.LoggerFactory) Fields(io.cdap.cdap.spi.data.table.field.Fields) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) StructuredTableId(io.cdap.cdap.spi.data.table.StructuredTableId) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) After(org.junit.After) Map(java.util.Map) Field(io.cdap.cdap.spi.data.table.field.Field) StructuredTableSpecification(io.cdap.cdap.spi.data.table.StructuredTableSpecification) ExecutorService(java.util.concurrent.ExecutorService) Before(org.junit.Before) Logger(org.slf4j.Logger) Collection(java.util.Collection) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) Set(java.util.Set) Test(org.junit.Test) CloseableIterator(io.cdap.cdap.api.dataset.lib.CloseableIterator) Executors(java.util.concurrent.Executors) TimeUnit(java.util.concurrent.TimeUnit) CountDownLatch(java.util.concurrent.CountDownLatch) List(java.util.List) Range(io.cdap.cdap.spi.data.table.field.Range) TransactionRunner(io.cdap.cdap.spi.data.transaction.TransactionRunner) Optional(java.util.Optional) Queue(java.util.Queue) Assert(org.junit.Assert) Collections(java.util.Collections) ConcurrentLinkedQueue(java.util.concurrent.ConcurrentLinkedQueue) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) ArrayList(java.util.ArrayList) List(java.util.List) Test(org.junit.Test)

Example 3 with Fields

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

the class SpannerStructuredTable method update.

@Override
public void update(Collection<Field<?>> fields) throws InvalidFieldException {
    List<Field<?>> primaryKeyFields = new ArrayList<>();
    List<Field<?>> updateFields = new ArrayList<>();
    Set<String> fieldNames = new HashSet<>();
    for (Field<?> field : fields) {
        fieldValidator.validateField(field);
        if (schema.isPrimaryKeyColumn(field.getName())) {
            primaryKeyFields.add(field);
        } else {
            updateFields.add(field);
        }
        fieldNames.add(field.getName());
    }
    if (!fieldNames.containsAll(schema.getPrimaryKeys())) {
        throw new InvalidFieldException(schema.getTableId(), fields, String.format("Given fields %s do not contain all the " + "primary keys %s", fieldNames, schema.getPrimaryKeys()));
    }
    String sql = "UPDATE " + escapeName(schema.getTableId().getName()) + " SET " + updateFields.stream().map(this::fieldToParam).collect(Collectors.joining(", ")) + " WHERE " + primaryKeyFields.stream().map(this::fieldToParam).collect(Collectors.joining(" AND "));
    LOG.trace("Updating row: {}", sql);
    Statement statement = fields.stream().reduce(Statement.newBuilder(sql), (builder, field) -> builder.bind(field.getName()).to(getValue(field)), (builder1, builder2) -> builder1).build();
    transactionContext.executeUpdate(statement);
}
Also used : IntStream(java.util.stream.IntStream) StructuredRow(io.cdap.cdap.spi.data.StructuredRow) LoggerFactory(org.slf4j.LoggerFactory) FieldValidator(io.cdap.cdap.spi.data.table.field.FieldValidator) Fields(io.cdap.cdap.spi.data.table.field.Fields) HashMap(java.util.HashMap) Value(com.google.cloud.spanner.Value) Function(java.util.function.Function) KeyRange(com.google.cloud.spanner.KeyRange) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) LinkedHashMap(java.util.LinkedHashMap) ResultSet(com.google.cloud.spanner.ResultSet) Key(com.google.cloud.spanner.Key) Map(java.util.Map) Field(io.cdap.cdap.spi.data.table.field.Field) ByteArray(com.google.cloud.ByteArray) LinkedHashSet(java.util.LinkedHashSet) Nullable(javax.annotation.Nullable) TransactionContext(com.google.cloud.spanner.TransactionContext) InvalidFieldException(io.cdap.cdap.spi.data.InvalidFieldException) Logger(org.slf4j.Logger) Collection(java.util.Collection) Set(java.util.Set) FieldType(io.cdap.cdap.spi.data.table.field.FieldType) CloseableIterator(io.cdap.cdap.api.dataset.lib.CloseableIterator) Collectors(java.util.stream.Collectors) KeySet(com.google.cloud.spanner.KeySet) Statement(com.google.cloud.spanner.Statement) Objects(java.util.Objects) AbstractCloseableIterator(io.cdap.cdap.api.dataset.lib.AbstractCloseableIterator) List(java.util.List) Struct(com.google.cloud.spanner.Struct) StructuredTable(io.cdap.cdap.spi.data.StructuredTable) Range(io.cdap.cdap.spi.data.table.field.Range) Optional(java.util.Optional) StructuredTableSchema(io.cdap.cdap.spi.data.table.StructuredTableSchema) Collections(java.util.Collections) Field(io.cdap.cdap.spi.data.table.field.Field) Statement(com.google.cloud.spanner.Statement) ArrayList(java.util.ArrayList) InvalidFieldException(io.cdap.cdap.spi.data.InvalidFieldException) HashSet(java.util.HashSet) LinkedHashSet(java.util.LinkedHashSet)

Example 4 with Fields

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

the class SpannerStructuredTable method insert.

private void insert(Collection<Field<?>> fields) throws InvalidFieldException {
    List<Field<?>> insertFields = new ArrayList<>();
    for (Field<?> field : fields) {
        fieldValidator.validateField(field);
        insertFields.add(field);
    }
    String sql = "INSERT INTO " + escapeName(schema.getTableId().getName()) + " (" + insertFields.stream().map(Field::getName).map(this::escapeName).collect(Collectors.joining(",")) + ") VALUES (" + insertFields.stream().map(f -> "@" + f.getName()).collect(Collectors.joining(",")) + ")";
    LOG.trace("Inserting row: {}", sql);
    Statement statement = fields.stream().reduce(Statement.newBuilder(sql), (builder, field) -> builder.bind(field.getName()).to(getValue(field)), (builder1, builder2) -> builder1).build();
    transactionContext.executeUpdate(statement);
}
Also used : IntStream(java.util.stream.IntStream) StructuredRow(io.cdap.cdap.spi.data.StructuredRow) LoggerFactory(org.slf4j.LoggerFactory) FieldValidator(io.cdap.cdap.spi.data.table.field.FieldValidator) Fields(io.cdap.cdap.spi.data.table.field.Fields) HashMap(java.util.HashMap) Value(com.google.cloud.spanner.Value) Function(java.util.function.Function) KeyRange(com.google.cloud.spanner.KeyRange) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) LinkedHashMap(java.util.LinkedHashMap) ResultSet(com.google.cloud.spanner.ResultSet) Key(com.google.cloud.spanner.Key) Map(java.util.Map) Field(io.cdap.cdap.spi.data.table.field.Field) ByteArray(com.google.cloud.ByteArray) LinkedHashSet(java.util.LinkedHashSet) Nullable(javax.annotation.Nullable) TransactionContext(com.google.cloud.spanner.TransactionContext) InvalidFieldException(io.cdap.cdap.spi.data.InvalidFieldException) Logger(org.slf4j.Logger) Collection(java.util.Collection) Set(java.util.Set) FieldType(io.cdap.cdap.spi.data.table.field.FieldType) CloseableIterator(io.cdap.cdap.api.dataset.lib.CloseableIterator) Collectors(java.util.stream.Collectors) KeySet(com.google.cloud.spanner.KeySet) Statement(com.google.cloud.spanner.Statement) Objects(java.util.Objects) AbstractCloseableIterator(io.cdap.cdap.api.dataset.lib.AbstractCloseableIterator) List(java.util.List) Struct(com.google.cloud.spanner.Struct) StructuredTable(io.cdap.cdap.spi.data.StructuredTable) Range(io.cdap.cdap.spi.data.table.field.Range) Optional(java.util.Optional) StructuredTableSchema(io.cdap.cdap.spi.data.table.StructuredTableSchema) Collections(java.util.Collections) Field(io.cdap.cdap.spi.data.table.field.Field) Statement(com.google.cloud.spanner.Statement) ArrayList(java.util.ArrayList)

Aggregations

CloseableIterator (io.cdap.cdap.api.dataset.lib.CloseableIterator)4 Field (io.cdap.cdap.spi.data.table.field.Field)4 Fields (io.cdap.cdap.spi.data.table.field.Fields)4 Range (io.cdap.cdap.spi.data.table.field.Range)4 ArrayList (java.util.ArrayList)4 Collection (java.util.Collection)4 Collections (java.util.Collections)4 HashMap (java.util.HashMap)4 List (java.util.List)4 Map (java.util.Map)4 Optional (java.util.Optional)4 Set (java.util.Set)4 Logger (org.slf4j.Logger)4 LoggerFactory (org.slf4j.LoggerFactory)4 AbstractCloseableIterator (io.cdap.cdap.api.dataset.lib.AbstractCloseableIterator)3 InvalidFieldException (io.cdap.cdap.spi.data.InvalidFieldException)3 StructuredRow (io.cdap.cdap.spi.data.StructuredRow)3 StructuredTable (io.cdap.cdap.spi.data.StructuredTable)3 StructuredTableSchema (io.cdap.cdap.spi.data.table.StructuredTableSchema)3 FieldType (io.cdap.cdap.spi.data.table.field.FieldType)3