Search in sources :

Example 96 with Row

use of com.google.cloud.automl.v1beta1.Row in project molgenis-emx2 by molgenis.

the class RowReaderJackson method read.

public static Iterable<Row> read(Reader in, Character separator) throws IOException {
    CsvSchema schema = CsvSchema.emptySchema().withHeader().withNullValue("").withAllowComments(true).withColumnSeparator(separator);
    MappingIterator<Map> iterator = reader.with(schema).readValues(in);
    // ... some reference to data
    return () -> new Iterator<>() {

        final Iterator<Map> it = iterator;

        @Override
        public boolean hasNext() {
            return it.hasNext();
        }

        @Deprecated
        public /**
         * @deprecated
         */
        Row next() {
            return new Row(it.next());
        }

        @Override
        public void remove() {
            throw new UnsupportedOperationException();
        }
    };
}
Also used : CsvSchema(com.fasterxml.jackson.dataformat.csv.CsvSchema) Iterator(java.util.Iterator) MappingIterator(com.fasterxml.jackson.databind.MappingIterator) Row(org.molgenis.emx2.Row) Map(java.util.Map)

Example 97 with Row

use of com.google.cloud.automl.v1beta1.Row in project molgenis-emx2 by molgenis.

the class ProductComponentPartsExample method populate.

public static void populate(Schema schema) {
    Table partTable = schema.getTable(PART);
    Row part1 = new Row().setString(NAME, FORMS).setInt(WEIGHT, 100);
    Row part2 = new Row().setString(NAME, LOGIN).setInt(WEIGHT, 50);
    partTable.insert(part1);
    partTable.insert(part2);
    Table componentTable = schema.getTable(COMPONENT);
    Row component1 = new Row().setString(NAME, EXPLORER).setRefArray(PARTS, FORMS, LOGIN);
    Row component2 = new Row().setString(NAME, NAVIGATOR).setRefArray(PARTS, LOGIN);
    componentTable.insert(component1);
    componentTable.insert(component2);
    Table productTable = schema.getTable(PRODUCT);
    Row product1 = new Row().setString(NAME, "molgenis").setRefArray(COMPONENTS, EXPLORER, NAVIGATOR);
    productTable.insert(product1);
}
Also used : Table(org.molgenis.emx2.Table) Row(org.molgenis.emx2.Row)

Example 98 with Row

use of com.google.cloud.automl.v1beta1.Row in project molgenis-emx2 by molgenis.

the class SqlTable method executeTransaction.

