Skip to content

Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows

feat: add sanitize_db filter for database-safe identifiers (#498)

Maximilian Roos962b548bbfa5
diff --git a/.claude-plugin/skills/worktrunk/reference/config.md b/.claude-plugin/skills/worktrunk/reference/config.md
index dcf45358d..dc8a68be7 100644
--- a/.claude-plugin/skills/worktrunk/reference/config.md
+++ b/.claude-plugin/skills/worktrunk/reference/config.md
@@ -166,7 +166,7 @@ The `[list]` section adds a URL column to `wt list`:
url = "http://localhost:{{ branch | hash_port }}"
```
-URLs are dimmed when the port isn't listening. The template supports `{{ branch }}` with filters `hash_port` (port 10000-19999) and `sanitize` (filesystem-safe).
+URLs are dimmed when the port isn't listening.
### CI platform override
@@ -329,9 +329,10 @@ Creates `~/.config/worktrunk/config.toml` with the following content:
# Worktree Path Template
# Variables:
-# {{ repo }} - Repository directory name (e.g., "myproject")
-# {{ branch }} - Raw branch name (e.g., "feature/auth")
-# {{ branch | sanitize }} - Branch name with / and \ replaced by - (e.g., "feature-auth")
+# {{ repo }} - Repository directory name (e.g., "myproject")
+# {{ branch }} - Raw branch name (e.g., "feature/auth")
+# {{ branch | sanitize }} - Filesystem-safe: / and \ replaced by - (e.g., "feature-auth")
+# {{ branch | sanitize_db }} - Database-safe: lowercase, underscores, hash suffix (e.g., "feature_auth_x7k")
#
# Paths are relative to the main worktree root (original repository directory).
#
@@ -535,8 +536,9 @@ With `--project`, creates `.config/wt.toml` in the current repository:
# {{ target }} - Target branch for the merge
#
# Filters:
-# {{ branch | sanitize }} - Replace / and \ with - (e.g., "feature-auth")
-# {{ branch | hash_port }} - Deterministic port 10000-19999
+# {{ branch | sanitize }} - Replace / and \ with - (e.g., "feature-auth")
+# {{ branch | sanitize_db }} - Database-safe identifier with hash suffix (e.g., "feature_auth_x7k")
+# {{ branch | hash_port }} - Deterministic port 10000-19999
# ============================================================================
# Hooks
diff --git a/.claude-plugin/skills/worktrunk/reference/hook.md b/.claude-plugin/skills/worktrunk/reference/hook.md
index ade972d1e..b127a0016 100644
--- a/.claude-plugin/skills/worktrunk/reference/hook.md
+++ b/.claude-plugin/skills/worktrunk/reference/hook.md
@@ -159,9 +159,10 @@ Templates support Jinja2 filters for transforming values:
| Filter | Example | Description |
|--------|---------|-------------|
| `sanitize` | `{{ branch \| sanitize }}` | Replace `/` and `\` with `-` |
+| `sanitize_db` | `{{ branch \| sanitize_db }}` | Database-safe identifier with hash suffix (`[a-z0-9_]`, max 63 chars) |
| `hash_port` | `{{ branch \| hash_port }}` | Hash to port 10000-19999 |
-The `sanitize` filter makes branch names safe for filesystem paths. The `hash_port` filter is useful for running dev servers on unique ports per worktree:
+The `sanitize` filter makes branch names safe for filesystem paths. The `sanitize_db` filter produces database-safe identifiers (lowercase alphanumeric and underscores, no leading digits, with a 3-character hash suffix to avoid collisions and reserved words). The `hash_port` filter is useful for running dev servers on unique ports per worktree:
```toml
[post-start]
@@ -244,7 +245,7 @@ db = """
docker run -d --rm \
--name {{ repo }}-{{ branch | sanitize }}-postgres \
-p {{ ('db-' ~ branch) | hash_port }}:5432 \
- -e POSTGRES_DB={{ repo }} \
+ -e POSTGRES_DB={{ branch | sanitize_db }} \
-e POSTGRES_PASSWORD=dev \
postgres:16
"""
@@ -262,7 +263,7 @@ Generate `.env.local` with the connection string:
[post-create]
env = """
cat > .env.local << EOF
-DATABASE_URL=postgres://postgres:dev@localhost:{{ ('db-' ~ branch) | hash_port }}/{{ repo }}
+DATABASE_URL=postgres://postgres:dev@localhost:{{ ('db-' ~ branch) | hash_port }}/{{ branch | sanitize_db }}
DEV_PORT={{ branch | hash_port }}
EOF
"""
diff --git a/.claude-plugin/skills/worktrunk/reference/tips-patterns.md b/.claude-plugin/skills/worktrunk/reference/tips-patterns.md
index c91e979a8..2677fdde5 100644
--- a/.claude-plugin/skills/worktrunk/reference/tips-patterns.md
+++ b/.claude-plugin/skills/worktrunk/reference/tips-patterns.md
@@ -78,7 +78,7 @@ db = """
docker run -d --rm \
--name {{ repo }}-{{ branch | sanitize }}-postgres \
-p {{ ('db-' ~ branch) | hash_port }}:5432 \
- -e POSTGRES_DB={{ repo }} \
+ -e POSTGRES_DB={{ branch | sanitize_db }} \
-e POSTGRES_PASSWORD=dev \
postgres:16
"""
@@ -90,13 +90,15 @@ db-stop = "docker stop {{ repo }}-{{ branch | sanitize }}-postgres 2>/dev/null |
The `('db-' ~ branch)` concatenation hashes differently than plain `branch`, so database and dev server ports don't collide.
Jinja2's operator precedence has pipe `|` with higher precedence than concatenation `~`, meaning expressions need parentheses to filter concatenated values.
+The `sanitize_db` filter produces database-safe identifiers (lowercase, underscores, no leading digits, with a short hash suffix to avoid collisions and SQL reserved words).
+
Generate `.env.local` with the correct `DATABASE_URL` using a `post-create` hook:
```toml
[post-create]
env = """
cat > .env.local << EOF
-DATABASE_URL=postgres://postgres:dev@localhost:{{ ('db-' ~ branch) | hash_port }}/{{ repo }}
+DATABASE_URL=postgres://postgres:dev@localhost:{{ ('db-' ~ branch) | hash_port }}/{{ branch | sanitize_db }}
DEV_PORT={{ branch | hash_port }}
EOF
"""
diff --git a/dev/config.example.toml b/dev/config.example.toml
index fbaf9713e..324429ed3 100644
--- a/dev/config.example.toml
+++ b/dev/config.example.toml
@@ -30,9 +30,10 @@
# Worktree Path Template
# Variables:
-# {{ repo }} - Repository directory name (e.g., "myproject")
-# {{ branch }} - Raw branch name (e.g., "feature/auth")
-# {{ branch | sanitize }} - Branch name with / and \ replaced by - (e.g., "feature-auth")
+# {{ repo }} - Repository directory name (e.g., "myproject")
+# {{ branch }} - Raw branch name (e.g., "feature/auth")
+# {{ branch | sanitize }} - Filesystem-safe: / and \ replaced by - (e.g., "feature-auth")
+# {{ branch | sanitize_db }} - Database-safe: lowercase, underscores, hash suffix (e.g., "feature_auth_x7k")
#
# Paths are relative to the main worktree root (original repository directory).
#
diff --git a/dev/wt.example.toml b/dev/wt.example.toml
index 6302d57c9..45977a0d5 100644
--- a/dev/wt.example.toml
+++ b/dev/wt.example.toml
@@ -33,8 +33,9 @@
# {{ target }} - Target branch for the merge
#
# Filters:
-# {{ branch | sanitize }} - Replace / and \ with - (e.g., "feature-auth")
-# {{ branch | hash_port }} - Deterministic port 10000-19999
+# {{ branch | sanitize }} - Replace / and \ with - (e.g., "feature-auth")
+# {{ branch | sanitize_db }} - Database-safe identifier with hash suffix (e.g., "feature_auth_x7k")
+# {{ branch | hash_port }} - Deterministic port 10000-19999
# ============================================================================
# Hooks
diff --git a/docs/content/config.md b/docs/content/config.md
index 3f6b12ca0..31cd54b03 100644
--- a/docs/content/config.md
+++ b/docs/content/config.md
@@ -174,7 +174,7 @@ The `[list]` section adds a URL column to `wt list`:
url = "http://localhost:{{ branch | hash_port }}"
```
-URLs are dimmed when the port isn't listening. The template supports `{{ branch }}` with filters `hash_port` (port 10000-19999) and `sanitize` (filesystem-safe).
+URLs are dimmed when the port isn't listening.
### CI platform override
@@ -339,9 +339,10 @@ Creates `~/.config/worktrunk/config.toml` with the following content:
# Worktree Path Template
# Variables:
-# {{ repo }} - Repository directory name (e.g., "myproject")
-# {{ branch }} - Raw branch name (e.g., "feature/auth")
-# {{ branch | sanitize }} - Branch name with / and \ replaced by - (e.g., "feature-auth")
+# {{ repo }} - Repository directory name (e.g., "myproject")
+# {{ branch }} - Raw branch name (e.g., "feature/auth")
+# {{ branch | sanitize }} - Filesystem-safe: / and \ replaced by - (e.g., "feature-auth")
+# {{ branch | sanitize_db }} - Database-safe: lowercase, underscores, hash suffix (e.g., "feature_auth_x7k")
#
# Paths are relative to the main worktree root (original repository directory).
#
@@ -545,8 +546,9 @@ With `--project`, creates `.config/wt.toml` in the current repository:
# {{ target }} - Target branch for the merge
#
# Filters:
-# {{ branch | sanitize }} - Replace / and \ with - (e.g., "feature-auth")
-# {{ branch | hash_port }} - Deterministic port 10000-19999
+# {{ branch | sanitize }} - Replace / and \ with - (e.g., "feature-auth")
+# {{ branch | sanitize_db }} - Database-safe identifier with hash suffix (e.g., "feature_auth_x7k")
+# {{ branch | hash_port }} - Deterministic port 10000-19999
# ============================================================================
# Hooks
diff --git a/docs/content/hook.md b/docs/content/hook.md
index e45e58a5d..19ca55640 100644
--- a/docs/content/hook.md
+++ b/docs/content/hook.md
@@ -167,9 +167,10 @@ Templates support Jinja2 filters for transforming values:
| Filter | Example | Description |
|--------|---------|-------------|
| `sanitize` | `{{ branch \| sanitize }}` | Replace `/` and `\` with `-` |
+| `sanitize_db` | `{{ branch \| sanitize_db }}` | Database-safe identifier with hash suffix (`[a-z0-9_]`, max 63 chars) |
| `hash_port` | `{{ branch \| hash_port }}` | Hash to port 10000-19999 |
-The `sanitize` filter makes branch names safe for filesystem paths. The `hash_port` filter is useful for running dev servers on unique ports per worktree:
+The `sanitize` filter makes branch names safe for filesystem paths. The `sanitize_db` filter produces database-safe identifiers (lowercase alphanumeric and underscores, no leading digits, with a 3-character hash suffix to avoid collisions and reserved words). The `hash_port` filter is useful for running dev servers on unique ports per worktree:
```toml
[post-start]
@@ -252,7 +253,7 @@ db = """
docker run -d --rm \
--name {{ repo }}-{{ branch | sanitize }}-postgres \
-p {{ ('db-' ~ branch) | hash_port }}:5432 \
- -e POSTGRES_DB={{ repo }} \
+ -e POSTGRES_DB={{ branch | sanitize_db }} \
-e POSTGRES_PASSWORD=dev \
postgres:16
"""
@@ -270,7 +271,7 @@ Generate `.env.local` with the connection string:
[post-create]
env = """
cat > .env.local << EOF
-DATABASE_URL=postgres://postgres:dev@localhost:{{ ('db-' ~ branch) | hash_port }}/{{ repo }}
+DATABASE_URL=postgres://postgres:dev@localhost:{{ ('db-' ~ branch) | hash_port }}/{{ branch | sanitize_db }}
DEV_PORT={{ branch | hash_port }}
EOF
"""
diff --git a/docs/content/tips-patterns.md b/docs/content/tips-patterns.md
index 988a47387..941912134 100644
--- a/docs/content/tips-patterns.md
+++ b/docs/content/tips-patterns.md
@@ -90,7 +90,7 @@ db = """
docker run -d --rm \
--name {{ repo }}-{{ branch | sanitize }}-postgres \
-p {{ ('db-' ~ branch) | hash_port }}:5432 \
- -e POSTGRES_DB={{ repo }} \
+ -e POSTGRES_DB={{ branch | sanitize_db }} \
-e POSTGRES_PASSWORD=dev \
postgres:16
"""
@@ -102,13 +102,15 @@ db-stop = "docker stop {{ repo }}-{{ branch | sanitize }}-postgres 2>/dev/null |
The `('db-' ~ branch)` concatenation hashes differently than plain `branch`, so database and dev server ports don't collide.
Jinja2's operator precedence has pipe `|` with higher precedence than concatenation `~`, meaning expressions need parentheses to filter concatenated values.
+The `sanitize_db` filter produces database-safe identifiers (lowercase, underscores, no leading digits, with a short hash suffix to avoid collisions and SQL reserved words).
+
Generate `.env.local` with the correct `DATABASE_URL` using a `post-create` hook:
```toml
[post-create]
env = """
cat > .env.local << EOF
-DATABASE_URL=postgres://postgres:dev@localhost:{{ ('db-' ~ branch) | hash_port }}/{{ repo }}
+DATABASE_URL=postgres://postgres:dev@localhost:{{ ('db-' ~ branch) | hash_port }}/{{ branch | sanitize_db }}
DEV_PORT={{ branch | hash_port }}
EOF
"""
diff --git a/src/cli/mod.rs b/src/cli/mod.rs
index 65af569e6..66c4fdc5c 100644
--- a/src/cli/mod.rs
+++ b/src/cli/mod.rs
@@ -1151,9 +1151,10 @@ Templates support Jinja2 filters for transforming values:
| Filter | Example | Description |
|--------|---------|-------------|
| `sanitize` | `{{ branch \| sanitize }}` | Replace `/` and `\` with `-` |
+| `sanitize_db` | `{{ branch \| sanitize_db }}` | Database-safe identifier with hash suffix (`[a-z0-9_]`, max 63 chars) |
| `hash_port` | `{{ branch \| hash_port }}` | Hash to port 10000-19999 |
-The `sanitize` filter makes branch names safe for filesystem paths. The `hash_port` filter is useful for running dev servers on unique ports per worktree:
+The `sanitize` filter makes branch names safe for filesystem paths. The `sanitize_db` filter produces database-safe identifiers (lowercase alphanumeric and underscores, no leading digits, with a 3-character hash suffix to avoid collisions and reserved words). The `hash_port` filter is useful for running dev servers on unique ports per worktree:
```toml
[post-start]
@@ -1236,7 +1237,7 @@ db = """
docker run -d --rm \
--name {{ repo }}-{{ branch | sanitize }}-postgres \
-p {{ ('db-' ~ branch) | hash_port }}:5432 \
- -e POSTGRES_DB={{ repo }} \
+ -e POSTGRES_DB={{ branch | sanitize_db }} \
-e POSTGRES_PASSWORD=dev \
postgres:16
"""
@@ -1254,7 +1255,7 @@ Generate `.env.local` with the connection string:
[post-create]
env = """
cat > .env.local << EOF
-DATABASE_URL=postgres://postgres:dev@localhost:{{ ('db-' ~ branch) | hash_port }}/{{ repo }}
+DATABASE_URL=postgres://postgres:dev@localhost:{{ ('db-' ~ branch) | hash_port }}/{{ branch | sanitize_db }}
DEV_PORT={{ branch | hash_port }}
EOF
"""
@@ -1577,7 +1578,7 @@ The `[list]` section adds a URL column to `wt list`:
url = "http://localhost:{{ branch | hash_port }}"
```
-URLs are dimmed when the port isn't listening. The template supports `{{ branch }}` with filters `hash_port` (port 10000-19999) and `sanitize` (filesystem-safe).
+URLs are dimmed when the port isn't listening.
### CI platform override
diff --git a/src/config/expansion.rs b/src/config/expansion.rs
index 370a7d55a..7ac9482ad 100644
--- a/src/config/expansion.rs
+++ b/src/config/expansion.rs
@@ -13,6 +13,11 @@
//! {{ branch | sanitize }} → feature-foo
//! ```
//!
+//! - `sanitize_db` — Transform to database-safe identifier (`[a-z0-9_]`, max 63 chars)
+//! ```text
+//! {{ branch | sanitize_db }} → feature_auth_oauth2
+//! ```
+//!
//! - `hash_port` — Hash a string to a deterministic port number (10000-19999)
//! ```text
//! {{ branch | hash_port }} → 12472
@@ -78,6 +83,94 @@ pub fn sanitize_branch_name(branch: &str) -> String {
branch.replace(['/', '\\'], "-")
}
+/// Sanitize a string for use as a database identifier.
+///
+/// Transforms input into an identifier compatible with most SQL databases
+/// (PostgreSQL, MySQL, SQL Server). The transformation is more aggressive than
+/// `sanitize_branch_name` to ensure compatibility with database identifier rules.
+///
+/// # Transformation Rules (applied in order)
+/// 1. Convert to lowercase (ensures portability across case-sensitive systems)
+/// 2. Replace non-alphanumeric characters with `_` (only `[a-z0-9_]` are safe)
+/// 3. Collapse consecutive underscores into single underscore
+/// 4. Add `_` prefix if identifier starts with a digit (SQL prohibits leading digits)
+/// 5. Append 3-character hash suffix for uniqueness (avoids reserved words and collisions)
+/// 6. Truncate to 63 characters (PostgreSQL limit; MySQL=64, SQL Server=128)
+///
+/// The hash suffix ensures that:
+/// - SQL reserved words are avoided (e.g., `user` → `user_abc`, not a reserved word)
+/// - Different inputs don't collide (e.g., `a-b` and `a_b` get different suffixes)
+///
+/// # Limitations
+/// - Empty input produces empty output (not a valid identifier in most DBs)
+///
+/// # Examples
+/// ```
+/// use worktrunk::config::sanitize_db;
+///
+/// // Hash suffix ensures uniqueness
+/// assert!(sanitize_db("feature/auth").starts_with("feature_auth_"));
+/// assert!(sanitize_db("123-bug-fix").starts_with("_123_bug_fix_"));
+/// assert!(sanitize_db("UPPERCASE.Branch").starts_with("uppercase_branch_"));
+///
+/// // Different inputs get different suffixes even if base transforms are identical
+/// assert_ne!(sanitize_db("a-b"), sanitize_db("a_b"));
+/// ```
+pub fn sanitize_db(s: &str) -> String {
+ if s.is_empty() {
+ return String::new();
+ }
+
+ // Single pass: lowercase, replace non-alphanumeric with underscore, collapse consecutive
+ let mut result = String::with_capacity(s.len() + 4); // +4 for _xxx suffix
+ let mut prev_underscore = false;
+ for c in s.chars() {
+ if c.is_ascii_alphanumeric() {
+ result.push(c.to_ascii_lowercase());
+ prev_underscore = false;
+ } else if !prev_underscore {
+ result.push('_');
+ prev_underscore = true;
+ }
+ }
+
+ // Prefix with underscore if starts with digit
+ if result.starts_with(|c: char| c.is_ascii_digit()) {
+ result.insert(0, '_');
+ }
+
+ // Truncate base to leave room for hash suffix (4 chars: _ + 3 hash chars)
+ // PostgreSQL limit is 63, so max base is 59
+ if result.len() > 59 {
+ result.truncate(59);
+ }
+
+ // Append 3-character hash suffix for collision avoidance and reserved word safety
+ // Hash is computed from original input, ensuring unique suffixes for colliding transforms
+ if !result.ends_with('_') {
+ result.push('_');
+ }
+ result.push_str(&short_hash(s));
+
+ result
+}
+
+/// Generate a 3-character hash suffix from a string.
+///
+/// Uses base36 (0-9, a-z) for a compact representation with 46,656 unique values.
+fn short_hash(s: &str) -> String {
+ let mut h = std::collections::hash_map::DefaultHasher::new();
+ s.hash(&mut h);
+ let hash = h.finish();
+
+ // Convert to base36 and take 3 characters
+ const CHARS: &[u8] = b"0123456789abcdefghijklmnopqrstuvwxyz";
+ let c0 = CHARS[(hash % 36) as usize];
+ let c1 = CHARS[((hash / 36) % 36) as usize];
+ let c2 = CHARS[((hash / 1296) % 36) as usize];
+ String::from_utf8(vec![c0, c1, c2]).unwrap()
+}
+
/// Expand a template with variable substitution.
///
/// # Arguments
@@ -87,9 +180,9 @@ pub fn sanitize_branch_name(branch: &str) -> String {
/// If false, substitute values literally (for filesystem paths).
///
/// # Filters
-/// The `sanitize` filter is available for branch names, replacing `/` and `\` with `-`:
-/// - `{{ branch }}` — raw branch name (e.g., `feature/foo`)
-/// - `{{ branch | sanitize }}` — sanitized for paths (e.g., `feature-foo`)
+/// - `sanitize` — Replace `/` and `\` with `-` for filesystem-safe paths
+/// - `sanitize_db` — Transform to database-safe identifier (`[a-z0-9_]`, max 63 chars)
+/// - `hash_port` — Hash to deterministic port number (10000-19999)
///
/// # Examples
/// ```
@@ -140,6 +233,9 @@ pub fn expand_template(
env.add_filter("sanitize", |value: Value| -> String {
sanitize_branch_name(value.as_str().unwrap_or_default())
});
+ env.add_filter("sanitize_db", |value: Value| -> String {
+ sanitize_db(value.as_str().unwrap_or_default())
+ });
env.add_filter("hash_port", |value: String| string_to_port(&value));
let tmpl = env
@@ -172,6 +268,117 @@ mod tests {
}
}
+ #[test]
+ fn test_sanitize_db() {
+ // Test that base transformations are correct (ignore hash suffix)
+ let cases = [
+ // Examples from spec
+ ("feature/auth-oauth2", "feature_auth_oauth2_"),
+ ("123-bug-fix", "_123_bug_fix_"),
+ ("UPPERCASE.Branch", "uppercase_branch_"),
+ // Lowercase conversion
+ ("MyBranch", "mybranch_"),
+ ("ALLCAPS", "allcaps_"),
+ // Non-alphanumeric replacement
+ ("feature/foo", "feature_foo_"),
+ ("feature-bar", "feature_bar_"),
+ ("feature.baz", "feature_baz_"),
+ ("feature@qux", "feature_qux_"),
+ // Consecutive underscore collapse
+ ("a--b", "a_b_"),
+ ("a///b", "a_b_"),
+ ("a...b", "a_b_"),
+ ("a-/-b", "a_b_"),
+ // Leading digit prefix
+ ("1branch", "_1branch_"),
+ ("123", "_123_"),
+ ("0test", "_0test_"),
+ // No prefix needed
+ ("branch1", "branch1_"),
+ ("_already", "_already_"),
+ // Edge cases (non-empty)
+ ("a", "a_"),
+ // Mixed cases
+ ("Feature/Auth-OAuth2", "feature_auth_oauth2_"),
+ ("user/TASK/123", "user_task_123_"),
+ // Non-ASCII characters become underscores
+ ("naïve-impl", "na_ve_impl_"),
+ ("über-feature", "_ber_feature_"),
+ ];
+ for (input, expected_prefix) in cases {
+ let result = sanitize_db(input);
+ assert!(
+ result.starts_with(expected_prefix),
+ "input: {input}, expected prefix: {expected_prefix}, got: {result}"
+ );
+ // Result should be prefix + 3-char hash
+ assert_eq!(
+ result.len(),
+ expected_prefix.len() + 3,
+ "input: {input}, result: {result}"
+ );
+ }
+
+ // Empty input stays empty (no hash suffix)
+ assert_eq!(sanitize_db(""), "");
+
+ // Special cases that collapse to just underscore + hash
+ for input in ["_", "-", "---", "日本語"] {
+ let result = sanitize_db(input);
+ assert!(result.starts_with('_'), "input: {input}, got: {result}");
+ assert_eq!(result.len(), 4, "input: {input}, got: {result}"); // _xxx
+ }
+ }
+
+ #[test]
+ fn test_sanitize_db_collision_avoidance() {
+ // Different inputs that would collide without hash suffix now differ
+ assert_ne!(sanitize_db("a-b"), sanitize_db("a_b"));
+ assert_ne!(sanitize_db("feature/auth"), sanitize_db("feature-auth"));
+ assert_ne!(sanitize_db("UPPERCASE"), sanitize_db("uppercase"));
+
+ // Same input always produces same output (deterministic)
+ assert_eq!(sanitize_db("test"), sanitize_db("test"));
+ assert_eq!(sanitize_db("feature/foo"), sanitize_db("feature/foo"));
+ }
+
+ #[test]
+ fn test_sanitize_db_reserved_words() {
+ // Reserved words get hash suffix, making them safe
+ let user = sanitize_db("user");
+ assert!(user.starts_with("user_"), "got: {user}");
+ assert_ne!(user, "user"); // Not a bare reserved word
+
+ let select = sanitize_db("select");
+ assert!(select.starts_with("select_"), "got: {select}");
+ assert_ne!(select, "select");
+ }
+
+ #[test]
+ fn test_sanitize_db_truncation() {
+ // Total output is always max 63 characters
+ // Base is truncated to 59 chars, then _xxx suffix (4 chars) is added
+
+ // Very long input: base truncated to 59, + 4 = 63
+ let long_input = "a".repeat(100);
+ let result = sanitize_db(&long_input);
+ assert_eq!(result.len(), 63, "result: {result}");
+ assert!(result.starts_with(&"a".repeat(58)), "result: {result}");
+ assert!(!result.ends_with('_'), "should end with hash chars");
+
+ // Short input: base + _ + hash
+ let short = "test";
+ let result = sanitize_db(short);
+ assert!(result.starts_with("test_"), "result: {result}");
+ assert_eq!(result.len(), 8, "result: {result}"); // test_ + 3 hash chars
+
+ // Truncation happens after prefix is added for digit-starting inputs
+ let digit_start = format!("1{}", "x".repeat(100));
+ let result = sanitize_db(&digit_start);
+ assert_eq!(result.len(), 63, "result: {result}");
+ assert!(result.starts_with("_1"), "result: {result}");
+ }
+
#[test]
fn test_expand_template_basic() {
// Single variable
@@ -292,6 +499,33 @@ mod tests {
);
}
+ #[test]
+ fn test_expand_template_sanitize_db_filter() {
+ let mut vars = HashMap::new();
+
+ // Basic transformation (with hash suffix)
+ vars.insert("branch", "feature/auth-oauth2");
+ let result = expand_template("{{ branch | sanitize_db }}", &vars, false).unwrap();
+ assert!(result.starts_with("feature_auth_oauth2_"), "got: {result}");
+
+ // Leading digit gets underscore prefix
+ vars.insert("branch", "123-bug-fix");
+ let result = expand_template("{{ branch | sanitize_db }}", &vars, false).unwrap();
+ assert!(result.starts_with("_123_bug_fix_"), "got: {result}");
+
+ // Uppercase conversion
+ vars.insert("branch", "UPPERCASE.Branch");
+ let result = expand_template("{{ branch | sanitize_db }}", &vars, false).unwrap();
+ assert!(result.starts_with("uppercase_branch_"), "got: {result}");
+
+ // Raw branch is unchanged
+ vars.insert("branch", "feature/foo");
+ assert_eq!(
+ expand_template("{{ branch }}", &vars, false).unwrap(),
+ "feature/foo"
+ );
+ }
+
#[test]
fn test_expand_template_trailing_newline() {
let mut vars = HashMap::new();
diff --git a/src/config/mod.rs b/src/config/mod.rs
index ec2475645..e9c52ef6e 100644
--- a/src/config/mod.rs
+++ b/src/config/mod.rs
@@ -29,7 +29,7 @@ pub use commands::{Command, CommandConfig};
pub use deprecation::check_and_migrate as check_deprecated_vars;
pub use deprecation::normalize_template_vars;
pub use expansion::{
- DEPRECATED_TEMPLATE_VARS, TEMPLATE_VARS, expand_template, sanitize_branch_name,
+ DEPRECATED_TEMPLATE_VARS, TEMPLATE_VARS, expand_template, sanitize_branch_name, sanitize_db,
};
pub use hooks::HooksConfig;
pub use project::{
diff --git a/tests/integration_tests/doc_templates.rs b/tests/integration_tests/doc_templates.rs
index e1bd6c70b..64d20cb5e 100644
--- a/tests/integration_tests/doc_templates.rs
+++ b/tests/integration_tests/doc_templates.rs
@@ -83,6 +83,74 @@ fn test_doc_sanitize_filter() {
);
}
+// =============================================================================
+// Sanitize DB Filter (docs/content/hook.md: Filters table)
+// "Transform to database-safe identifier ([a-z0-9_], max 63 chars)"
+// =============================================================================
+
+#[test]
+fn test_doc_sanitize_db_filter() {
+ let mut vars = HashMap::new();
+
+ // From docs: {{ branch | sanitize_db }} transforms to database-safe identifier
+ // Output includes a 3-character hash suffix for uniqueness
+ vars.insert("branch", "feature/auth-oauth2");
+ let result = expand_template("{{ branch | sanitize_db }}", &vars, false).unwrap();
+ assert!(
+ result.starts_with("feature_auth_oauth2_"),
+ "sanitize_db should replace non-alphanumeric with _ and lowercase, got: {result}"
+ );
+
+ // Leading digits get underscore prefix
+ vars.insert("branch", "123-bug-fix");
+ let result = expand_template("{{ branch | sanitize_db }}", &vars, false).unwrap();
+ assert!(
+ result.starts_with("_123_bug_fix_"),
+ "sanitize_db should prefix leading digits with _, got: {result}"
+ );
+
+ // Uppercase conversion
+ vars.insert("branch", "UPPERCASE.Branch");
+ let result = expand_template("{{ branch | sanitize_db }}", &vars, false).unwrap();
+ assert!(
+ result.starts_with("uppercase_branch_"),
+ "sanitize_db should convert to lowercase, got: {result}"
+ );
+
+ // Consecutive underscores collapsed
+ vars.insert("branch", "a--b//c");
+ let result = expand_template("{{ branch | sanitize_db }}", &vars, false).unwrap();
+ assert!(
+ result.starts_with("a_b_c_"),
+ "sanitize_db should collapse consecutive underscores, got: {result}"
+ );
+
+ // Different inputs that would otherwise collide get different suffixes
+ vars.insert("branch", "a-b");
+ let result1 = expand_template("{{ branch | sanitize_db }}", &vars, false).unwrap();
+ vars.insert("branch", "a_b");
+ let result2 = expand_template("{{ branch | sanitize_db }}", &vars, false).unwrap();
+ assert_ne!(
+ result1, result2,
+ "a-b and a_b should produce different outputs"
+ );
+}
+
+#[test]
+fn test_doc_sanitize_db_truncation() {
+ let mut vars = HashMap::new();
+
+ // Truncates to 63 characters (PostgreSQL limit)
+ let long_branch = "a".repeat(100);
+ vars.insert("branch", long_branch.as_str());
+ let result = expand_template("{{ branch | sanitize_db }}", &vars, false).unwrap();
+ assert_eq!(
+ result.len(),
+ 63,
+ "sanitize_db should truncate to 63 characters"
+ );
+}
+
// =============================================================================
// Hash Port Filter (docs/content/hook.md: Filters table)
// "Hash to port 10000-19999"
diff --git a/tests/snapshots/integration__integration_tests__help__help_config_create.snap b/tests/snapshots/integration__integration_tests__help__help_config_create.snap
index a71c1bd63..a6974020c 100644
--- a/tests/snapshots/integration__integration_tests__help__help_config_create.snap
+++ b/tests/snapshots/integration__integration_tests__help__help_config_create.snap
@@ -8,7 +8,7 @@ info:
- "--help"
env:
CLICOLOR_FORCE: "1"
- COLUMNS: "150"
+ COLUMNS: "500"
GIT_EDITOR: ""
RUST_LOG: warn
SOURCE_DATE_EPOCH: "1735776000"
@@ -78,9 +78,10 @@ Creates ~/.config/worktrunk/config.toml with the following content:

# Worktree Path Template
# Variables:
- # {{ repo }} - Repository directory name (e.g., "myproject")
- # {{ branch }} - Raw branch name (e.g., "feature/auth")
- # {{ branch | sanitize }} - Branch name with / and \ replaced by - (e.g., "feature-auth")
+ # {{ repo }} - Repository directory name (e.g., "myproject")
+ # {{ branch }} - Raw branch name (e.g., "feature/auth")
+ # {{ branch | sanitize }} - Filesystem-safe: / and \ replaced by - (e.g., "feature-auth")
+ # {{ branch | sanitize_db }} - Database-safe: lowercase, underscores, hash suffix (e.g., "feature_auth_x7k")
#
# Paths are relative to the main worktree root (original repository directory).
#
@@ -282,8 +283,9 @@ With --project, creates .config/wt.toml in the current repositor
# {{ target }} - Target branch for the merge
#
# Filters:
- # {{ branch | sanitize }} - Replace / and \ with - (e.g., "feature-auth")
- # {{ branch | hash_port }} - Deterministic port 10000-19999
+ # {{ branch | sanitize }} - Replace / and \ with - (e.g., "feature-auth")
+ # {{ branch | sanitize_db }} - Database-safe identifier with hash suffix (e.g., "feature_auth_x7k")
+ # {{ branch | hash_port }} - Deterministic port 10000-19999

# ============================================================================
# Hooks
diff --git a/tests/snapshots/integration__integration_tests__help__help_config_long.snap b/tests/snapshots/integration__integration_tests__help__help_config_long.snap
index 2a4576342..31050c640 100644
--- a/tests/snapshots/integration__integration_tests__help__help_config_long.snap
+++ b/tests/snapshots/integration__integration_tests__help__help_config_long.snap
@@ -184,7 +184,7 @@ The [list] section adds a URL column to wt list:
[list]
url = "http://localhost:{{ branch | hash_port }}"
-URLs are dimmed when the port isn't listening. The template supports {{ branch }} with filters hash_port (port 10000-19999) and sanitize (filesystem-safe).
+URLs are dimmed when the port isn't listening.
CI platform override