Skip to content

feat(sidebar): list the session's temporary tables - #3746

Merged
datlechin merged 3 commits into
mainfrom
feat/2510-temporary-tables
Oct 21, 2026
Merged

datlechin merged 3 commits into
mainfrom
feat/2510-temporary-tables

Conversation

@datlechin

Copy link
Copy Markdown
Member

Summary

  • Sidebar gets a Temporary section under Recent, in every layout, listed only while the session holds a temporary table. A row opens and browses like any table; its menu offers Open in New Tab, Show Structure and Copy Name.
  • The list is read on the session the query tabs run on, never a pooled connection: PostgreSQL from pg_my_temp_schema(), SQLite from sqlite_temp_master, SQL Server from tempdb.sys.tables matched back to the session with OBJECT_ID, MySQL and MariaDB from the names CREATE TEMPORARY TABLE and RENAME statements gave, checked with SHOW CREATE TABLE.
  • It refreshes after any statement that can change tables (now also DISCARD TEMP and DISCARD ALL), and a list read on a connection that has since been replaced is hidden.
  • A tab opened on a temporary table carries that identity (TabTableContext.isTemporary, persisted) and a session-bound DatabaseScope, so its rows, columns and structure all come from the session. Its rows and structure are read-only, and it keeps no Recent entry, saved filters or hidden columns, which are keyed by a name a permanent table can share.
  • PluginKit: PluginCapabilities.temporaryTables and fetchTemporaryTables(), additive with a default. Kit stays 40.
  • Drivers read a temporary table's own definition: SQLite DDL, checks, generated columns, triggers and index text from temp before main; SQL Server columns and indexes from tempdb; MySQL and MariaDB skip INFORMATION_SCHEMA and SHOW TABLE STATUS for one, which describe the table it hides.

Test plan

  • TemporaryTableStoreTests, ScopedDriverRoutingTests, SidebarObjectSelectionTests, DatabaseTreeMenuSpecTests, DatabaseTreeTemporarySelectionTests, DataRefreshScopeTests, TableTabDuplicationTests, TabObjectKindTests.
  • SQLiteTemporaryTableTests (live in-process SQLite), MySQLTemporaryTableNamesTests, PostgreSQLTableListingTests, MSSQLTemporaryTableQueriesTests, SQLCatalogEffectClassifierTests.
  • UI flow TemporaryTableSidebarUITests: CREATE TEMP TABLE scratch AS SELECT 'kept' AS note in a query tab lists scratch under Temporary, and opening it shows its row.
  • Measured on SQL Server 2022, PostgreSQL 17, MySQL 8.4.11 and MariaDB 11.4.13: each listing query, another session's #t left out, [dbo].[#t] reads, and INFORMATION_SCHEMA.COLUMNS answering with the hidden table's default.

Screenshots

CREATE TEMP TABLE scratch AS SELECT 'kept' AS note, 42 AS answer on SQLite, then a click on the new row. Before this change the sidebar lists nothing new.

After, light
After, dark

Not in this PR

  • SQL Server lists a #name with more than three trailing underscores only by trying every padding length, which took 1.4 s with 300 temporary tables on the server, so such a name is not listed.
  • Column widths of a temporary table are saved under the key of a permanent table of the same name: the grid derives the key from the name alone (DataGridCoordinator.columnLayoutKey).
  • On MySQL and SQLite a tab on a permanent table reads its rows on the session, so while a temporary table of the same name exists it shows the temporary table's rows. That predates this change.

Fixes #2510

@datlechin
datlechin enabled auto-merge (squash) October 21, 2026 07:32

@J2TeamNNL J2TeamNNL left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Review findings, posted inline. The SQL Server schema-qualified #temp finding is untested.

return nil
}
}
return DatabaseTreeTableRef(database: database, schema: nil, table: table)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

