Java Code Examples for org.apache.calcite.avatica.AvaticaUtils

The following examples show how to use org.apache.calcite.avatica.AvaticaUtils. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: Quicksql   Source File: Lattice.java    License: MIT License 6 votes vote down vote up
/** Builds a lattice. */
public Lattice build() {
  LatticeStatisticProvider.Factory statisticProvider =
      this.statisticProvider != null
          ? AvaticaUtils.instantiatePlugin(
              LatticeStatisticProvider.Factory.class,
              this.statisticProvider)
          : Lattices.CACHED_SQL;
  Preconditions.checkArgument(rootSchema.isRoot(), "must be root schema");
  final ImmutableList.Builder<Column> columnBuilder =
      ImmutableList.<Column>builder()
      .addAll(baseColumns)
      .addAll(derivedColumnsByName.values());
  return new Lattice(rootSchema, rootNode, auto,
      algorithm, algorithmMaxMillis, statisticProvider, rowCountEstimate,
      columnBuilder.build(), ImmutableSortedSet.copyOf(defaultMeasureSet),
      tileListBuilder.build(), ImmutableListMultimap.copyOf(columnUses));
}
 
Example 2
Source Project: Quicksql   Source File: RelJson.java    License: MIT License 6 votes vote down vote up
SqlOperator toOp(RelInput relInput, Map<String, Object> map) {
  // in case different operator has the same kind, check with both name and kind.
  String name = map.get("name").toString();
  String kind = map.get("kind").toString();
  String syntax = map.get("syntax").toString();
  SqlKind sqlKind = SqlKind.valueOf(kind);
  SqlSyntax  sqlSyntax = SqlSyntax.valueOf(syntax);
  List<SqlOperator> operators = new ArrayList<>();
  SqlStdOperatorTable.instance().lookupOperatorOverloads(
      new SqlIdentifier(name, new SqlParserPos(0, 0)),
      null,
      sqlSyntax,
      operators,
      SqlNameMatchers.liberal());
  for (SqlOperator operator: operators) {
    if (operator.kind == sqlKind) {
      return operator;
    }
  }
  String class_ = (String) map.get("class");
  if (class_ != null) {
    return AvaticaUtils.instantiatePlugin(SqlOperator.class, class_);
  }
  return null;
}
 
Example 3
Source Project: Quicksql   Source File: CalciteMetaImpl.java    License: MIT License 6 votes vote down vote up
private <E> MetaResultSet createResultSet(Enumerable<E> enumerable,
    Class clazz, String... names) {
  final List<ColumnMetaData> columns = new ArrayList<>();
  final List<Field> fields = new ArrayList<>();
  final List<String> fieldNames = new ArrayList<>();
  for (String name : names) {
    final int index = fields.size();
    final String fieldName = AvaticaUtils.toCamelCase(name);
    final Field field;
    try {
      field = clazz.getField(fieldName);
    } catch (NoSuchFieldException e) {
      throw new RuntimeException(e);
    }
    columns.add(columnMetaData(name, index, field.getType(), false));
    fields.add(field);
    fieldNames.add(fieldName);
  }
  //noinspection unchecked
  final Iterable<Object> iterable = (Iterable<Object>) (Iterable) enumerable;
  return createResultSet(Collections.emptyMap(),
      columns, CursorFactory.record(clazz, fields, fieldNames),
      new Frame(0, true, iterable));
}
 
Example 4
Source Project: Quicksql   Source File: ModelHandler.java    License: MIT License 6 votes vote down vote up
public void visit(JsonCustomSchema jsonSchema) {
  try {
    final SchemaPlus parentSchema = currentMutableSchema("sub-schema");
    checkRequiredAttributes(jsonSchema, "name", "factory");
    final SchemaFactory schemaFactory =
        AvaticaUtils.instantiatePlugin(SchemaFactory.class,
            jsonSchema.factory);
    final Schema schema =
        schemaFactory.create(
            parentSchema, jsonSchema.name, operandMap(jsonSchema, jsonSchema.operand));
    final SchemaPlus schemaPlus = parentSchema.add(jsonSchema.name, schema);
    populateSchema(jsonSchema, schemaPlus);
  } catch (Exception e) {
    throw new RuntimeException("Error instantiating " + jsonSchema, e);
  }
}
 
