Goose Database Migration - SSH Tunnels and Team Collaboration Guide

October 10, 2025

Goose Database Migration: SSH Tunnels and Team Collaboration Guide

This guide covers two essential topics for production database migrations with Goose:

  1. Connecting to remote databases via SSH tunnels
  2. Managing migration conflicts in team environments

Part 1: SSH Tunnel Connection for Remote Database Migrations

The Problem

Goose doesn't have built-in SSH tunnel support. When your database is in a VPC accessible only through a bastion/jump host (VPS), you need to establish an SSH tunnel first.

Architecture Overview

Local Machine (goose) โ†’ SSH Tunnel โ†’ VPS (Bastion) โ†’ VPC โ†’ Database Server

Step-by-Step Setup

1. Set Correct Private Key Permissions

SSH requires strict permissions on private key files:

chmod 600 /path/to/your/private-key.pem

If permissions are too open (e.g., 0644), SSH will refuse to use the key.

2. Establish SSH Tunnel

ssh -N -L <local_port>:<db_private_ip>:<db_port> <ssh_user>@<vps_public_ip> -i /path/to/private-key.pem

Parameters:

  • -N: Don't execute remote commands (tunnel only)
  • -L: Local port forwarding
  • <local_port>: Port on your local machine (e.g., 5432)
  • <db_private_ip>: Database's private IP within VPC (e.g., 10.0.0.5)
  • <db_port>: Database port (e.g., 5432 for PostgreSQL)

Example:

ssh -N -L 5432:10.0.0.5:5432 user@vps.example.com -i ~/.ssh/server-key.pem

Keep this terminal window open while running migrations.

3. Run Goose Migration

In a new terminal, connect to 127.0.0.1 using your local port:

# PostgreSQL
goose postgres "host=127.0.0.1 port=5432 user=db_user password=db_pass dbname=mydb sslmode=disable" up

# MySQL
goose mysql "db_user:db_pass@tcp(127.0.0.1:3306)/mydb" up

Handling Special Characters in Passwords

