Skip to content

Add support for text protocol #326

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
107 changes: 107 additions & 0 deletions src/include/postgres_text_reader.hpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,107 @@
//===----------------------------------------------------------------------===//
// DuckDB
//
// postgres_text_reader.hpp
//
//
//===----------------------------------------------------------------------===//

#pragma once

#include "duckdb.hpp"
#include "duckdb/common/exception.hpp"
#include "duckdb/common/types.hpp"
#include "duckdb/common/types/vector.hpp"
#include "libpq-fe.h"
#include "postgres_conversion.hpp"
#include "postgres_connection.hpp"
#include "postgres_utils.hpp"
#include <cstring>

namespace duckdb {

struct PostgresTextReader {
explicit PostgresTextReader(PostgresConnection &con_p) : con(con_p), result(nullptr), col_vec(LogicalType::VARCHAR) {
}

~PostgresTextReader() {
Reset();
}

PostgresConnection &GetConn() {
return con;
}

void ReadTextFrom(const string &query) {
Reset();
result = PQexec(con.GetConn(), query.c_str());
if (!result || PQresultStatus(result) != PGRES_TUPLES_OK ) {
throw IOException("Failed to execute query: %s", string(PQerrorMessage(con.GetConn())));
}
}

void Reset() {
if (result) {
PQclear(result);
result = nullptr;
}
}

void ReadColumn(const PostgresType &pg_type, idx_t col_idx) {
col_vec.Resize(0, RowCount());
col_vec.Initialize(true);
for (idx_t row_idx = 0; row_idx < RowCount(); row_idx++) {
if (PQgetisnull(result, row_idx, col_idx)) {
FlatVector::SetNull(col_vec, row_idx, true);
continue;
}
char *value = PQgetvalue(result, row_idx, col_idx);
int value_len = PQgetlength(result, row_idx, col_idx);
FlatVector::SetNull(col_vec, row_idx, false);
switch (pg_type.info) {
case PostgresTypeAnnotation::FIXED_LENGTH_CHAR: {
// CHAR column - remove trailing spaces
while (value_len > 0 && value[value_len - 1] == ' ') {
value_len--;
}
FlatVector::GetData<string_t>(col_vec)[row_idx] = StringVector::AddStringOrBlob(col_vec, value, value_len);
break;
}

default:
FlatVector::GetData<string_t>(col_vec)[row_idx] = StringVector::AddStringOrBlob(col_vec, value, value_len);
break;
}

}
}

void LoadResultTo (const LogicalType &type, const PostgresType &pg_type, Vector &out_vec, idx_t &col_idx) {
switch (type.id()) {
case LogicalTypeId::LIST:
case LogicalTypeId::ENUM:
throw NotImplementedException("Type %s doesn't support straight casting from string", type.ToString());

default:
break;
}
ReadColumn(pg_type, col_idx);
VectorOperations::DefaultCast(col_vec, out_vec, RowCount());
}

// Get result metadata
idx_t ColumnCount() {
return PQnfields(result);
}

idx_t RowCount() {
return PQntuples(result);
}

private:
PostgresConnection &con;
PGresult *result;
Vector col_vec;
};

} // namespace duckdb
2 changes: 2 additions & 0 deletions src/postgres_extension.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -181,6 +181,8 @@ static void LoadInternal(DatabaseInstance &db) {
LogicalType::VARCHAR, Value(), SetPostgresNullByteReplacement);
config.AddExtensionOption("pg_debug_show_queries", "DEBUG SETTING: print all queries sent to Postgres to stdout",
LogicalType::BOOLEAN, Value::BOOLEAN(false), SetPostgresDebugQueryPrint);
config.AddExtensionOption("pg_use_legacy_text_protocol", "Whether or not to use legacy TEXT protocol to read data. Set this to yes will ignore pg_use_binary_copy",
LogicalType::BOOLEAN, Value::BOOLEAN(false));

OptimizerExtension postgres_optimizer;
postgres_optimizer.optimize_function = PostgresOptimizer::Optimize;
Expand Down
66 changes: 63 additions & 3 deletions src/postgres_scanner.cpp
Original file line number Diff line number Diff line change
@@ -1,7 +1,10 @@
#include "duckdb.hpp"

#include <csignal>
#include <libpq-fe.h>