Example 5
Source Project: Quicksql   Source File: ModelHandler.java    License: MIT License 6 votes vote down vote up
public void visit(JsonJdbcSchema jsonSchema) {
  checkRequiredAttributes(jsonSchema, "name");
  final SchemaPlus parentSchema = currentMutableSchema("jdbc schema");
  final DataSource dataSource =
      JdbcSchema.dataSource(jsonSchema.jdbcUrl,
          jsonSchema.jdbcDriver,
          jsonSchema.jdbcUser,
          jsonSchema.jdbcPassword);
  final JdbcSchema schema;
  if (jsonSchema.sqlDialectFactory == null || jsonSchema.sqlDialectFactory.isEmpty()) {
    schema =
        JdbcSchema.create(parentSchema, jsonSchema.name, dataSource,
            jsonSchema.jdbcCatalog, jsonSchema.jdbcSchema);
  } else {
    SqlDialectFactory factory = AvaticaUtils.instantiatePlugin(
        SqlDialectFactory.class, jsonSchema.sqlDialectFactory);
    schema =
        JdbcSchema.create(parentSchema, jsonSchema.name, dataSource,
            factory, jsonSchema.jdbcCatalog, jsonSchema.jdbcSchema);
  }
  final SchemaPlus schemaPlus = parentSchema.add(jsonSchema.name, schema);
  populateSchema(jsonSchema, schemaPlus);
}
 
Example 6
Source Project: Quicksql   Source File: ModelHandler.java    License: MIT License 6 votes vote down vote up
public void visit(JsonCustomTable jsonTable) {
  try {
    checkRequiredAttributes(jsonTable, "name", "factory");
    final SchemaPlus schema = currentMutableSchema("table");
    final TableFactory tableFactory =
        AvaticaUtils.instantiatePlugin(TableFactory.class,
            jsonTable.factory);
    final Table table =
        tableFactory.create(schema, jsonTable.name,
            operandMap(null, jsonTable.operand), null);
    for (JsonColumn column : jsonTable.columns) {
      column.accept(this);
    }
    schema.add(jsonTable.name, table);
  } catch (Exception e) {
    throw new RuntimeException("Error instantiating " + jsonTable, e);
  }
}
 
Example 7
Source Project: Quicksql   Source File: QuicksqlServerMeta.java    License: MIT License 6 votes vote down vote up
@Override
public ExecuteBatchResult prepareAndExecuteBatch(StatementHandle h,
    List<String> sqlCommands) throws NoSuchStatementException {
    try {
        // Get the statement
        final StatementInfo info = statementCache.getIfPresent(h.id);
        if (info == null) {
            throw new NoSuchStatementException(h);
        }

        // addBatch() for each sql command
        final Statement stmt = info.statement;
        for (String sqlCommand : sqlCommands) {
            stmt.addBatch(sqlCommand);
        }

        // Execute the batch and return the results
        return new ExecuteBatchResult(AvaticaUtils.executeLargeBatch(stmt));
    } catch (SQLException e) {
        throw propagate(e);
    }
}
 
