Weave 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

Danpu Laravel Package

rah/danpu

Danpu is a lightweight PHP library for dumping and restoring MySQL/MariaDB databases. Export schema and data to SQL files, optionally gzip-compressed, then import them again through a simple API or CLI, without relying on mysqldump binaries.

View on GitHub
Deep Wiki
Context7

Getting Started

Install with composer require rah/danpu. There is no Laravel service provider or facade — this is a small, framework-agnostic, PDO-based library. That is actually an advantage: it does not care which Laravel version you run, only that PHP and PDO MySQL work.

Look first at:

  • Rah\Danpu\Config — the full list of options (file, dsn, user, pass, ignore, create, data, drop, tempDir, gzip, etc.).
  • Rah\Danpu\Dump — a fluent wrapper that sets those config properties via magic methods.
  • Rah\Danpu\Export and Rah\Danpu\Import — their constructors perform the work. There is no ->run(); instantiating the object exports or imports the database.
  • Rah\Danpu\Exception — the library's exception type.

The first practical use case is an Artisan command that writes a backup to storage/app/backups:

use Rah\Danpu\Dump;
use Rah\Danpu\Export;

$db = config('database.connections.mysql');

$dsn = sprintf(
    'mysql:host=%s;port=%s;dbname=%s;charset=%s',
    $db['host'],
    $db['port'],
    $db['database'],
    $db['charset'] ?? 'utf8mb4'
);

$dump = (new Dump)
    ->file(storage_path('app/backups/'.now()->format('Ymd_His').'.sql'))
    ->dsn($dsn)
    ->user($db['username'])
    ->pass($db['password'])
    ->tempDir(storage_path('app/backups'));

new Export($dump);

Importing is symmetric: build the same Dump, then new Import($dump). The target database must already exist; Danpu will not create the database itself.

Implementation Patterns

Wrap it in a small service and command. Danpu objects are not injectable services, so keep the PDO/DSN details in one place and expose intent-specific methods.

final class DatabaseDumpService
{
    public function export(array $db, string $file, array $ignore = []): void
    {
        $dump = $this->dump($db, $file)->ignore($ignore);
        new \Rah\Danpu\Export($dump);
    }

    public function import(array $db, string $file): void
    {
        new \Rah\Danpu\Import($this->dump($db, $file));
    }

    private function dump(array $db, string $file): \Rah\Danpu\Dump
    {
        return (new \Rah\Danpu\Dump)
            ->file($file)
            ->dsn(sprintf(
                'mysql:host=%s;port=%s;dbname=%s;charset=%s',
                $db['host'], $db['port'], $db['database'], $db['charset'] ?? 'utf8mb4'
            ))
            ->user($db['username'])
            ->pass($db['password'])
            ->tempDir(dirname($file));
    }
}

Then schedule the command in routes/console.php or the old Kernel::$commands:

Schedule::command('db:backup')->dailyAt('02:00')->onOneServer();

Use the config flags intentionally. These are the day-to-day options:

// Schema only, no INSERTs
$dump->data(false);
new Export($dump);

// Data only, importing into an existing schema
$dump->create(false)->drop(false)->data(true);
new Import($dump);

// Skip noisy tables
$dump->ignore(['cache', 'sessions', 'jobs', 'failed_jobs', 'telescope_entries']);

ignore() takes exact table names, so maintain the list explicitly rather than expecting wildcards.

Refresh local/staging databases from a production-like dump. Dump on a safe environment, then import locally:

$dump = (new Dump)
    ->file(storage_path('app/backups/prod.sql'))
    ->dsn('mysql:host=127.0.0.1;port=3306;dbname=app_local;charset=utf8mb4')
    ->user('root')
    ->pass('');

new Import($dump);

For CI, run the import once to build a known schema and then run your normal test suite. For small test suites, Laravel's RefreshDatabase is still faster; Danpu is more useful for large baseline fixtures or reproducing production-shaped data.

