Skip to content

Re-add {database} macro support in clickhouse-client prompt - #100607

Open
il9ue wants to merge 6 commits into
ClickHouse:masterfrom
il9ue:fix/49118-database-macro-in-prompt
Open

il9ue wants to merge 6 commits into
ClickHouse:masterfrom
il9ue:fix/49118-database-macro-in-prompt

Conversation

@il9ue

@il9ue il9ue commented Mar 24, 2026 •

Copy link
Copy Markdown
Contributor

Re-add {database} macro support in clickhouse-client prompt

Closes #49118

Changelog category (leave one):

  • Improvement

Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):

Documentation entry for user-facing changes

  • Documentation is written (mandatory for new features)

  • The {database} macro is now available again in the prompt_by_server_display_name client configuration setting, alongside {host}, {port}, {user}, and {display_name}. It displays the current database and updates dynamically when switching databases via USE.

Example configuration:

<prompt_by_server_display_name>
    <default>{database}@{host} :) </default>
</prompt_by_server_display_name>

Workflow [PR]
Sync PR [sync-upstream/pr/100607]

@ilejn

ilejn commented Mar 25, 2026 •

Copy link
Copy Markdown
Contributor

Generally LGTM.

ClientBase::default_database seems a valid source of information.
Using 'expect' is fine, probably there is no reasonable way to persuade clickhouse-client that an output is a terminal while it is a file.

Concerns/questions.

  1. clickhouse-local supports prompt customization as well. Does your change help here?
  2. ClickHouse has server side setting <default_database>my_database</default_database> . I am not sure, but it seems that if default_database is not specified at client, but is specified at server, prompt would be misleading.

If (2) is true, I suggest we should abandon the development.

@il9ue

il9ue commented Mar 25, 2026

Copy link
Copy Markdown
Contributor Author

Thanks for the review!

  1. Yes — getPrompt() and default_database are in ClientBase, so clickhouse-local benefits from this as well.
  2. Good catch. If the server has a non-default default_database and the client doesn't specify --database, the prompt would indeed be wrong. Before abandoning, I'd like to check whether we can sync the client's state by reading back currentDatabase() after connection. If that's feasible and not too invasive, it would fix the root issue. If it's too complex, I agree we should drop this.

@il9ue
il9ue force-pushed the fix/49118-database-macro-in-prompt branch from c6905ed to 7d9b6fb Compare March 30, 2026 13:12
@il9ue

il9ue commented Mar 30, 2026

Copy link
Copy Markdown
Contributor Author

I've implemented alternative one rather than abandoning the PR.

What changed:

Added ClientBase::syncDefaultDatabase() which fires a lightweight
SELECT currentDatabase() immediately after the connection handshake
and writes the result back into default_database. This means the
prompt correctly reflects the server's actual current database even
when --database is not passed on the CLI.

Key design decisions:

  • Called at end of connect(), after handshake, before first prompt render
  • Wrapped in try/catch — failure logs a WARNING and degrades gracefully,
    it will not break the connection
  • default_database is only updated if the returned value is non-empty
  • Since getPrompt() and default_database live in ClientBase,
    both clickhouse-client and clickhouse-local benefit automatically
  • Added a third expect test covering the server-side default_database scenario

Happy to adjust the hook point in the connect flow if you see a better
place for the call, or switch to reading from the native protocol handshake
to avoid the extra round-trip if that's preferred

@il9ue
il9ue force-pushed the fix/49118-database-macro-in-prompt branch from 7d9b6fb to 2fffb34 Compare March 30, 2026 13:16
@ilejn

ilejn commented Mar 30, 2026

Copy link
Copy Markdown
Contributor

That's really impressive.
The only thing that bothers me is how reload of server configuration affects already existing sessions, IOW if it is possible to change default database (server side) for a session that is already started.

@il9ue
il9ue force-pushed the fix/49118-database-macro-in-prompt branch from 2fffb34 to 7801dfc Compare April 2, 2026 13:46
@il9ue

il9ue commented Apr 2, 2026

Copy link
Copy Markdown
Contributor Author

Valid point — I investigated this. Looking at TCPHandler.cpp, default_database is only applied to the session context once during the connection handshake via setCurrentDatabase(). After that, the session's current database is owned entirely by the session context and only changes via USE statements.

SYSTEM RELOAD CONFIG in InterpreterSystemQuery.cpp has no code path that propagates default_database changes to existing sessions. So syncDefaultDatabase() at connect time is sufficient — an already running session cannot have its default database changed by a server config reload. I've added a code comment documenting this boundary for future readers/editors!

That's really impressive. The only thing that bothers me is how reload of server configuration affects already existing sessions, IOW if it is possible to change default database (server side) for a session that is already started.

@ilejn

ilejn commented Apr 6, 2026 •

Copy link
Copy Markdown
Contributor

Hello @il9ue ,
I've considered @SaltTan 's suggestion to unify this code with autocompletion (see Client/Suggest.h) at least in term of using disable_suggestion parameter.
Personally I think that current implementation is sufficient and it is not needed to add anything else, but this is up to you.