Example 8
Source Project: Quicksql   Source File: QuicksqlServerMeta.java    License: MIT License 6 votes vote down vote up
@Override
public ExecuteBatchResult executeBatchProtobuf(StatementHandle h,
    List<Requests.UpdateBatch> updateBatches) throws NoSuchStatementException {
    try {
        final StatementInfo info = statementCache.getIfPresent(h.id);
        if (null == info) {
            throw new NoSuchStatementException(h);
        }

        final PreparedStatement preparedStmt = (PreparedStatement) info.statement;
        for (Requests.UpdateBatch update : updateBatches) {
            int i = 1;
            for (Common.TypedValue value : update.getParameterValuesList()) {
                // Use the value and then increment
                preparedStmt.setObject(i++, TypedValue.protoToJdbc(value, calendar));
            }
            preparedStmt.addBatch();
        }
        return new ExecuteBatchResult(AvaticaUtils.executeLargeBatch(preparedStmt));
    } catch (SQLException e) {
        throw propagate(e);
    }
}
 
Example 9
Source Project: kylin-on-parquet-v2   Source File: KylinMeta.java    License: Apache License 2.0 6 votes vote down vote up
@SuppressWarnings({"rawtypes", "unchecked"})
private MetaResultSet createResultSet(List iterable, Class clazz, String... names) {
    final List<ColumnMetaData> columns = new ArrayList<ColumnMetaData>();
    final List<Field> fields = new ArrayList<Field>();
    final List<String> fieldNames = new ArrayList<String>();
    for (String name : names) {
        final int index = fields.size();
        final String fieldName = AvaticaUtils.toCamelCase(name);
        final Field field;
        try {
            field = clazz.getField(fieldName);
        } catch (NoSuchFieldException e) {
            throw new RuntimeException(e);
        }
        columns.add(columnMetaData(name, index, field.getType(), true));
        fields.add(field);
        fieldNames.add(fieldName);
    }

    CursorFactory cursorFactory = CursorFactory.record(clazz, fields, fieldNames);
    Signature signature = new Signature(columns, "", null, Collections.<String, Object> emptyMap(), cursorFactory, StatementType.SELECT);
    StatementHandle sh = this.createStatement(connection().handle);
    Frame frame = new Frame(0, true, iterable);

    return MetaResultSet.create(connection().id, sh.id, true, signature, frame);
}
 
Example 10
Source Project: calcite-sql-rewriter   Source File: JournalledJdbcSchema.java    License: Apache License 2.0 6 votes vote down vote up
private static DataSource parseDataSource(Map<String, Object> operand) throws IOException {
	final String connection = (String) operand.get("connection");

	Map<String, Object> jdbcConfig;
	if (connection != null) {
		try (InputStream connConfig = ClassLoader.getSystemResourceAsStream(connection)) {
			jdbcConfig = new ObjectMapper().readValue(
					connConfig,
					new TypeReference<Map<String, Object>>(){}
			);
		}
	} else {
		jdbcConfig = operand;
	}

	final String dataSourceName = (String) jdbcConfig.get("dataSource");
	if (dataSourceName != null) {
		return AvaticaUtils.instantiatePlugin(DataSource.class, dataSourceName);
	}

	final String jdbcUrl = (String) jdbcConfig.get("jdbcUrl");
	final String jdbcDriver = (String) jdbcConfig.get("jdbcDriver");
	final String jdbcUser = (String) jdbcConfig.get("jdbcUser");
	final String jdbcPassword = (String) jdbcConfig.get("jdbcPassword");
	return dataSource(jdbcUrl, jdbcDriver, jdbcUser, jdbcPassword);
}
 
Example 11
Source Project: calcite-avatica   Source File: JdbcMeta.java    License: Apache License 2.0 6 votes vote down vote up
@Override public ExecuteBatchResult prepareAndExecuteBatch(StatementHandle h,
    List<String> sqlCommands) throws NoSuchStatementException {
  try {
    // Get the statement
    final StatementInfo info = statementCache.getIfPresent(h.id);
    if (info == null) {
      throw new NoSuchStatementException(h);
    }

    // addBatch() for each sql command
    final Statement stmt = info.statement;
    for (String sqlCommand : sqlCommands) {
      stmt.addBatch(sqlCommand);
    }

    // Execute the batch and return the results
    return new ExecuteBatchResult(AvaticaUtils.executeLargeBatch(stmt));
  } catch (SQLException e) {
    throw propagate(e);
  }
}
 
