Primo Committ

This commit is contained in:
paoloar77
2024-05-07 12:17:25 +02:00
commit e73d0e5113
7204 changed files with 884387 additions and 0 deletions

View File

@@ -0,0 +1,32 @@
# Contributing
Contributions are **welcome** and will be fully **credited**.
We accept contributions via Pull Requests on [Github](https://github.com/spatie/db-dumper).
## Pull Requests
- **[PSR-2 Coding Standard](https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-2-coding-style-guide.md)** - The easiest way to apply the conventions is to install [PHP Code Sniffer](http://pear.php.net/package/PHP_CodeSniffer).
- **Add tests!** - Your patch won't be accepted if it doesn't have tests.
- **Document any change in behaviour** - Make sure the `README.md` and any other relevant documentation are kept up-to-date.
- **Consider our release cycle** - We try to follow [SemVer v2.0.0](http://semver.org/). Randomly breaking public APIs is not an option.
- **Create feature branches** - Don't ask us to pull from your master branch.
- **One pull request per feature** - If you want to do more than one thing, send multiple pull requests.
- **Send coherent history** - Make sure each individual commit in your pull request is meaningful. If you had to make multiple intermediate commits while developing, please [squash them](http://www.git-scm.com/book/en/v2/Git-Tools-Rewriting-History#Changing-Multiple-Commit-Messages) before submitting.
## Running Tests
``` bash
$ composer test
```
**Happy coding**!

View File

@@ -0,0 +1 @@
github: spatie

View File

@@ -0,0 +1,23 @@
name: Check & fix styling
on: [push]
jobs:
php-cs-fixer:
runs-on: ubuntu-latest
steps:
- name: Checkout code
uses: actions/checkout@v2
with:
ref: ${{ github.head_ref }}
- name: Run PHP CS Fixer
uses: docker://oskarstark/php-cs-fixer-ga
with:
args: --config=.php_cs.dist --allow-risky=yes
- name: Commit changes
uses: stefanzweifel/git-auto-commit-action@v4
with:
commit_message: Fix styling

View File

@@ -0,0 +1,50 @@
name: run-tests
on:
push:
pull_request:
schedule:
- cron: '0 0 * * *'
jobs:
test:
runs-on: ${{ matrix.os }}
strategy:
fail-fast: true
matrix:
php: [8.0, 7.4, 7.3, 7.2]
laravel: [8.*, 7.*, 6.*]
dependency-version: [prefer-lowest, prefer-stable]
os: [ubuntu-latest]
name: P${{ matrix.php }} - ${{ matrix.os }}
steps:
- name: Checkout code
uses: actions/checkout@v2
- name: Install sqlite3
run: sudo apt-get install sqlite3 libsqlite3-dev
- name: Setup PHP
uses: shivammathur/setup-php@v2
with:
php-version: ${{ matrix.php }}
extensions: dom, curl, libxml, mbstring, zip, pcntl, pdo, sqlite, pdo_sqlite, mysql, mysqli, pdo_mysql, bcmath, soap, intl, gd, exif, iconv, imagick
coverage: none
- name: Install dependencies
run: composer update --${{ matrix.dependency-version }} --prefer-dist --no-interaction
- name: Execute tests
run: vendor/bin/phpunit
- name: Send Slack notification
uses: 8398a7/action-slack@v2
if: failure()
with:
status: ${{ job.status }}
author_name: ${{ github.actor }}
env:
SLACK_WEBHOOK_URL: ${{ secrets.SLACK_WEBHOOK }}
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}

40
vendor/spatie/db-dumper/.php_cs.dist vendored Normal file
View File

@@ -0,0 +1,40 @@
<?php
$finder = Symfony\Component\Finder\Finder::create()
->in([
__DIR__ . '/src',
__DIR__ . '/tests',
])
->name('*.php')
->notName('*.blade.php')
->ignoreDotFiles(true)
->ignoreVCS(true);
return PhpCsFixer\Config::create()
->setRules([
'@PSR2' => true,
'array_syntax' => ['syntax' => 'short'],
'ordered_imports' => ['sortAlgorithm' => 'alpha'],
'no_unused_imports' => true,
'not_operator_with_successor_space' => true,
'trailing_comma_in_multiline_array' => true,
'phpdoc_scalar' => true,
'unary_operator_spaces' => true,
'binary_operator_spaces' => true,
'blank_line_before_statement' => [
'statements' => ['break', 'continue', 'declare', 'return', 'throw', 'try'],
],
'phpdoc_single_line_var_spacing' => true,
'phpdoc_var_without_name' => true,
'class_attributes_separation' => [
'elements' => [
'method',
],
],
'method_argument_space' => [
'on_multiline' => 'ensure_fully_multiline',
'keep_multiple_spaces_after_comma' => true,
],
'single_trait_insert_per_statement' => true,
])
->setFinder($finder);

244
vendor/spatie/db-dumper/CHANGELOG.md vendored Normal file
View File

@@ -0,0 +1,244 @@
# Changelog
All notable changes to `db-dumper` will be documented in this file
## 2.21.1 - 2021-02-24
- fix attempt to generate dump over http connection when using socket (#145)
## 2.21.0 - 2021-01-27
- fix: make the process more extensible, avoid touching anything (#141)
## 2.20.0 - 2021-01-26
- revert changes in 2.19.0
## 2.19.0 - 2021-01-25
- fix: add some public functions that allow extensibility (#139)
## 2.18.0 - 2020-10-10
- support PHP 8
## 2.17.0 - 2020-09-10
- add `doNotUseColumnStatistics`
## 2.16.1 - 2020-05-15
- fix using gzip compression on windows (#130)
## 2.16.0 - 2020-04-15
- allow for adding options after the db name (#129)
## 2.15.3 - 2020-01-26
- Fix incomplete credential guard (#126)
## 2.15.2 - 2020-01-16
- Fix sqlite3 dump on Windows
## 2.15.1 - 2019-11-23
- allow symfony 5 components
## 2.15.0 - 2019-11-11
- add `doNotCreateTables` to Postgres driver (#116)
## 2.14.3 - 2019-08-21
- fix memory leak (issue #109)
## 2.14.2 - 2019-06-28
- Determine quotes for windows for MongoDB and PostgreSql dumps (#107)
## 2.14.1 - 2019-05-10
- wrap the dump command in an `if` statement when using compression (#100)
- drop support for PHP 7.2 and lower
## 2.14.0 - 2019-04-17
- add --skip-lock-tables and --quick option (#95)
## 2.13.2 - 2019-03-03
- fix process warnings
## 2.13.1 - 2019-03-01
- remove pipefail operator when compressing dump
## 2.13.0 - 2019-03-01
- add ability to specify all databases as MySQL option
## 2.12.0 - 2018-12-10
- add `doNotCreateTables`
## 2.11.1 - 2018-09-27
- add `useExtension`
## 2.11.0 - 2018-09-26
- add `Compressor`
## 2.10.1 - 2018-08-30
- allow destination paths to have a space character
## 2.10.0 - 2018-04-27
- add support for compressing dumps
## 2.9.0 - 2018-03-05
- add support for setting `--set-gtid-purged`
## 2.8.2 - 2018-01-20
- add support for Symfony 4
## 2.8.1 - 2017-11-24
- fix SQLite dump
## 2.8.0 - 2017-11-13
- add `setAuthenticationDatabase`
## 2.7.4 - 2017-11-07
- fix for dumping a MongoDB without username or password
## 2.7.3 - 2017-09-09
- allow empty passwords for MongoDB dumps
## 2.7.2 - 2017-09-07
- make `--databases` optional
## 2.7.1 - 2017-08-18
- made option passing more flexible by adding `--databases` option to the MySQL dumper
## 2.7.0 - 2017-04-13
- `MongoDb` dumps won't be compressed by default anymore
- add `enableCompression` on `MongoDb`
## 2.6.1 - 2017-04-13
- fix sqlite dumper
## 2.6.0 - 2017-04-13
- add support for MongoDB
## 2.5.1 - 2017-04-07
- prefix excluded tables with database name when dumping a MySql db
## 2.5.0 - 2017-04-05
- add `--default-character-set` option for MySql
- improve the preservation of the used charset when dumping a MySql db
## 2.4.1 - 2016-12-31
- fix bug where custom binary path with spaces on linux would not process correctly
## 2.4.0 - 2016-12-30
- add `skipComments`
## 2.3.0 - 2016-11-21
- add support for SQLite
## 2.1.1 - 2016-11-19
- made a change so the package can be used on Windows
## 2.1.0 - 2016-10-21
- added `getHost`
## 2.0.1 - 2016-09-17
- fix for dump paths with spaces
## 2.0.0 - 2016-09-07
- refactored all classes
- added the ability to add artribrary options
## 1.5.1 - 2016-06-14
- Removed -d flag from pg_dump for compability with pgsql 7.3+
## 1.5.0 - 2016-06-01
- Added `includeTables` and `excludeTables`
## 1.4.0 - 2016-04-27
- Added --single-transaction option to Mysql dump command
## 1.3.0 - 2016-04-03
- Added the ability to use insert when dumping a PostgreSQL db
## 1.2.4 - 2016-03-24
- Added more details about a dump failure in the error message
## 1.2.3 - 2016-03-18
- Fixed an issue where paths containing spaces would cause problems
## 1.2.2 - 2016-03-16
- Added an option to set a timeout
## 1.2.1 - 2016-03-14
- Fixed PostgreSQL dump
## 1.2.0 - 2016-03-13
- Added support for PostgreSQL
## 1.1.0 - 2016-02-21
- Lowered PHP and symfony requirements
## 1.0.4 - 2016-02-14
- Fixed a bug when the backup has failed.
## 1.0.3 - 2016-02-01
- Added missing abstract `getDbName`-method
## 1.0.2 - 2016-02-01
- Added missing abstract `dumpToFile`-method
## 1.0.1 - 2016-01-19
- Fixed typo in `checkIfDumpWasSuccessFul`-method name
- Fixed bug running Process
## 1.0.0 - 2016-01-19
- Initial release

21
vendor/spatie/db-dumper/LICENSE.md vendored Normal file
View File

@@ -0,0 +1,21 @@
The MIT License (MIT)
Copyright (c) Spatie bvba <info@spatie.be>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

301
vendor/spatie/db-dumper/README.md vendored Normal file
View File

@@ -0,0 +1,301 @@
# Dump the contents of a database
[![Latest Version on Packagist](https://img.shields.io/packagist/v/spatie/db-dumper.svg?style=flat-square)](https://packagist.org/packages/spatie/db-dumper)
![run-tests](https://github.com/spatie/db-dumper/workflows/run-tests/badge.svg)
[![MIT Licensed](https://img.shields.io/badge/license-MIT-brightgreen.svg?style=flat-square)](LICENSE.md)
[![Total Downloads](https://img.shields.io/packagist/dt/spatie/db-dumper.svg?style=flat-square)](https://packagist.org/packages/spatie/db-dumper)
This repo contains an easy to use class to dump a database using PHP. Currently MySQL, PostgreSQL, SQLite and MongoDB are supported. Behind
the scenes `mysqldump`, `pg_dump`, `sqlite3` and `mongodump` are used.
Here's are simple examples of how to create a database dump with different drivers:
**MySQL**
```php
Spatie\DbDumper\Databases\MySql::create()
->setDbName($databaseName)
->setUserName($userName)
->setPassword($password)
->dumpToFile('dump.sql');
```
**PostgreSQL**
```php
Spatie\DbDumper\Databases\PostgreSql::create()
->setDbName($databaseName)
->setUserName($userName)
->setPassword($password)
->dumpToFile('dump.sql');
```
**SQLite**
```php
Spatie\DbDumper\Databases\Sqlite::create()
->setDbName($pathToDatabaseFile)
->dumpToFile('dump.sql');
```
**MongoDB**
```php
Spatie\DbDumper\Databases\MongoDb::create()
->setDbName($databaseName)
->setUserName($userName)
->setPassword($password)
->dumpToFile('dump.gz');
```
## Support us
[<img src="https://github-ads.s3.eu-central-1.amazonaws.com/db-dumper.jpg?t=1" width="419px" />](https://spatie.be/github-ad-click/db-dumper)
We invest a lot of resources into creating [best in class open source packages](https://spatie.be/open-source). You can support us by [buying one of our paid products](https://spatie.be/open-source/support-us).
We highly appreciate you sending us a postcard from your hometown, mentioning which of our package(s) you are using. You'll find our address on [our contact page](https://spatie.be/about-us). We publish all received postcards on [our virtual postcard wall](https://spatie.be/open-source/postcards).
## Requirements
For dumping MySQL-db's `mysqldump` should be installed.
For dumping PostgreSQL-db's `pg_dump` should be installed.
For dumping SQLite-db's `sqlite3` should be installed.
For dumping MongoDB-db's `mongodump` should be installed.
## Installation
You can install the package via composer:
``` bash
composer require spatie/db-dumper
```
## Usage
This is the simplest way to create a dump of a MySql db:
```php
Spatie\DbDumper\Databases\MySql::create()
->setDbName($databaseName)
->setUserName($userName)
->setPassword($password)
->dumpToFile('dump.sql');
```
If you're working with PostgreSQL just use that dumper, most methods are available on both the MySql. and PostgreSql-dumper.
```php
Spatie\DbDumper\Databases\PostgreSql::create()
->setDbName($databaseName)
->setUserName($userName)
->setPassword($password)
->dumpToFile('dump.sql');
```
If the `mysqldump` (or `pg_dump`) binary is installed in a non default location you can let the package know by using the`setDumpBinaryPath()`-function:
```php
Spatie\DbDumper\Databases\MySql::create()
->setDumpBinaryPath('/custom/location')
->setDbName($databaseName)
->setUserName($userName)
->setPassword($password)
->dumpToFile('dump.sql');
```
If your application is deployed and you need to change the host (default is 127.0.0.1), you can add the `setHost()`-function:
```php
Spatie\DbDumper\Databases\MySql::create()
->setDbName($databaseName)
->setUserName($userName)
->setPassword($password)
->setHost($host)
->dumpToFile('dump.sql');
```
### Dump specific tables
Using an array:
```php
Spatie\DbDumper\Databases\MySql::create()
->setDbName($databaseName)
->setUserName($userName)
->setPassword($password)
->includeTables(['table1', 'table2', 'table3'])
->dumpToFile('dump.sql');
```
Using a string:
```php
Spatie\DbDumper\Databases\MySql::create()
->setDbName($databaseName)
->setUserName($userName)
->setPassword($password)
->includeTables('table1, table2, table3')
->dumpToFile('dump.sql');
```
### Don't use column_statics table with some old version of MySql service.
In order to use "_--column-statistics=0_" as option in mysqldump command you can use _doNotUseColumnStatistics()_ method.
If you have installed _mysqldump 8_, it queries by default _column_statics_ table in _information_schema_ database.
In some old version of MySql (service) like 5.7, this table it not exists. So you could have an exception during the execution of mysqldump. To avoid this, you could use _doNotUseColumnStatistics()_ method.
```php
Spatie\DbDumper\Databases\MySql::create()
->setDbName($databaseName)
->setUserName($userName)
->setPassword($password)
->doNotUseColumnStatistics()
->dumpToFile('dump.sql');
```
### Excluding tables from the dump
Using an array:
```php
Spatie\DbDumper\Databases\MySql::create()
->setDbName($databaseName)
->setUserName($userName)
->setPassword($password)
->excludeTables(['table1', 'table2', 'table3'])
->dumpToFile('dump.sql');
```
Using a string:
```php
Spatie\DbDumper\Databases\MySql::create()
->setDbName($databaseName)
->setUserName($userName)
->setPassword($password)
->excludeTables('table1, table2, table3')
->dumpToFile('dump.sql');
```
### Do not write CREATE TABLE statements that create each dumped table.
```php
$dumpCommand = MySql::create()
->setDbName('dbname')
->setUserName('username')
->setPassword('password')
->doNotCreateTables()
->getDumpCommand('dump.sql', 'credentials.txt');
```
### Adding extra options
If you want to add an arbitrary option to the dump command you can use `addExtraOption`
```php
$dumpCommand = MySql::create()
->setDbName('dbname')
->setUserName('username')
->setPassword('password')
->addExtraOption('--xml')
->getDumpCommand('dump.sql', 'credentials.txt');
```
If you're working with MySql you can set the database name using `--databases` as an extra option. This is particularly useful when used in conjunction with the `--add-drop-database` `mysqldump` option (see the [mysqldump docs](https://dev.mysql.com/doc/refman/5.7/en/mysqldump.html#option_mysqldump_add-drop-database)).
```php
$dumpCommand = MySql::create()
->setUserName('username')
->setPassword('password')
->addExtraOption('--databases dbname')
->addExtraOption('--add-drop-database')
->getDumpCommand('dump.sql', 'credentials.txt');
```
With MySql, you also have the option to use the `--all-databases` extra option. This is useful when you want to run a full backup of all the databases in the specified MySQL connection.
```php
$dumpCommand = MySql::create()
->setUserName('username')
->setPassword('password')
->addExtraOption('--all-databases')
->getDumpCommand('dump.sql', 'credentials.txt');
```
Please note that using the `->addExtraOption('--databases dbname')` or `->addExtraOption('--all-databases')` will override the database name set on a previous `->setDbName()` call.
### Using compression
If you want to compress the outputted file, you can use one of the compressors and the resulted dump file will be compressed.
There is one compressor that comes out of the box: `GzipCompressor`. It will compress your db dump with `gzip`. Make sure `gzip` is installed on your system before using this.
```php
$dumpCommand = MySql::create()
->setDbName('dbname')
->setUserName('username')
->setPassword('password')
->useCompressor(new GzipCompressor())
->dumpToFile('dump.sql.gz');
```
### Creating your own compressor
You can create you own compressor implementing the `Compressor` interface. Here's how that interface looks like:
```php
namespace Spatie\DbDumper\Compressors;
interface Compressor
{
public function useCommand(): string;
public function useExtension(): string;
}
```
The `useCommand` should simply return the compression command the db dump will get pumped to. Here's the implementation of `GzipCompression`.
```php
namespace Spatie\DbDumper\Compressors;
class GzipCompressor implements Compressor
{
public function useCommand(): string
{
return 'gzip';
}
public function useExtension(): string
{
return 'gz';
}
}
```
## Changelog
Please see [CHANGELOG](CHANGELOG.md) for more information what has changed recently.
## Testing
``` bash
composer test
```
## Contributing
Please see [CONTRIBUTING](.github/CONTRIBUTING.md) for details.
## Security
If you discover any security related issues, please email freek@spatie.be instead of using the issue tracker.
## Credits
- [Freek Van der Herten](https://github.com/freekmurze)
- [All Contributors](../../contributors)
Initial PostgreSQL support was contributed by [Adriano Machado](https://github.com/ammachado). SQlite support was contributed by [Peter Matseykanets](https://twitter.com/pmatseykanets).
## License
The MIT License (MIT). Please see [License File](LICENSE.md) for more information.

41
vendor/spatie/db-dumper/composer.json vendored Normal file
View File

@@ -0,0 +1,41 @@
{
"name": "spatie/db-dumper",
"description": "Dump databases",
"keywords": [
"spatie",
"dump",
"database",
"mysqldump",
"db-dumper"
],
"homepage": "https://github.com/spatie/db-dumper",
"license": "MIT",
"authors": [
{
"name": "Freek Van der Herten",
"email": "freek@spatie.be",
"homepage": "https://spatie.be",
"role": "Developer"
}
],
"require": {
"php" : "^7.2|^8.0",
"symfony/process": "^4.2|^5.0"
},
"require-dev": {
"phpunit/phpunit": "^7.0|^8.0|^9.0"
},
"autoload": {
"psr-4": {
"Spatie\\DbDumper\\": "src"
}
},
"autoload-dev": {
"psr-4": {
"Spatie\\DbDumper\\Test\\": "tests"
}
},
"scripts": {
"test": "vendor/bin/phpunit"
}
}

View File

@@ -0,0 +1,10 @@
<?php
namespace Spatie\DbDumper\Compressors;
interface Compressor
{
public function useCommand(): string;
public function useExtension(): string;
}

View File

@@ -0,0 +1,16 @@
<?php
namespace Spatie\DbDumper\Compressors;
class GzipCompressor implements Compressor
{
public function useCommand(): string
{
return 'gzip';
}
public function useExtension(): string
{
return 'gz';
}
}

View File

@@ -0,0 +1,131 @@
<?php
namespace Spatie\DbDumper\Databases;
use Spatie\DbDumper\DbDumper;
use Spatie\DbDumper\Exceptions\CannotStartDump;
use Symfony\Component\Process\Process;
class MongoDb extends DbDumper
{
protected $port = 27017;
/** @var null|string */
protected $collection = null;
/** @var null|string */
protected $authenticationDatabase = null;
/**
* Dump the contents of the database to the given file.
*
* @param string $dumpFile
*
* @throws \Spatie\DbDumper\Exceptions\CannotStartDump
* @throws \Spatie\DbDumper\Exceptions\DumpFailed
*/
public function dumpToFile(string $dumpFile)
{
$this->guardAgainstIncompleteCredentials();
$process = $this->getProcess($dumpFile);
$process->run();
$this->checkIfDumpWasSuccessFul($process, $dumpFile);
}
/**
* Verifies if the dbname and host options are set.
*
* @throws \Spatie\DbDumper\Exceptions\CannotStartDump
* @return void
*/
public function guardAgainstIncompleteCredentials()
{
foreach (['dbName', 'host'] as $requiredProperty) {
if (strlen($this->$requiredProperty) === 0) {
throw CannotStartDump::emptyParameter($requiredProperty);
}
}
}
/**
* @param string $collection
*
* @return \Spatie\DbDumper\Databases\MongoDb
*/
public function setCollection(string $collection)
{
$this->collection = $collection;
return $this;
}
/**
* @param string $authenticationDatabase
*
* @return \Spatie\DbDumper\Databases\MongoDb
*/
public function setAuthenticationDatabase(string $authenticationDatabase)
{
$this->authenticationDatabase = $authenticationDatabase;
return $this;
}
/**
* Generate the dump command for MongoDb.
*
* @param string $filename
*
* @return string
*/
public function getDumpCommand(string $filename): string
{
$quote = $this->determineQuote();
$command = [
"{$quote}{$this->dumpBinaryPath}mongodump{$quote}",
"--db {$this->dbName}",
'--archive',
];
if ($this->userName) {
$command[] = "--username '{$this->userName}'";
}
if ($this->password) {
$command[] = "--password '{$this->password}'";
}
if (isset($this->host)) {
$command[] = "--host {$this->host}";
}
if (isset($this->port)) {
$command[] = "--port {$this->port}";
}
if (isset($this->collection)) {
$command[] = "--collection {$this->collection}";
}
if ($this->authenticationDatabase) {
$command[] = "--authenticationDatabase {$this->authenticationDatabase}";
}
return $this->echoToFile(implode(' ', $command), $filename);
}
/**
* @param string $dumpFile
* @return Process
*/
public function getProcess(string $dumpFile): Process
{
$command = $this->getDumpCommand($dumpFile);
return Process::fromShellCommandline($command, null, null, null, $this->timeout);
}
}

View File

@@ -0,0 +1,368 @@
<?php
namespace Spatie\DbDumper\Databases;
use Spatie\DbDumper\DbDumper;
use Spatie\DbDumper\Exceptions\CannotStartDump;
use Symfony\Component\Process\Process;
class MySql extends DbDumper
{
/** @var bool */
protected $skipComments = true;
/** @var bool */
protected $useExtendedInserts = true;
/** @var bool */
protected $useSingleTransaction = false;
/** @var bool */
protected $skipLockTables = false;
/** @var bool */
protected $doNotUseColumnStatistics = false;
/** @var bool */
protected $useQuick = false;
/** @var string */
protected $defaultCharacterSet = '';
/** @var bool */
protected $dbNameWasSetAsExtraOption = false;
/** @var bool */
protected $allDatabasesWasSetAsExtraOption = false;
/** @var string */
protected $setGtidPurged = 'AUTO';
/** @var bool */
protected $createTables = true;
/** @var false|resource */
private $tempFileHandle;
public function __construct()
{
$this->port = 3306;
}
/**
* @return $this
*/
public function skipComments()
{
$this->skipComments = true;
return $this;
}
/**
* @return $this
*/
public function dontSkipComments()
{
$this->skipComments = false;
return $this;
}
/**
* @return $this
*/
public function useExtendedInserts()
{
$this->useExtendedInserts = true;
return $this;
}
/**
* @return $this
*/
public function dontUseExtendedInserts()
{
$this->useExtendedInserts = false;
return $this;
}
/**
* @return $this
*/
public function useSingleTransaction()
{
$this->useSingleTransaction = true;
return $this;
}
/**
* @return $this
*/
public function dontUseSingleTransaction()
{
$this->useSingleTransaction = false;
return $this;
}
/**
* @return $this
*/
public function skipLockTables()
{
$this->skipLockTables = true;
return $this;
}
/**
* @return $this
*/
public function doNotUseColumnStatistics()
{
$this->doNotUseColumnStatistics = true;
return $this;
}
/**
* @return $this
*/
public function dontSkipLockTables()
{
$this->skipLockTables = false;
return $this;
}
/**
* @return $this
*/
public function useQuick()
{
$this->useQuick = true;
return $this;
}
/**
* @return $this
*/
public function dontUseQuick()
{
$this->useQuick = false;
return $this;
}
/**
* @param string $characterSet
*
* @return $this
*/
public function setDefaultCharacterSet(string $characterSet)
{
$this->defaultCharacterSet = $characterSet;
return $this;
}
/**
* @return $this
*/
public function setGtidPurged(string $setGtidPurged)
{
$this->setGtidPurged = $setGtidPurged;
return $this;
}
/**
* Dump the contents of the database to the given file.
*
* @param string $dumpFile
*
* @throws \Spatie\DbDumper\Exceptions\CannotStartDump
* @throws \Spatie\DbDumper\Exceptions\DumpFailed
*/
public function dumpToFile(string $dumpFile)
{
$this->guardAgainstIncompleteCredentials();
$tempFileHandle = tmpfile();
$this->setTempFileHandle($tempFileHandle);
$process = $this->getProcess($dumpFile);
$process->run();
$this->checkIfDumpWasSuccessFul($process, $dumpFile);
}
public function addExtraOption(string $extraOption)
{
if (strpos($extraOption, '--all-databases') !== false) {
$this->dbNameWasSetAsExtraOption = true;
$this->allDatabasesWasSetAsExtraOption = true;
}
if (preg_match('/^--databases (\S+)/', $extraOption, $matches) === 1) {
$this->setDbName($matches[1]);
$this->dbNameWasSetAsExtraOption = true;
}
return parent::addExtraOption($extraOption);
}
/**
* @return $this
*/
public function doNotCreateTables()
{
$this->createTables = false;
return $this;
}
/**
* Get the command that should be performed to dump the database.
*
* @param string $dumpFile
* @param string $temporaryCredentialsFile
*
* @return string
*/
public function getDumpCommand(string $dumpFile, string $temporaryCredentialsFile): string
{
$quote = $this->determineQuote();
$command = [
"{$quote}{$this->dumpBinaryPath}mysqldump{$quote}",
"--defaults-extra-file=\"{$temporaryCredentialsFile}\"",
];
if (! $this->createTables) {
$command[] = '--no-create-info';
}
if ($this->skipComments) {
$command[] = '--skip-comments';
}
$command[] = $this->useExtendedInserts ? '--extended-insert' : '--skip-extended-insert';
if ($this->useSingleTransaction) {
$command[] = '--single-transaction';
}
if ($this->skipLockTables) {
$command[] = '--skip-lock-tables';
}
if ($this->doNotUseColumnStatistics) {
$command[] = '--column-statistics=0';
}
if ($this->useQuick) {
$command[] = '--quick';
}
if ($this->socket !== '') {
$command[] = "--socket={$this->socket}";
}
foreach ($this->excludeTables as $tableName) {
$command[] = "--ignore-table={$this->dbName}.{$tableName}";
}
if (! empty($this->defaultCharacterSet)) {
$command[] = '--default-character-set='.$this->defaultCharacterSet;
}
foreach ($this->extraOptions as $extraOption) {
$command[] = $extraOption;
}
if ($this->setGtidPurged !== 'AUTO') {
$command[] = '--set-gtid-purged='.$this->setGtidPurged;
}
if (! $this->dbNameWasSetAsExtraOption) {
$command[] = $this->dbName;
}
if (! empty($this->includeTables)) {
$includeTables = implode(' ', $this->includeTables);
$command[] = "--tables {$includeTables}";
}
foreach ($this->extraOptionsAfterDbName as $extraOptionAfterDbName) {
$command[] = $extraOptionAfterDbName;
}
return $this->echoToFile(implode(' ', $command), $dumpFile);
}
public function getContentsOfCredentialsFile(): string
{
$contents = [
'[client]',
"user = '{$this->userName}'",
"password = '{$this->password}'",
"port = '{$this->port}'",
];
if ($this->socket === '') {
$contents[] = "host = '{$this->host}'";
}
return implode(PHP_EOL, $contents);
}
public function guardAgainstIncompleteCredentials()
{
foreach (['userName', 'host'] as $requiredProperty) {
if (strlen($this->$requiredProperty) === 0) {
throw CannotStartDump::emptyParameter($requiredProperty);
}
}
if (strlen($this->dbName) === 0 && ! $this->allDatabasesWasSetAsExtraOption) {
throw CannotStartDump::emptyParameter('dbName');
}
}
/**
* @param string $dumpFile
* @return Process
*/
public function getProcess(string $dumpFile): Process
{
fwrite($this->getTempFileHandle(), $this->getContentsOfCredentialsFile());
$temporaryCredentialsFile = stream_get_meta_data($this->getTempFileHandle())['uri'];
$command = $this->getDumpCommand($dumpFile, $temporaryCredentialsFile);
return Process::fromShellCommandline($command, null, null, null, $this->timeout);
}
/**
* @return false|resource
*/
public function getTempFileHandle()
{
return $this->tempFileHandle;
}
/**
* @param false|resource $tempFileHandle
*/
public function setTempFileHandle($tempFileHandle)
{
$this->tempFileHandle = $tempFileHandle;
}
}

View File

@@ -0,0 +1,169 @@
<?php
namespace Spatie\DbDumper\Databases;
use Spatie\DbDumper\DbDumper;
use Spatie\DbDumper\Exceptions\CannotStartDump;
use Symfony\Component\Process\Process;
class PostgreSql extends DbDumper
{
/** @var bool */
protected $useInserts = false;
/** @var bool */
protected $createTables = true;
/** @var false|resource */
private $tempFileHandle;
public function __construct()
{
$this->port = 5432;
}
/**
* @return $this
*/
public function useInserts()
{
$this->useInserts = true;
return $this;
}
/**
* Dump the contents of the database to the given file.
*
* @param string $dumpFile
*
* @throws \Spatie\DbDumper\Exceptions\CannotStartDump
* @throws \Spatie\DbDumper\Exceptions\DumpFailed
*/
public function dumpToFile(string $dumpFile)
{
$this->guardAgainstIncompleteCredentials();
$tempFileHandle = tmpfile();
$this->setTempFileHandle($tempFileHandle);
$process = $this->getProcess($dumpFile);
$process->run();
$this->checkIfDumpWasSuccessFul($process, $dumpFile);
}
/**
* Get the command that should be performed to dump the database.
*
* @param string $dumpFile
*
* @return string
*/
public function getDumpCommand(string $dumpFile): string
{
$quote = $this->determineQuote();
$command = [
"{$quote}{$this->dumpBinaryPath}pg_dump{$quote}",
"-U {$this->userName}",
'-h '.($this->socket === '' ? $this->host : $this->socket),
"-p {$this->port}",
];
if ($this->useInserts) {
$command[] = '--inserts';
}
if (! $this->createTables) {
$command[] = '--data-only';
}
foreach ($this->extraOptions as $extraOption) {
$command[] = $extraOption;
}
if (! empty($this->includeTables)) {
$command[] = '-t '.implode(' -t ', $this->includeTables);
}
if (! empty($this->excludeTables)) {
$command[] = '-T '.implode(' -T ', $this->excludeTables);
}
return $this->echoToFile(implode(' ', $command), $dumpFile);
}
public function getContentsOfCredentialsFile(): string
{
$contents = [
$this->host,
$this->port,
$this->dbName,
$this->userName,
$this->password,
];
return implode(':', $contents);
}
public function guardAgainstIncompleteCredentials()
{
foreach (['userName', 'dbName', 'host'] as $requiredProperty) {
if (empty($this->$requiredProperty)) {
throw CannotStartDump::emptyParameter($requiredProperty);
}
}
}
protected function getEnvironmentVariablesForDumpCommand(string $temporaryCredentialsFile): array
{
return [
'PGPASSFILE' => $temporaryCredentialsFile,
'PGDATABASE' => $this->dbName,
];
}
/**
* @return $this
*/
public function doNotCreateTables()
{
$this->createTables = false;
return $this;
}
/**
* @param string $dumpFile
* @return Process
*/
public function getProcess(string $dumpFile): Process
{
$command = $this->getDumpCommand($dumpFile);
fwrite($this->getTempFileHandle(), $this->getContentsOfCredentialsFile());
$temporaryCredentialsFile = stream_get_meta_data($this->getTempFileHandle())['uri'];
$envVars = $this->getEnvironmentVariablesForDumpCommand($temporaryCredentialsFile);
return Process::fromShellCommandline($command, null, $envVars, null, $this->timeout);
}
/**
* @return false|resource
*/
public function getTempFileHandle()
{
return $this->tempFileHandle;
}
/**
* @param false|resource $tempFileHandle
*/
public function setTempFileHandle($tempFileHandle)
{
$this->tempFileHandle = $tempFileHandle;
}
}

View File

@@ -0,0 +1,60 @@
<?php
namespace Spatie\DbDumper\Databases;
use Spatie\DbDumper\DbDumper;
use Symfony\Component\Process\Process;
class Sqlite extends DbDumper
{
/**
* Dump the contents of the database to a given file.
*
* @param string $dumpFile
*
* @throws \Spatie\DbDumper\Exceptions\DumpFailed
*/
public function dumpToFile(string $dumpFile)
{
$process = $this->getProcess($dumpFile);
$process->run();
$this->checkIfDumpWasSuccessFul($process, $dumpFile);
}
/**
* Get the command that should be performed to dump the database.
*
* @param string $dumpFile
*
* @return string
*/
public function getDumpCommand(string $dumpFile): string
{
$dumpInSqlite = "echo 'BEGIN IMMEDIATE;\n.dump'";
if ($this->isWindows()) {
$dumpInSqlite = '(echo BEGIN IMMEDIATE; & echo .dump)';
}
$quote = $this->determineQuote();
$command = sprintf(
"{$dumpInSqlite} | {$quote}%ssqlite3{$quote} --bail {$quote}%s{$quote}",
$this->dumpBinaryPath,
$this->dbName
);
return $this->echoToFile($command, $dumpFile);
}
/**
* @param string $dumpFile
* @return Process
*/
public function getProcess(string $dumpFile): Process
{
$command = $this->getDumpCommand($dumpFile);
return Process::fromShellCommandline($command, null, null, null, $this->timeout);
}
}

306
vendor/spatie/db-dumper/src/DbDumper.php vendored Normal file
View File

@@ -0,0 +1,306 @@
<?php
namespace Spatie\DbDumper;
use Spatie\DbDumper\Compressors\Compressor;
use Spatie\DbDumper\Compressors\GzipCompressor;
use Spatie\DbDumper\Exceptions\CannotSetParameter;
use Spatie\DbDumper\Exceptions\DumpFailed;
use Symfony\Component\Process\Process;
abstract class DbDumper
{
/** @var string */
protected $dbName;
/** @var string */
protected $userName;
/** @var string */
protected $password;
/** @var string */
protected $host = 'localhost';
/** @var int */
protected $port = 5432;
/** @var string */
protected $socket = '';
/** @var int */
protected $timeout = 0;
/** @var string */
protected $dumpBinaryPath = '';
/** @var array */
protected $includeTables = [];
/** @var array */
protected $excludeTables = [];
/** @var array */
protected $extraOptions = [];
/** @var array */
protected $extraOptionsAfterDbName = [];
/** @var object */
protected $compressor = null;
public static function create()
{
return new static();
}
public function getDbName(): string
{
return $this->dbName;
}
/**
* @param string $dbName
*
* @return $this
*/
public function setDbName(string $dbName)
{
$this->dbName = $dbName;
return $this;
}
/**
* @param string $userName
*
* @return $this
*/
public function setUserName(string $userName)
{
$this->userName = $userName;
return $this;
}
/**
* @param string $password
*
* @return $this
*/
public function setPassword(string $password)
{
$this->password = $password;
return $this;
}
/**
* @param string $host
*
* @return $this
*/
public function setHost(string $host)
{
$this->host = $host;
return $this;
}
public function getHost(): string
{
return $this->host;
}
/**
* @param int $port
*
* @return $this
*/
public function setPort(int $port)
{
$this->port = $port;
return $this;
}
/**
* @param string $socket
*
* @return $this
*/
public function setSocket(string $socket)
{
$this->socket = $socket;
return $this;
}
/**
* @param int $timeout
*
* @return $this
*/
public function setTimeout(int $timeout)
{
$this->timeout = $timeout;
return $this;
}
public function setDumpBinaryPath(string $dumpBinaryPath)
{
if ($dumpBinaryPath !== '' && substr($dumpBinaryPath, -1) !== '/') {
$dumpBinaryPath .= '/';
}
$this->dumpBinaryPath = $dumpBinaryPath;
return $this;
}
/**
* @deprecated
*
* @return $this
*/
public function enableCompression()
{
$this->compressor = new GzipCompressor();
return $this;
}
public function getCompressorExtension(): string
{
return $this->compressor->useExtension();
}
public function useCompressor(Compressor $compressor)
{
$this->compressor = $compressor;
return $this;
}
/**
* @param string|array $includeTables
*
* @return $this
*
* @throws \Spatie\DbDumper\Exceptions\CannotSetParameter
*/
public function includeTables($includeTables)
{
if (! empty($this->excludeTables)) {
throw CannotSetParameter::conflictingParameters('includeTables', 'excludeTables');
}
if (! is_array($includeTables)) {
$includeTables = explode(', ', $includeTables);
}
$this->includeTables = $includeTables;
return $this;
}
/**
* @param string|array $excludeTables
*
* @return $this
*
* @throws \Spatie\DbDumper\Exceptions\CannotSetParameter
*/
public function excludeTables($excludeTables)
{
if (! empty($this->includeTables)) {
throw CannotSetParameter::conflictingParameters('excludeTables', 'includeTables');
}
if (! is_array($excludeTables)) {
$excludeTables = explode(', ', $excludeTables);
}
$this->excludeTables = $excludeTables;
return $this;
}
/**
* @param string $extraOption
*
* @return $this
*/
public function addExtraOption(string $extraOption)
{
if (! empty($extraOption)) {
$this->extraOptions[] = $extraOption;
}
return $this;
}
/**
* @param string $extraOptionAtEnd
*
* @return $this
*/
public function addExtraOptionAfterDbName(string $extraOptionAfterDbName)
{
if (! empty($extraOptionAfterDbName)) {
$this->extraOptionsAfterDbName[] = $extraOptionAfterDbName;
}
return $this;
}
abstract public function dumpToFile(string $dumpFile);
public function checkIfDumpWasSuccessFul(Process $process, string $outputFile)
{
if (! $process->isSuccessful()) {
throw DumpFailed::processDidNotEndSuccessfully($process);
}
if (! file_exists($outputFile)) {
throw DumpFailed::dumpfileWasNotCreated();
}
if (filesize($outputFile) === 0) {
throw DumpFailed::dumpfileWasEmpty();
}
}
protected function getCompressCommand(string $command, string $dumpFile): string
{
$compressCommand = $this->compressor->useCommand();
if ($this->isWindows()) {
return "{$command} | {$compressCommand} > {$dumpFile}";
}
return "(((({$command}; echo \$? >&3) | {$compressCommand} > {$dumpFile}) 3>&1) | (read x; exit \$x))";
}
protected function echoToFile(string $command, string $dumpFile): string
{
$dumpFile = '"'.addcslashes($dumpFile, '\\"').'"';
if ($this->compressor) {
return $this->getCompressCommand($command, $dumpFile);
}
return $command.' > '.$dumpFile;
}
protected function determineQuote(): string
{
return $this->isWindows() ? '"' : "'";
}
protected function isWindows(): bool
{
return strtoupper(substr(PHP_OS, 0, 3)) === 'WIN';
}
}

View File

@@ -0,0 +1,19 @@
<?php
namespace Spatie\DbDumper\Exceptions;
use Exception;
class CannotSetParameter extends Exception
{
/**
* @param string $name
* @param string $conflictName
*
* @return \Spatie\DbDumper\Exceptions\CannotSetParameter
*/
public static function conflictingParameters($name, $conflictName)
{
return new static("Cannot set `{$name}` because it conflicts with parameter `{$conflictName}`.");
}
}

View File

@@ -0,0 +1,18 @@
<?php
namespace Spatie\DbDumper\Exceptions;
use Exception;
class CannotStartDump extends Exception
{
/**
* @param string $name
*
* @return \Spatie\DbDumper\Exceptions\CannotStartDump
*/
public static function emptyParameter($name)
{
return new static("Parameter `{$name}` cannot be empty.");
}
}

View File

@@ -0,0 +1,35 @@
<?php
namespace Spatie\DbDumper\Exceptions;
use Exception;
use Symfony\Component\Process\Process;
class DumpFailed extends Exception
{
/**
* @param \Symfony\Component\Process\Process $process
*
* @return \Spatie\DbDumper\Exceptions\DumpFailed
*/
public static function processDidNotEndSuccessfully(Process $process)
{
return new static("The dump process failed with exitcode {$process->getExitCode()} : {$process->getExitCodeText()} : {$process->getErrorOutput()}");
}
/**
* @return \Spatie\DbDumper\Exceptions\DumpFailed
*/
public static function dumpfileWasNotCreated()
{
return new static('The dumpfile could not be created');
}
/**
* @return \Spatie\DbDumper\Exceptions\DumpFailed
*/
public static function dumpfileWasEmpty()
{
return new static('The created dumpfile is empty');
}
}