xref: /aosp_15_r20/external/tensorflow/tensorflow/core/kernels/data/experimental/sql/sqlite_query_connection.cc (revision b6fb3261f9314811a0f4371741dbb8839866f948)
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/experimental/sql/sqlite_query_connection.h"
16 
17 #include "tensorflow/core/framework/dataset.h"
18 #include "tensorflow/core/framework/register_types.h"
19 #include "tensorflow/core/lib/strings/stringprintf.h"
20 
21 namespace tensorflow {
22 namespace data {
23 namespace experimental {
24 namespace sql {
25 
SqliteQueryConnection()26 SqliteQueryConnection::SqliteQueryConnection() {}
27 
~SqliteQueryConnection()28 SqliteQueryConnection::~SqliteQueryConnection() {
29   if (db_ != nullptr) db_->Unref();
30 }
31 
Open(const string & data_source_name,const string & query,const DataTypeVector & output_types)32 Status SqliteQueryConnection::Open(const string& data_source_name,
33                                    const string& query,
34                                    const DataTypeVector& output_types) {
35   if (db_ != nullptr) {
36     return errors::FailedPrecondition(
37         "Failed to open query connection: Connection already opened.");
38   }
39   TF_RETURN_IF_ERROR(Sqlite::Open(
40       data_source_name, SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, &db_));
41   query_ = query;
42   output_types_ = output_types;
43   return OkStatus();
44 }
45 
Close()46 Status SqliteQueryConnection::Close() {
47   stmt_ = SqliteStatement();
48   db_->Unref();
49   db_ = nullptr;
50   return OkStatus();
51 }
52 
GetNext(IteratorContext * ctx,std::vector<Tensor> * out_tensors,bool * end_of_sequence)53 Status SqliteQueryConnection::GetNext(IteratorContext* ctx,
54                                       std::vector<Tensor>* out_tensors,
55                                       bool* end_of_sequence) {
56   if (!stmt_) TF_RETURN_IF_ERROR(PrepareQuery());
57   TF_RETURN_IF_ERROR(stmt_.Step(end_of_sequence));
58   if (!*end_of_sequence) {
59     for (int i = 0; i < column_count_; i++) {
60       DataType dt = output_types_[i];
61       // TODO(mrry): Pass in the `IteratorContext::allocator()`.
62       out_tensors->emplace_back(ctx->allocator({}), dt, TensorShape({}));
63       FillTensorWithResultSetEntry(dt, i, &out_tensors->back());
64     }
65   }
66   return OkStatus();
67 }
68 
PrepareQuery()69 Status SqliteQueryConnection::PrepareQuery() {
70   TF_RETURN_IF_ERROR(db_->Prepare(query_, &stmt_));
71   int column_count = stmt_.ColumnCount();
72   if (column_count != static_cast<int>(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 OkStatus();
81 }
82 
FillTensorWithResultSetEntry(const DataType & data_type,int column_index,Tensor * tensor)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_tstring(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(ERROR)
111           << "Use of unsupported TensorFlow data type by 'SqlQueryConnection': "
112           << DataTypeString(data_type) << ".";
113   }
114   // clang-format on
115 }
116 
117 }  // namespace sql
118 }  // namespace experimental
119 }  // namespace data
120 }  // namespace tensorflow
121