Example 12
Source Project: calcite-avatica   Source File: JdbcMeta.java    License: Apache License 2.0 6 votes vote down vote up
@Override public ExecuteBatchResult executeBatchProtobuf(StatementHandle h,
    List<Requests.UpdateBatch> updateBatches) throws NoSuchStatementException {
  try {
    final StatementInfo info = statementCache.getIfPresent(h.id);
    if (null == info) {
      throw new NoSuchStatementException(h);
    }

    final PreparedStatement preparedStmt = (PreparedStatement) info.statement;
    for (Requests.UpdateBatch update : updateBatches) {
      int i = 1;
      for (Common.TypedValue value : update.getParameterValuesList()) {
        // Use the value and then increment
        preparedStmt.setObject(i++, TypedValue.protoToJdbc(value, calendar));
      }
      preparedStmt.addBatch();
    }
    return new ExecuteBatchResult(AvaticaUtils.executeLargeBatch(preparedStmt));
  } catch (SQLException e) {
    throw propagate(e);
  }
}
 
Example 13
Source Project: calcite-avatica   Source File: RemoteMetaTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test public void testRemoteStatementInsert() throws Exception {
  ConnectionSpec.getDatabaseLock().lock();
  try {
    final String t = AvaticaUtils.unique("TEST_TABLE2");
    AvaticaConnection conn = (AvaticaConnection) DriverManager.getConnection(url);
    Statement statement = conn.createStatement();
    final String create =
        String.format(Locale.ROOT, "create table if not exists %s ("
            + "  id int not null, msg varchar(255) not null)", t);
    int status = statement.executeUpdate(create);
    assertEquals(status, 0);

    statement = conn.createStatement();
    final String update =
        String.format(Locale.ROOT, "insert into %s values ('%d', '%s')",
            t, RANDOM.nextInt(Integer.MAX_VALUE), UUID.randomUUID());
    status = statement.executeUpdate(update);
    assertEquals(status, 1);
  } finally {
    ConnectionSpec.getDatabaseLock().unlock();
  }
}
 
Example 14
Source Project: calcite-avatica   Source File: AbstractCursor.java    License: Apache License 2.0 6 votes vote down vote up
@Override public Object getObject() throws SQLException {
  final Object object = super.getObject();
  if (object == null || object instanceof ArrayImpl) {
    return object;
  } else if (object instanceof List) {
    List<?> list = (List<?>) object;
    // Run the array values through the component accessor
    List<Object> convertedValues = new ArrayList<>(list.size());
    for (Object val : list) {
      if (null == val) {
        convertedValues.add(null);
      } else {
        // Set the current value in the SlotGetter so we can use the Accessor to coerce it.
        componentSlotGetter.slot = val;
        convertedValues.add(convertValue());
      }
    }
    return convertedValues;
  }
  // The object can be java array in case of user-provided class for row storage.
  return AvaticaUtils.primitiveList(object);
}
 
Example 15
Source Project: calcite-avatica   Source File: LocalService.java    License: Apache License 2.0 6 votes vote down vote up
public ExecuteResponse apply(ExecuteRequest request) {
  try (final Context ignore = executeTimer.start()) {
    try {
      final Meta.ExecuteResult executeResult = meta.execute(request.statementHandle,
          request.parameterValues, AvaticaUtils.toSaturatedInt(request.maxRowCount));

      final List<ResultSetResponse> results = new ArrayList<>(executeResult.resultSets.size());
      for (Meta.MetaResultSet metaResultSet : executeResult.resultSets) {
        results.add(toResponse(metaResultSet));
      }
      return new ExecuteResponse(results, false, serverLevelRpcMetadata);
    } catch (NoSuchStatementException e) {
      return new ExecuteResponse(null, true, serverLevelRpcMetadata);
    }
  }
}
 