private static int executeTransaction(Database db, String schemaName, String tableName, Iterable<Row> rows, MutationType transactionType) {
    long start = System.currentTimeMillis();
    final AtomicInteger count = new AtomicInteger(0);
    final Map<String, List<Row>> subclassRows = new LinkedHashMap<>();
    final Map<String, Set<String>> columnsProvided = new LinkedHashMap<>();
    SqlSchema schema = (SqlSchema) db.getSchema(schemaName);
    SqlTable table = schema.getTable(tableName);
    String tableClass = getMgTableClass(table.getMetadata());
    // validate
    if (table.getMetadata().getPrimaryKeys().isEmpty())
        throw new MolgenisException("Transaction failed: Table " + table.getName() + " cannot process row insert/update/delete requests because no primary key is defined");
    db.tx(db2 -> {
        for (Row row : rows) {
            // set table class if not set, and see for first time
            if (row.notNull(MG_TABLECLASS) && !subclassRows.containsKey(row.getString(MG_TABLECLASS))) {
                // validate
                String rowTableName = row.getString(MG_TABLECLASS);
                if (!rowTableName.contains(".")) {
                    if (schema.getTable(rowTableName) != null) {
                        row.setString(MG_TABLECLASS, schemaName + "." + rowTableName);
                    } else {
                        throw new MolgenisException(MG_TABLECLASS + " value failed in row " + count.get() + ": found '" + rowTableName + "'");
                    }
                } else {
                    String rowSchemaName = rowTableName.split("\\.")[0];
                    String rowTableName2 = rowTableName.split("\\.")[1];
                    if (db.getSchema(rowSchemaName) == null || db.getSchema(rowSchemaName).getTable(rowTableName2) == null) {
                        throw new MolgenisException("invalid value in column '" + MG_TABLECLASS + "' on row " + count.get() + ": found '" + rowTableName + "'");
                    }
                }
            } else {
                row.set(MG_TABLECLASS, tableClass);
            }
            // create batches for each table class
            String subclassName = row.getString(MG_TABLECLASS);
            if (!subclassRows.containsKey(subclassName)) {
                subclassRows.put(subclassName, new ArrayList<>());
            }
            // check columns provided didn't change
            if (columnsProvided.get(subclassName) == null) {
                columnsProvided.put(subclassName, new LinkedHashSet<>(row.getColumnNames()));
            }
            // execute batch if 1000 rows, or columns provided changes
            if (columnsProvidedAreDifferent(columnsProvided.get(subclassName), row) || subclassRows.get(subclassName).size() >= 1000) {
                executeBatch((SqlSchema) db2.getSchema(subclassName.split("\\.")[0]), transactionType, count, subclassRows, subclassName, columnsProvided.get(subclassName));
                // reset columns provided
                columnsProvided.get(subclassName).clear();
                columnsProvided.get(subclassName).addAll(row.getColumnNames());
            }
            // add to batch list, and execute if batch is large enough
            subclassRows.get(subclassName).add(row);
        }
        // execute any remaining batches
        for (Map.Entry<String, List<Row>> batch : subclassRows.entrySet()) {
            if (batch.getValue().size() > 0) {
                executeBatch((SqlSchema) db2.getSchema(batch.getKey().split("\\.")[0]), transactionType, count, subclassRows, batch.getKey(), columnsProvided.get(batch.getKey()));
            }
        }
    });
    log(db.getActiveUser(), table.getJooqTable().getName(), start, count, transactionType.name().toLowerCase() + "d (incl subclass if applicable)");
    return count.get();
}
Also used : AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Row(org.molgenis.emx2.Row)

Example 99 with Row

use of com.google.cloud.automl.v1beta1.Row in project molgenis-emx2 by molgenis.

the class SqlTable method updateBatch.

private static int updateBatch(SqlTable table, List<Row> rows, Set<String> updateColumns) {
    boolean inherit = table.getMetadata().getInherit() != null;
    if (inherit) {
        SqlTable inheritedTable = table.getInheritedTable();
        inheritedTable.updateBatch(inheritedTable, rows, updateColumns);
    }
    // get metadata
    Set<Column> columns = table.getColumnsToBeUpdated(updateColumns);
    List<Column> pkeyFields = table.getMetadata().getPrimaryKeyColumns();
    // check that columns exist for validation
    checkForMissingVariablesColumns(columns);
    // create batch of updates
    List<UpdateConditionStep> list = new ArrayList();
    String user = table.getSchema().getDatabase().getActiveUser();
    if (user == null) {
        user = ADMIN_USER;
    }
    LocalDateTime now = LocalDateTime.now();
    for (Row row : rows) {
        Map values = SqlTypeUtils.getValuesAsMap(row, columns);
        if (!inherit) {
            values.put(MG_UPDATEDBY, user);
            values.put(MG_UPDATEDON, now);
        }
        if (!row.isDraft()) {
            checkRequired(row, columns);
            checkValidation(values, columns);
        }
        list.add(table.getJooq().update(table.getJooqTable()).set(values).where(table.getUpdateCondition(row, pkeyFields)));
    }
    return Arrays.stream(table.getJooq().batch(list).execute()).reduce(Integer::sum).getAsInt();
}
Also used : LocalDateTime(java.time.LocalDateTime) Row(org.molgenis.emx2.Row)

Example 100 with Row

use of com.google.cloud.automl.v1beta1.Row in project molgenis-emx2 by molgenis.

the class SqlTable method copyIn.