I suggest we should mention clickhouse-client and clickhouse-local in changelog explicitly .

@ilejn

ilejn commented Apr 14, 2026 •

Copy link
Copy Markdown
Contributor

I reviewed again and I have few concerns to share

  1. We are building prompt even though a session is non-interactive. In this case (especially if we have very short sessions) extra query can be noticeable. Although avoiding syncDefaultDatabase() for non-interactive sessions leads to inconsistency, doing so may be reasonable. Extra comments are needed in both cases (if we do sync for non-interactive session or do not do).
  2. Not sure about Test3. Is my understanding correct that this test is happy with any result? If yes, shouldn't it be less permissive?
  3. clickhouse-local is not covered by tests, doesn't seem great.

@ilejn

ilejn commented Apr 15, 2026

Copy link
Copy Markdown
Contributor

Our options for non-interactive sessions

  1. Perform database sync as it currently done in this PR
  2. Do not do sync
  3. 2 + put empty string or something like 'UNDETERMIND'

Further thoughts about ClientBase::syncDefaultDatabase .
It is cheap, although it is not free (as in beer).

  1. We do sync unconditionally, regardless whether database macro actually used or not. Why? [just a question; it is possible it is useful for completion]
  2. We do sync even if default database specified at client. Why?

@il9ue
il9ue force-pushed the fix/49118-database-macro-in-prompt branch from 805df09 to 45a94d8 Compare April 15, 2026 06:23
@il9ue

il9ue commented Apr 15, 2026

Copy link
Copy Markdown
Contributor Author

Thanks for all the detailed feedback — addressed everything in the latest push:

1. Non-interactive sessions / extra round-trip cost
Guarded syncDefaultDatabase() with three conditions so it only fires
when actually needed:

if (is_interactive && default_database.empty() && prompt.find("{database}") != String::npos)
syncDefaultDatabase();

  • is_interactive: skips the round-trip entirely in batch mode where
    the prompt is never displayed
  • default_database.empty(): if --database was passed, the value is
    already correct and must not be overridden by the server's value
  • prompt.find("{database}"): skips the query when the macro isn't
    in the prompt at all, making it a pure no-op in that case

2. Test 3 too permissive
Replaced the loose [a-z_]+ regex with the literal string default,
which is the concrete expected value when no --database flag is passed.

3. clickhouse-local not covered by tests
Added 04057_local_prompt_database.expect covering:

  • {database} shows default without --database flag — works via
    the default_database.empty() ? "default" : default_database fallback
    in getPrompt(), no server round-trip needed for local
  • {database} updates to system after USE system;

4. Changelog — explicitly mentioning both clickhouse-client and clickhouse-local
Re-add support for the {database} macro in prompt_by_server_display_name
for clickhouse-client and clickhouse-local. The database name updates
dynamically after USE statements and correctly reflects the --database
CLI flag and server-side default_database configuration.

Note on ClientBase.cpp / LocalServer.cpp
No changes were needed there. LocalServer::connect() never called
syncDefaultDatabase() to begin with, and the getPrompt() fallback
already handles the empty default_database case correctly for local.

@ilejn

ilejn commented Apr 15, 2026

Copy link
Copy Markdown
Contributor

LGTM

@il9ue

il9ue commented Apr 15, 2026

Copy link
Copy Markdown
Contributor Author

Hi @alexey-milovidov — hope you don't mind the ping.

I wanted to flag PR #100607 (re-adding {database} macro in clickhouse-client prompt) for your attention. The implementation has gone through several rounds of review and all raised concerns have been addressed, but the CI workflow won't run without a maintainer trigger.

Quick summary of what's in the PR:

  • {database} now substitutes dynamically from default_database, updating correctly after USE statements
  • syncDefaultDatabase() fires SELECT currentDatabase() after the handshake to handle server-side default_database config
  • Guarded with is_interactive, default_database.empty(), and prompt.find("{database}") to avoid unnecessary round-trips
  • Tests cover both clickhouse-client and clickhouse-local
  • Confirmed via TCPHandler.cpp that SYSTEM RELOAD CONFIG cannot affect already-established sessions

Would really appreciate it if you could trigger the workflow or leave any final feedback. Happy to address anything further.

il9ue pushed a commit to Altinity/ClickHouse that referenced this pull request May 26, 2026
Backport of ClickHouse#100607 to antalya-25.8.

- Dynamic {database} substitution in ClientBase::getPrompt() from
  default_database (updated by USE and --database).
- ClientBase::syncDefaultDatabase() runs SELECT currentDatabase()
  after the handshake so the prompt reflects server-side
  default_database when --database is not passed.
- Sync call in Client::connect() is guarded by is_interactive,
  default_database.empty(), and prompt contains {database}.
- Expect tests for both clickhouse-client and clickhouse-local.

Closes ClickHouse#49118
zvonand added a commit to Altinity/ClickHouse that referenced this pull request Jul 15, 2026
Backport ClickHouse#100607 to 25.8.16: Re-add {database} macro support in clickhouse-client prompt
zvonand added a commit to Altinity/ClickHouse that referenced this pull request Jul 16, 2026
…100607