Example 16
Source Project: calcite-avatica   Source File: AvaticaUtilsTest.java    License: Apache License 2.0 6 votes vote down vote up
/** Unit test for
 * {@link org.apache.calcite.avatica.AvaticaUtils#unique(java.lang.String)}. */
@Test public void testUnique() {
  // Below, the "probably" comments indicate the strings that will be
  // generated the first time you run the test.
  final Set<String> list = new LinkedHashSet<>();
  list.add(AvaticaUtils.unique("a")); // probably "a"
  assertThat(list.size(), is(1));
  list.add(AvaticaUtils.unique("a")); // probably "a_1"
  assertThat(list.size(), is(2));
  list.add(AvaticaUtils.unique("b")); // probably "b"
  assertThat(list.size(), is(3));
  list.add(AvaticaUtils.unique("a_1")); // probably "a_1_3"
  assertThat(list.size(), is(4));
  list.add(AvaticaUtils.unique("A")); // probably "A"
  assertThat(list.size(), is(5));
  list.add(AvaticaUtils.unique("a")); // probably "a_5"
  assertThat(list.size(), is(6));
}
 
Example 17
Source Project: quark   Source File: QuarkMetaImpl.java    License: Apache License 2.0 6 votes vote down vote up
private <E> MetaResultSet createResultSet(Enumerable<E> enumerable,
    Class clazz, String... names) {
  final List<ColumnMetaData> columns = new ArrayList<>();
  final List<Field> fields = new ArrayList<>();
  final List<String> fieldNames = new ArrayList<>();
  for (String name : names) {
    final int index = fields.size();
    final String fieldName = AvaticaUtils.toCamelCase(name);
    final Field field;
    try {
      field = clazz.getField(fieldName);
    } catch (NoSuchFieldException e) {
      throw new RuntimeException(e);
    }
    columns.add(columnMetaData(name, index, field.getType(), false));
    fields.add(field);
    fieldNames.add(fieldName);
  }
  //noinspection unchecked
  final Iterable<Object> iterable = (Iterable<Object>) (Iterable) enumerable;
  return createResultSet(Collections.<String, Object>emptyMap(),
      columns, CursorFactory.record(clazz, fields, fieldNames),
      new Frame(0, true, iterable));
}
 
Example 18
Source Project: kylin   Source File: KylinMeta.java    License: Apache License 2.0 6 votes vote down vote up
@SuppressWarnings({"rawtypes", "unchecked"})
private MetaResultSet createResultSet(List iterable, Class clazz, String... names) {
    final List<ColumnMetaData> columns = new ArrayList<ColumnMetaData>();
    final List<Field> fields = new ArrayList<Field>();
    final List<String> fieldNames = new ArrayList<String>();
    for (String name : names) {
        final int index = fields.size();
        final String fieldName = AvaticaUtils.toCamelCase(name);
        final Field field;
        try {
            field = clazz.getField(fieldName);
        } catch (NoSuchFieldException e) {
            throw new RuntimeException(e);
        }
        columns.add(columnMetaData(name, index, field.getType(), true));
        fields.add(field);
        fieldNames.add(fieldName);
    }

    CursorFactory cursorFactory = CursorFactory.record(clazz, fields, fieldNames);
    Signature signature = new Signature(columns, "", null, Collections.<String, Object> emptyMap(), cursorFactory, StatementType.SELECT);
    StatementHandle sh = this.createStatement(connection().handle);
    Frame frame = new Frame(0, true, iterable);

    return MetaResultSet.create(connection().id, sh.id, true, signature, frame);
}
 
