org.apache.calcite.avatica.Meta Java Examples

The following examples show how to use org.apache.calcite.avatica.Meta. 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 File: QuarkMetaImpl.java    From quark with Apache License 2.0 6 votes vote down vote up
protected MetaResultSet createResultSet(
    Map<String, Object> internalParameters, List<ColumnMetaData> columns,
    CursorFactory cursorFactory, final Frame firstFrame) {
  try {
    final QuarkConnectionImpl connection = getConnection();
    final AvaticaStatement statement = connection.createStatement();
    final CalcitePrepare.CalciteSignature<Object> signature =
        new CalcitePrepare.CalciteSignature<Object>("",
            ImmutableList.<AvaticaParameter>of(), internalParameters, null,
            columns, cursorFactory, null, ImmutableList.<RelCollation>of(), -1,
            null, Meta.StatementType.SELECT) {
          @Override public Enumerable<Object> enumerable(
              DataContext dataContext) {
            return Linq4j.asEnumerable(firstFrame.rows);
          }
        };
    return MetaResultSet.create(connection.id, statement.getId(), true,
        signature, firstFrame);
  } catch (SQLException e) {
    throw new RuntimeException(e);
  }
}
 
Example #2
Source File: CalciteConnectionImpl.java    From Quicksql with MIT License 6 votes vote down vote up
private CalcitePreparedStatement prepareStatement_(
    CalcitePrepare.Query<?> query,
    int resultSetType,
    int resultSetConcurrency,
    int resultSetHoldability) throws SQLException {
  try {
    final Meta.Signature signature =
        parseQuery(query, createPrepareContext(), -1);
    final CalcitePreparedStatement calcitePreparedStatement =
        (CalcitePreparedStatement) factory.newPreparedStatement(this, null,
            signature, resultSetType, resultSetConcurrency, resultSetHoldability);
    server.getStatement(calcitePreparedStatement.handle).setSignature(signature);
    return calcitePreparedStatement;
  } catch (Exception e) {
    throw Helper.INSTANCE.createException(
        "Error while preparing statement [" + query.sql + "]", e);
  }
}
 
Example #3
Source File: QuarkMetaFactoryImpl.java    From quark with Apache License 2.0 6 votes vote down vote up
@Override
public Meta create(List<String> args) {
  String url = "jdbc:quark:fat:db:";

  try {
    if (args.size() == 1) {
      String filePath = args.get(0);
      ObjectMapper objectMapper = new ObjectMapper();
      serverConfig = objectMapper.readValue(new File(filePath), ServerConfig.class);

      url = url + filePath;
    } else {
      throw new RuntimeException(
          "1 argument expected. Received " + Arrays.toString(args.toArray()));
    }
    return new JdbcMeta(url, new Properties());
  } catch (SQLException | IOException e) {
    throw new RuntimeException(e);
  }
}
 
Example #4
Source File: LocalService.java    From calcite-avatica with Apache License 2.0 6 votes vote down vote up
public ExecuteBatchResponse apply(ExecuteBatchRequest request) {
  final Meta.StatementHandle h = new Meta.StatementHandle(request.connectionId,
      request.statementId, null);
  try {
    ExecuteBatchResult result;
    if (request.hasProtoUpdateBatches() && meta instanceof ProtobufMeta) {
      result = ((ProtobufMeta) meta).executeBatchProtobuf(h, request.getProtoUpdateBatches());
    } else {
      result = meta.executeBatch(h, request.parameterValues);
    }
    return new ExecuteBatchResponse(request.connectionId, request.statementId,
        result.updateCounts, false, serverLevelRpcMetadata);
  } catch (NoSuchStatementException e) {
    return new ExecuteBatchResponse(request.connectionId, request.statementId, null, true,
        serverLevelRpcMetadata);
  }
}
 
Example #5
Source File: JdbcMeta.java    From calcite-avatica with Apache License 2.0 6 votes vote down vote up
public Frame fetch(StatementHandle h, long offset, int fetchMaxRowCount) throws
    NoSuchStatementException, MissingResultsException {
  LOG.trace("fetching {} offset:{} fetchMaxRowCount:{}", h, offset, fetchMaxRowCount);
  try {
    final StatementInfo statementInfo = statementCache.getIfPresent(h.id);
    if (null == statementInfo) {
      // Statement might have expired, or never existed on this server.
      throw new NoSuchStatementException(h);
    }

    if (!statementInfo.isResultSetInitialized()) {
      // The Statement exists, but the results are missing. Need to call syncResults(...)
      throw new MissingResultsException(h);
    }
    if (statementInfo.getResultSet() == null) {
      return Frame.EMPTY;
    } else {
      return JdbcResultSet.frame(statementInfo, statementInfo.getResultSet(), offset,
          fetchMaxRowCount, calendar, Optional.<Meta.Signature>absent());
    }
  } catch (SQLException e) {
    throw propagate(e);
  }
}
 
