Skip to content

Commit 1ab239b

Browse files
authored
Merge branch 'main' into fix/service-password-literals-1512
2 parents 7726fce + 8b3b281 commit 1ab239b

18 files changed

Lines changed: 378 additions & 25 deletions

‎.github/PULL_REQUEST_TEMPLATE.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33

44
## Checklist
55
<!--- We appreciate your help and want to give you credit. Please take a moment to put an `x` in the boxes below as you complete them. -->
6+
- [ ] I searched the existing issues and pull requests on this topic and linked them above (see "Before Opening a Pull Request" in `CONTRIBUTING.rst`).
67
- [ ] I've added this contribution to the `changelog.rst`.
78
- [ ] I've added my name to the `AUTHORS` file (or it's already there).
89
<!-- We would appreciate if you comply with our code style guidelines. -->

‎.github/workflows/publish.yml‎

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -65,7 +65,7 @@ jobs:
6565
- name: Set up Python
6666
uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5.6.0
6767
with:
68-
python-version: '3.13'
68+
python-version: '3.14'
6969

7070
- name: Install dependencies
7171
run: uv sync --all-extras -p 3.14
@@ -84,7 +84,9 @@ jobs:
8484
runs-on: ubuntu-latest
8585
if: startsWith(github.ref, 'refs/tags/')
8686
needs: [build]
87-
environment: release
87+
environment:
88+
name: release
89+
url: https://pypi.org/p/pgcli
8890
permissions:
8991
id-token: write
9092
steps:

‎AUTHORS‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,8 @@ Core Devs:
1616

1717
Contributors:
1818
-------------
19+
* AC (ac1982)
20+
* Wu Shuwen (dajiaohuang)
1921
* Brett
2022
* Étienne BERSAC (bersace)
2123
* Daniel Schwarz
@@ -156,6 +158,10 @@ Contributors:
156158
* Chris (ChrisJr404)
157159
* Pieter Ouwerkerk (pouwerkerk)
158160
* jackwalkerlabs
161+
* VXNCXNX
162+
* Wei-Lun Li (b84330808)
163+
164+
* jackwalkerlabs (Codex-assisted)
159165

160166
Creator:
161167
--------

‎CONTRIBUTING.rst‎

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,19 @@ Development Guide
22
-----------------
33
This is a guide for developers who would like to contribute to this project.
44

5+
Before Opening a Pull Request
6+
-----------------------------
7+
8+
Reviews are done by volunteers in their spare time. Please check first:
9+
10+
* Search the open and closed issues and pull requests for the same topic.
11+
* If there is none, open an issue.
12+
* If there is an issue but no pull request, say on the issue that you are
13+
working on a fix, and link your pull request there when you open it.
14+
* If there is a pull request already, comment on it instead of opening a new
15+
one. If you still think a separate one is better, open it and link the
16+
existing one, saying how they differ.
17+
518
GitHub Workflow
619
---------------
720