Example 19
Source Project: calcite   Source File: Lattice.java    License: Apache License 2.0 6 votes vote down vote up
/** Builds a lattice. */
public Lattice build() {
  LatticeStatisticProvider.Factory statisticProvider =
      this.statisticProvider != null
          ? AvaticaUtils.instantiatePlugin(
              LatticeStatisticProvider.Factory.class,
              this.statisticProvider)
          : Lattices.CACHED_SQL;
  Preconditions.checkArgument(rootSchema.isRoot(), "must be root schema");
  final ImmutableList.Builder<Column> columnBuilder =
      ImmutableList.<Column>builder()
      .addAll(baseColumns)
      .addAll(derivedColumnsByName.values());
  return new Lattice(rootSchema, rootNode, auto,
      algorithm, algorithmMaxMillis, statisticProvider, rowCountEstimate,
      columnBuilder.build(), ImmutableSortedSet.copyOf(defaultMeasureSet),
      tileListBuilder.build(), ImmutableListMultimap.copyOf(columnUses));
}
 
Example 20
Source Project: calcite   Source File: RelJson.java    License: Apache License 2.0 6 votes vote down vote up
SqlOperator toOp(Map<String, Object> map) {
  // in case different operator has the same kind, check with both name and kind.
  String name = map.get("name").toString();
  String kind = map.get("kind").toString();
  String syntax = map.get("syntax").toString();
  SqlKind sqlKind = SqlKind.valueOf(kind);
  SqlSyntax  sqlSyntax = SqlSyntax.valueOf(syntax);
  List<SqlOperator> operators = new ArrayList<>();
  SqlStdOperatorTable.instance().lookupOperatorOverloads(
      new SqlIdentifier(name, new SqlParserPos(0, 0)),
      null,
      sqlSyntax,
      operators,
      SqlNameMatchers.liberal());
  for (SqlOperator operator: operators) {
    if (operator.kind == sqlKind) {
      return operator;
    }
  }
  String class_ = (String) map.get("class");
  if (class_ != null) {
    return AvaticaUtils.instantiatePlugin(SqlOperator.class, class_);
  }
  return null;
}
 
Example 21
Source Project: calcite   Source File: CalciteMetaImpl.java    License: Apache License 2.0 6 votes vote down vote up
private <E> MetaResultSet createResultSet(Enumerable<E> enumerable,
    Class clazz, String... names) {
  Objects.requireNonNull(names);
  final List<ColumnMetaData> columns = new ArrayList<>(names.length);
  final List<Field> fields = new ArrayList<>(names.length);
  final List<String> fieldNames = new ArrayList<>(names.length);
  for (String name : names) {
    final int index = fields.size();
    final String fieldName = AvaticaUtils.toCamelCase(name);
    final Field field;
    try {
      field = clazz.getField(fieldName);
    } catch (NoSuchFieldException e) {
      throw new RuntimeException(e);
    }
    columns.add(columnMetaData(name, index, field.getType(), false));
    fields.add(field);
    fieldNames.add(fieldName);
  }
  //noinspection unchecked
  final Iterable<Object> iterable = (Iterable<Object>) (Iterable) enumerable;
  return createResultSet(Collections.emptyMap(),
      columns, CursorFactory.record(clazz, fields, fieldNames),
      new Frame(0, true, iterable));
}
 
Example 22
Source Project: calcite   Source File: ModelHandler.java    License: Apache License 2.0 6 votes vote down vote up
public void visit(JsonCustomSchema jsonSchema) {
  try {
    final SchemaPlus parentSchema = currentMutableSchema("sub-schema");
    checkRequiredAttributes(jsonSchema, "name", "factory");
    final SchemaFactory schemaFactory =
        AvaticaUtils.instantiatePlugin(SchemaFactory.class,
            jsonSchema.factory);
    final Schema schema =
        schemaFactory.create(
            parentSchema, jsonSchema.name, operandMap(jsonSchema, jsonSchema.operand));
    final SchemaPlus schemaPlus = parentSchema.add(jsonSchema.name, schema);
    populateSchema(jsonSchema, schemaPlus);
  } catch (Exception e) {
    throw new RuntimeException("Error instantiating " + jsonSchema, e);
  }
}
 
