Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Database Commands Bundle Laravel Package

abmundi/database-commands-bundle

Symfony bundle to automate MySQL database dumps and imports via a db:dump console command and Capifony tasks. Creates timestamped dumps (with hard link to latest), supports download from remote and import into local production/testing environments.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation:

    composer require abmundi/database-commands-bundle:dev-master
    

    Register the bundle in config/bundles.php (Laravel 5.4+):

    return [
        // ...
        Abmundi\DatabaseCommandsBundle\AbmundiDatabaseCommandsBundle::class => ['all' => true],
    ];
    
  2. Verify Dependencies: Ensure your server has mysql, mysqldump, and bunzip2 installed and available in $PATH.

  3. First Use Case: Dump your database to a .sql file:

    php artisan db:dump
    

    This generates a dump in var/dumps/ (default path). Check the README for other commands like db:restore, db:optimize, etc.


Implementation Patterns

Console Workflows

  1. Database Dumps:

    • Local Development: Use db:dump to create backups before migrations or deployments.
      php artisan db:dump --path=custom/path --compress=1
      
    • Remote Servers: Schedule db:dump via cron or Capistrano (see Capifony tasks below) for automated backups.
  2. Restoration:

    • Restore from a dump:
      php artisan db:restore --file=path/to/backup.sql
      
    • Pre-Restore Checks: Use --drop to drop tables before restoring (useful for clean migrations):
      php artisan db:restore --file=backup.sql --drop=1
      
  3. Optimization:

    • Run db:optimize to repair and optimize tables:
      php artisan db:optimize --tables=table1,table2
      
    • Integrate this into post-deployment scripts to maintain database health.

Capifony Integration (Symfony)

If using Capifony (or Capistrano), leverage the 5 provided tasks:

  1. db:dump: Trigger a dump before deployment.
  2. db:restore: Restore from a dump post-deployment.
  3. db:optimize: Run optimizations during maintenance windows.
  4. db:backup: Alias for db:dump (check task list).
  5. db:cleanup: Remove old dumps (configure retention in config.yml).

Example Capifony Task:

# config/deploy.rb
after "deploy:update_code", "deploy:db_dump"
namespace :deploy do
  task :db_dump, roles: :db do
    run "cd #{current_path} && php app/console db:dump --compress=1"
  end
end

Laravel-Specific Adaptations

  1. Artisan Command Aliases: Add aliases in app/Console/Kernel.php for brevity:

    protected $commands = [
        // ...
        'db:dump' => \Abmundi\DatabaseCommandsBundle\Command\DumpCommand::class,
    ];
    
  2. Customizing Output Paths: Publish the config file to override defaults:

    php artisan vendor:publish --provider="Abmundi\DatabaseCommandsBundle\AbmundiDatabaseCommandsBundle" --tag=config
    

    Update config/abmundi_database_commands.php:

    return [
        'dump_path' => storage_path('app/dumps'),
        'compression' => 'bzip2',
    ];
    
  3. Event Listeners: Trigger dumps/restores via Laravel events (e.g., deploying or deployed events in Forge/Senv):

    // app/Providers/EventServiceProvider.php
    public function boot()
    {
        if ($this->app->environment('production')) {
            event(new Deploying);
        }
    }
    

Gotchas and Tips

Pitfalls

  1. Dependency Conflicts:

    • The bundle assumes mysql, mysqldump, and bunzip2 are globally available. On Laravel Forge/Senv, ensure these are installed in the server’s base image or user’s $PATH.
    • Fix: Add a deployment hook to install dependencies:
      # In your deploy script
      run "sudo apt-get install -y mysql-client coreutils" # Ubuntu/Debian
      
  2. Permission Issues:

    • Dumps are written to var/dumps/ (Symfony) or storage/app/dumps (Laravel). Ensure the web server user (e.g., www-data) has write permissions.
    • Fix: Set permissions in your deploy script:
      run "chmod -R 775 storage/"
      run "chown -R www-data:www-data storage/"
      
  3. Large Database Dumps:

    • Dumps may exceed PHP’s memory_limit or timeout. Increase limits in php.ini or use --chunk (if supported):
      php artisan db:dump --memory=1024M
      
    • Alternative: Use mysqldump directly with Laravel’s task scheduler:
      php artisan schedule:run --command="mysqldump -uDB_USER -pDB_PASS DB_NAME > dump.sql"
      
  4. Capifony Task Naming:

    • The bundle’s Capifony tasks assume Symfony’s app/console path. In Laravel, override the task path in Capistrano:
      set :console, "php artisan"
      

Debugging

  1. Command Output:

    • Enable verbose mode for troubleshooting:
      php artisan db:dump -v
      
    • Check Laravel logs (storage/logs/laravel.log) for errors.
  2. Dump Integrity:

    • Validate dumps with:
      mysql -uDB_USER -pDB_PASS DB_NAME < dump.sql --force
      
    • For compressed dumps, decompress first:
      bunzip2 dump.sql.bz2
      
  3. Configuration Overrides:

    • If commands fail silently, verify your config/abmundi_database_commands.php is loaded. Clear config cache if needed:
      php artisan config:clear
      

Extension Points

  1. Custom Commands: Extend the bundle by creating a new command class (e.g., php artisan db:backup-to-s3) and reuse its logic:

    use Abmundi\DatabaseCommandsBundle\Command\BaseCommand;
    
    class S3DumpCommand extends BaseCommand {
        protected function execute(InputInterface $input, OutputInterface $output) {
            $dump = $this->dumpDatabase();
            Storage::disk('s3')->put('dumps/backup.sql', $dump);
        }
    }
    
  2. Pre/Post Hooks: Override the bundle’s services to add logic before/after dumps. Example in config/services.php:

    'abmundi.database_commands.dump.listener' => function ($container) {
        return new class {
            public function onDump(\Abmundi\DatabaseCommandsBundle\Event\DumpEvent $event) {
                // Add custom logic (e.g., log dump start/end)
            }
        };
    },
    
  3. Database-Specific Logic: The bundle defaults to MySQL. For PostgreSQL or SQLite, subclass BaseCommand and override getDumpCommand():

    protected function getDumpCommand() {
        return "pg_dump -U{$this->getDbUser()} {$this->getDbName()} > {$this->getDumpPath()}";
    }
    
  4. Testing: Mock the Process component in PHPUnit to test commands:

    $process = $this->createMock(\Symfony\Component\Process\Process::class);
    $process->method('run')->willReturn(0);
    $this->container->instance(\Symfony\Component\Process\Process::class, $process);
    
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
emuniq/filament-browser-notifications
syriable/filament-translator
hungnm28/livewire-form
wenprise/eloquent
crudly/encrypted
fadion/bouncy
cuci/prototurk-sdk
gos/pubsub-router-bundle
cuci/prototurk-sdk-symfony
clementtalleu/easyadmin-markdown-bundle
codeflextech/permission-manager
karnoweb/livewire-datepicker
sayedenam/sayed-dashboard
milito/query-filter
apiboxsym/user-bundle
apiboxsym/health-check-bundle
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui