Home | History | Annotate | Download | only in sql
      1 /* Copyright 2017 The TensorFlow Authors. All Rights Reserved.
      2 
      3 Licensed under the Apache License, Version 2.0 (the "License");
      4 you may not use this file except in compliance with the License.
      5 You may obtain a copy of the License at
      6 
      7     http://www.apache.org/licenses/LICENSE-2.0
      8 
      9 Unless required by applicable law or agreed to in writing, software
     10 distributed under the License is distributed on an "AS IS" BASIS,
     11 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     12 See the License for the specific language governing permissions and
     13 limitations under the License.
     14 ==============================================================================*/
     15 #include "tensorflow/core/kernels/data/sql/sqlite_query_connection.h"
     16 
     17 #include "tensorflow/core/framework/register_types.h"
     18 #include "tensorflow/core/kernels/data/dataset.h"
     19 #include "tensorflow/core/lib/strings/stringprintf.h"
     20 
     21 namespace tensorflow {
     22 
     23 namespace sql {
     24 
     25 SqliteQueryConnection::SqliteQueryConnection() {}
     26 
     27 SqliteQueryConnection::~SqliteQueryConnection() {
     28   if (db_ != nullptr) db_->Unref();
     29 }
     30 
     31 Status SqliteQueryConnection::Open(const string& data_source_name,
     32                                    const string& query,
     33                                    const DataTypeVector& output_types) {
     34   if (db_ != nullptr) {
     35     return errors::FailedPrecondition(
     36         "Failed to open query connection: Connection already opened.");
     37   }
     38   TF_RETURN_IF_ERROR(Sqlite::Open(
     39       data_source_name, SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, &db_));
     40   query_ = query;
     41   output_types_ = output_types;
     42   return Status::OK();
     43 }
     44 
     45 Status SqliteQueryConnection::Close() {
     46   stmt_ = SqliteStatement();
     47   db_->Unref();
     48   db_ = nullptr;
     49   return Status::OK();
     50 }
     51 
     52 Status SqliteQueryConnection::GetNext(IteratorContext* ctx,
     53                                       std::vector<Tensor>* out_tensors,
     54                                       bool* end_of_sequence) {
     55   if (!stmt_) TF_RETURN_IF_ERROR(PrepareQuery());
     56   TF_RETURN_IF_ERROR(stmt_.Step(end_of_sequence));
     57   if (!*end_of_sequence) {
     58     for (int i = 0; i < column_count_; i++) {
     59       DataType dt = output_types_[i];
     60       // TODO(mrry): Pass in the `IteratorContext::allocator()`.
     61       Tensor tensor(ctx->allocator({}), dt, {});
     62       FillTensorWithResultSetEntry(dt, i, &tensor);
     63       out_tensors->emplace_back(std::move(tensor));
     64     }
     65   }
     66   return Status::OK();
     67 }
     68 
     69 Status SqliteQueryConnection::PrepareQuery() {
     70   TF_RETURN_IF_ERROR(db_->Prepare(query_, &stmt_));
     71   int column_count = stmt_.ColumnCount();
     72   if (column_count != output_types_.size()) {
     73     stmt_ = SqliteStatement();
     74     return errors::InvalidArgument(tensorflow::strings::Printf(
     75         "The number of columns in query (%d) must match the number of "
     76         "elements in output_types (%zu).",
     77         column_count, output_types_.size()));
     78   }
     79   column_count_ = column_count;
     80   return Status::OK();
     81 }
     82 
     83 void SqliteQueryConnection::FillTensorWithResultSetEntry(
     84     const DataType& data_type, int column_index, Tensor* tensor) {
     85 #define CASE(T, M)                                                 \
     86   case DataTypeToEnum<T>::value:                                   \
     87     tensor->scalar<T>()() = static_cast<T>(stmt_.M(column_index)); \
     88     break;
     89 #define INT_CASE(T) CASE(T, ColumnInt)
     90 #define DOUBLE_CASE(T) CASE(T, ColumnDouble)
     91 #define STRING_CASE(T) CASE(T, ColumnString)
     92   // clang-format off
     93   switch (data_type) {
     94     TF_CALL_int8(INT_CASE)
     95     TF_CALL_uint8(INT_CASE)
     96     TF_CALL_int16(INT_CASE)
     97     TF_CALL_uint16(INT_CASE)
     98     TF_CALL_int32(INT_CASE)
     99     TF_CALL_uint32(INT_CASE)
    100     TF_CALL_int64(INT_CASE)
    101     TF_CALL_uint64(INT_CASE)
    102     TF_CALL_float(DOUBLE_CASE)
    103     TF_CALL_double(DOUBLE_CASE)
    104     TF_CALL_string(STRING_CASE)
    105     case DT_BOOL:
    106       tensor->scalar<bool>()() = stmt_.ColumnInt(column_index) != 0;
    107       break;
    108     // Error preemptively thrown by SqlDatasetOp::MakeDataset in this case.
    109     default:
    110       LOG(FATAL)
    111           << "Use of unsupported TensorFlow data type by 'SqlQueryConnection': "
    112           << DataTypeString(data_type) << ".";
    113   }
    114   // clang-format on
    115 }
    116 
    117 }  // namespace sql
    118 
    119 }  // namespace tensorflow
    120