GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — Fix query tool auto execution after session restore by dev-hari-prasad · Pull Request #10055 · pgadmin-org/pgadmin4

Conversation

@dev-hari-prasad

@dev-hari-prasad dev-hari-prasad commented Jun 9, 2026 •
edited by coderabbitai Bot
Loading

Uh oh!

There was an error while loading. Please reload this page.

Copy link
Copy Markdown
Contributor

What this fixes

Fixes an issue where Query Tool tabs are restored from a previous session can/start automatically executing their queries when pgAdmin starts.

What was happening

While looking into this, I found that is_query_tool was only being checked against the string value 'true'`.

During the session restoration process the value can be restored as a boolean instead. When that happens, the tab gets treated as a view/edit data tab instead of a Query toool tab and can end up going through the auto execution logic during initialization. Which can lead to descurtive and unwanted queries to run against the database and this is not what a user would expect.

Fix

This change addresses the restore flow in a few places:

  • Handle both boolean and string values for is_query_tool
  • Prevent automatic execution while a Query Tool tab is being restored when the app starts
  • Make sure the Query Tool tabs persist the correct is_query_tool state in the saved metadata

Testing

  • Open Query Tool
  • Write a query and leave the tab open
  • Close pgAdmin
  • Start pgAdmin again
  • Verify the query text is restored
  • Verify the query is not executed automatically

PS: You will need to build the app with the changes made in this branch inorder to see this in effect otherwise the offical build will emit the same bevhiour as descirbied in the issue #10031.

Fixes #10031

Summary by CodeRabbit

  • Bug Fixes
    • Query Tool now correctly recognizes the enabled state when the parameter is true or the string "true".
    • Improved restoration behavior to prevent unintended SQL script restore and avoid local restore when appropriate.
    • Automatic execution is blocked during restore to prevent accidental runs.
    • Restoring the tool reliably re-enables the editor and clears the restore flag.
    • When activating the Query Tool, the URL parameter is updated to reflect the enabled state.

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

All reactions
@dev-hari-prasad
Fix query auto execution on session restore
0d9c38d
- Handle both boolean and string values for is_query_tool
- Fix Query Tool tabs being incorrectly detected during restore
- Prevent queries from running automatically when restoring a session

The issue was caused by is_query_tool only checking for the string
'true'. During session restore the value can come back as a boolean,
which caused Query Tool tabs to be treated as View/Edit Data tabs and
trigger the auto execution path.
@coderabbitai

coderabbitai Bot commented Jun 9, 2026 •
edited
Loading

Uh oh!

There was an error while loading. Please reload this page.

Copy link
Copy Markdown

Review Change Stack

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review

Walkthrough

QueryToolComponent normalizes is_query_tool (accepts boolean true or string 'true'), normalizes restore to boolean, prevents SQL auto-execution while restore is true, clears restore and re-enables the editor when restoring, patches panel toolUrl to include is_query_tool=true when toggling, and adds restore to propTypes.

Changes

Query Tool Restore and Auto-Execution Prevention

Layer / File(s) Summary
Parameter type flexibility for is_query_tool
web/pgadmin/tools/sqleditor/static/js/components/QueryToolComponent.jsx
Initial qtState.params.is_query_tool and connection_list title/label construction now treat both boolean true and string 'true' as enabled.
Restore state management and execution prevention
web/pgadmin/tools/sqleditor/static/js/components/QueryToolComponent.jsx
getSQLScript becomes async with conditional restore paths; restoreToolContent sets editor_disabled=false and clears params.restore to boolean false via functional setQtStatePartial; initializeQueryTool requires qtState.params.restore !== true before firing execution.
Toggle query tool URL patching
web/pgadmin/tools/sqleditor/static/js/components/QueryToolComponent.jsx
toggleQueryTool tries (guarded by existence checks and try/catch) to update the current panel's metaData.toolUrl search param is_query_tool to 'true' before setting params.is_query_tool = true in state.
PropTypes: add restore field
web/pgadmin/tools/sqleditor/static/js/components/QueryToolComponent.jsx
QueryToolComponent.propTypes.params now includes restore: PropTypes.oneOfType([PropTypes.bool, PropTypes.string]).

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related PRs

  • pgadmin-org/pgadmin4#9470: Modifies restoreToolContent logic in QueryToolComponent.jsx to adjust query tool state during restoration, overlapping with this PR's restore lifecycle updates.
🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title 'Fix query tool auto execution after session restore' directly and clearly describes the main objective of the PR, which is to prevent Query Tool tabs from automatically executing when restored during application startup.
Linked Issues check ✅ Passed All code changes align with the linked issue objectives: handling both boolean and string is_query_tool values [#10031], preventing auto-execution during session restore [#10031], and properly persisting the is_query_tool state [#10031].
Out of Scope Changes check ✅ Passed All changes are directly related to fixing query tool auto-execution during session restore; no extraneous modifications to unrelated functionality were introduced.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
  • X
  • Mastodon
  • Reddit
  • LinkedIn

Comment @coderabbitai help to get the list of available commands.

All reactions

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

coderabbitai[bot]
coderabbitai Bot reviewed Jun 9, 2026
View reviewed changes

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

There was a problem hiding this comment.

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick comments (3)
web/pgadmin/tools/sqleditor/static/js/components/QueryToolComponent.jsx (3)

345-352: ⚡ Quick win

Consider normalizing the restore parameter lifecycle.

The restore flag has an inconsistent type lifecycle:

  • Starts as boolean true in saved metaData (context snippet 2: restore: true)
  • Submitted as string 'true' via form textarea (context snippet 1)
  • Set to string 'false' here after restoration completes
  • Checked with loose inequality != 'true' on line 390

While the loose inequality != on line 390 handles both boolean true and string 'true' correctly, explicitly setting it to string 'false' rather than boolean false adds cognitive overhead. Consider either:

  1. Normalizing to boolean throughout (set to false here, check with !== true on line 390), or
  2. Documenting why string 'false' is required for persistence/serialization.

The functional update pattern prev => ({...prev, ...}) is correct for React 19.

💡 Suggested normalization (if no serialization constraint)
     setQtStatePartial(prev => ({
       ...prev,
       editor_disabled: false,
       params: {
         ...prev.params,
-        restore: 'false'
+        restore: false
       }
     }));

And on line 390:

-        if((!qtState.params.is_query_tool || reexecute) && qtState.params.restore != 'true') {
+        if((!qtState.params.is_query_tool || reexecute) && qtState.params.restore !== true) {
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@web/pgadmin/tools/sqleditor/static/js/components/QueryToolComponent.jsx`
around lines 345 - 352, The restore flag in setQtStatePartial is being set to
the string 'false' which mismatches its boolean usage elsewhere (saved metaData
uses true and it's checked later with a loose comparison); change the code in
the state updater (setQtStatePartial) to set params.restore to the boolean false
instead of the string 'false', and update the check that reads the flag (the
condition that currently compares against 'true') to use a strict boolean check
(e.g., !== true) so the restore lifecycle is normalized to boolean across
setQtStatePartial, params.restore, and the restore-checking logic.

917-920: ⚖️ Poor tradeoff

Replace brittle string substitution with URL parameter manipulation.

The current implementation directly mutates panel.metaData.toolUrl using simple string replacement. This approach is fragile:

  1. Silent failure: If 'is_query_tool=false' isn't present (unexpected URL format), the replace silently does nothing.
  2. First-match only: String.replace() without a regex only replaces the first occurrence.
  3. No URL encoding handling: Doesn't handle potential encoding variations.
  4. Brittle pattern matching: Could theoretically match the substring in other contexts (though unlikely given the URL structure from context snippets).

Additionally, directly mutating panel.metaData may have side effects if the object is shared or tracked elsewhere.

🔧 Robust URL parameter manipulation
     toggleQueryTool: () => setQtStatePartial((prev)=>{
       let panel = qtPanelDocker?.find(qtPanelId);
       if (panel?.metaData?.toolUrl) {
-        panel.metaData.toolUrl = panel.metaData.toolUrl.replace('is_query_tool=false', 'is_query_tool=true');
+        try {
+          const url = new URL(panel.metaData.toolUrl, window.location.origin);
+          url.searchParams.set('is_query_tool', 'true');
+          panel.metaData.toolUrl = url.pathname + url.search + url.hash;
+        } catch (e) {
+          console.warn('Failed to update is_query_tool parameter:', e);
+        }
       }
       return {
         ...prev,

This approach:

  • Properly parses the URL
  • Updates the specific parameter
  • Handles any URL structure
  • Catches malformed URLs
  • Preserves all other parameters
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@web/pgadmin/tools/sqleditor/static/js/components/QueryToolComponent.jsx`
around lines 917 - 920, The current direct string replacement on
panel.metaData.toolUrl is brittle; instead parse the toolUrl using the
URL/URLSearchParams APIs (inside a try/catch to handle malformed URLs), set the
search parameter is_query_tool to "true" via
url.searchParams.set('is_query_tool','true'), reconstruct the full URL with
url.toString(), and then assign the new string back (preferably by replacing the
toolUrl property immutably, e.g. panel.metaData = Object.assign({},
panel.metaData, {toolUrl: newUrl})) so you avoid silent failures, encoding
issues, and unintended shared-object side effects; locate this change around the
qtPanelDocker?.find(qtPanelId) / panel.metaData.toolUrl code.

141-141: ⚡ Quick win

Use consistent equality operators when checking is_query_tool.

The type-flexibility check mixes strict equality (=== true) and loose equality (== 'true'). While functionally correct here, mixing operators is inconsistent and can obscure intent.

Additionally, this pattern only explicitly handles true and 'true', but URL parameters from context snippets show is_query_tool=false is also possible (from view-data mode). The current logic treats any non-true/'true' value (including the string 'false') as falsy, which works but could be made more explicit.

♻️ Proposed fix for consistency
-      is_query_tool: params.is_query_tool === true || params.is_query_tool == 'true',
+      is_query_tool: params.is_query_tool === true || params.is_query_tool === 'true',

Apply the same fix on line 157:

-        _.unescape(params.role) || _.unescape(params.user), params.is_query_tool === true || params.is_query_tool == 'true'),
+        _.unescape(params.role) || _.unescape(params.user), params.is_query_tool === true || params.is_query_tool === 'true'),

Alternatively, for more explicit boolean coercion:

-      is_query_tool: params.is_query_tool === true || params.is_query_tool == 'true',
+      is_query_tool: params.is_query_tool === true || params.is_query_tool === 'true',

Also applies to: 157-157

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@web/pgadmin/tools/sqleditor/static/js/components/QueryToolComponent.jsx` at
line 141, The boolean check for is_query_tool mixes === and == and doesn't
explicitly handle string values like 'false'; replace the expression used to
derive is_query_tool (currently: params.is_query_tool === true ||
params.is_query_tool == 'true') with a consistent coercion such as
String(params.is_query_tool) === 'true' (or params.is_query_tool === true ||
params.is_query_tool === 'true') to use strict equality in both branches; update
the same expression wherever it appears (the other occurrence that initializes
is_query_tool in this component) so both places use the identical, explicit
check.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Nitpick comments:
In `@web/pgadmin/tools/sqleditor/static/js/components/QueryToolComponent.jsx`:
- Around line 345-352: The restore flag in setQtStatePartial is being set to the
string 'false' which mismatches its boolean usage elsewhere (saved metaData uses
true and it's checked later with a loose comparison); change the code in the
state updater (setQtStatePartial) to set params.restore to the boolean false
instead of the string 'false', and update the check that reads the flag (the
condition that currently compares against 'true') to use a strict boolean check
(e.g., !== true) so the restore lifecycle is normalized to boolean across
setQtStatePartial, params.restore, and the restore-checking logic.
- Around line 917-920: The current direct string replacement on
panel.metaData.toolUrl is brittle; instead parse the toolUrl using the
URL/URLSearchParams APIs (inside a try/catch to handle malformed URLs), set the
search parameter is_query_tool to "true" via
url.searchParams.set('is_query_tool','true'), reconstruct the full URL with
url.toString(), and then assign the new string back (preferably by replacing the
toolUrl property immutably, e.g. panel.metaData = Object.assign({},
panel.metaData, {toolUrl: newUrl})) so you avoid silent failures, encoding
issues, and unintended shared-object side effects; locate this change around the
qtPanelDocker?.find(qtPanelId) / panel.metaData.toolUrl code.
- Line 141: The boolean check for is_query_tool mixes === and == and doesn't
explicitly handle string values like 'false'; replace the expression used to
derive is_query_tool (currently: params.is_query_tool === true ||
params.is_query_tool == 'true') with a consistent coercion such as
String(params.is_query_tool) === 'true' (or params.is_query_tool === true ||
params.is_query_tool === 'true') to use strict equality in both branches; update
the same expression wherever it appears (the other occurrence that initializes
is_query_tool in this component) so both places use the identical, explicit
check.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 13354e15-d117-46d6-9736-8833f3cd5f37

📥 Commits

Reviewing files that changed from the base of the PR and between 04fa05c and 0d9c38d.

📒 Files selected for processing (1)
  • web/pgadmin/tools/sqleditor/static/js/components/QueryToolComponent.jsx

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

All reactions
@dev-hari-prasad
Clean up QueryToolComponent state and URL handling
29433f2
- Normalize is_query_tool check with strict equality
- Normalize restore flag to use boolean types instead of strings
- Refactor fragile toolUrl replacement to use URL API with searchParams
coderabbitai[bot]
coderabbitai Bot reviewed Jun 10, 2026
View reviewed changes

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

There was a problem hiding this comment.

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
web/pgadmin/tools/sqleditor/static/js/components/QueryToolComponent.jsx (1)

293-304: ⚠️ Potential issue | 🔴 Critical | ⚡ Quick win

Critical: Restore guard type inconsistency allows execution during restore.

Lines 293 and 300 check restore against the string 'true' using loose equality, but line 390 uses strict inequality against the boolean true. When params.restore arrives as the string 'true' from the URL (the expected format), the guard at line 390 evaluates 'true' !== true to true, allowing execution to proceed and defeating the restore guard's purpose.

Line 350 sets restore: false after restore completes, but this doesn't protect the initial execution check at line 390 when the component mounts with restore='true'.

🛡️ Recommended fix: normalize restore during initialization

Apply this fix at line 141 to normalize restore during state initialization (matching the is_query_tool pattern):

       is_query_tool: params.is_query_tool === true || params.is_query_tool === 'true',
+      restore: params.restore === true || params.restore === 'true',
       node_name: retrieveNodeName(selectedNodeInfo),

And update line 390 to use strict equality with the normalized boolean:

-        if((!qtState.params.is_query_tool || reexecute) && qtState.params.restore !== true) {
+        if((!qtState.params.is_query_tool || reexecute) && !qtState.params.restore) {
           eventBus.current.fireEvent(QUERY_TOOL_EVENTS.TRIGGER_EXECUTION, explainObject, macroSQL, executeCursor, executeServerCursor);

This ensures consistent boolean handling throughout the restore lifecycle.

Also applies to: 350-350, 390-390

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@web/pgadmin/tools/sqleditor/static/js/components/QueryToolComponent.jsx`
around lines 293 - 304, qtState.params.restore is treated inconsistently (string
'true' vs boolean true) which lets restores bypass guards; normalize
params.restore to a boolean during state initialization (same approach used for
is_query_tool) so qtState.params.restore is true/false, then change the runtime
guard that currently checks restore against the string to a strict boolean check
(e.g., use qtState.params.restore === true) and ensure restoreToolContent and
the subsequent setQtStatePartial({ restore: false }) work with the normalized
boolean value.
🧹 Nitpick comments (2)
web/pgadmin/tools/sqleditor/static/js/components/QueryToolComponent.jsx (2)

919-926: 💤 Low value

Consider validating toolUrl before URL construction.

The URL API approach is solid, but if panel.metaData.toolUrl has an unexpected format (e.g., already a full URL with a different origin, or malformed), the try/catch will silently log a warning without indicating the root cause. Consider adding a pre-check or enriching the error message to aid debugging.

💡 Optional: enrich error logging
         try {
           const url = new URL(panel.metaData.toolUrl, window.location.origin);
           url.searchParams.set('is_query_tool', 'true');
           panel.metaData = Object.assign({}, panel.metaData, {toolUrl: url.pathname + url.search + url.hash});
         } catch (e) {
-          console.warn('Failed to update is_query_tool parameter:', e);
+          console.warn('Failed to update is_query_tool parameter for toolUrl:', panel.metaData.toolUrl, e);
         }

This helps trace which URL caused the parse failure.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@web/pgadmin/tools/sqleditor/static/js/components/QueryToolComponent.jsx`
around lines 919 - 926, The try/catch around new URL(panel.metaData.toolUrl,
window.location.origin) should validate and handle edge cases before blindly
constructing the URL: check panel.metaData.toolUrl for emptiness and whether it
looks like an absolute URL (contains "://" or startsWith("http")), and if
absolute use new URL(panel.metaData.toolUrl) while if relative use new
URL(panel.metaData.toolUrl, window.location.origin); also enrich the catch to
include the offending panel.metaData.toolUrl and window.location.origin and the
caught error (e) in the processLogger/console message so you can see the root
cause when URL construction fails.

1010-1028: 💤 Low value

Missing PropTypes entry for restore parameter.

The restore parameter is used throughout the component (lines 293, 300, 350, 390), but it's not declared in the PropTypes definition. Adding it would improve type safety and documentation.

📝 Suggested addition
     is_query_tool: PropTypes.oneOfType([PropTypes.bool, PropTypes.string]).isRequired,
+    restore: PropTypes.oneOfType([PropTypes.bool, PropTypes.string]),
     server_cursor: PropTypes.oneOfType([PropTypes.bool, PropTypes.string]),
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@web/pgadmin/tools/sqleditor/static/js/components/QueryToolComponent.jsx`
around lines 1010 - 1028, Add a missing PropTypes entry for the params.restore
prop on QueryToolComponent: update the params PropTypes shape to include a
non-required restore property (e.g., params.restore:
PropTypes.oneOfType([PropTypes.bool, PropTypes.string])) so the restore prop
used in the component (references to params.restore) is declared and
type-checked.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Outside diff comments:
In `@web/pgadmin/tools/sqleditor/static/js/components/QueryToolComponent.jsx`:
- Around line 293-304: qtState.params.restore is treated inconsistently (string
'true' vs boolean true) which lets restores bypass guards; normalize
params.restore to a boolean during state initialization (same approach used for
is_query_tool) so qtState.params.restore is true/false, then change the runtime
guard that currently checks restore against the string to a strict boolean check
(e.g., use qtState.params.restore === true) and ensure restoreToolContent and
the subsequent setQtStatePartial({ restore: false }) work with the normalized
boolean value.

---

Nitpick comments:
In `@web/pgadmin/tools/sqleditor/static/js/components/QueryToolComponent.jsx`:
- Around line 919-926: The try/catch around new URL(panel.metaData.toolUrl,
window.location.origin) should validate and handle edge cases before blindly
constructing the URL: check panel.metaData.toolUrl for emptiness and whether it
looks like an absolute URL (contains "://" or startsWith("http")), and if
absolute use new URL(panel.metaData.toolUrl) while if relative use new
URL(panel.metaData.toolUrl, window.location.origin); also enrich the catch to
include the offending panel.metaData.toolUrl and window.location.origin and the
caught error (e) in the processLogger/console message so you can see the root
cause when URL construction fails.
- Around line 1010-1028: Add a missing PropTypes entry for the params.restore
prop on QueryToolComponent: update the params PropTypes shape to include a
non-required restore property (e.g., params.restore:
PropTypes.oneOfType([PropTypes.bool, PropTypes.string])) so the restore prop
used in the component (references to params.restore) is declared and
type-checked.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 7576b2cd-c69b-41c5-ae5f-d9230246945d

📥 Commits

Reviewing files that changed from the base of the PR and between 0d9c38d and 29433f2.

📒 Files selected for processing (1)
  • web/pgadmin/tools/sqleditor/static/js/components/QueryToolComponent.jsx

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

All reactions
@dev-hari-prasad
Update QueryToolComponent.jsx
aefee3f
coderabbitai[bot]
coderabbitai Bot reviewed Jun 10, 2026
View reviewed changes

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

There was a problem hiding this comment.

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick comments (2)
web/pgadmin/tools/sqleditor/static/js/components/QueryToolComponent.jsx (2)

921-923: ⚡ Quick win

Simplify the absolute URL detection.

The condition toolUrl.includes('://') || toolUrl.startsWith('http') could incorrectly classify edge cases. For instance, a URL string "http" (without ://) would match the second condition and be treated as absolute, causing new URL("http") to throw an error.

♻️ Proposed fix to use a more robust check
-const isAbsolute = toolUrl.includes('://') || toolUrl.startsWith('http');
+const isAbsolute = toolUrl.includes('://');
 const url = isAbsolute ? new URL(toolUrl) : new URL(toolUrl, window.location.origin);

The includes('://') check reliably identifies absolute URLs (http://, https://, file://, etc.) without false positives.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@web/pgadmin/tools/sqleditor/static/js/components/QueryToolComponent.jsx`
around lines 921 - 923, The absolute-URL detection using isAbsolute (currently
toolUrl.includes('://') || toolUrl.startsWith('http')) is too permissive; change
the check to rely only on the presence of '://'. Locate the variables toolUrl,
isAbsolute, and url in QueryToolComponent.jsx and update isAbsolute to use
toolUrl.includes('://') only, then construct url using new URL(toolUrl) when
isAbsolute is true and new URL(toolUrl, window.location.origin) otherwise to
avoid treating short strings like "http" as absolute.

158-158: ⚡ Quick win

Consider reusing the normalized is_query_tool value.

The normalization check params.is_query_tool === true || params.is_query_tool === 'true' is duplicated from line 141. Since the params object (containing the normalized is_query_tool) is constructed before connection_list, you could reference the already-normalized value to reduce duplication.

♻️ Proposed refactor to eliminate duplication

Compute the normalized boolean once before the state object:

+const normalizedParams = {
+  ...params,
+  title: _.unescape(params.title),
+  is_query_tool: params.is_query_tool === true || params.is_query_tool === 'true',
+  restore: params.restore === true || params.restore === 'true',
+  node_name: retrieveNodeName(selectedNodeInfo),
+  dbname: _.unescape(params.database_name) || getDatabaseLabel(selectedNodeInfo),
+  server_cursor: preferencesStore.getPreferencesForModule('sqleditor').server_cursor === true,
+};
+
 const [qtState, setQtState] = useState({
   preferences: { ... },
   is_new_tab: window.location == window.parent?.location,
   ...
-  params: {
-    ...params,
-    title: _.unescape(params.title),
-    is_query_tool: params.is_query_tool === true || params.is_query_tool === 'true',
-    restore: params.restore === true || params.restore === 'true',
-    node_name: retrieveNodeName(selectedNodeInfo),
-    dbname: _.unescape(params.database_name) || getDatabaseLabel(selectedNodeInfo),
-    server_cursor: preferencesStore.getPreferencesForModule('sqleditor').server_cursor === true,
-  },
+  params: normalizedParams,
   connection_list: [{
     ...
     conn_title: getTitle(
       pgAdmin, null, selectedNodeInfo, true, _.unescape(params.server_name), _.unescape(params.database_name) || getDatabaseLabel(selectedNodeInfo),
-      _.unescape(params.role) || _.unescape(params.user), params.is_query_tool === true || params.is_query_tool === 'true'),
+      _.unescape(params.role) || _.unescape(params.user), normalizedParams.is_query_tool),
     ...
   }],
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@web/pgadmin/tools/sqleditor/static/js/components/QueryToolComponent.jsx` at
line 158, The duplicated normalization of params.is_query_tool should be
removed: use the already-normalized boolean stored on params (or a local
variable like isQueryTool set when building params) when constructing
connection_list instead of re-evaluating params.is_query_tool === true ||
params.is_query_tool === 'true'; update the connection_list call in
QueryToolComponent.jsx to reference params.is_query_tool (or the local
isQueryTool) so the normalized value is computed once and reused.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Nitpick comments:
In `@web/pgadmin/tools/sqleditor/static/js/components/QueryToolComponent.jsx`:
- Around line 921-923: The absolute-URL detection using isAbsolute (currently
toolUrl.includes('://') || toolUrl.startsWith('http')) is too permissive; change
the check to rely only on the presence of '://'. Locate the variables toolUrl,
isAbsolute, and url in QueryToolComponent.jsx and update isAbsolute to use
toolUrl.includes('://') only, then construct url using new URL(toolUrl) when
isAbsolute is true and new URL(toolUrl, window.location.origin) otherwise to
avoid treating short strings like "http" as absolute.
- Line 158: The duplicated normalization of params.is_query_tool should be
removed: use the already-normalized boolean stored on params (or a local
variable like isQueryTool set when building params) when constructing
connection_list instead of re-evaluating params.is_query_tool === true ||
params.is_query_tool === 'true'; update the connection_list call in
QueryToolComponent.jsx to reference params.is_query_tool (or the local
isQueryTool) so the normalized value is computed once and reused.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: d8ae2cda-8f88-4f6d-8427-a09d8dbf75b5

📥 Commits

Reviewing files that changed from the base of the PR and between 29433f2 and aefee3f.

📒 Files selected for processing (1)
  • web/pgadmin/tools/sqleditor/static/js/components/QueryToolComponent.jsx

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

All reactions
@dev-hari-prasad
Refactoring: Clean up state initialization and URL checks
b8a2a4e
- Extracted isQueryTool to eliminate duplicate checks
- Simplified absolute-URL detection to use '://' only
@dev-hari-prasad

dev-hari-prasad commented Jun 10, 2026

Copy link
Copy Markdown
Contributor Author

The PR is ready to merge. I have addressed all concerns of CodeRabbit. Pls consider merging this after updating the branch. I have used AI in the last two commit eg. Refactoring: Clean up state initialization and URL checks and Update QueryToolComponent.jsx, but rest assured, I have thoroughly read and understood the changes, made the initial changes myself, and verified everything manually.

Pls review the changes @asheshv if any changes are required, let me know.

All reactions

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

mzabuawala
mzabuawala reviewed Jun 10, 2026
View reviewed changes
Comment thread web/pgadmin/tools/sqleditor/static/js/components/QueryToolComponent.jsx Resolved

Uh oh!

There was an error while loading. Please reload this page.

mzabuawala
mzabuawala reviewed Jun 10, 2026
View reviewed changes
Comment thread web/pgadmin/tools/sqleditor/static/js/components/QueryToolComponent.jsx Resolved

Uh oh!

There was an error while loading. Please reload this page.

@asheshv
asheshv requested a review from Copilot June 10, 2026 13:59
Copilot started reviewing on behalf of asheshv June 10, 2026 13:59
View session
Copilot AI reviewed Jun 10, 2026
View reviewed changes

Copilot AI left a comment

Copy link
Copy Markdown

There was a problem hiding this comment.

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Fixes an issue where restored SQL Editor/Query Tool tabs could be misclassified on startup (due to is_query_tool being restored as a boolean), which could lead to unintended query auto-execution.

Changes:

  • Normalize is_query_tool and restore to support both boolean and string inputs during initialization.
  • Improve restore flow by clearing the restore flag after content restoration and adjusting initialization behavior.
  • Attempt to persist “promoted to Query Tool” state by updating the panel’s stored toolUrl.

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

All reactions
Comment thread web/pgadmin/tools/sqleditor/static/js/components/QueryToolComponent.jsx Resolved

Uh oh!

There was an error while loading. Please reload this page.

Comment thread web/pgadmin/tools/sqleditor/static/js/components/QueryToolComponent.jsx Resolved

Uh oh!

There was an error while loading. Please reload this page.

@dev-hari-prasad

dev-hari-prasad commented Jun 10, 2026

Copy link
Copy Markdown
Contributor Author

I'll address the suggestions and requested changes in a day or a two.

All reactions

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

@dev-hari-prasad
Fix restore execution and continue smooth Query Tool promotion
a0a4ee8
Await restored content, preserve View/Edit Data execution, and save updated tool URLs.
@dev-hari-prasad

dev-hari-prasad commented Jun 18, 2026

Copy link
Copy Markdown
Contributor Author

The requested changes and improvements from @mzabuawala and Co-pilto are both adresssed pls review once @asheshv

All reactions

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

@dev-hari-prasad
Merge branch 'master' into bug/prevent-query-auto-execution
93bab32
@dpage

dpage commented Jun 19, 2026

Copy link
Copy Markdown
Contributor

Thanks @dev-hari-prasad, this is a solid fix for a genuinely nasty bug, a restored DELETE/UPDATE auto-running on startup is exactly the sort of thing we want to stop. The root-cause analysis is right: is_query_tool was only compared against the string 'true', so when session restore rehydrated it as a boolean it was misclassified and fell through to the auto-execute path. Normalising both is_query_tool and restore to real booleans and guarding the execution gate is the correct approach.

I traced the gate at if(!is_query_tool || (reexecute && restore !== true)) across the cases and it behaves correctly: View/Edit Data still auto-executes, a Query Tool on normal open does not, reexecute (e.g. after reconnect) does, and a restored Query Tool does not. I also confirmed there are no leftover == 'true' comparisons for either flag and that restore is reset to false once restoreToolContent() completes.

On the existing threads:

  • restoreToolContent() async/await (mzabuawala): addressed, getSQLScript is now async and awaits it.
  • toggleQueryTool layout not saved (Copilot): addressed, saveLayout() is now called.
  • "the restore guard also blocks restored View/Edit Data tabs" (Copilot): this no longer applies to the current code. The restore check sits only inside the reexecute sub-clause, and !is_query_tool short-circuits to true for View/Edit Data, so those tabs still auto-execute on restore. I think this one can be resolved, it was likely written against an earlier commit.
  • "IMO this check is not required" (mzabuawala): this one is still open and has no line anchor, so it isn't clear which check is meant, @mzabuawala could you point at the specific line? That's the main thing left holding this up.

Two minor notes, neither blocking:

  • getSQLScript() is now async but its caller in the mount effect invokes it without await (a useEffect callback can't be async anyway), so it runs concurrently with initializeQueryTool(). It's fine in practice because the auto-exec guard relies on the restore === true value captured at render time rather than on restore finishing first, so there's no race that re-enables execution, just be aware the async signature implies an ordering the caller doesn't enforce. Awaiting restoreToolContent() inside getSQLScript was the right call.
  • Given how destructive the underlying bug is, a small regression test would be worthwhile. The full restore flow is awkward in Jest, but the cheap, high-value part, that is_query_tool/restore normalise from both boolean and string and that the gate does not fire for reexecute && restore, is unit-testable.

No changelog entry needed, by the way, we now add those in a batch just before release rather than per-PR.

dev-hari-prasad reacted with thumbs up emoji
All reactions
  • 👍 1 reaction

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

@dev-hari-prasad

dev-hari-prasad commented Jul 4, 2026

Copy link
Copy Markdown
Contributor Author

Is this PR ready for merge, or is there something else I need to address?

@dpage

All reactions

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

dpage
dpage reviewed Aug 18, 2026
View reviewed changes

@dpage dpage left a comment

Copy link
Copy Markdown
Contributor

There was a problem hiding this comment.

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for digging into this, and apologies for the slow review. I've gone through the change in full file context rather than just the diff. The underlying bug is real and nasty, and one of the three behavioural changes here is the right fix for it, but I think the other two are wrong, so I'd hold off merging as it stands.

First, a correction to the premise, because it matters for whoever reads this in a year's time: the params that reach QueryToolComponent are built from request.args and request.form in panel() (web/pgadmin/tools/sqleditor/__init__.py:364), so is_query_tool always arrives as a string and can never be a boolean. The actual mechanism is the promotion path: typing into the editor of a View/Edit Data tab calls promoteToQueryTool() (Query.jsx:390), which flips is_query_tool in memory only, whilst the persisted metaData.toolUrl still carries is_query_tool=false. On restore the tab is therefore treated as View/Edit Data, !qtState.params.is_query_tool is true, and TRIGGER_EXECUTION fires against whatever SQL was restored into the editor. That is the bug, and the toggleQueryTool change is exactly the right fix for it; the is_query_tool and restore normalisation is harmless defensive tidying that does no work today. It would be worth rewriting the PR description accordingly.

Detailed comments are inline, two of which I'd treat as blockers. A few smaller notes that don't attach neatly to a line:

  • Anyone upgrading with an already-promoted tab in their saved layout will still have is_query_tool=false persisted, so they'll hit the bug once more after upgrading. Probably acceptable, but worth being aware of.
  • There are no tests. The interesting behaviour here is docker and layout bound so a full test would be awkward, but a small Jest spec around the URL rewriting would be cheap, and would have caught the first of the two blockers below.
  • CI is green (32 passed, 2 skipped); the BLOCKED merge state is purely the unresolved review threads.

No release notes entry is needed, incidentally: we now batch those up shortly before a release rather than doing one per PR.

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

All reactions
Comment thread web/pgadmin/tools/sqleditor/static/js/components/QueryToolComponent.jsx Resolved

Uh oh!

There was an error while loading. Please reload this page.

Comment thread web/pgadmin/tools/sqleditor/static/js/components/QueryToolComponent.jsx Resolved

Uh oh!

There was an error while loading. Please reload this page.

Comment thread web/pgadmin/tools/sqleditor/static/js/components/QueryToolComponent.jsx Resolved

Uh oh!

There was an error while loading. Please reload this page.

Comment thread web/pgadmin/tools/sqleditor/static/js/components/QueryToolComponent.jsx Resolved

Uh oh!

There was an error while loading. Please reload this page.

@dev-hari-prasad
Fix toolUrl persistence and clean up Query Tool restore logic
798ecef
@dev-hari-prasad

dev-hari-prasad commented Sep 5, 2026

Copy link
Copy Markdown
Contributor Author

Hello, I have pushed a follow-up commit to fix a couple of edge cases found by Dave:

  • Saved relative toolUrl: Switched from url.toString() to url.pathname + url.search. In Desktop mode (fixedPort: false), the backend port changes on restart, so saving an absolute URL broke tab restores against the old dead port.
  • Fixed password re-prompt query re-run: Reverted the check in initializeQueryTool back to !is_query_tool || reexecute. The old restore !== true clause closed over initial render state, causing restored tabs to silently fail re-executing queries after a password prompt / dropped connection.
  • State updater cleanup: Moved the panel lookup and saveLayout() call outside setQtStatePartial to keep the React updater pure, and added a warning if the panel lookup misses.
  • Made getSQLScript synchronous: Removed the misleading async/await since the mount useEffect couldn't await it anyway.

Tested in desktop mode, and tab restores + promotions are working now. Ready for review, and sorry for the delay.

amoshmedica reacted with heart emoji
All reactions
  • ❤️ 1 reaction

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

dpage pushed a commit that referenced this pull request Sep 22, 2026
@dev-hari-prasad @dpage
Fix Query Tool tabs auto-running their query after a session restore (#…
e78c7fe
…10055)

Typing in the editor of a View/Edit Data tab promotes it to a Query Tool, but
that promotion only ever updated the component's own state: the tab's saved
metadata kept the original tool URL, with is_query_tool=false in its query
string. On the next start-up the tab was therefore restored as a View/Edit Data
tab, and View/Edit Data tabs execute their query as soon as the connection is
made, so whatever SQL the user had left in the editor ran unprompted. A
restored DELETE or UPDATE running by itself is not a pleasant way to start the
day.

toggleQueryTool now rewrites is_query_tool in the panel's stored toolUrl and
saves the layout, so a promoted tab comes back as a Query Tool and no longer
takes the auto-execute path. The URL is kept relative, because in Desktop mode
the runtime picks a fresh port on every launch and an absolute URL would point
the restored tab at a dead origin.

is_query_tool and restore are also normalised to real booleans up front rather
than compared against the string 'true' in each place they are read, and a
failed restore no longer leaves the editor disabled with nothing logged.

Fixes #10031
@dpage

dpage commented Sep 22, 2026

Copy link
Copy Markdown
Contributor

Merged as e78c7fe02, rebased onto current master and squashed to a single commit with you as the author. GitHub won't auto-close it given the changed SHA, so I'm closing it by hand.

I folded in one small change on the way: restoreToolContent() was still called without await or .catch, which was @mzabuawala's outstanding point. Nothing in the current call chain actually rejects (getToolContent swallows everything into return null, and warnFileReload only ever resolves), so there was no live bug, but if that ever changes the consequence is an unhandled rejection with editor_disabled stuck at true, leaving the restored tab permanently read-only with nothing logged. It now catches, reports through HANDLE_API_ERROR and re-enables the editor.

Thanks for sticking with this one through several rounds of review; it's a genuinely nasty bug to have had in the wild, and the fix is a good one.

All reactions

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

@dpage dpage closed this Sep 22, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Reviewers

@dpage dpage dpage left review comments
@coderabbitai coderabbitai[bot] coderabbitai[bot] left review comments
Copilot code review Copilot
Copilot review effort
Applies to this pull request for everyone.Learn more about Copilot code review.
Copilot left review comments
+1 more reviewer
@mzabuawala mzabuawala mzabuawala left review comments
Reviewers whose approvals may not affect merge requirements

Uh oh!

There was an error while loading. Please reload this page.

Assignees

No one assigned

Labels

None yet

Projects

None yet

Milestone

No milestone

Development

Successfully merging this pull request may close these issues.

Open queries autoruns when I start the app

Uh oh!

There was an error while loading. Please reload this page.

4 participants

@dev-hari-prasad @dpage @mzabuawala
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
You are visitor 01402775 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.