public void copyIn(Iterable<Row> rows) {
    db.getJooq().connection(connection -> {
        try {
            CopyManager cm = new CopyManager(connection.unwrap(BaseConnection.class));
            // must be batched
            StringBuilder tmp = new StringBuilder();
            tmp.append(this.getMetadata().getLocalColumnNames().stream().map(c -> "\"" + c + "\"").collect(Collectors.joining(",")) + "\n");
            for (Row row : rows) {
                StringBuilder line = new StringBuilder();
                for (Column c : this.getMetadata().getStoredColumns()) {
                    if (!row.containsName(c.getName())) {
                        line.append(",");
                    } else {
                        Object value = getTypedValue(row, c);
                        line.append(value + ",");
                    }
                }
                tmp.append(line.substring(0, line.length() - 1) + "\n");
            }
            String tableName = "\"" + getSchema().getMetadata().getName() + "\".\"" + getName() + "\"";
            String columnNames = "(" + this.getMetadata().getLocalColumnNames().stream().map(c -> "\"" + c + "\"").collect(Collectors.joining(",")) + ")";
            String sql = "COPY " + tableName + columnNames + " FROM STDIN (FORMAT CSV,HEADER )";
            cm.copyIn(sql, new StringReader(tmp.toString()));
        } catch (Exception e) {
            throw new MolgenisException("copyOut failed: ", e);
        }
    });
}
Also used : EvaluateExpressions.checkValidation(org.molgenis.emx2.sql.EvaluateExpressions.checkValidation) java.util(java.util) DSL(org.jooq.impl.DSL) Logger(org.slf4j.Logger) LocalDateTime(java.time.LocalDateTime) LoggerFactory(org.slf4j.LoggerFactory) Constants(org.molgenis.emx2.Constants) org.molgenis.emx2(org.molgenis.emx2) Collectors(java.util.stream.Collectors) EvaluateExpressions.checkForMissingVariablesColumns(org.molgenis.emx2.sql.EvaluateExpressions.checkForMissingVariablesColumns) ADMIN_USER(org.molgenis.emx2.sql.SqlDatabase.ADMIN_USER) Query(org.molgenis.emx2.Query) MutationType(org.molgenis.emx2.MutationType) StringReader(java.io.StringReader) Table(org.molgenis.emx2.Table) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) org.jooq(org.jooq) Writer(java.io.Writer) BaseConnection(org.postgresql.core.BaseConnection) CopyManager(org.postgresql.copy.CopyManager) SqlTypeUtils.getTypedValue(org.molgenis.emx2.sql.SqlTypeUtils.getTypedValue) Row(org.molgenis.emx2.Row) StringReader(java.io.StringReader) CopyManager(org.postgresql.copy.CopyManager) Row(org.molgenis.emx2.Row) BaseConnection(org.postgresql.core.BaseConnection)

Aggregations

Test (org.junit.Test)56 Row (org.molgenis.emx2.Row)39 Row (com.google.bigtable.v2.Row)16 ByteString (com.google.protobuf.ByteString)11 Function (com.google.common.base.Function)8 ArrayList (java.util.ArrayList)8 Table (org.molgenis.emx2.Table)8 Row (com.google.api.ads.admanager.axis.v202108.Row)6 Family (com.google.bigtable.v2.Family)6 ByteKey (org.apache.beam.sdk.io.range.ByteKey)6 Schema (org.molgenis.emx2.Schema)6 Row (com.google.api.ads.admanager.axis.v202105.Row)5 Row (com.google.api.ads.admanager.axis.v202111.Row)5 Row (com.google.api.ads.admanager.axis.v202202.Row)5 Row (com.google.api.ads.admanager.jaxws.v202105.Row)5 Row (com.google.api.ads.admanager.jaxws.v202108.Row)5 Row (com.google.api.ads.admanager.jaxws.v202202.Row)5 ResultSet (com.google.api.ads.admanager.axis.v202108.ResultSet)4 Row (com.google.api.ads.admanager.jaxws.v202111.Row)4 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)4