A SQL Server temp table row has schema nil, so opening it fills in the browse schema (dbo) and the query becomes [dbo].[#scratch]. I believe SQL Server rejects a schema-qualified #temp name (not run). If so, clicking a Temporary row on MSSQL errors instead of showing rows. Tests only cover the listing SQL and a SQLite fixture.

tabMgr.onTableOpened = { tableName, schemaName, databaseName, isView, objectType, isPreview in
// A temporary table goes with its session, and a Recent entry would outlive it.
let scope = DatabaseScope(connectionId: connectionId, database: databaseName, schema: schemaName)
guard !TemporaryTableStore.shared.holds(table: tableName, in: scope) else { return }

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

This skips Recent whenever a temp table with the same name exists, but never checks that the opened table is the temp one. If a temp orders hides the permanent orders, opening the permanent one (via FK, quick switcher) is never recorded in Recent. The callback has no isTemporary parameter.

func fetchTemporaryTables() async throws -> [PluginTableInfo] {
guard listsTemporaryTables else { return [] }
var tables: [String: PluginTableInfo] = [:]
for candidate in temporaryTableCandidates {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

One serial SHOW CREATE TABLE runs per candidate name, and names are never removed after DROP TEMPORARY TABLE. A script that creates and drops 500 temp tables leaves 500 candidates, and every table-affecting catalog change then queues 500 round trips on the user's session. Drop candidates on a seen DROP, or prune names answered with 1146.

}

// A listing read on a connection that has since been replaced names tables that went with it.
private func isCurrent(_ listing: TemporaryTableListing, connectionId: UUID, database: String) -> Bool {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Session identity is an ObjectIdentifier of a driver, which can be reused once the old driver is freed. After a reconnect, a new driver at the same address makes a stale listing pass isCurrent, so dead temp tables stay in the sidebar and keep suppressing Recent. A generation counter or a weak driver reference avoids this.

let database: String
let schema: String?
// Set for an object only the session can see, a temporary table: a pooled connection is another session.
let isSessionBound: Bool

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

isSessionBound is part of the synthesized Hashable identity, so every cache keyed by scope forks. A temp tab gets its own schema provider that does a full catalog populate, and checks like browseScope == scope and DataRefreshRequest.reaches needed hand patches. Keep routing separate from identity (a flag on the call, or a separate key).

if reader.accept("IF") {
guard reader.accept("NOT"), reader.accept("EXISTS") else { return nil }
}
return reader.tableName()

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

created(by:) and tableName() drop the schema qualifier, and candidates are matched by bare name. RENAME TABLE other_db.t TO x is treated as renaming the temp t, and a temp t created under another database is reported as a candidate for the browsed one. The tracker should key on (schema, name).

var columnContentWidths: [String: CGFloat]?
var windowGroupIndex: Int?
var isPinned: Bool = false
var isTemporary: Bool = false

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

isTemporary is persisted with the tab, but the temp table does not survive the session. After a restart or reconnect the tab restores with isTemporary, the old pg_temp_N schema on PostgreSQL, and auto-loads a query on a table that no longer exists. Drop restored temp tabs, or open them without auto-executing.

guard viewModel != nil else { return [] }
let database = browsingDatabase
let search = SidebarSearch(searchText)
return temporaryTables.tables(connectionId: connectionId, database: database ?? "").compactMap { table in

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

The Temporary section lists only the browse database's temp tables. If the user creates one in database a, then browses b, the section disappears but the open tab keeps its session-bound scope for a. executionRoute returns .unavailable for the foreign database, so refresh, pagination and structure fail with the pooled connection error.

let sql = MSSQLSchemaQueries.columns(schema: effectiveSchema(schema), table: table)
let sql = MSSQLSchemaQueries.namesTemporaryTable(table)
? MSSQLSchemaQueries.temporaryColumns(table: table)
: MSSQLSchemaQueries.columns(schema: effectiveSchema(schema), table: table)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

namesTemporaryTable is only hasPrefix("#"). A permanent table named #audit is read from tempdb..#audit and shows an empty structure. A global ##shared table is routed to tempdb but excluded from the sidebar listing (LIKE N'#[^#]%'), so the two paths disagree on what is temporary.

// 12-digit suffix (measured on SQL Server 2022), so the name is the prefix `OBJECT_ID` resolves back to the row.
// Trailing underscores of the name itself are lost to the padding, so up to three are tried: every candidate is
// tried against every session's tables, and trying all 116 took 1.4 s with 300 temporary tables on the server.
public static let temporaryTables = """

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

The listing recovers the name by trying up to 3 trailing underscores, so #stage____ (4 or more) is silently omitted. The CROSS APPLY also runs 1 to 4 OBJECT_ID lookups per foreign session's temp table on every catalog change, and the comment itself notes 1.4 s with 300 tables.

@datlechin
datlechin merged commit 1daf410 into main Oct 21, 2026
8 checks passed
@J2TeamNNL

Copy link
Copy Markdown
Contributor

Fixes for the review findings are in J2TeamNNL@9ebac7d

Fixed (5):

  • SQL Server temp table opened as [dbo].[#name]: a temporary table now keeps the schema its row named (none on SQL Server), in the open path, the new-window path and the first-load schema fill.
  • Recent skipped by name lookup: the open callback now skips Recent only when the tab itself is temporary, so a permanent table of the same name is still recorded. The name lookup is removed.
  • MySQL candidates never pruned: DROP TEMPORARY TABLE now removes its names. A 1146 prune would lose a table that lives in another database, so it is not used.
  • Session identity by ObjectIdentifier: the listing now holds the driver weakly, so a new driver at a reused address no longer matches an old listing.
  • Restored temp tabs: temporary tabs are no longer written to the saved tab state.

Skipped (5):

  • isSessionBound in scope identity: a routing and identity split touches every cache key and DataRefreshRequest. Too wide to do safely without a local build. Better as its own change.
  • MySQL names without schema: each candidate is checked with SHOW CREATE TABLE in the browsed database, so a wrong name is never listed. It only costs a round trip, which the DROP pruning now bounds.
  • Foreign database tab: with a parked lane the route is the session driver. Otherwise the temp table went with the old connection, and the tab shows the "switch the connection to that database" message, not a pool error.
  • #audit and ##shared in MSSQL: # names are reserved for temporary objects, and ##shared is correctly read from tempdb. The name alone cannot tell a permanent #audit, so I left it.
  • Three trailing underscores and the OBJECT_ID cost: this is the measured trade-off in the code comment. Widening it makes the listing slower for everyone.

Not built or run locally (no Xcode). SwiftLint crashed here; changed files pass swiftc -parse.

Cherry-pick:

git fetch https://github.com/J2TeamNNL/TablePro review-fix/3746 && git cherry-pick 9ebac7d8e718c1fbc090dc314a995b85da9517c7

@datlechin
datlechin deleted the feat/2510-temporary-tables branch October 21, 2026 09:56
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Show temporary tables in the object list

2 participants