Skip to content

Commit 16cc5db

Browse files
authored
feat: debugging printer with variable substitution (#17333)
1 parent 9270188 commit 16cc5db

File tree

2 files changed

+63
-0
lines changed

2 files changed

+63
-0
lines changed
+30
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
# Licensed under the Apache License, Version 2.0 (the "License");
2+
# you may not use this file except in compliance with the License.
3+
# You may obtain a copy of the License at
4+
#
5+
# http://www.apache.org/licenses/LICENSE-2.0
6+
#
7+
# Unless required by applicable law or agreed to in writing, software
8+
# distributed under the License is distributed on an "AS IS" BASIS,
9+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
10+
# See the License for the specific language governing permissions and
11+
# limitations under the License.
12+
13+
import logging
14+
15+
from sqlalchemy import select
16+
17+
from warehouse.packaging.models import Project
18+
from warehouse.utils.db import query_printer
19+
20+
21+
def test_print_query_renders_params(caplog):
22+
caplog.set_level(logging.DEBUG)
23+
24+
query = select(Project.id, Project.name).where(Project.name == "value")
25+
assert "WHERE projects.name = :name_1" in str(query)
26+
27+
query_printer.print_query(query)
28+
29+
assert ":name_1" not in caplog.text
30+
assert "WHERE projects.name = 'value'" in caplog.text

warehouse/utils/db/query_printer.py

+33
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
# Licensed under the Apache License, Version 2.0 (the "License");
2+
# you may not use this file except in compliance with the License.
3+
# You may obtain a copy of the License at
4+
#
5+
# http://www.apache.org/licenses/LICENSE-2.0
6+
#
7+
# Unless required by applicable law or agreed to in writing, software
8+
# distributed under the License is distributed on an "AS IS" BASIS,
9+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
10+
# See the License for the specific language governing permissions and
11+
# limitations under the License.
12+
13+
""" Logs the query with the parameters embedded into the query."""
14+
15+
import logging
16+
17+
from sqlalchemy.dialects import postgresql
18+
19+
20+
def print_query(query) -> None:
21+
"""
22+
Prints the query with the parameters embedded into the query.
23+
24+
Useful for development/debugging purposes.
25+
"""
26+
logging.debug(
27+
str(
28+
query.compile(
29+
dialect=postgresql.dialect(),
30+
compile_kwargs={"literal_binds": True},
31+
)
32+
)
33+
)

0 commit comments

Comments
 (0)