Example #6
Source File: JdbcResultSet.java    From calcite-avatica with Apache License 2.0 6 votes vote down vote up
public static JdbcResultSet create(String connectionId, int statementId,
    ResultSet resultSet, int maxRowCount, Meta.Signature signature) {
  try {
    final Calendar calendar = DateTimeUtils.calendar();
    final int fetchRowCount;
    if (maxRowCount == JdbcMeta.UNLIMITED_COUNT) {
      fetchRowCount = -1;
    } else if (maxRowCount < 0L) {
      fetchRowCount = AvaticaStatement.DEFAULT_FETCH_SIZE;
    } else if (maxRowCount > AvaticaStatement.DEFAULT_FETCH_SIZE) {
      fetchRowCount = AvaticaStatement.DEFAULT_FETCH_SIZE;
    } else {
      fetchRowCount = maxRowCount;
    }
    final Meta.Frame firstFrame = frame(null, resultSet, 0, fetchRowCount, calendar,
        Optional.of(signature));
    if (firstFrame.done) {
      resultSet.close();
    }
    return new JdbcResultSet(connectionId, statementId, true, signature,
        firstFrame);
  } catch (SQLException e) {
    throw new RuntimeException(e);
  }
}
 
Example #7
Source File: QuarkMetaImpl.java    From quark with Apache License 2.0 6 votes vote down vote up
@Override
public Frame fetch(StatementHandle h, long offset, int fetchMaxRowCount) {
  final QuarkConnectionImpl calciteConnection = getConnection();
  QuarkJdbcStatement stmt = calciteConnection.server.getStatement(h);
  final Signature signature = stmt.getSignature();
  final Iterator<Object> iterator;
  if (stmt.getResultSet() == null) {
    final Iterable<Object> iterable =
        Linq4j.emptyEnumerable();
    iterator = iterable.iterator();
    stmt.setResultSet(iterator);
  } else {
    iterator = stmt.getResultSet();
  }
  final List<List<Object>> list = new ArrayList<>();
  List<List<Object>> rows =
      MetaImpl.collect(signature.cursorFactory,
          LimitIterator.of(iterator, fetchMaxRowCount), list);
  boolean done = fetchMaxRowCount == 0 || list.size() < fetchMaxRowCount;
  return new Meta.Frame(offset, done, (List<Object>) (List) rows);
}
 
Example #8
Source File: QuarkMetaImpl.java    From quark with Apache License 2.0 6 votes vote down vote up
public Meta.ExecuteResult prepareAndExecute(Meta.StatementHandle h,
                                            String sql,
                                            long maxRowCount,
                                            Meta.PrepareCallback callback) {
  try {
    MetaResultSet metaResultSet = null;
    synchronized (callback.getMonitor()) {
      callback.clear();
      ParserResult result = getConnection().parse(sql);
      metaResultSet = new PlanExecutor(h, getConnection(),
          connectionCache, maxRowCount).execute(result);
      callback.assign(metaResultSet.signature, metaResultSet.firstFrame,
          metaResultSet.updateCount);
    }
    callback.execute();
    return new ExecuteResult(ImmutableList.of(metaResultSet));
  } catch (Exception e) {
    throw propagate(e);
  }
}
 
Example #9
Source File: CalcitePrepare.java    From calcite with Apache License 2.0 6 votes vote down vote up
public CalciteSignature(String sql,
    List<AvaticaParameter> parameterList,
    Map<String, Object> internalParameters,
    RelDataType rowType,
    List<ColumnMetaData> columns,
    Meta.CursorFactory cursorFactory,
    CalciteSchema rootSchema,
    List<RelCollation> collationList,
    long maxRowCount,
    Bindable<T> bindable,
    Meta.StatementType statementType) {
  super(columns, sql, parameterList, internalParameters, cursorFactory,
      statementType);
  this.rowType = rowType;
  this.rootSchema = rootSchema;
  this.collationList = collationList;
  this.maxRowCount = maxRowCount;
  this.bindable = bindable;
}
 
