Skip to content

Commit

Permalink
feat: debugging printer with variable substitution (pypi#17333)
Browse files Browse the repository at this point in the history
  • Loading branch information
miketheman authored Jan 2, 2025
1 parent 9270188 commit 16cc5db
Show file tree
Hide file tree
Showing 2 changed files with 63 additions and 0 deletions.
30 changes: 30 additions & 0 deletions tests/unit/utils/db/test_query_printer.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import logging

from sqlalchemy import select

from warehouse.packaging.models import Project
from warehouse.utils.db import query_printer


def test_print_query_renders_params(caplog):
caplog.set_level(logging.DEBUG)

query = select(Project.id, Project.name).where(Project.name == "value")
assert "WHERE projects.name = :name_1" in str(query)

query_printer.print_query(query)

assert ":name_1" not in caplog.text
assert "WHERE projects.name = 'value'" in caplog.text
33 changes: 33 additions & 0 deletions warehouse/utils/db/query_printer.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

""" Logs the query with the parameters embedded into the query."""

import logging

from sqlalchemy.dialects import postgresql


def print_query(query) -> None:
"""
Prints the query with the parameters embedded into the query.
Useful for development/debugging purposes.
"""
logging.debug(
str(
query.compile(
dialect=postgresql.dialect(),
compile_kwargs={"literal_binds": True},
)
)
)

0 comments on commit 16cc5db

Please sign in to comment.