Example 23
Source Project: calcite   Source File: ModelHandler.java    License: Apache License 2.0 6 votes vote down vote up
public void visit(JsonJdbcSchema jsonSchema) {
  checkRequiredAttributes(jsonSchema, "name");
  final SchemaPlus parentSchema = currentMutableSchema("jdbc schema");
  final DataSource dataSource =
      JdbcSchema.dataSource(jsonSchema.jdbcUrl,
          jsonSchema.jdbcDriver,
          jsonSchema.jdbcUser,
          jsonSchema.jdbcPassword);
  final JdbcSchema schema;
  if (jsonSchema.sqlDialectFactory == null || jsonSchema.sqlDialectFactory.isEmpty()) {
    schema =
        JdbcSchema.create(parentSchema, jsonSchema.name, dataSource,
            jsonSchema.jdbcCatalog, jsonSchema.jdbcSchema);
  } else {
    SqlDialectFactory factory = AvaticaUtils.instantiatePlugin(
        SqlDialectFactory.class, jsonSchema.sqlDialectFactory);
    schema =
        JdbcSchema.create(parentSchema, jsonSchema.name, dataSource,
            factory, jsonSchema.jdbcCatalog, jsonSchema.jdbcSchema);
  }
  final SchemaPlus schemaPlus = parentSchema.add(jsonSchema.name, schema);
  populateSchema(jsonSchema, schemaPlus);
}
 
Example 24
Source Project: calcite   Source File: ModelHandler.java    License: Apache License 2.0 6 votes vote down vote up
public void visit(JsonCustomTable jsonTable) {
  try {
    checkRequiredAttributes(jsonTable, "name", "factory");
    final SchemaPlus schema = currentMutableSchema("table");
    final TableFactory tableFactory =
        AvaticaUtils.instantiatePlugin(TableFactory.class,
            jsonTable.factory);
    final Table table =
        tableFactory.create(schema, jsonTable.name,
            operandMap(null, jsonTable.operand), null);
    for (JsonColumn column : jsonTable.columns) {
      column.accept(this);
    }
    schema.add(jsonTable.name, table);
  } catch (Exception e) {
    throw new RuntimeException("Error instantiating " + jsonTable, e);
  }
}
 
Example 25
Source Project: Quicksql   Source File: JdbcSchema.java    License: MIT License 5 votes vote down vote up
/**
 * Creates a JdbcSchema, taking credentials from a map.
 *
 * @param parentSchema Parent schema
 * @param name Name
 * @param operand Map of property/value pairs
 * @return A JdbcSchema
 */
public static JdbcSchema create(
    SchemaPlus parentSchema,
    String name,
    Map<String, Object> operand) {
  DataSource dataSource;
  try {
    final String dataSourceName = (String) operand.get("dataSource");
    if (dataSourceName != null) {
      dataSource =
          AvaticaUtils.instantiatePlugin(DataSource.class, dataSourceName);
    } else {
      final String jdbcUrl = (String) operand.get("jdbcUrl");
      final String jdbcDriver = (String) operand.get("jdbcDriver");
      final String jdbcUser = (String) operand.get("jdbcUser");
      final String jdbcPassword = (String) operand.get("jdbcPassword");
      dataSource = dataSource(jdbcUrl, jdbcDriver, jdbcUser, jdbcPassword);
    }
  } catch (Exception e) {
    throw new RuntimeException("Error while reading dataSource", e);
  }
  String jdbcCatalog = (String) operand.get("jdbcCatalog");
  String jdbcSchema = (String) operand.get("jdbcSchema");
  String sqlDialectFactory = (String) operand.get("sqlDialectFactory");

  if (sqlDialectFactory == null || sqlDialectFactory.isEmpty()) {
    return JdbcSchema.create(
        parentSchema, name, dataSource, jdbcCatalog, jdbcSchema);
  } else {
    SqlDialectFactory factory = AvaticaUtils.instantiatePlugin(
        SqlDialectFactory.class, sqlDialectFactory);
    return JdbcSchema.create(
        parentSchema, name, dataSource, factory, jdbcCatalog, jdbcSchema);
  }
}
 