Take snapshots before risky migrations. In a deploy script, export first, then run php artisan migrate. If the migration fails, the dump is your rollback artifact. Keep the filename tied to the release or git SHA.

Dump per tenant. For multi-database tenancy, loop over tenant connection configs and produce one file per database. Avoid running them in parallel against the same MySQL server unless you have measured the I/O impact.

Push dumps to object storage. Write locally first, then upload:

new Export($dump);

Storage::disk('s3')->put(
    'backups/'.$filename,
    fopen($file, 'r')
);

unlink($file);

Do not stream Danpu directly into S3; it expects a local filesystem path.

Gotchas and Tips

The package is effectively unmaintained. Last release was 2018. It still works for many MySQL/PDO setups, but pin the version, test on your PHP version (especially PHP 8.x), and be prepared to fork or replace it. Because it has no Laravel dependency, framework upgrades are not the problem; PHP deprecations and PDO behavior are.

Dumps are not guaranteed to be consistent snapshots. Danpu does not expose mysqldump --single-transaction. If the database is being written to during the export, tables can be captured at different points in time. For production backups, dump from a replica, pause writes, or lock tables for the duration. Treat Danpu as a convenient application-level dump, not a replacement for a proper MySQL backup strategy.

It is not a full mysqldump replacement. Tables are the focus. Triggers, stored routines, events, and definer clauses are not reliably included. If your application depends on them, use mysqldump --routines --triggers --events or run both tools and keep the outputs together.

Foreign keys can break imports. Check whether your version emits SET FOREIGN_KEY_CHECKS=0; if not, wrap the import or import in dependency order. Circular references are the usual failure mode.

sql_mode and version differences cause import failures. A dump from MySQL 8 with utf8mb4_0900_ai_ci or zero dates will fail on MySQL 5.7 or MariaDB with different strict-mode settings. Set the session sql_mode before import, or normalize the dump. This is a common source of "works locally, fails in CI" bugs.

Include the charset in the DSN. charset=utf8mb4 matters for both export and import. Without it, PDO may connect with a different client charset and produce mangled data or failed SET NAMES assumptions.

The database must exist before import. The DSN needs a valid dbname; Danpu does not issue CREATE DATABASE. Create the schema first in your provisioning step.

Watch disk space and temp directories. Danpu writes to a temporary file and then moves it into place. Put tempDir() on the same filesystem as the target file to keep the rename cheap, and ensure the web user/CLI user has write permission. Never dump into public/.

Large imports are slow. Import executes statements rather than piping into the mysql client. For multi-gigabyte restores, the CLI client will usually be much faster. For application-sized databases, Danpu is fine. Raise max_execution_time for CLI (often already 0), and run imports from a command or queued job — never inside a web request.

Catch and log Rah\Danpu\Exception. Error messages can be generic. Log the target path, database name, and phase (export vs import), but never the password. Verify the file exists and is non-zero after export before considering the backup successful.

Security and retention. Dumps are plaintext by default and contain PII, password hashes, and API tokens. Store them outside the webroot, encrypt at rest if they leave the host, set a retention policy, and do not commit them. The gzip option is compression, not encryption.

Extension strategy. The library is small. Subclass Dump, Export, or Import only if you need to change internals; otherwise keep a thin adapter around it so you can swap in mysqldump, mariadb-dump, or a hosted backup service later without rewriting your commands.

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.
diephp/sequences
users-au/socialite-provider
twidpay/twid-logger
mrnewport/laravel-plaid
mrnewport/laravel-repo
mrnewport/laravel-docsign
mrnewport/laravel-stow
mrnewport/laravel-flow
mrnewport/laravel-priceable
mrnewport/laravel-nestedterms
fredmeng/laravel-apidoc-generator
itstructure/laravel-multilingual-tools
pdustdar/elasticsearch
markupai/php-sdk
rlacerda83/lumem-microservice-shipment
uni-method/symfony-lib
tacticmedia/scim-server-bundle
neika-ai/symfony-bundle
mattleads/agent-publishing-bundle
glavweb/framework-bundle