Skip to content

fix: deduplicate workspace provisioning#34

Open
mahatoankitkumar wants to merge 3 commits into
mainfrom
fix/library
Open

fix: deduplicate workspace provisioning#34
mahatoankitkumar wants to merge 3 commits into
mainfrom
fix/library

Conversation

@mahatoankitkumar

@mahatoankitkumar mahatoankitkumar commented Jun 8, 2026

Copy link
Copy Markdown
Contributor

This pull request refactors how workspace schema provisioning is handled, centralizing the logic and making it more flexible by supporting table prefixes. The main change is to move the schema creation and DDL application logic into a reusable function, and to ensure the table prefix is consistently applied.

Refactoring and centralization:

  • Moved the schema provisioning logic (including schema creation and DDL execution with table prefix support) into the public function provision_schema in crates/common/src/db/workspaces.rs, making it reusable and easier to maintain.
  • Updated the create function to use the new provision_schema signature, passing an empty string as the table prefix for now.
  • Refactored the KronosLibraryClient::provision_workspace implementation to call the new provision_schema function, removing duplicated logic and ensuring table prefixing is handled consistently.

Summary by CodeRabbit

  • Refactor
    • Improved internal database schema provisioning structure for better modularity and maintainability.

@coderabbitai

coderabbitai Bot commented Jun 8, 2026

Copy link
Copy Markdown

Review Change Stack

Important

Review skipped

Auto incremental reviews are disabled on this repository.

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: b8ee79a4-c9a6-4bee-857d-ad62323bd071

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Use the checkbox below for a quick retry:

  • 🔍 Trigger review

Walkthrough

The PR refactors workspace schema provisioning by extracting table-prefix handling into a public provision_schema function. The function now accepts a configurable prefix, uses schema-scoped connections, and dynamically renders DDL. Call sites in create and KronosLibraryClient::provision_workspace are updated to delegate through this new contract.

Changes

Schema provisioning refactor with table prefix support

Layer / File(s) Summary
Refactored provision_schema function with table prefix support
crates/common/src/db/workspaces.rs
provision_schema is made public, gains a table_prefix parameter, and refactors connection handling to use schema-scoped connections and computed prefix strings (empty or "{table_prefix}_") for DDL substitution.
Update provision_schema call sites
crates/common/src/db/workspaces.rs, crates/worker/src/client.rs
The create function passes an explicit empty prefix; KronosLibraryClient::provision_workspace delegates to the refactored function with the client's table prefix instead of executing inlined SQL statements.

🎯 2 (Simple) | ⏱️ ~8 minutes

🐰 A schema once scattered in code so wide,
Now nestled neat with prefixes applied!
From client to common, the logic takes flight,
One provision_schema keeps all things right. ✨

🚥 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: deduplicate workspace provisioning' accurately summarizes the main change—consolidating workspace provisioning logic into a reusable function to eliminate duplication.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

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

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch fix/library

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

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

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🤖 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.

Inline comments:
In `@crates/common/src/db/workspaces.rs`:
- Around line 104-111: provision_schema currently interpolates schema_name into
SQL before validation, exposing a SQL injection risk; update provision_schema to
validate schema_name at function entry (reusing the same validation
logic/pattern used by create and scoped_connection) and reject or sanitize
invalid names before calling sqlx::query(format!(...)); ensure callers such as
KronosLibraryClient::provision_workspace can only pass validated names and keep
the CREATE SCHEMA statement unchanged aside from using the already-validated
schema_name.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 4b0b892b-9441-4ca2-a92d-ad70bc0aa656

📥 Commits

Reviewing files that changed from the base of the PR and between c696b82 and becf669.

📒 Files selected for processing (2)
  • crates/common/src/db/workspaces.rs
  • crates/worker/src/client.rs

Comment on lines +104 to +111
pub async fn provision_schema(
pool: &PgPool,
schema_name: &str,
table_prefix: &str,
) -> Result<(), sqlx::Error> {
sqlx::query(&format!("CREATE SCHEMA IF NOT EXISTS \"{}\"", schema_name))
.execute(pool)
.await?;

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🔴 Critical | ⚡ Quick win

Add input validation before SQL interpolation in the now-public function.

provision_schema is now a public API, but schema_name is interpolated into SQL at line 109 before scoped_connection performs its validation at line 113. Callers like KronosLibraryClient::provision_workspace pass external input directly, creating a SQL injection vector through quoted identifier escapes.

Validate at function entry, consistent with the create function's pattern.

🛡️ Proposed fix to add validation
 pub async fn provision_schema(
     pool: &PgPool,
     schema_name: &str,
     table_prefix: &str,
 ) -> Result<(), sqlx::Error> {
+    use crate::tenant::validate_table_prefix;
+    assert!(
+        validate_schema_name(schema_name),
+        "Invalid schema name: {}",
+        schema_name
+    );
+    assert!(
+        validate_table_prefix(table_prefix),
+        "Invalid table prefix: {}",
+        table_prefix
+    );
+
     sqlx::query(&format!("CREATE SCHEMA IF NOT EXISTS \"{}\"", schema_name))
         .execute(pool)
         .await?;
🧰 Tools
🪛 OpenGrep (1.22.0)

[ERROR] 109-109: SQL query built via format!() passed to a database method. Use parameterized queries with bind parameters instead.

(coderabbit.sql-injection.rust-format-query)

🤖 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 `@crates/common/src/db/workspaces.rs` around lines 104 - 111, provision_schema
currently interpolates schema_name into SQL before validation, exposing a SQL
injection risk; update provision_schema to validate schema_name at function
entry (reusing the same validation logic/pattern used by create and
scoped_connection) and reject or sanitize invalid names before calling
sqlx::query(format!(...)); ensure callers such as
KronosLibraryClient::provision_workspace can only pass validated names and keep
the CREATE SCHEMA statement unchanged aside from using the already-validated
schema_name.

Source: Linters/SAST tools

schema_name: &str,
table_prefix: &str,
) -> Result<(), sqlx::Error> {
sqlx::query(&format!("CREATE SCHEMA IF NOT EXISTS \"{}\"", schema_name))

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Possible to use bind parameters here @mahatoankitkumar instead of string concatenation ?

Ankit.Mahato and others added 2 commits June 10, 2026 14:29
Embedders previously needed their own sqlx dependency for two reasons:
building the PgPool to pass to KronosLibraryClient::new, and naming sqlx
types (PgPool, sqlx::Error) when implementing SchemaProvider. Re-exporting
sqlx from kronos-common removes the need for a separate pin (which could
also drift to an incompatible version), and from_database_url + pool()
let callers skip pool construction entirely while still sharing the pool.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
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.

2 participants