@@ -44,7 +57,7 @@ Set up [uv](https://docs.astral.sh/uv/getting-started/installation/) for develop
4457

4558
cd pgcli
4659
uv venv
47-
source ./pgcli-dev/bin/activate
60+
source .venv/bin/activate
4861

4962
Once the virtualenv is activated, install pgcli using pip as follows:
5063

‎RELEASES.md‎

Lines changed: 32 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,4 +3,35 @@ Releasing pgcli
33

44
You have been made the maintainer of `pgcli`? Congratulations!
55

6-
To release a new version of the package, [create a new release](https://github.com/dbcli/pgcli/releases) in Github. This will trigger a Github action which will run all the tests, build the wheel and upload it to PyPI.
6+
To release a new version of the package:
7+
8+
1. Set the version number (that should follow SemVer) in
9+
`changelog.rst` by turning the "Upcoming" section title into
10+
something like "4.7.0 (2026-09-19)" (i.e. the version number
11+
followed by the date of the release, most probably today); and add
12+
a new empty "Upcoming" section.
13+
14+
2. Set the same version number in `__init__.py`.
15+
16+
3. [Create a new GitHub release](https://github.com/dbcli/pgcli/releases/new):
17+
18+
1. Click on "Select tag", input the new tag name (it should start
19+
with "v", for example "v4.7.0") and click "Create new tag".
20+
21+
2. Select target branch: `main`.
22+
23+
3. Input release title: the version number (without "v"), for example
24+
"4.7.0".
25+
26+
4. In the release notes, copy the corresponding section from
27+
`changelog.rst`. Double-check the rendered text. Warning:
28+
changelog is in reSTructuredText, release notes are in Markdown,
29+
syntax is similar but not exactly compatible.
30+
31+
5. No binary file to upload, default release label ("Latest"), no
32+
"discussion for this release".
33+
34+
6. Click on "Publish release".
35+
36+
This will trigger a GitHub action that runs all the tests, builds
37+
the package and uploads it to PyPI.

‎changelog.rst‎

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,46 @@
11
Upcoming
22
========
33

4+
Features:
5+
---------
6+
* Add ``\\cd`` and ``\\ls`` filesystem commands, with path completion for
7+
filesystem-aware commands including ``\\e``, ``\\i``, ``\\log-file``, and ``\\o``.
8+
* Add a ``\service`` prompt token for connections made using ``service=...``
9+
or ``PGSERVICE``. For example, set ``prompt = '\service> '``.
10+
11+
Bug fixes:
12+
----------
13+
* Display database errors from ``\ef`` and ``\ev`` without exiting the
14+
interactive session, allowing recovery from an aborted transaction.
15+
* Fix the development setup instructions to activate the ``.venv`` directory
16+
created by ``uv venv``.
17+
* Read ``alias_map_file`` as UTF-8 (with or without a BOM) instead of the
18+
locale encoding, which made non-ASCII aliases fail on Windows.
19+
20+
Internal:
21+
---------
22+
* Add a "Before Opening a Pull Request" section to the development guide,
23+
and a matching item to the pull request checklist.
24+
* Require ``cli_helpers >= 2.15.2``. That release aligns vertical (expanded)
25+
output by display width, so a header of wide characters like ``配列`` lines
26+
up; ``test_format_array_output_expanded`` had the old misalignment written
27+
down and fails with it.
28+
29+
4.7.1 (2026-09-20)
30+
==================
31+
32+
Bug fixes:
33+
----------
34+
* Fix wrong version number that was shown in `pgcli --version` for
35+
version 4.7.0.
36+
37+
38+
4.7.0 (2026-09-19)
39+
==================
40+
41+
**Brown bag release:** this version shows (in `pgcli --version`) as
42+
"4.6.0" instead of "4.7.0".
43+
444
Features:
545
---------
646
* Add support for `single-command` to run a SQL command and exit.
@@ -72,6 +112,8 @@ Bug fixes:
72112
issues (CVE-2026-59893, CVE-2026-54284, CVE-2026-71491) and a string-escaping
73113
bug (CVE-2026-59894); the previous ``<0.6`` cap prevented users from
74114
installing the fixed release.
115+
* Detect an unconditional ``UPDATE`` with ``sqlparse`` rather than splitting on whitespace, so a
116+
``WHERE`` appearing inside a string literal no longer suppresses the destructive-statement warning.
75117

76118
Features:
77119
---------

‎pgcli/__init__.py‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1 +1 @@
1-
__version__ = "4.6.0"
1+
__version__ = "4.7.1"

‎pgcli/main.py‎

Lines changed: 40 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -82,7 +82,7 @@
8282

8383
from getpass import getuser
8484

85-
from psycopg import OperationalError, InterfaceError, Notify
85+
from psycopg import DatabaseError, OperationalError, InterfaceError, Notify
8686
from psycopg.conninfo import make_conninfo, conninfo_to_dict
8787
from psycopg.errors import Diagnostic
8888

@@ -237,6 +237,7 @@ def __init__(
237237
self.never_passwd_prompt = never_passwd_prompt
238238
self.pgexecute = pgexecute
239239
self.dsn_alias = None
240+
self.service_name = None
240241
self.watch_command = None
241242
self.force_destructive = force_destructive
242243

@@ -466,6 +467,18 @@ def refresh_callback():
466467
arg_type=NO_QUERY,
467468
)
468469
self.pgspecial.register(self.execute_from_file, "\\i", "\\i filename", "Execute commands from file.")
470+
self.pgspecial.register(
471+
self.change_directory,
472+
"\\cd",
473+
"\\cd [directory]",
474+
"Change the current working directory.",
475+
)
476+
self.pgspecial.register(
477+
self.list_directory,
478+
"\\ls",
479+
"\\ls [path]",
480+
"List files in a directory.",
481+
)
469482
self.pgspecial.register(
470483
self.write_to_file,
471484
"\\o",
@@ -611,6 +624,28 @@ def execute_from_file(self, pattern, **_):
611624
explain_mode=self.explain_mode,
612625
)
613626

627+
def change_directory(self, pattern, **_):
628+
try:
629+
directory = pathlib.Path(pattern or "~").expanduser()
630+
os.chdir(directory)
631+
except (OSError, RuntimeError) as e:
632+
return [(None, None, None, str(e), "", False, True)]
633+
634+
return [(None, None, None, str(pathlib.Path.cwd()), "", True, True)]
635+
636+
def list_directory(self, pattern, **_):
637+
try:
638+
path = pathlib.Path(pattern or ".").expanduser()
639+
path.stat()
640+
entries = list(path.iterdir()) if path.is_dir() else [path]
641+
entries_with_types = [(entry, entry.is_dir()) for entry in entries]
642+
entries_with_types.sort(key=lambda item: (not item[1], item[0].name.casefold(), item[0].name))
643+
output = "\n".join(entry.name + (os.sep if is_directory else "") for entry, is_directory in entries_with_types)
644+
except (OSError, RuntimeError) as e:
645+
return [(None, None, None, str(e), "", False, True)]
646+
647+
return [(None, None, None, output, "", True, True)]
648+
614649
def write_to_logfile(self, pattern, **_):
615650
if not pattern:
616651
self.log_file = None
@@ -703,6 +738,7 @@ def connect_service(self, service, user):
703738
port=service_config.get("port"),
704739
passwd=service_config.get("password"),
705740
)
741+
self.service_name = service or os.getenv("PGSERVICE")
706742

707743
def connect_uri(self, uri):
708744
kwargs = conninfo_to_dict(uri)
@@ -869,6 +905,7 @@ def should_ask_for_password(exc):
869905
sys.exit(1)
870906

871907
self.pgexecute = pgexecute
908+
self.service_name = None
872909

873910
def handle_editor_command(self, text):
874911
r"""
@@ -1133,7 +1170,7 @@ def run_cli(self):
11331170

11341171
try:
11351172
text = self.handle_editor_command(text)
1136-
except RuntimeError as e:
1173+
except (RuntimeError, DatabaseError) as e:
11371174
logger.error("sql: %r, error: %r", text, e)
11381175
logger.error("traceback: %r", traceback.format_exc())
11391176
click.secho(str(e), err=True, fg="red")
@@ -1494,6 +1531,7 @@ def get_completions(self, text, cursor_positition):
14941531
def get_prompt(self, string):
14951532
# should be before replacing \\d
14961533
string = string.replace("\\dsn_alias", self.dsn_alias or "")
1534+
string = string.replace("\\service", self.service_name or "")
14971535
string = string.replace("\\t", self.now.strftime("%x %X"))
14981536
string = string.replace("\\u", self.pgexecute.user or "(none)")
14991537
string = string.replace("\\H", self.pgexecute.host or "(none)")

‎pgcli/packages/parseutils/__init__.py‎

Lines changed: 20 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -20,18 +20,33 @@ def query_starts_with(formatted_sql, prefixes):
2020
return bool(formatted_sql) and formatted_sql.split()[0] in prefixes
2121

2222

23-
def query_is_unconditional_update(formatted_sql):
24-
"""Check if the query starts with UPDATE and contains no WHERE."""
25-
tokens = formatted_sql.split()
26-
return bool(tokens) and tokens[0] == "update" and "where" not in tokens
23+
def query_is_unconditional_update(query):
24+
"""Check if the query starts with UPDATE and contains no top-level WHERE clause.
25+
26+
Uses sqlparse's parse tree (rather than naive whitespace splitting) so that
27+
the word "where" appearing inside a string literal, comment, or a nested
28+
subquery doesn't get mistaken for an actual WHERE clause.
29+
"""
30+
statements = sqlparse.parse(query)
31+
if not statements:
32+
return False
33+
statement = statements[0]
34+
35+
first_token = statement.token_first(skip_cm=True)
36+
if first_token is None or first_token.ttype is not sqlparse.tokens.DML:
37+
return False
38+
if first_token.value.upper() != "UPDATE":
39+
return False
40+
41+
return not any(isinstance(token, sqlparse.sql.Where) for token in statement.tokens)
2742

2843

2944
def is_destructive(queries, keywords):
3045
"""Returns if any of the queries in *queries* is destructive."""
3146
for query in sqlparse.split(queries):
3247
if query:
3348
formatted_sql = sqlparse.format(query.lower(), strip_comments=True).strip()
34-
if "unconditional_update" in keywords and query_is_unconditional_update(formatted_sql):
49+
if "unconditional_update" in keywords and query_is_unconditional_update(query):
3550
return True
3651
if query_starts_with(formatted_sql, keywords):
3752
return True

‎pgcli/packages/sqlcompletion.py‎

Lines changed: 12 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -45,7 +45,11 @@
4545
Datatype = namedtuple("Datatype", ["schema"])
4646
Alias = namedtuple("Alias", ["aliases"])
4747

48-
Path = namedtuple("Path", [])
48+
Path = namedtuple("Path", ["only_directories"])
49+
Path.__new__.__defaults__ = (False,)
50+
51+
PATH_COMMANDS = frozenset(("\\e", "\\i", "\\log-file", "\\ls", "\\o"))
52+
DIRECTORY_COMMANDS = frozenset(("\\cd",))
4953

5054

5155
class SqlStatement:
@@ -124,8 +128,13 @@ def suggest_type(full_text, text_before_cursor):
124128
A scope for a column category will be a list of tables.
125129
"""
126130

127-
if full_text.startswith("\\i "):
128-
return (Path(),)
131+
command_text = text_before_cursor.lstrip()
132+
command, _, _ = parse_special_command(command_text)
133+
if command != command_text:
134+
if command in PATH_COMMANDS:
135+
return (Path(),)
136+
if command in DIRECTORY_COMMANDS:
137+
return (Path(only_directories=True),)
129138

130139
# This is a temporary hack; the exception handling
131140
# here should be removed once sqlparse has been fixed

0 commit comments

Comments
 (0)