Skip to content

Commit 3d4357c

Browse files
authored
Include schema in filter for indexes (#17480)
1 parent 4d2be99 commit 3d4357c

File tree

4 files changed

+12
-8
lines changed

4 files changed

+12
-8
lines changed

postgres/changelog.d/17480.fixed

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Fixed a bug where schemas with tables of the same name were incorrectly reporting indexes of those tables multiple times

postgres/datadog_checks/postgres/metadata.py

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -104,9 +104,10 @@
104104
PG_INDEXES_QUERY = """
105105
SELECT indexname AS NAME,
106106
indexdef AS definition,
107+
schemaname,
107108
tablename
108109
FROM pg_indexes
109-
WHERE {table_names_like};
110+
WHERE schemaname='{schema_name}' AND ({table_names_like});
110111
"""
111112

112113
PG_CHECK_FOR_FOREIGN_KEY = """
@@ -144,7 +145,7 @@
144145
SELECT relname,
145146
pg_get_partkeydef(oid) AS partition_key
146147
FROM pg_class
147-
WHERE relname in ({table_names});
148+
WHERE oid in ({table_ids});
148149
"""
149150

150151
NUM_PARTITIONS_QUERY = """
@@ -295,7 +296,7 @@ def report_postgres_metadata(self):
295296
tables_buffer = []
296297

297298
for tables in table_chunks:
298-
table_info = self._query_table_information(cursor, tables)
299+
table_info = self._query_table_information(cursor, schema['name'], tables)
299300

300301
tables_buffer = [*tables_buffer, *table_info]
301302
for t in table_info:
@@ -455,7 +456,7 @@ def _query_tables_for_schema(
455456
return table_payloads
456457

457458
def _query_table_information(
458-
self, cursor: psycopg2.extensions.cursor, table_info: List[Dict[str, Union[str, bool]]]
459+
self, cursor: psycopg2.extensions.cursor, schema_name: str, table_info: List[Dict[str, Union[str, bool]]]
459460
) -> List[Dict[str, Union[str, Dict]]]:
460461
"""
461462
Collect table information . Returns a dictionary
@@ -481,11 +482,10 @@ def _query_table_information(
481482
tables = {t.get("name"): {**t, "num_partitions": 0} for t in table_info}
482483
table_name_lookup = {t.get("id"): t.get("name") for t in table_info}
483484
table_ids = ",".join(["'{}'".format(t.get("id")) for t in table_info])
484-
table_names = ",".join(["'{}'".format(t.get("name")) for t in table_info])
485485
table_names_like = " OR ".join(["tablename LIKE '{}%'".format(t.get("name")) for t in table_info])
486486

487487
# Get indexes
488-
cursor.execute(PG_INDEXES_QUERY.format(table_names_like=table_names_like))
488+
cursor.execute(PG_INDEXES_QUERY.format(schema_name=schema_name, table_names_like=table_names_like))
489489
rows = cursor.fetchall()
490490
for row in rows:
491491
# Partition indexes in some versions of Postgres have appended digits for each partition
@@ -497,7 +497,7 @@ def _query_table_information(
497497

498498
# Get partitions
499499
if VersionUtils.transform_version(str(self._check.version))["version.major"] != "9":
500-
cursor.execute(PARTITION_KEY_QUERY.format(table_names=table_names))
500+
cursor.execute(PARTITION_KEY_QUERY.format(table_ids=table_ids))
501501
rows = cursor.fetchall()
502502
for row in rows:
503503
tables.get(row.get("relname"))["partition_key"] = row.get("partition_key")

postgres/tests/compose/resources/03_load_data.sh

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,8 @@ psql -v ON_ERROR_STOP=1 --username "$POSTGRES_USER" datadog_test <<-EOSQL
2828
SELECT * FROM persons;
2929
SELECT * FROM persons;
3030
SELECT * FROM persons;
31+
CREATE SCHEMA public2;
32+
CREATE TABLE public2.cities (city VARCHAR(255), country VARCHAR(255), PRIMARY KEY(city));
3133
GRANT ALL PRIVILEGES ON ALL TABLES IN SCHEMA public TO bob;
3234
GRANT ALL PRIVILEGES ON ALL TABLES IN SCHEMA public TO blocking_bob;
3335
EOSQL

postgres/tests/test_metadata.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -97,7 +97,7 @@ def test_collect_schemas(integration_check, dbm_instance, aggregator):
9797
# there should only two schemas, 'public' and 'datadog'. datadog is empty
9898
schema = database_metadata[0]['schemas'][0]
9999
schema_name = schema['name']
100-
assert schema_name in ['public', 'datadog']
100+
assert schema_name in ['public', 'public2', 'datadog']
101101
if schema_name == 'public':
102102
for table in schema['tables']:
103103
tables_got.append(table['name'])
@@ -120,6 +120,7 @@ def test_collect_schemas(integration_check, dbm_instance, aggregator):
120120
if table['name'] == "cities":
121121
keys = list(table.keys())
122122
assert_fields(keys, ["indexes", "columns", "toast_table", "id", "name", "owner"])
123+
assert len(table['indexes']) == 1
123124
assert_fields(list(table['indexes'][0].keys()), ['name', 'definition'])
124125
if float(POSTGRES_VERSION) >= 11:
125126
if table['name'] in ('test_part', 'test_part_no_activity'):

0 commit comments

Comments
 (0)