Skip to content

Commit

Permalink
Merge pull request ClickHouse#73354 from ClickHouse/backport/24.3/71396
Browse files Browse the repository at this point in the history
Backport ClickHouse#71396 to 24.3: Fix: ERROR: column "attgenerated" does not exist for old PostgreSQL
  • Loading branch information
kssenii authored Dec 16, 2024
2 parents ba17c2b + 1945d75 commit 8b4dbc2
Showing 1 changed file with 10 additions and 2 deletions.
12 changes: 10 additions & 2 deletions src/Databases/PostgreSQL/fetchPostgreSQLTableStructure.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -301,18 +301,26 @@ PostgreSQLTableStructure fetchPostgreSQLTableStructure(
? " AND relnamespace = (SELECT oid FROM pg_namespace WHERE nspname = 'public')"
: fmt::format(" AND relnamespace = (SELECT oid FROM pg_namespace WHERE nspname = {})", quoteString(postgres_schema));


/// Bypassing the error of the missing column `attgenerated` in the system table `pg_attribute` for PostgreSQL versions below 12.
/// This trick involves executing a special query to the DBMS in advance to obtain the correct line with comment /// if column has GENERATED.
/// The result of the query will be the name of the column `attgenerated` or an empty string declaration for PostgreSQL version 11 and below.
/// This change does not degrade the function's performance but restores support for older versions and fix ERROR: column "attgenerated" does not exist.
pqxx::result gen_result{tx.exec("select case when current_setting('server_version_num')::int < 120000 then '''''' else 'attgenerated' end as generated")};
std::string generated = gen_result[0][0].as<std::string>();

std::string query = fmt::format(
"SELECT attname AS name, " /// column name
"format_type(atttypid, atttypmod) AS type, " /// data type
"attnotnull AS not_null, " /// is nullable
"attndims AS dims, " /// array dimensions
"atttypid as type_id, "
"atttypmod as type_modifier, "
"attgenerated as generated " /// if column has GENERATED
"{} as generated " /// if column has GENERATED
"FROM pg_attribute "
"WHERE attrelid = (SELECT oid FROM pg_class WHERE {}) "
"AND NOT attisdropped AND attnum > 0 "
"ORDER BY attnum ASC", where);
"ORDER BY attnum ASC", generated, where);

auto postgres_table_with_schema = postgres_schema.empty() ? postgres_table : doubleQuoteString(postgres_schema) + '.' + doubleQuoteString(postgres_table);
table.physical_columns = readNamesAndTypesList(tx, postgres_table_with_schema, query, use_nulls, false);
Expand Down

0 comments on commit 8b4dbc2

Please sign in to comment.