If your password contains special characters (@, $, #, :, /, ?, &), they may cause connection failures.

Wrap the entire DSN in single quotes to prevent shell interpretation:

goose postgres 'host=127.0.0.1 port=5432 user=dbuser password=Secret$P@ss dbname=mydb sslmode=disable' up

Solution 2: Use Key-Value Format

More resilient to special characters:

goose postgres "host=127.0.0.1 port=5432 user=dbuser password='Secret$P@ss' dbname=mydb sslmode=disable" up

Solution 3: URL Encode Special Characters

CharacterEncoded
@%40
$%24
#%23
:%3A
/%2F
?%3F
&%26

Note: URL encoding may not work with all PostgreSQL drivers. Try single quotes first.

Using ssh-agent (For Frequent Operations)

# Start ssh-agent
eval "$(ssh-agent -s)"

# Add your key
ssh-add /path/to/private-key.pem

# Now connect without -i flag
ssh -N -L 5432:10.0.0.5:5432 user@vps.example.com

Part 2: Managing Migration Conflicts in Team Environments

The Core Problem

When multiple developers create migrations simultaneously, conflicts can occur:

  • Filename conflicts: Two migrations with the same version number
  • Logical conflicts: Two migrations modifying the same database objects

Prevention: Use Timestamp Naming

Goose supports two naming schemes:

SchemeExampleConflict Risk
Sequential00001_initial.sqlHigh
Timestamp20251224103859_add_users.sqlLow

Always use timestamps - they're virtually guaranteed to be unique.

Best Practices: Safely Modifying the Same Table

When multiple developers need to modify the same table simultaneously, follow these practices to avoid conflicts:

1. Additive-Only Changes

Core principle: Migrations should only add new content, avoid modifying or deleting existing structures.

-- โœ… Good: Adding new columns
ALTER TABLE users ADD COLUMN phone VARCHAR(20);
ALTER TABLE users ADD COLUMN avatar_url TEXT;

-- โŒ Avoid: Renaming columns (breaks other migrations)
ALTER TABLE users RENAME COLUMN email TO user_email;

-- โŒ Avoid: Changing column types
ALTER TABLE users ALTER COLUMN name TYPE TEXT;

2. Separate Migration Responsibilities

If two features both need to modify the users table:

DeveloperFeatureMigration Content
AliceAuthenticationAdd last_login, login_attempts
BobUser ProfileAdd avatar_url, bio

Both migrations are independent and can be applied in any order.

3. Use Defensive SQL (IF NOT EXISTS / IF EXISTS)

Defensive SQL prevents errors from duplicate operations:

-- PostgreSQL: Add column only if it doesn't exist
ALTER TABLE users ADD COLUMN IF NOT EXISTS phone VARCHAR(20);

-- Create index safely
CREATE INDEX IF NOT EXISTS idx_users_email ON users(email);

-- Drop with existence check
ALTER TABLE users DROP COLUMN IF EXISTS deprecated_field;

4. Avoid Long-Running Table Locks

Large operations should be split into smaller steps:

-- โŒ Dangerous: Long table lock
ALTER TABLE large_table ADD COLUMN status VARCHAR(20) DEFAULT 'active';

-- โœ… Safer: Execute in steps
-- Migration 1: Add column (no default, instant)
ALTER TABLE large_table ADD COLUMN status VARCHAR(20);

-- Migration 2: Batch update (can be done in batches)
UPDATE large_table SET status = 'active' WHERE status IS NULL;

-- Migration 3: Set default and constraints
ALTER TABLE large_table ALTER COLUMN status SET DEFAULT 'active';
ALTER TABLE large_table ALTER COLUMN status SET NOT NULL;

5. Use Naming Conventions/Namespaces

Teams can agree on column name prefixes to avoid naming conflicts:

-- Authentication module
ALTER TABLE users ADD COLUMN auth_last_login TIMESTAMP;
ALTER TABLE users ADD COLUMN auth_token_expires TIMESTAMP;

-- Profile module
ALTER TABLE users ADD COLUMN profile_avatar_url TEXT;
ALTER TABLE users ADD COLUMN profile_bio TEXT;

6. Decision Tree: When to Coordinate?

Does your migration modify an existing table?
โ”œโ”€โ”€ No (new table) โ†’ No coordination needed
โ””โ”€โ”€ Yes โ†’ Is it only adding new columns?
    โ”œโ”€โ”€ Yes (ADD COLUMN) โ†’ Low risk, proceed normally
    โ””โ”€โ”€ No โ†’ Are you modifying/deleting existing columns?
        โ”œโ”€โ”€ Yes โ†’ โš ๏ธ Must coordinate with team
        โ””โ”€โ”€ No (adding indexes only) โ†’ Medium risk, check table performance dependencies

Feature Flags and Gradual Rollout for Schema Changes

When you need to make breaking changes (rename columns, change types, remove columns), use feature flags to enable safe, gradual migration.

The Expand-Contract Pattern

This is the safest approach for breaking schema changes:

Phase 1: EXPAND   - Add new structure, keep old
Phase 2: MIGRATE  - Gradually move data/traffic to new structure
Phase 3: CONTRACT - Remove old structure when safe

Complete Example: Renaming a Column

Scenario: Rename users.email to users.primary_email

Phase 1: Expand (Migration 1)

-- Add new column, keep old one
ALTER TABLE users ADD COLUMN primary_email VARCHAR(255);

-- Copy existing data
UPDATE users SET primary_email = email WHERE primary_email IS NULL;

-- Add trigger to keep columns in sync during transition
CREATE OR REPLACE FUNCTION sync_email_columns()
RETURNS TRIGGER AS $$
BEGIN
    IF TG_OP = 'INSERT' OR TG_OP = 'UPDATE' THEN
        IF NEW.primary_email IS NULL AND NEW.email IS NOT NULL THEN
            NEW.primary_email := NEW.email;
        ELSIF NEW.email IS NULL AND NEW.primary_email IS NOT NULL THEN
            NEW.email := NEW.primary_email;
        END IF;
    END IF;
    RETURN NEW;
END;
$$ LANGUAGE plpgsql;

CREATE TRIGGER trg_sync_email
    BEFORE INSERT OR UPDATE ON users
    FOR EACH ROW EXECUTE FUNCTION sync_email_columns();

Phase 2: Migrate (Application Code with Feature Flag)

// Feature flag controls which column to use
func GetUserEmail(user *User) string {
    if featureflags.IsEnabled("use_primary_email") {
        return user.PrimaryEmail
    }
    return user.Email
}

// Writes go to both columns during transition
func SetUserEmail(user *User, email string) {
    user.Email = email
    user.PrimaryEmail = email
}

Gradual Rollout Timeline:

Week 1: Deploy code that writes to BOTH columns
        Feature flag: 0% (read from old column)

Week 2: Enable feature flag for internal users (1%)
        Monitor for issues

Week 3: Gradual rollout: 10% โ†’ 25% โ†’ 50% โ†’ 100%
        All reads now use new column

Week 4: Remove writes to old column
        All code uses only primary_email

Phase 3: Contract (Migration 2 - after full rollout)

-- Remove sync trigger
DROP TRIGGER IF EXISTS trg_sync_email ON users;
DROP FUNCTION IF EXISTS sync_email_columns();

-- Remove old column (only after ALL code uses new column)
ALTER TABLE users DROP COLUMN email;

Feature Flag Implementation Options

Option 1: Environment Variables (Simple)

func useNewEmailColumn() bool {
    return os.Getenv("FEATURE_USE_PRIMARY_EMAIL") == "true"
}

Option 2: Database-backed Flags (More Control)

// Feature flags table
// CREATE TABLE feature_flags (
//     name VARCHAR(100) PRIMARY KEY,
//     enabled BOOLEAN DEFAULT FALSE,
//     rollout_percentage INT DEFAULT 0,
//     updated_at TIMESTAMP
// );

func isFeatureEnabled(flagName string, userID int) bool {
    flag := getFlag(flagName)
    if !flag.Enabled {
        return false
    }
    // Percentage-based rollout
    return (userID % 100) < flag.RolloutPercentage
}

Option 3: Third-party Services

  • LaunchDarkly
  • Unleash (self-hosted)
  • Flagsmith

Rollback Safety with Feature Flags

If issues are discovered during rollout:

Normal Flow:
v1.0 โ†’ v1.1 (expand) โ†’ v1.2 (migrate) โ†’ v1.3 (contract)

Rollback Scenario:
v1.2 has issues โ†’ Set feature flag to 0% โ†’ Instant rollback
                โ†’ No database migration needed
                โ†’ Fix code โ†’ Re-enable flag gradually

Summary: Safe Breaking Change Timeline

PhaseDatabaseCodeFeature FlagDuration
1. ExpandAdd new column + sync triggerWrite to both, read from old0%1 deploy
2. MigrateNo changesWrite to both, read controlled by flag0% โ†’ 100%1-2 weeks
3. StabilizeNo changesWrite to both, read from new100%1 week
4. Clean CodeNo changesWrite/read only new column100% (remove flag)1 deploy
5. ContractRemove old column + triggerNo changesN/A1 deploy

Resolving Conflicts: The Complete Workflow

Scenario: Your Branch Has New Migrations, Main Also Has New Migrations

Option A: Using Merge (Safer, Simpler)

# 1. Ensure main is up-to-date
git switch main
git pull origin main

# 2. Switch to your feature branch
git switch feature/my-task

# 3. Merge main into your branch
git merge main

# 4. Resolve any Git conflicts manually

# 5. Commit the merge
git add .
git commit -m "Merge main to resolve conflicts"

# 6. Test migrations locally (CRITICAL)
goose $DB_DSN down-to 0
goose $DB_DSN up

# 7. Push (no force required)
git push origin feature/my-task

Option B: Using Rebase (Cleaner History)

# 1. Ensure main is up-to-date
git switch main
git pull origin main

# 2. Switch to your feature branch
git switch feature/my-task

# 3. Rebase onto main
git rebase main

# 4. Resolve conflicts at each step
git add .
git rebase --continue

# 5. Test migrations locally
goose $DB_DSN down-to 0
goose $DB_DSN up

# 6. Force push (required after rebase)
git push origin feature/my-task --force-with-lease

Local Testing Protocol (Critical Step)

Before pushing, always verify migration compatibility:

# 1. Reset database to clean state
goose $DB_DSN down-to 0

# 2. Apply all migrations in order
goose $DB_DSN up

This ensures:

  • Collaborators' migrations apply first (earlier timestamps)
  • Your new migrations apply correctly on top

GitHub Merge Strategies

StrategyMain Branch HistoryUse Case
Create merge commitNon-linear (messy)Avoid for clean history
Squash and mergeLinear (all commits become one)Good for feature branches with many small commits
Rebase and mergeLinear (preserves individual commits)Best for clean, traceable history

Recommended: Use git merge main locally for safety, then use Rebase and merge or Squash and merge on GitHub.

Helping Team Members with Rebase

When assisting a less experienced teammate:

Using Merge (No Force Push Required):

# 1. Fetch their branch
git switch -c interns/feature-x origin/interns/feature-x

# 2. Merge main
git merge main

# 3. Resolve conflicts and test
goose $DB_DSN down-to 0
goose $DB_DSN up

# 4. Push normally
git push origin interns/feature-x

Teammate can simply git pull to sync.

Using Rebase (Requires Force Push):

# 1. Create backup
git branch interns/feature-x-backup

# 2. Rebase
git rebase main

# 3. Test migrations
goose $DB_DSN down-to 0
goose $DB_DSN up

# 4. Force push
git push origin interns/feature-x --force-with-lease

Important: Notify teammate to run:

git fetch origin
git reset --hard origin/interns/feature-x

Team SOP Summary

  1. Always use timestamp naming for migration files
  2. Sync frequently - pull main before creating new migrations
  3. Test locally - run full migration cycle before pushing
  4. Communicate - coordinate when modifying the same tables
  5. Use CI/CD validation - run migrations on fresh database in pipeline

Quick Reference: Conflict Resolution Decision Tree

Has your branch diverged from main?
โ”œโ”€โ”€ No โ†’ Push normally
โ””โ”€โ”€ Yes โ†’ Do you need clean history?
    โ”œโ”€โ”€ No โ†’ git merge main โ†’ test โ†’ push
    โ””โ”€โ”€ Yes โ†’ git rebase main โ†’ test โ†’ force push

Troubleshooting

"Permission denied" for SSH key

chmod 600 /path/to/key.pem

"Password authentication failed"

  • Verify username/password in DSN
  • Check for special characters - use single quotes
  • Verify database allows connections from VPS IP

"Connection refused" on localhost

  • Verify SSH tunnel is still running
  • Check if local port is correct
  • Ensure database is running on remote server

Migration version conflicts

  • Never manually edit migration file names after they've been applied
  • If goose reports version mismatch, check goose_db_version table

ยฉ 2025 borui. All rights reserved. This content may be freely reproduced, displayed, modified, or distributed with proper attribution to borui and a link to the article: borui (2025-10-10). Goose Database Migration - SSH Tunnels and Team Collaboration Guide. https://caiborui.com/blog/2025-10-10-en-goose-ssh-tunnel-migration-team-guide

@misc{borui2025-0c082a38,
  author = {borui},
  title = {{Goose Database Migration - SSH Tunnels and Team Collaboration Guide}},
  year = {2025},
  publisher = {borui's blog},
  url = {https://caiborui.com/blog/2025-10-10-en-goose-ssh-tunnel-migration-team-guide}
}