Example #10
Source File: Service.java    From calcite-avatica with Apache License 2.0 6 votes vote down vote up
static ResultSetResponse fromProto(Responses.ResultSetResponse msg) {
  String connectionId = null;
  if (msg.hasField(CONNECTION_ID_DESCRIPTOR)) {
    connectionId = msg.getConnectionId();
  }

  Meta.Signature signature = null;
  if (msg.hasField(SIGNATURE_DESCRIPTOR)) {
    signature = Meta.Signature.fromProto(msg.getSignature());
  }

  Meta.Frame frame = null;
  if (msg.hasField(FIRST_FRAME_DESCRIPTOR)) {
    frame = Meta.Frame.fromProto(msg.getFirstFrame());
  }

  RpcMetadataResponse metadata = null;
  if (msg.hasField(METADATA_DESCRIPTOR)) {
    metadata = RpcMetadataResponse.fromProto(msg.getMetadata());
  }

  return new ResultSetResponse(connectionId, msg.getStatementId(), msg.getOwnStatement(),
      signature, frame, msg.getUpdateCount(), metadata);
}
 
Example #11
Source File: LocalService.java    From calcite-avatica with 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 #12
Source File: LocalService.java    From calcite-avatica with Apache License 2.0 5 votes vote down vote up
public ResultSetResponse apply(SchemasRequest request) {
  final Meta.ConnectionHandle ch =
      new Meta.ConnectionHandle(request.connectionId);
  final Meta.MetaResultSet resultSet =
      meta.getSchemas(ch, request.catalog, Meta.Pat.of(request.schemaPattern));
  return toResponse(resultSet);
}
 
Example #13
Source File: CalcitePrepare.java    From calcite with Apache License 2.0 5 votes vote down vote up
@Deprecated // to be removed before 2.0
public CalciteSignature(String sql, List<AvaticaParameter> parameterList,
    Map<String, Object> internalParameters, RelDataType rowType,
    List<ColumnMetaData> columns, Meta.CursorFactory cursorFactory,
    CalciteSchema rootSchema, List<RelCollation> collationList,
    long maxRowCount, Bindable<T> bindable) {
  this(sql, parameterList, internalParameters, rowType, columns,
      cursorFactory, rootSchema, collationList, maxRowCount, bindable,
      null);
}
 
Example #14
Source File: AlternatingRemoteMetaTest.java    From calcite-avatica with Apache License 2.0 5 votes vote down vote up
private static Meta.ExecuteResult prepareAndExecuteInternal(AvaticaConnection conn,
    final AvaticaStatement statement, String sql, int maxRowCount) throws Exception {
  Method m =
      AvaticaConnection.class.getDeclaredMethod("prepareAndExecuteInternal",
          AvaticaStatement.class, String.class, long.class);
  m.setAccessible(true);
  return (Meta.ExecuteResult) m.invoke(conn, statement, sql, maxRowCount);
}
 
Example #15
Source File: LocalService.java    From calcite-avatica with Apache License 2.0 5 votes vote down vote up
public ConnectionSyncResponse apply(ConnectionSyncRequest request) {
  try (final Context ignore = connectionSyncTimer.start()) {
    final Meta.ConnectionHandle ch =
        new Meta.ConnectionHandle(request.connectionId);
    final Meta.ConnectionProperties connProps =
        meta.connectionSync(ch, request.connProps);
    return new ConnectionSyncResponse(connProps, serverLevelRpcMetadata);
  }
}
 
Example #16
Source File: LocalService.java    From calcite-avatica with Apache License 2.0 5 votes vote down vote up
public PrepareResponse apply(PrepareRequest request) {
  try (final Context ignore = prepareTimer.start()) {
    final Meta.ConnectionHandle ch =
        new Meta.ConnectionHandle(request.connectionId);
    final Meta.StatementHandle h =
        meta.prepare(ch, request.sql, request.maxRowCount);
    return new PrepareResponse(h, serverLevelRpcMetadata);
  }
}
 