#include "duckdb/common/exception.hpp"
#include "duckdb/common/unique_ptr.hpp"
#include "duckdb/main/extension_util.hpp"
#include "duckdb/common/shared_ptr.hpp"
#include "duckdb/common/helper.hpp"
Expand All @@ -10,6 +13,7 @@
#include "postgres_scanner.hpp"
#include "postgres_result.hpp"
#include "postgres_binary_reader.hpp"
#include "postgres_text_reader.hpp"
#include "storage/postgres_catalog.hpp"
#include "storage/postgres_transaction.hpp"
#include "storage/postgres_table_set.hpp"
Expand All @@ -34,6 +38,10 @@ struct PostgresLocalState : public LocalTableFunctionState {

void ScanChunk(ClientContext &context, const PostgresBindData &bind_data, PostgresGlobalState &gstate,
DataChunk &output);
void ScanChunkWithBinaryReader(ClientContext &context, const PostgresBindData &bind_data, PostgresGlobalState &gstate,
DataChunk &output);
void ScanChunkWithTextReader(ClientContext &context, const PostgresBindData &bind_data, PostgresGlobalState &gstate,
DataChunk &output);
};

struct PostgresGlobalState : public GlobalTableFunctionState {
Expand Down Expand Up @@ -248,6 +256,18 @@ static void PostgresInitInternal(ClientContext &context, const PostgresBindData
filter += " AND ";
}
filter += filter_string;
};
lstate.exec = false;
lstate.done = false;
Value use_legacy_text_protocol;
if (context.TryGetCurrentSetting("pg_use_legacy_text_protocol", use_legacy_text_protocol)) {
if (BooleanValue::Get(use_legacy_text_protocol)) {
lstate.sql = StringUtil::Format(
R"(SELECT %s FROM %s.%s %s%s;)",
col_names, KeywordHelper::WriteQuoted(bind_data->schema_name, '"'),
KeywordHelper::WriteQuoted(bind_data->table_name, '"'), filter, bind_data->limit);
return;
}
}
if (bind_data->table_name.empty()) {
D_ASSERT(!bind_data->sql.empty());
Expand All @@ -261,8 +281,7 @@ static void PostgresInitInternal(ClientContext &context, const PostgresBindData
col_names, KeywordHelper::WriteQuoted(bind_data->schema_name, '"'),
KeywordHelper::WriteQuoted(bind_data->table_name, '"'), filter, bind_data->limit);
}
lstate.exec = false;
lstate.done = false;

}

static idx_t PostgresMaxThreads(ClientContext &context, const FunctionData *bind_data_p) {
Expand Down Expand Up @@ -417,7 +436,7 @@ static unique_ptr<LocalTableFunctionState> PostgresInitLocalState(ExecutionConte
return GetLocalState(context.client, input, gstate);
}

void PostgresLocalState::ScanChunk(ClientContext &context, const PostgresBindData &bind_data,
void PostgresLocalState::ScanChunkWithBinaryReader(ClientContext &context, const PostgresBindData &bind_data,
PostgresGlobalState &gstate, DataChunk &output) {
idx_t output_offset = 0;
PostgresBinaryReader reader(connection);
Expand Down Expand Up @@ -472,6 +491,47 @@ void PostgresLocalState::ScanChunk(ClientContext &context, const PostgresBindDat
}
}

void PostgresLocalState::ScanChunkWithTextReader(ClientContext &context, const PostgresBindData &bind_data,
PostgresGlobalState &gstate, DataChunk &output) {
PostgresTextReader reader(connection);
if (done && !PostgresParallelStateNext(context, &bind_data, *this, gstate)) {
return;
}

if (!exec) {
reader.ReadTextFrom(sql);
exec = true;
}

output.SetCardinality(reader.RowCount());
for (idx_t output_idx = 0; output_idx < output.ColumnCount(); output_idx++) {
auto col_idx = column_ids[output_idx];
auto &out_vec = output.data[output_idx];
if (col_idx == COLUMN_IDENTIFIER_ROW_ID) {
PostgresType ctid_type;
ctid_type.info = PostgresTypeAnnotation::CTID;
reader.LoadResultTo(LogicalType::BIGINT, ctid_type, out_vec, col_idx);
} else {
reader.LoadResultTo(bind_data.types[col_idx], bind_data.postgres_types[col_idx], out_vec, col_idx);
}
}
reader.Reset();
done = true;
return;
}

void PostgresLocalState::ScanChunk(ClientContext &context, const PostgresBindData &bind_data,
PostgresGlobalState &gstate, DataChunk &output) {
Value use_legacy_text_protocol;
if (context.TryGetCurrentSetting("pg_use_legacy_text_protocol", use_legacy_text_protocol)) {
if (BooleanValue::Get(use_legacy_text_protocol)) {
ScanChunkWithTextReader(context, bind_data, gstate, output);
return;
}
}
ScanChunkWithBinaryReader(context, bind_data, gstate, output);
}

static void PostgresScan(ClientContext &context, TableFunctionInput &data, DataChunk &output) {
auto &bind_data = data.bind_data->Cast<PostgresBindData>();
auto &gstate = data.global_state->Cast<PostgresGlobalState>();
Expand Down
Loading