Usage | db-dumper-go | Spatie       

 SPATIE  

db-dumper-go
============

spatie.be/open-source

  [Docs](https://spatie.be/docs)  [Db-dumper-go](https://spatie.be/docs/db-dumper-go/v1)  Usage

 Version   v1      

 Other versions for crawler [v1](https://spatie.be/docs/db-dumper-go/v1) 

  Usage    
- [ Introduction ](https://spatie.be/docs/db-dumper-go/v1/introduction)
- [ Requirements ](https://spatie.be/docs/db-dumper-go/v1/requirements)
- [ Installation and setup ](https://spatie.be/docs/db-dumper-go/v1/installation-and-setup)
- [ Usage ](https://spatie.be/docs/db-dumper-go/v1/usage)
- [ Processes and output ](https://spatie.be/docs/db-dumper-go/v1/processes-and-output)
- [ Testing ](https://spatie.be/docs/db-dumper-go/v1/testing)
- [ Releasing ](https://spatie.be/docs/db-dumper-go/v1/releasing)
- [ Contributing ](https://spatie.be/docs/db-dumper-go/v1/contributing)
- [ Security vulnerabilities ](https://spatie.be/docs/db-dumper-go/v1/security-vulnerabilities)
- [ Credits ](https://spatie.be/docs/db-dumper-go/v1/credits)
- [ License ](https://spatie.be/docs/db-dumper-go/v1/license)
- [ Changelog ](https://spatie.be/docs/db-dumper-go/v1/changelog)
- [ Support us ](https://spatie.be/docs/db-dumper-go/v1/support-us)

 Usage
=====

This is the simplest way to create a dump of a MySQL database:

```
dumper := dbdumper.New(dbdumper.MySQL)
dumper.DBName = databaseName
dumper.UserName = userName
dumper.Password = password
err := dumper.DumpToFile(ctx, "dump.sql")
```

If you're working with PostgreSQL just use `dbdumper.New(dbdumper.PostgreSQL)`. Most settings are available on both the MySQL and PostgreSQL dumpers.

If the `mysqldump` or `pg_dump` binary is installed in a non-default location, set the directory containing it:

```
dumper.BinaryPath = "/custom/location"
```

To change the host or port, set `Host` and `Port`. The default host is `localhost`. Default ports are 3306 for MySQL and MariaDB, 5432 for PostgreSQL and 27017 for MongoDB. Pass IPv6 addresses without brackets to `Host`, for example `::1`. URLs use brackets as usual.

```
dumper.Host = "database.internal"
dumper.Port = 3307
dumper.Socket = "/var/run/mysqld/mysqld.sock"
dumper.Timeout = 30 * time.Second
```

`Socket` selects the MySQL/MariaDB socket or PostgreSQL socket directory. A zero timeout disables the package deadline. The context can always impose a deadline or cancellation. Configure the dumper before concurrent use and use different output paths.

### Handling AUTO\_INCREMENT values in dumps

#### Skipping AUTO\_INCREMENT values

To omit the next AUTO\_INCREMENT value from MySQL or MariaDB table definitions, use `SkipAutoIncrement`:

```
dumper.SkipAutoIncrement = true
```

This changes table options, not inserted primary keys or matching text inside row values.

### Including AUTO\_INCREMENT values in the dump

By default, AUTO\_INCREMENT values are included. To restore that behavior after disabling it:

```
dumper.SkipAutoIncrement = false
```

### Use a database URL

In some applications or environments, database credentials are provided as URLs instead of individual components. Use `SetDatabaseURL`:

```
if err := dumper.SetDatabaseURL("mysql://username:password@hostname:3306/dbname"); err != nil {
    return err
}
```

The dumper connects to `hostname` on port 3306 and dumps `dbname` with `username` and `password`. Query values for `host`, `port`, `database`, `username` and `password` override URL components. Empty and literal `null` values leave an existing setting unchanged. Values such as `0` and `false` remain strings. Invalid ports return an error without changing configuration.

SQLite accepts absolute URLs such as `sqlite:///path/to/db.sqlite` and relative URLs such as `sqlite:db.sqlite`. The URL does not switch the driver selected by `New`.

### Dump specific tables

Use a slice of literal table names or native tool patterns:

```
dumper.IncludeTables = []string{"table1", "table2", "table3"}
```

For comma-separated application input, split and trim it before assigning the slice. Slice entries themselves are not split.

### Don't use column statistics with some old versions of MySQL

MySQL 8's dump tool can query column statistics that older servers do not have. Disable that query with:

```
dumper.NoColumnStatistics = true
```

This adds `--column-statistics=0` and needs a compatible MySQL dump tool.

### Excluding tables from the dump

```
dumper.ExcludeTables = []string{"table1", "table2", "table3"}
```

Nonempty `IncludeTables` and `ExcludeTables` conflict. Clear one before using the other. MySQL/MariaDB, PostgreSQL and SQLite support table selection. Use MongoDB's `Collection` for collection selection instead.

### Excluding table data from the dump

To dump the structure of certain tables but not their data, for example log tables, use `ExcludeTablesData`. This works with both MySQL and MariaDB.

```
dumper.ExcludeTables = []string{"cache"}
dumper.ExcludeTablesData = []string{"logs", "sessions"}
```

MariaDB uses its native `--ignore-table-data` option. Oracle MySQL has no equivalent option. It uses schema, data and trigger passes, in that order. This keeps triggers from firing during restore. Only the data pass dumps rows. Avoid DDL changes while the dump runs because metadata comes from separate connections. This fallback requires SQL output, not `--xml` or `-X`. Bare table names apply to the configured or effective database, not every database selected by `--all-databases`.

### Including routines in the dump

To include stored procedures and functions in a MySQL or MariaDB dump:

```
dumper.IncludeRoutines = true
```

### Do not write CREATE TABLE statements that create each dumped table

```
dumper.NoCreateTables = true
```

This adds `--no-create-info` for MySQL/MariaDB or `--data-only` for PostgreSQL.

### Do not write row data

```
dumper.NoData = true
```

This adds `--no-data` for MySQL/MariaDB or `--schema-only` for PostgreSQL. As in PHP, SQLite and MongoDB do not implement these schema/data switches.

### Append instead of overwriting a dump file

Use `Append` with MySQL or MariaDB to append instead of overwriting. This is useful for two-step dumps when you want the whole schema but only some of the data.

```
dumper.Append = true
```

Append cannot be combined with compression. A dump is appended only after its processes succeed. Disk failure while copying can still leave a partial append. Concurrent appends are not synchronized.

### Adding extra options

Use one slice entry per command-line argument. No shell splitting or evaluation occurs:

```
dumper.ExtraOptions = []string{"--xml"}
dumper.ExtraOptionsAfterDBName = []string{"--where=id > 7"}
```

`ExtraOptionsAfterDBName` applies to MySQL and MariaDB. To select databases and include database creation statements:

```
dumper.ExtraOptions = []string{"--databases", "dbname", "--add-drop-database"}
```

To back up all databases:

```
dumper.ExtraOptions = []string{"--all-databases"}
```

These options replace the positional database name without changing `DBName`. Never pass `"--databases dbname"` as one entry. Do not accept extra options from untrusted input. Native tools can read and write files or connect elsewhere even without a shell.

### Using compression

There are two compressors out of the box:

- `dbdumper.GzipCompressor{}` uses `gzip`.
- `dbdumper.Bzip2Compressor{}` uses `bzip2`.

```
dumper.Compressor = dbdumper.GzipCompressor{}
err := dumper.DumpToFile(ctx, "dump.sql.gz")
```

The extension is not added automatically. `dumper.Compressor.Extension()` returns `gz`, `bz2` or a custom extension. Set `Compressor` to `nil` to disable compression.

### Creating your own compressor

Implement the `Compressor` interface:

```
type Compressor interface {
    Command() (program string, args []string)
    Extension() string
}
```

The executable reads the completed dump from stdin and writes compressed bytes to stdout. Return a nonzero exit status on failure. For example, a custom gzip level:

```
type BestGzip struct{}

func (BestGzip) Command() (string, []string) { return "gzip", []string{"-9"} }
func (BestGzip) Extension() string { return "gz" }

// In your backup function:
dumper.Compressor = BestGzip{}
```

### Other native options

MySQL and MariaDB also support `SkipSSL`, `SSLFlag`, `KeepComments`, `NoExtendedInserts`, `SingleTransaction`, `SkipLockTables`, `Quick`, `DefaultCharacterSet` and `GTIDPurged`. Flags default to false. Comments are skipped and extended inserts are enabled unless you opt out. `GTIDPurged` defaults to the native tool's AUTO behavior. Disable SSL with `SkipSSL = true`. `SSLFlag` can be `skip-ssl`, `ssl-mode=DISABLED` or `ssl-mode=PREFERRED`. The default disable flag is `ssl-mode=DISABLED` for MySQL and `skip-ssl` for MariaDB.

Set `WithoutSandboxMode = true` on MariaDB to remove its leading sandbox directive when present. Set `UseInserts = true` on PostgreSQL to use INSERT statements instead of COPY. MongoDB supports `Collection` and `AuthenticationDatabase`, with optional username/password authentication. SQLite's `Tables(ctx)` returns sorted user table names without internal `sqlite_%` tables.

See [processes and output](processes-and-output) for command inspection, execution replacement and failure behavior.

 A good
match?
-------------

### What we do best

- All things Laravel
- Custom frontend components
- Building APIs
- AI-powered features
- Simplifying things
- Clean solutions
- Integrating services

### Not our cup of tea

- WordPress themes
- Cutting corners
- Free mockups to win a job
- "Just execute the briefing"

 In short: we'd like to be a **substantial part** of your project.

 [ Get in touch via email ](mailto:info@spatie.be?subject=A%20good%20match%21&body=Tell%20us%20as%20much%20as%20you%20can%20about%0A-%20your%20online%20project%0A-%20your%20planning%0A-%20your%20budget%0A-%20%E2%80%A6%0A%0AAnything%20that%20helps%20us%20to%20start%20straightforward%21)