Example #17
Source File: QuarkJdbc41Factory.java    From quark with Apache License 2.0 5 votes vote down vote up
@Override
public AvaticaResultSet newResultSet(AvaticaStatement statement,
                                     QueryState state,
                                     Meta.Signature signature,
                                     TimeZone timeZone,
                                     Meta.Frame firstFrame) {
  final ResultSetMetaData metaData =
      newResultSetMetaData(statement, signature);
  return new QuarkResultSet(statement, signature, metaData, timeZone,
      firstFrame);
}
 
Example #18
Source File: CalcitePrepareImpl.java    From calcite with Apache License 2.0 5 votes vote down vote up
/**
 * Deduces the broad type of statement.
 * Currently returns SELECT for most statement types, but this may change.
 *
 * @param kind Kind of statement
 */
private Meta.StatementType getStatementType(SqlKind kind) {
  switch (kind) {
  case INSERT:
  case DELETE:
  case UPDATE:
    return Meta.StatementType.IS_DML;
  default:
    return Meta.StatementType.SELECT;
  }
}
 
Example #19
Source File: CalciteConnectionImpl.java    From calcite with Apache License 2.0 5 votes vote down vote up
public void addStatement(CalciteConnection connection,
    Meta.StatementHandle h) {
  final CalciteConnectionImpl c = (CalciteConnectionImpl) connection;
  final CalciteServerStatement previous =
      statementMap.put(h.id, new CalciteServerStatementImpl(c));
  if (previous != null) {
    throw new AssertionError();
  }
}
 
Example #20
Source File: AbstractService.java    From calcite-avatica with Apache License 2.0 5 votes vote down vote up
PrepareResponse finagle(PrepareResponse response) {
  final Meta.StatementHandle statement = finagle(response.statement);
  if (statement == response.statement) {
    return response;
  }
  return new PrepareResponse(statement, rpcMetadata);
}
 