Revert "Backport ClickHouse#100607 to 25.8.16: Re-add {database} macro support in clickhouse-client prompt"
il9ue added 4 commits July 17, 2026 14:41
The {database} macro was removed in PR ClickHouse#42508 because it read from
static config and did not update after USE statements. This re-adds
the macro by substituting it dynamically from the default_database
member variable, which is updated on USE and --database flag.

Closes ClickHouse#49118
…efault

Problem:
If the server has a non-default default_database configured server-side
and the client does not pass --database, the client's default_database
member was empty/wrong, causing {database} in the prompt to display an
incorrect value.

Solution:
Add ClientBase::syncDefaultDatabase() which fires a lightweight
SELECT currentDatabase() immediately after the connection handshake
completes and writes the result back into default_database. This ensures
the prompt always reflects the true current database regardless of
whether it was set via --database CLI flag or server-side configuration.

Details:
- Declared syncDefaultDatabase() in private section of ClientBase.h
- Implemented in ClientBase.cpp using the existing connection packet
  send/receive pattern
- Called at the end of connect(), after handshake, before first prompt render
- Wrapped in try/catch: failure logs a WARNING and degrades gracefully
  rather than breaking the connection
- default_database is only updated if the returned value is non-empty
- Added Test 3 to 04056_client_prompt_database.expect covering the
  server-side default_database scenario

Closes ClickHouse#49118
Documents why syncing once at connect is sufficient:
- TCPHandler.cpp only applies default_database to session context
  during the connection handshake
- SYSTEM RELOAD CONFIG has no code path that propagates default_database
  changes to already-established sessions
- Therefore, server config reloads cannot affect the current database
  of a running session
Changes:

programs/client/Client.cpp:
Guard syncDefaultDatabase() with three conditions:

  if (is_interactive && default_database.empty() && prompt.find("{database}") != String::npos)
      syncDefaultDatabase();

- is_interactive: prompt is never shown in batch mode; the extra
  SELECT currentDatabase() round-trip would only add latency
- default_database.empty(): if --database was passed, default_database
  is already correct; overriding it with the server value would be wrong
- prompt.find("{database}"): the query is meaningless if the macro
  is not in the prompt at all

tests/queries/0_stateless/04056_client_prompt_database.expect:
Test 3 now expects the literal string "default" instead of the loose
regex [a-z_]+, which was underspecified and would pass even if an
incorrect database name were shown.

tests/queries/0_stateless/04057_local_prompt_database.expect (new):
Added expect test for clickhouse-local:
- Test 1: verifies {database} shows "default" when no --database flag
  is passed, via the empty fallback in getPrompt()
- Test 2: verifies {database} updates to "system" after USE system;

src/Client/ClientBase.cpp / programs/local/LocalServer.cpp:
No changes needed. LocalServer::connect() never called
syncDefaultDatabase() to begin with, and the getPrompt() fallback
already handles the empty default_database case correctly for local.
@il9ue
il9ue force-pushed the fix/49118-database-macro-in-prompt branch from 5e7a557 to fefa71a Compare July 17, 2026 13:51
@ilejn

ilejn commented Jul 21, 2026

Copy link
Copy Markdown
Contributor

Hello @alexey-milovidov , could you have a look please.
Surprisingly some CH users really miss this feature.
It was removed by you in #42508

@abashkeev abashkeev added the comp-cli clickhouse-client (interactive CLI) and client library. label Sep 4, 2026
@maxknv maxknv added the external Author is not a member of the ClickHouse organization label Nov 2, 2026
@alexey-milovidov alexey-milovidov added the can be tested Allows running workflows for external contributors label Nov 14, 2026
@clickhouse-gh clickhouse-gh Bot closed this Nov 14, 2026
@clickhouse-gh clickhouse-gh Bot reopened this Nov 14, 2026
@clickhouse-gh

clickhouse-gh Bot commented Nov 15, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [da6c8d8]

Summary: ❌

job_name test_name status info comment
Fast test FAIL
04056_client_prompt_database FAIL cidb
04057_local_prompt_database FAIL cidb
Code Review DROPPED
Fast test (arm_darwin) DROPPED
Build (amd_debug) DROPPED
Build (amd_asan_ubsan) DROPPED
Build (amd_tsan) DROPPED
Build (amd_msan) DROPPED
Build (amd_binary) DROPPED
Build (arm_debug) DROPPED
Build (arm_asan_ubsan) DROPPED

@clickhouse-gh clickhouse-gh Bot added the pr-improvement Pull request with some product improvements label Nov 15, 2026
Move `syncDefaultDatabase` and `executeQueryForSingleString` out of the
`USE_CLIENT_AI` block, so that the client links in builds without AI support.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

can be tested Allows running workflows for external contributors comp-cli clickhouse-client (interactive CLI) and client library. external Author is not a member of the ClickHouse organization pr-improvement Pull request with some product improvements

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Support for database in prompt_by_server_display_name setting

5 participants