Example 26
Source Project: Quicksql   Source File: UtilTest.java    License: MIT License 5 votes vote down vote up
/**
 * Unit test for {@link AvaticaUtils#toCamelCase(String)}.
 */
@Test public void testToCamelCase() {
  assertEquals("myJdbcDriver", AvaticaUtils.toCamelCase("MY_JDBC_DRIVER"));
  assertEquals("myJdbcDriver", AvaticaUtils.toCamelCase("MY_JDBC__DRIVER"));
  assertEquals("myJdbcDriver", AvaticaUtils.toCamelCase("my_jdbc_driver"));
  assertEquals("abCdefGHij", AvaticaUtils.toCamelCase("ab_cdEf_g_Hij"));
  assertEquals("JdbcDriver", AvaticaUtils.toCamelCase("_JDBC_DRIVER"));
  assertEquals("", AvaticaUtils.toCamelCase("_"));
  assertEquals("", AvaticaUtils.toCamelCase(""));
}
 
Example 27
Source Project: Quicksql   Source File: UtilTest.java    License: MIT License 5 votes vote down vote up
/** Unit test for {@link AvaticaUtils#camelToUpper(String)}. */
@Test public void testCamelToUpper() {
  assertEquals("MY_JDBC_DRIVER", AvaticaUtils.camelToUpper("myJdbcDriver"));
  assertEquals("MY_J_D_B_C_DRIVER",
      AvaticaUtils.camelToUpper("myJDBCDriver"));
  assertEquals("AB_CDEF_G_HIJ", AvaticaUtils.camelToUpper("abCdefGHij"));
  assertEquals("_JDBC_DRIVER", AvaticaUtils.camelToUpper("JdbcDriver"));
  assertEquals("", AvaticaUtils.camelToUpper(""));
}
 
Example 28
Source Project: Quicksql   Source File: QuidemTest.java    License: MIT License 5 votes vote down vote up
private Method findMethod(String path) {
  // E.g. path "sql/agg.iq" gives method "testSqlAgg"
  String methodName =
      AvaticaUtils.toCamelCase(
          "test_" + path.replace(File.separatorChar, '_').replaceAll("\\.iq$", ""));
  Method m;
  try {
    m = getClass().getMethod(methodName);
  } catch (NoSuchMethodException e) {
    m = null;
  }
  return m;
}
 
Example 29
Source Project: Quicksql   Source File: QuicksqlRemoteMeta.java    License: MIT License 5 votes vote down vote up
@SuppressWarnings("deprecation")
@Override public ExecuteResult prepareAndExecute(StatementHandle h, String sql, long maxRowCount,
    PrepareCallback callback) throws NoSuchStatementException {
  // The old semantics were that maxRowCount was also treated as the maximum number of
  // elements in the first Frame of results. A value of -1 would also preserve this, but an
  // explicit (positive) number is easier to follow, IMO.
  return prepareAndExecute(h, sql, maxRowCount, AvaticaUtils.toSaturatedInt(maxRowCount),
      callback);
}
 
Example 30
Source Project: Quicksql   Source File: QuicksqlServerResultSet.java    License: MIT License 5 votes vote down vote up
/**
 * Converts an Array into a List using {@link Array#getArray()}. This implementation assumes
 * a non-nested array. Use {link {@link #extractUsingResultSet(Array, Calendar)} if nested
 * arrays may be possible.
 */
static List<?> extractUsingArray(Array array, Calendar calendar) throws SQLException {
  // No option but to guess as to what the type actually is...
  Object o = array.getArray();
  if (o instanceof List) {
    return (List<?>) o;
  }
  // Assume that it's a Java array.
  return AvaticaUtils.primitiveList(o);
}