Example #21
Source File: QuarkMetaResultSet.java    From quark with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a result set with maxRowCount.
 * If {@code maxRowCount} is -2 ({@link QuarkMetaImpl#UNLIMITED_COUNT}),
 * returns an unlimited number of rows in a single frame; any other
 * negative value (typically -1) returns an unlimited number of rows
 * in frames of the default frame size.
 */
public static QuarkMetaResultSet create(String connectionId, int statementId,
                                        ResultSet resultSet, long maxRowCount) {
  try {
    Meta.Signature sig = QuarkMetaImpl.signature(resultSet.getMetaData());
    return create(connectionId, statementId, resultSet, maxRowCount, sig);
  } catch (SQLException e) {
    throw new RuntimeException(e);
  }
}
 
Example #22
Source File: Service.java    From calcite-avatica with Apache License 2.0 5 votes vote down vote up
@Override FetchResponse deserialize(Message genericMsg) {
  final Responses.FetchResponse msg = ProtobufService.castProtobufMessage(genericMsg,
      Responses.FetchResponse.class);

  RpcMetadataResponse metadata = null;
  if (msg.hasField(METADATA_DESCRIPTOR)) {
    metadata = RpcMetadataResponse.fromProto(msg.getMetadata());
  }

  return new FetchResponse(Meta.Frame.fromProto(msg.getFrame()), msg.getMissingStatement(),
      msg.getMissingResults(), metadata);
}
 
Example #23
Source File: LocalService.java    From calcite-avatica with Apache License 2.0 5 votes vote down vote up
public CommitResponse apply(CommitRequest request) {
  try (final Context ignore = commitTimer.start()) {
    meta.commit(new Meta.ConnectionHandle(request.connectionId));

    // If commit() errors, let the ErrorResponse be sent back via an uncaught Exception.
    return new CommitResponse();
  }
}
 
Example #24
Source File: QuicksqlConnectionImpl.java    From Quicksql with MIT License 5 votes vote down vote up
public Signature mockPreparedSignature(String sql) {
    List<AvaticaParameter> params = new ArrayList<AvaticaParameter>();
    int startIndex = 0;
    while (sql.indexOf("?", startIndex) >= 0) {
        AvaticaParameter param = new AvaticaParameter(false, 0, 0, 0, null, null, null);
        params.add(param);
        startIndex = sql.indexOf("?", startIndex) + 1;
    }

    ArrayList<ColumnMetaData> columns = new ArrayList<ColumnMetaData>();
    Map<String, Object> internalParams = Collections.<String, Object> emptyMap();

    return new Meta.Signature(columns, sql, params, internalParams, CursorFactory.ARRAY, Meta.StatementType.SELECT);
}
 
Example #25
Source File: QuicksqlJdbc41Factory.java    From Quicksql with MIT License 5 votes vote down vote up
QuickSqlJdbc41PreparedStatement(QuicksqlConnectionImpl connection,
    Meta.StatementHandle h, Signature signature,
    int resultSetType, int resultSetConcurrency, int resultSetHoldability)
    throws SQLException {
  super(connection, h, signature, resultSetType, resultSetConcurrency,
      resultSetHoldability);
}
 
Example #26
Source File: DremioResultSetImpl.java    From dremio-oss with Apache License 2.0 5 votes vote down vote up
DremioResultSetImpl(AvaticaStatement statement, QueryState state,
                   Meta.Signature signature, ResultSetMetaData resultSetMetaData,
                   TimeZone timeZone, Meta.Frame firstFrame) throws SQLException {
  super(statement, state, signature, resultSetMetaData, timeZone, firstFrame);
  connection = (DremioConnectionImpl) statement.getConnection();
  cursor = new DremioCursor(connection, statement, signature);
}
 
Example #27
Source File: CalciteRemoteDriverTest.java    From Quicksql with MIT License 5 votes vote down vote up
public Meta create(List<String> args) {
  try {
    final Connection connection = CalciteAssert.hr().connect();
    return new CalciteMetaImpl((CalciteConnectionImpl) connection);
  } catch (Exception e) {
    throw TestUtil.rethrow(e);
  }
}
 
Example #28
Source File: CalciteRemoteDriverTest.java    From Quicksql with MIT License 5 votes vote down vote up
@Test public void testMetaFunctionsLocal() throws Exception {
  final Connection connection =
      CalciteAssert.hr().connect();
  assertThat(connection.isClosed(), is(false));
  for (Meta.DatabaseProperty p : Meta.DatabaseProperty.values()) {
    switch (p) {
    case GET_NUMERIC_FUNCTIONS:
      assertThat(connection.getMetaData().getNumericFunctions(),
          not(equalTo("")));
      break;
    case GET_SYSTEM_FUNCTIONS:
      assertThat(connection.getMetaData().getSystemFunctions(),
          CoreMatchers.notNullValue());
      break;
    case GET_TIME_DATE_FUNCTIONS:
      assertThat(connection.getMetaData().getTimeDateFunctions(),
          not(equalTo("")));
      break;
    case GET_S_Q_L_KEYWORDS:
      assertThat(connection.getMetaData().getSQLKeywords(),
          not(equalTo("")));
      break;
    case GET_STRING_FUNCTIONS:
      assertThat(connection.getMetaData().getStringFunctions(),
          not(equalTo("")));
      break;
    default:
    }
  }
  connection.close();
  assertThat(connection.isClosed(), is(true));
}
 
Example #29
Source File: Main.java    From quark with Apache License 2.0 5 votes vote down vote up
public void run(String[] args) throws Exception {
  logJVMInfo();
  try {

    Class<? extends Meta.Factory> factoryClass = QuarkMetaFactoryImpl.class;

    Meta.Factory factory =
        factoryClass.getDeclaredConstructor().newInstance();
    Meta meta = factory.create(Arrays.asList(args));

    int port = 8765;
    if (QuarkMetaFactoryImpl.serverConfig.port != 0) {
      port = QuarkMetaFactoryImpl.serverConfig.port;
    }
    LOG.debug("Listening on port " + port);

    final HandlerFactory handlerFactory = new HandlerFactory();
    Service service = new LocalService(meta);
    server = new HttpServer(port, getHandler(service, handlerFactory));
    Class.forName("com.qubole.quark.fatjdbc.QuarkDriver");
    server.start();
    runningLatch.countDown();
    server.join();
  } catch (Throwable t) {
    LOG.fatal("Unrecoverable service error. Shutting down.", t);
    this.t = t;
  }
}
 
Example #30
Source File: QuicksqlJdbc41Factory.java    From Quicksql with MIT License 5 votes vote down vote up
public QuickSqlJdbc41Statement newStatement(AvaticaConnection connection,
    Meta.StatementHandle h,
    int resultSetType,
    int resultSetConcurrency,
    int resultSetHoldability) {
  return new QuickSqlJdbc41Statement(
      (QuicksqlConnectionImpl) connection,
      h,
      resultSetType, resultSetConcurrency,
      resultSetHoldability);
}