mirror of
https://github.com/archtechx/tenancy.git
synced 2025-12-12 14:14:04 +00:00
merge 3.x
This commit is contained in:
commit
eca7b336bc
30 changed files with 524 additions and 147 deletions
11
.github/workflows/ci.yml
vendored
11
.github/workflows/ci.yml
vendored
|
|
@ -15,8 +15,11 @@ jobs:
|
|||
|
||||
strategy:
|
||||
matrix:
|
||||
php: ["7.4", "8.0.11"]
|
||||
laravel: ["^6.0", "^8.0"]
|
||||
php: ["7.3", "8.0"]
|
||||
laravel: ["^6.0", "^8.0", "^9.0"]
|
||||
exclude:
|
||||
- laravel: "^9.0"
|
||||
php: "7.3"
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v2
|
||||
|
|
@ -26,7 +29,3 @@ jobs:
|
|||
run: docker-compose exec -T test composer require --no-interaction "laravel/framework:${{ matrix.laravel }}"
|
||||
- name: Run tests
|
||||
run: ./test
|
||||
- name: Send code coverage to codecov
|
||||
env:
|
||||
CODECOV_TOKEN: 24382d15-84e7-4a55-bea4-c4df96a24a9b
|
||||
run: bash <(curl -s https://codecov.io/bash)
|
||||
|
|
|
|||
2
.gitignore
vendored
2
.gitignore
vendored
|
|
@ -8,3 +8,5 @@ psysh
|
|||
phpunit_var_*.xml
|
||||
coverage/
|
||||
clover.xml
|
||||
tests/Etc/tmp/queuetest.json
|
||||
docker-compose.override.yml
|
||||
|
|
|
|||
|
|
@ -9,3 +9,16 @@ StyleCI will flag code style violations in your pull requests.
|
|||
Run `docker-compose up -d` to start the containers. Then run `./test` to run the tests.
|
||||
|
||||
When you're done testing, run `docker-compose down` to shut down the containers.
|
||||
|
||||
### Docker on M1
|
||||
|
||||
You can add:
|
||||
```yaml
|
||||
services:
|
||||
mysql:
|
||||
platform: linux/amd64
|
||||
mysql2:
|
||||
platform: linux/amd64
|
||||
```
|
||||
|
||||
to `docker-compose.override.yml` to make `docker-compose up-d` work on M1.
|
||||
|
|
|
|||
|
|
@ -30,7 +30,7 @@ RUN docker-php-ext-configure pgsql -with-pgsql=/usr/local/pgsql \
|
|||
# && if [ "${PHP_VERSION}" = "7.4" ]; then docker-php-ext-configure gd --with-freetype --with-jpeg; else docker-php-ext-configure gd --with-freetype-dir=/usr/include/ --with-jpeg-dir=/usr/include/; fi \
|
||||
&& docker-php-ext-install -j$(nproc) gd pdo pdo_mysql pdo_pgsql pdo_sqlite pgsql zip gmp bcmath pcntl ldap sysvmsg exif \
|
||||
# install the redis php extension
|
||||
&& pecl install redis-5.3.2 \
|
||||
&& pecl install redis-5.3.7 \
|
||||
&& docker-php-ext-enable redis \
|
||||
# install the pcov extention
|
||||
&& pecl install pcov \
|
||||
|
|
|
|||
|
|
@ -3,10 +3,9 @@
|
|||
</p>
|
||||
|
||||
<p align="center">
|
||||
<a href="https://laravel.com"><img alt="Laravel 6.x/7.x/8.x" src="https://img.shields.io/badge/laravel-6.x/7.x/8.x-red.svg"></a>
|
||||
<a href="https://laravel.com"><img alt="Laravel 9.x" src="https://img.shields.io/badge/laravel-9.x-red.svg"></a>
|
||||
<a href="https://packagist.org/packages/stancl/tenancy"><img alt="Latest Stable Version" src="https://poser.pugx.org/stancl/tenancy/version"></a>
|
||||
<a href="https://github.com/stancl/tenancy/actions"><img alt="GitHub Actions CI status" src="https://github.com/stancl/tenancy/workflows/CI/badge.svg"></a>
|
||||
<a href="https://codecov.io/gh/stancl/tenancy"><img alt="codecov" src="https://codecov.io/gh/stancl/tenancy/branch/3.x/graph/badge.svg"></a>
|
||||
<a href="https://github.com/stancl/tenancy/blob/3.x/DONATIONS.md"><img alt="Donate" src="https://img.shields.io/badge/Donate-%3C3-red"></a>
|
||||
</p>
|
||||
|
||||
|
|
|
|||
|
|
@ -42,7 +42,8 @@ return [
|
|||
'central_connection' => env('DB_CONNECTION', 'central'),
|
||||
|
||||
/**
|
||||
* Connection used as a "template" for the tenant database connection.
|
||||
* Connection used as a "template" for the dynamically created tenant database connection.
|
||||
* Note: don't name your template connection tenant. That name is reserved by package.
|
||||
*/
|
||||
'template_tenant_connection' => null,
|
||||
|
||||
|
|
|
|||
|
|
@ -11,17 +11,16 @@
|
|||
],
|
||||
"require": {
|
||||
"ext-json": "*",
|
||||
"illuminate/support": "dev-master",
|
||||
"illuminate/support": "^6.0|^7.0|^8.0|^9.0",
|
||||
"facade/ignition-contracts": "^1.0",
|
||||
"ramsey/uuid": "^3.7|^4.0",
|
||||
"stancl/jobpipeline": "dev-master",
|
||||
"stancl/virtualcolumn": "dev-master"
|
||||
},
|
||||
"require-dev": {
|
||||
"vlucas/phpdotenv": "^3.3|^4.0|^5.0",
|
||||
"laravel/framework": "dev-master",
|
||||
"orchestra/testbench-browser-kit": "dev-master",
|
||||
"league/flysystem-aws-s3-v3": "*",
|
||||
"laravel/framework": "^6.0|^7.0|^8.0|^9.0",
|
||||
"orchestra/testbench": "^4.0|^5.0|^6.0|^7.0",
|
||||
"league/flysystem-aws-s3-v3": "^1.0|^3.0",
|
||||
"doctrine/dbal": "^2.10",
|
||||
"spatie/valuestore": "^1.2.5"
|
||||
},
|
||||
|
|
|
|||
|
|
@ -4,7 +4,7 @@ services:
|
|||
build:
|
||||
context: .
|
||||
args:
|
||||
PHP_VERSION: ${PHP_VERSION}
|
||||
PHP_VERSION: ${PHP_VERSION:-8.1}
|
||||
depends_on:
|
||||
mysql:
|
||||
condition: service_healthy
|
||||
|
|
|
|||
|
|
@ -6,6 +6,7 @@ namespace Stancl\Tenancy\Bootstrappers;
|
|||
|
||||
use Stancl\Tenancy\Contracts\TenancyBootstrapper;
|
||||
use Stancl\Tenancy\Contracts\Tenant;
|
||||
use Stancl\Tenancy\Contracts\TenantWithDatabase;
|
||||
use Stancl\Tenancy\Database\DatabaseManager;
|
||||
use Stancl\Tenancy\Exceptions\TenantDatabaseDoesNotExistException;
|
||||
|
||||
|
|
|
|||
|
|
@ -5,7 +5,6 @@ declare(strict_types=1);
|
|||
namespace Stancl\Tenancy\Bootstrappers;
|
||||
|
||||
use Illuminate\Contracts\Foundation\Application;
|
||||
use Illuminate\Filesystem\FilesystemAdapter;
|
||||
use Illuminate\Support\Facades\Storage;
|
||||
use Stancl\Tenancy\Contracts\TenancyBootstrapper;
|
||||
use Stancl\Tenancy\Contracts\Tenant;
|
||||
|
|
@ -54,23 +53,24 @@ class FilesystemTenancyBootstrapper implements TenancyBootstrapper
|
|||
}
|
||||
|
||||
// Storage facade
|
||||
Storage::forgetDisk($this->app['config']['tenancy.filesystem.disks']);
|
||||
|
||||
foreach ($this->app['config']['tenancy.filesystem.disks'] as $disk) {
|
||||
/** @var FilesystemAdapter $filesystemDisk */
|
||||
$filesystemDisk = Storage::disk($disk);
|
||||
// todo@v4 \League\Flysystem\PathPrefixer is making this a lot more painful in flysystem v2
|
||||
|
||||
// todo0 @v4 \League\Flysystem\PathPrefixer is making this a lot more painful in flysystem v2
|
||||
$originalRoot = $this->app['config']["filesystems.disks.{$disk}.root"];
|
||||
$this->originalPaths['disks'][$disk] = $originalRoot;
|
||||
|
||||
$this->originalPaths['disks'][$disk] = $filesystemDisk->getAdapter()->getPathPrefix();
|
||||
$finalPrefix = str_replace(
|
||||
['%storage_path%', '%tenant%'],
|
||||
[storage_path(), $tenant->getTenantKey()],
|
||||
$this->app['config']["tenancy.filesystem.root_override.{$disk}"] ?? '',
|
||||
);
|
||||
|
||||
if ($root = str_replace(
|
||||
'%storage_path%',
|
||||
storage_path(),
|
||||
$this->app['config']["tenancy.filesystem.root_override.{$disk}"] ?? ''
|
||||
)) {
|
||||
$filesystemDisk->getAdapter()->setPathPrefix($finalPrefix = $root);
|
||||
} else {
|
||||
$root = $this->app['config']["filesystems.disks.{$disk}.root"];
|
||||
$filesystemDisk->getAdapter()->setPathPrefix($finalPrefix = $root . "/{$suffix}");
|
||||
if (! $finalPrefix) {
|
||||
$finalPrefix = $originalRoot
|
||||
? rtrim($originalRoot, '/') . '/'. $suffix
|
||||
: $suffix;
|
||||
}
|
||||
|
||||
$this->app['config']["filesystems.disks.{$disk}.root"] = $finalPrefix;
|
||||
|
|
@ -87,14 +87,9 @@ class FilesystemTenancyBootstrapper implements TenancyBootstrapper
|
|||
$this->app['url']->setAssetRoot($this->app['config']['app.asset_url']);
|
||||
|
||||
// Storage facade
|
||||
Storage::forgetDisk($this->app['config']['tenancy.filesystem.disks']);
|
||||
foreach ($this->app['config']['tenancy.filesystem.disks'] as $disk) {
|
||||
/** @var FilesystemAdapter $filesystemDisk */
|
||||
$filesystemDisk = Storage::disk($disk);
|
||||
|
||||
$root = $this->originalPaths['disks'][$disk];
|
||||
|
||||
$filesystemDisk->getAdapter()->setPathPrefix($root);
|
||||
$this->app['config']["filesystems.disks.{$disk}.root"] = $root;
|
||||
$this->app['config']["filesystems.disks.{$disk}.root"] = $this->originalPaths['disks'][$disk];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -4,14 +4,18 @@ declare(strict_types=1);
|
|||
|
||||
namespace Stancl\Tenancy\Bootstrappers;
|
||||
|
||||
use Illuminate\Support\Str;
|
||||
use Illuminate\Config\Repository;
|
||||
use Illuminate\Contracts\Events\Dispatcher;
|
||||
use Illuminate\Contracts\Foundation\Application;
|
||||
use Illuminate\Queue\Events\JobProcessing;
|
||||
use Illuminate\Queue\QueueManager;
|
||||
use Illuminate\Support\Testing\Fakes\QueueFake;
|
||||
use Stancl\Tenancy\Contracts\TenancyBootstrapper;
|
||||
use Stancl\Tenancy\Contracts\Tenant;
|
||||
use Illuminate\Queue\Events\JobFailed;
|
||||
use Illuminate\Queue\Events\JobProcessed;
|
||||
use Illuminate\Queue\Events\JobProcessing;
|
||||
use Illuminate\Contracts\Events\Dispatcher;
|
||||
use Illuminate\Queue\Events\JobRetryRequested;
|
||||
use Illuminate\Support\Testing\Fakes\QueueFake;
|
||||
use Illuminate\Contracts\Foundation\Application;
|
||||
use Stancl\Tenancy\Contracts\TenancyBootstrapper;
|
||||
|
||||
class QueueTenancyBootstrapper implements TenancyBootstrapper
|
||||
{
|
||||
|
|
@ -21,6 +25,16 @@ class QueueTenancyBootstrapper implements TenancyBootstrapper
|
|||
/** @var QueueManager */
|
||||
protected $queue;
|
||||
|
||||
/**
|
||||
* Don't persist the same tenant across multiple jobs even if they have the same tenant ID.
|
||||
*
|
||||
* This is useful when you're changing the tenant's state (e.g. properties in the `data` column) and want the next job to initialize tenancy again
|
||||
* with the new data. Features like the Tenant Config are only executed when tenancy is initialized, so the re-initialization is needed in some cases.
|
||||
*
|
||||
* @var bool
|
||||
*/
|
||||
public static $forceRefresh = false;
|
||||
|
||||
/**
|
||||
* The normal constructor is only executed after tenancy is bootstrapped.
|
||||
* However, we're registering a hook to initialize tenancy. Therefore,
|
||||
|
|
@ -28,7 +42,7 @@ class QueueTenancyBootstrapper implements TenancyBootstrapper
|
|||
*/
|
||||
public static function __constructStatic(Application $app)
|
||||
{
|
||||
static::setUpJobListener($app->make(Dispatcher::class));
|
||||
static::setUpJobListener($app->make(Dispatcher::class), $app->runningUnitTests());
|
||||
}
|
||||
|
||||
public function __construct(Repository $config, QueueManager $queue)
|
||||
|
|
@ -39,25 +53,90 @@ class QueueTenancyBootstrapper implements TenancyBootstrapper
|
|||
$this->setUpPayloadGenerator();
|
||||
}
|
||||
|
||||
protected static function setUpJobListener($dispatcher)
|
||||
protected static function setUpJobListener($dispatcher, $runningTests)
|
||||
{
|
||||
$dispatcher->listen(JobProcessing::class, function ($event) {
|
||||
$tenantId = $event->job->payload()['tenant_id'] ?? null;
|
||||
$previousTenant = null;
|
||||
|
||||
// The job is not tenant-aware
|
||||
$dispatcher->listen(JobProcessing::class, function ($event) use (&$previousTenant) {
|
||||
$previousTenant = tenant();
|
||||
|
||||
static::initializeTenancyForQueue($event->job->payload()['tenant_id'] ?? null);
|
||||
});
|
||||
|
||||
if (version_compare(app()->version(), '8.64', '>=')) {
|
||||
// JobRetryRequested only exists since Laravel 8.64
|
||||
$dispatcher->listen(JobRetryRequested::class, function ($event) use (&$previousTenant) {
|
||||
$previousTenant = tenant();
|
||||
|
||||
static::initializeTenancyForQueue($event->payload()['tenant_id'] ?? null);
|
||||
});
|
||||
}
|
||||
|
||||
// If we're running tests, we make sure to clean up after any artisan('queue:work') calls
|
||||
$revertToPreviousState = function ($event) use (&$previousTenant, $runningTests) {
|
||||
if ($runningTests) {
|
||||
static::revertToPreviousState($event, $previousTenant);
|
||||
}
|
||||
};
|
||||
|
||||
$dispatcher->listen(JobProcessed::class, $revertToPreviousState); // artisan('queue:work') which succeeds
|
||||
$dispatcher->listen(JobFailed::class, $revertToPreviousState); // artisan('queue:work') which fails
|
||||
}
|
||||
|
||||
protected static function initializeTenancyForQueue($tenantId)
|
||||
{
|
||||
if (! $tenantId) {
|
||||
// The job is not tenant-aware
|
||||
if (tenancy()->initialized) {
|
||||
// Tenancy was initialized, so we revert back to the central context
|
||||
tenancy()->end();
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
// Tenancy is already initialized for the tenant (e.g. dispatchNow was used)
|
||||
if (tenancy()->initialized && tenant()->getTenantKey() === $tenantId) {
|
||||
if (static::$forceRefresh) {
|
||||
// Re-initialize tenancy between all jobs
|
||||
if (tenancy()->initialized) {
|
||||
tenancy()->end();
|
||||
}
|
||||
|
||||
tenancy()->initialize(tenancy()->find($tenantId));
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
if (tenancy()->initialized) {
|
||||
// Tenancy is already initialized
|
||||
if (tenant()->getTenantKey() === $tenantId) {
|
||||
// It's initialized for the same tenant (e.g. dispatchNow was used, or the previous job also ran for this tenant)
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
// Tenancy was either not initialized, or initialized for a different tenant.
|
||||
// Therefore, we initialize it for the correct tenant.
|
||||
tenancy()->initialize(tenancy()->find($tenantId));
|
||||
});
|
||||
}
|
||||
|
||||
protected static function revertToPreviousState($event, &$previousTenant)
|
||||
{
|
||||
$tenantId = $event->job->payload()['tenant_id'] ?? null;
|
||||
|
||||
// The job was not tenant-aware
|
||||
if (! $tenantId) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Revert back to the previous tenant
|
||||
if (tenant() && $previousTenant && $previousTenant->isNot(tenant())) {
|
||||
tenancy()->initialize($previousTenant);
|
||||
}
|
||||
|
||||
// End tenancy
|
||||
if (tenant() && (! $previousTenant)) {
|
||||
tenancy()->end();
|
||||
}
|
||||
}
|
||||
|
||||
protected function setUpPayloadGenerator()
|
||||
|
|
|
|||
|
|
@ -20,8 +20,10 @@ class CacheManager extends BaseCacheManager
|
|||
$tags = [config('tenancy.cache.tag_base') . tenant()->getTenantKey()];
|
||||
|
||||
if ($method === 'tags') {
|
||||
if (count($parameters) !== 1) {
|
||||
throw new \Exception("Method tags() takes exactly 1 argument. {count($parameters)} passed.");
|
||||
$count = count($parameters);
|
||||
|
||||
if ($count !== 1) {
|
||||
throw new \Exception("Method tags() takes exactly 1 argument. $count passed.");
|
||||
}
|
||||
|
||||
$names = $parameters[0];
|
||||
|
|
|
|||
|
|
@ -8,32 +8,26 @@ use Illuminate\Contracts\Events\Dispatcher;
|
|||
use Illuminate\Database\Console\Migrations\MigrateCommand;
|
||||
use Illuminate\Database\Migrations\Migrator;
|
||||
use Stancl\Tenancy\Concerns\DealsWithMigrations;
|
||||
use Stancl\Tenancy\Concerns\ExtendsLaravelCommand;
|
||||
use Stancl\Tenancy\Concerns\HasATenantsOption;
|
||||
use Stancl\Tenancy\Events\DatabaseMigrated;
|
||||
use Stancl\Tenancy\Events\MigratingDatabase;
|
||||
|
||||
class Migrate extends MigrateCommand
|
||||
{
|
||||
use HasATenantsOption, DealsWithMigrations;
|
||||
use HasATenantsOption, DealsWithMigrations, ExtendsLaravelCommand;
|
||||
|
||||
/**
|
||||
* The console command description.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
protected $description = 'Run migrations for tenant(s)';
|
||||
|
||||
/**
|
||||
* Create a new command instance.
|
||||
*
|
||||
* @param Migrator $migrator
|
||||
* @param Dispatcher $dispatcher
|
||||
*/
|
||||
protected static function getTenantCommandName(): string
|
||||
{
|
||||
return 'tenants:migrate';
|
||||
}
|
||||
|
||||
public function __construct(Migrator $migrator, Dispatcher $dispatcher)
|
||||
{
|
||||
parent::__construct($migrator, $dispatcher);
|
||||
|
||||
$this->setName('tenants:migrate');
|
||||
$this->specifyParameters();
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -7,6 +7,7 @@ namespace Stancl\Tenancy\Commands;
|
|||
use Illuminate\Console\Command;
|
||||
use Stancl\Tenancy\Concerns\DealsWithMigrations;
|
||||
use Stancl\Tenancy\Concerns\HasATenantsOption;
|
||||
use Symfony\Component\Console\Input\InputOption;
|
||||
|
||||
final class MigrateFresh extends Command
|
||||
{
|
||||
|
|
@ -23,6 +24,8 @@ final class MigrateFresh extends Command
|
|||
{
|
||||
parent::__construct();
|
||||
|
||||
$this->addOption('--drop-views', null, InputOption::VALUE_NONE, 'Drop views along with tenant tables.', null);
|
||||
|
||||
$this->setName('tenants:migrate-fresh');
|
||||
}
|
||||
|
||||
|
|
@ -37,6 +40,7 @@ final class MigrateFresh extends Command
|
|||
$this->info('Dropping tables.');
|
||||
$this->call('db:wipe', array_filter([
|
||||
'--database' => 'tenant',
|
||||
'--drop-views' => $this->option('drop-views'),
|
||||
'--force' => true,
|
||||
]));
|
||||
|
||||
|
|
|
|||
|
|
@ -7,13 +7,19 @@ namespace Stancl\Tenancy\Commands;
|
|||
use Illuminate\Database\Console\Migrations\RollbackCommand;
|
||||
use Illuminate\Database\Migrations\Migrator;
|
||||
use Stancl\Tenancy\Concerns\DealsWithMigrations;
|
||||
use Stancl\Tenancy\Concerns\ExtendsLaravelCommand;
|
||||
use Stancl\Tenancy\Concerns\HasATenantsOption;
|
||||
use Stancl\Tenancy\Events\DatabaseRolledBack;
|
||||
use Stancl\Tenancy\Events\RollingBackDatabase;
|
||||
|
||||
class Rollback extends RollbackCommand
|
||||
{
|
||||
use HasATenantsOption, DealsWithMigrations;
|
||||
use HasATenantsOption, DealsWithMigrations, ExtendsLaravelCommand;
|
||||
|
||||
protected static function getTenantCommandName(): string
|
||||
{
|
||||
return 'tenants:rollback';
|
||||
}
|
||||
|
||||
/**
|
||||
* The console command description.
|
||||
|
|
@ -31,8 +37,7 @@ class Rollback extends RollbackCommand
|
|||
{
|
||||
parent::__construct($migrator);
|
||||
|
||||
$this->setName('tenants:rollback');
|
||||
$this->specifyParameters();
|
||||
$this->specifyTenantSignature();
|
||||
}
|
||||
|
||||
/**
|
||||
|
|
|
|||
|
|
@ -34,7 +34,6 @@ class Run extends Command
|
|||
{
|
||||
tenancy()->runForMultiple($this->option('tenants'), function ($tenant) {
|
||||
$this->line("Tenant: {$tenant->getTenantKey()}");
|
||||
tenancy()->initialize($tenant);
|
||||
|
||||
$callback = function ($prefix = '') {
|
||||
return function ($arguments, $argument) use ($prefix) {
|
||||
|
|
|
|||
23
src/Concerns/ExtendsLaravelCommand.php
Normal file
23
src/Concerns/ExtendsLaravelCommand.php
Normal file
|
|
@ -0,0 +1,23 @@
|
|||
<?php
|
||||
|
||||
namespace Stancl\Tenancy\Concerns;
|
||||
|
||||
trait ExtendsLaravelCommand
|
||||
{
|
||||
protected function specifyTenantSignature(): void
|
||||
{
|
||||
$this->specifyParameters();
|
||||
}
|
||||
|
||||
public function getName(): ?string
|
||||
{
|
||||
return static::getTenantCommandName();
|
||||
}
|
||||
|
||||
public static function getDefaultName(): ?string
|
||||
{
|
||||
return static::getTenantCommandName();
|
||||
}
|
||||
|
||||
abstract protected static function getTenantCommandName(): string;
|
||||
}
|
||||
|
|
@ -7,10 +7,12 @@ namespace Stancl\Tenancy\Database;
|
|||
use Illuminate\Config\Repository;
|
||||
use Illuminate\Contracts\Foundation\Application;
|
||||
use Illuminate\Database\DatabaseManager as BaseDatabaseManager;
|
||||
use Stancl\Tenancy\Contracts\ManagesDatabaseUsers;
|
||||
use Stancl\Tenancy\Contracts\TenantCannotBeCreatedException;
|
||||
use Stancl\Tenancy\Contracts\TenantWithDatabase;
|
||||
use Stancl\Tenancy\Exceptions\DatabaseManagerNotRegisteredException;
|
||||
use Stancl\Tenancy\Exceptions\TenantDatabaseAlreadyExistsException;
|
||||
use Stancl\Tenancy\Exceptions\TenantDatabaseUserAlreadyExistsException;
|
||||
|
||||
/**
|
||||
* @internal Class is subject to breaking changes in minor and patch versions.
|
||||
|
|
@ -38,7 +40,7 @@ class DatabaseManager
|
|||
*/
|
||||
public function connectToTenant(TenantWithDatabase $tenant)
|
||||
{
|
||||
$this->database->purge('tenant');
|
||||
$this->purgeTenantConnection();
|
||||
$this->createTenantConnection($tenant);
|
||||
$this->setDefaultConnection('tenant');
|
||||
}
|
||||
|
|
@ -48,10 +50,7 @@ class DatabaseManager
|
|||
*/
|
||||
public function reconnectToCentral()
|
||||
{
|
||||
if (tenancy()->initialized) {
|
||||
$this->database->purge('tenant');
|
||||
}
|
||||
|
||||
$this->purgeTenantConnection();
|
||||
$this->setDefaultConnection($this->config->get('tenancy.database.central_connection'));
|
||||
}
|
||||
|
||||
|
|
@ -60,7 +59,7 @@ class DatabaseManager
|
|||
*/
|
||||
public function setDefaultConnection(string $connection)
|
||||
{
|
||||
$this->app['config']['database.default'] = $connection;
|
||||
$this->config['database.default'] = $connection;
|
||||
$this->database->setDefaultConnection($connection);
|
||||
}
|
||||
|
||||
|
|
@ -69,7 +68,19 @@ class DatabaseManager
|
|||
*/
|
||||
public function createTenantConnection(TenantWithDatabase $tenant)
|
||||
{
|
||||
$this->app['config']['database.connections.tenant'] = $tenant->database()->connection();
|
||||
$this->config['database.connections.tenant'] = $tenant->database()->connection();
|
||||
}
|
||||
|
||||
/**
|
||||
* Purge the tenant database connection.
|
||||
*/
|
||||
public function purgeTenantConnection()
|
||||
{
|
||||
if (array_key_exists('tenant', $this->database->getConnections())) {
|
||||
$this->database->purge('tenant');
|
||||
}
|
||||
|
||||
unset($this->config['database.connections.tenant']);
|
||||
}
|
||||
|
||||
/**
|
||||
|
|
@ -81,8 +92,14 @@ class DatabaseManager
|
|||
*/
|
||||
public function ensureTenantCanBeCreated(TenantWithDatabase $tenant): void
|
||||
{
|
||||
if ($tenant->database()->manager()->databaseExists($database = $tenant->database()->getName())) {
|
||||
$manager = $tenant->database()->manager();
|
||||
|
||||
if ($manager->databaseExists($database = $tenant->database()->getName())) {
|
||||
throw new TenantDatabaseAlreadyExistsException($database);
|
||||
}
|
||||
|
||||
if ($manager instanceof ManagesDatabaseUsers && $manager->userExists($username = $tenant->database()->getUsername())) {
|
||||
throw new TenantDatabaseUserAlreadyExistsException($username);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -36,8 +36,8 @@ class CreateDatabase implements ShouldQueue
|
|||
return false;
|
||||
}
|
||||
|
||||
$databaseManager->ensureTenantCanBeCreated($this->tenant);
|
||||
$this->tenant->database()->makeCredentials();
|
||||
$databaseManager->ensureTenantCanBeCreated($this->tenant);
|
||||
$this->tenant->database()->manager()->createDatabase($this->tenant);
|
||||
|
||||
event(new DatabaseCreated($this->tenant));
|
||||
|
|
|
|||
|
|
@ -5,7 +5,7 @@ declare(strict_types=1);
|
|||
namespace Stancl\Tenancy\Middleware;
|
||||
|
||||
use Closure;
|
||||
use Illuminate\Foundation\Http\Exceptions\MaintenanceModeException;
|
||||
use Symfony\Component\HttpKernel\Exception\HttpException;
|
||||
use Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode;
|
||||
use Stancl\Tenancy\Exceptions\TenancyNotInitializedException;
|
||||
use Symfony\Component\HttpFoundation\IpUtils;
|
||||
|
|
@ -29,7 +29,12 @@ class CheckTenantForMaintenanceMode extends CheckForMaintenanceMode
|
|||
return $next($request);
|
||||
}
|
||||
|
||||
throw new MaintenanceModeException($data['time'], $data['retry'], $data['message']);
|
||||
throw new HttpException(
|
||||
503,
|
||||
'Service Unavailable',
|
||||
null,
|
||||
isset($data['retry']) ? ['Retry-After' => $data['retry']] : []
|
||||
);
|
||||
}
|
||||
|
||||
return $next($request);
|
||||
|
|
|
|||
|
|
@ -66,10 +66,10 @@ class Tenancy
|
|||
return;
|
||||
}
|
||||
|
||||
$this->initialized = false;
|
||||
|
||||
event(new Events\TenancyEnded($this));
|
||||
|
||||
$this->initialized = false;
|
||||
|
||||
$this->tenant = null;
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -7,7 +7,6 @@ namespace Stancl\Tenancy\TenantDatabaseManagers;
|
|||
use Stancl\Tenancy\Concerns\CreatesDatabaseUsers;
|
||||
use Stancl\Tenancy\Contracts\ManagesDatabaseUsers;
|
||||
use Stancl\Tenancy\DatabaseConfig;
|
||||
use Stancl\Tenancy\Exceptions\TenantDatabaseUserAlreadyExistsException;
|
||||
|
||||
class PermissionControlledMySQLDatabaseManager extends MySQLDatabaseManager implements ManagesDatabaseUsers
|
||||
{
|
||||
|
|
@ -26,10 +25,6 @@ class PermissionControlledMySQLDatabaseManager extends MySQLDatabaseManager impl
|
|||
$hostname = $databaseConfig->connection()['host'];
|
||||
$password = $databaseConfig->getPassword();
|
||||
|
||||
if ($this->userExists($username)) {
|
||||
throw new TenantDatabaseUserAlreadyExistsException($username);
|
||||
}
|
||||
|
||||
$this->database()->statement("CREATE USER `{$username}`@`%` IDENTIFIED BY '{$password}'");
|
||||
|
||||
$grants = implode(', ', static::$grants);
|
||||
|
|
|
|||
|
|
@ -46,7 +46,11 @@ class PostgreSQLSchemaManager implements TenantDatabaseManager
|
|||
|
||||
public function makeConnectionConfig(array $baseConfig, string $databaseName): array
|
||||
{
|
||||
if (version_compare(app()->version(), '9.0', '>=')) {
|
||||
$baseConfig['search_path'] = $databaseName;
|
||||
} else {
|
||||
$baseConfig['schema'] = $databaseName;
|
||||
}
|
||||
|
||||
return $baseConfig;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -4,23 +4,27 @@ declare(strict_types=1);
|
|||
|
||||
namespace Stancl\Tenancy\Tests;
|
||||
|
||||
use Illuminate\Support\Facades\Cache;
|
||||
use Illuminate\Filesystem\FilesystemAdapter;
|
||||
use ReflectionObject;
|
||||
use ReflectionProperty;
|
||||
use Illuminate\Support\Str;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Stancl\JobPipeline\JobPipeline;
|
||||
use Stancl\Tenancy\Tests\Etc\Tenant;
|
||||
use Illuminate\Support\Facades\Cache;
|
||||
use Illuminate\Support\Facades\Event;
|
||||
use Illuminate\Support\Facades\Redis;
|
||||
use Illuminate\Support\Facades\Storage;
|
||||
use Stancl\JobPipeline\JobPipeline;
|
||||
use Stancl\Tenancy\Bootstrappers\CacheTenancyBootstrapper;
|
||||
use Stancl\Tenancy\Bootstrappers\DatabaseTenancyBootstrapper;
|
||||
use Stancl\Tenancy\Bootstrappers\FilesystemTenancyBootstrapper;
|
||||
use Stancl\Tenancy\Bootstrappers\RedisTenancyBootstrapper;
|
||||
use Stancl\Tenancy\Events\TenancyEnded;
|
||||
use Stancl\Tenancy\Events\TenancyInitialized;
|
||||
use Stancl\Tenancy\Events\TenantCreated;
|
||||
use Stancl\Tenancy\Jobs\CreateDatabase;
|
||||
use Stancl\Tenancy\Events\TenantCreated;
|
||||
use Stancl\Tenancy\Events\TenancyInitialized;
|
||||
use Stancl\Tenancy\Listeners\BootstrapTenancy;
|
||||
use Stancl\Tenancy\Listeners\RevertToCentralContext;
|
||||
use Stancl\Tenancy\Tests\Etc\Tenant;
|
||||
use Stancl\Tenancy\Bootstrappers\CacheTenancyBootstrapper;
|
||||
use Stancl\Tenancy\Bootstrappers\RedisTenancyBootstrapper;
|
||||
use Stancl\Tenancy\Bootstrappers\DatabaseTenancyBootstrapper;
|
||||
use Stancl\Tenancy\Bootstrappers\FilesystemTenancyBootstrapper;
|
||||
|
||||
class BootstrapperTest extends TestCase
|
||||
{
|
||||
|
|
@ -165,6 +169,7 @@ class BootstrapperTest extends TestCase
|
|||
$tenant2 = Tenant::create();
|
||||
|
||||
tenancy()->initialize($tenant1);
|
||||
|
||||
Storage::disk('public')->put('foo', 'bar');
|
||||
$this->assertSame('bar', Storage::disk('public')->get('foo'));
|
||||
|
||||
|
|
@ -184,30 +189,38 @@ class BootstrapperTest extends TestCase
|
|||
$this->assertFalse(Storage::disk('public')->exists('foo'));
|
||||
$this->assertFalse(Storage::disk('public')->exists('abc'));
|
||||
|
||||
$expected_storage_path = $old_storage_path . '/tenant' . tenant('id'); // /tenant = suffix base
|
||||
|
||||
// Check that disk prefixes respect the root_override logic
|
||||
$this->assertSame($expected_storage_path . '/app/', $this->getDiskPrefix('local'));
|
||||
$this->assertSame($expected_storage_path . '/app/public/', $this->getDiskPrefix('public'));
|
||||
$this->assertSame('tenant' . tenant('id') . '/', $this->getDiskPrefix('s3'), '/');
|
||||
|
||||
// Check suffixing logic
|
||||
$new_storage_path = storage_path();
|
||||
$this->assertEquals($old_storage_path . '/' . config('tenancy.filesystem.suffix_base') . tenant('id'), $new_storage_path);
|
||||
|
||||
foreach (config('tenancy.filesystem.disks') as $disk) {
|
||||
$suffix = config('tenancy.filesystem.suffix_base') . tenant('id');
|
||||
|
||||
/** @var FilesystemAdapter $filesystemDisk */
|
||||
$filesystemDisk = Storage::disk($disk);
|
||||
|
||||
$current_path_prefix = $filesystemDisk->getAdapter()->getPathPrefix();
|
||||
|
||||
if ($override = config("tenancy.filesystem.root_override.{$disk}")) {
|
||||
$correct_path_prefix = str_replace('%storage_path%', storage_path(), $override);
|
||||
} else {
|
||||
if ($base = $old_storage_facade_roots[$disk]) {
|
||||
$correct_path_prefix = $base . "/$suffix/";
|
||||
} else {
|
||||
$correct_path_prefix = "$suffix/";
|
||||
}
|
||||
$this->assertEquals($expected_storage_path, $new_storage_path);
|
||||
}
|
||||
|
||||
$this->assertSame($correct_path_prefix, $current_path_prefix);
|
||||
protected function getDiskPrefix(string $disk): string
|
||||
{
|
||||
/** @var FilesystemAdapter $disk */
|
||||
$disk = Storage::disk($disk);
|
||||
$adapter = $disk->getAdapter();
|
||||
|
||||
if (! Str::startsWith(app()->version(), '9.')) {
|
||||
return $adapter->getPathPrefix();
|
||||
}
|
||||
|
||||
$prefixer = (new ReflectionObject($adapter))->getProperty('prefixer');
|
||||
$prefixer->setAccessible(true);
|
||||
|
||||
// reflection -> instance
|
||||
$prefixer = $prefixer->getValue($adapter);
|
||||
|
||||
$prefix = (new ReflectionProperty($prefixer, 'prefix'));
|
||||
$prefix->setAccessible(true);
|
||||
|
||||
return $prefix->getValue($prefixer);
|
||||
}
|
||||
|
||||
// for queues see QueueTest
|
||||
|
|
|
|||
|
|
@ -10,6 +10,7 @@ use Illuminate\Support\Str;
|
|||
use Stancl\JobPipeline\JobPipeline;
|
||||
use Stancl\Tenancy\Bootstrappers\DatabaseTenancyBootstrapper;
|
||||
use Stancl\Tenancy\Contracts\ManagesDatabaseUsers;
|
||||
use Stancl\Tenancy\Events\DatabaseCreated;
|
||||
use Stancl\Tenancy\Events\TenancyInitialized;
|
||||
use Stancl\Tenancy\Events\TenantCreated;
|
||||
use Stancl\Tenancy\Exceptions\TenantDatabaseUserAlreadyExistsException;
|
||||
|
|
@ -67,14 +68,18 @@ class DatabaseUsersTest extends TestCase
|
|||
$this->assertTrue($manager->databaseExists($tenant->database()->getName()));
|
||||
|
||||
$this->expectException(TenantDatabaseUserAlreadyExistsException::class);
|
||||
Event::fake([DatabaseCreated::class]);
|
||||
|
||||
$tenant2 = Tenant::create([
|
||||
'tenancy_db_username' => $username,
|
||||
]);
|
||||
|
||||
/** @var ManagesDatabaseUsers $manager */
|
||||
$manager = $tenant2->database()->manager();
|
||||
$manager2 = $tenant2->database()->manager();
|
||||
|
||||
// database was not created because of DB transaction
|
||||
$this->assertFalse($manager->databaseExists($tenant2->database()->getName()));
|
||||
$this->assertFalse($manager2->databaseExists($tenant2->database()->getName()));
|
||||
Event::assertNotDispatched(DatabaseCreated::class);
|
||||
}
|
||||
|
||||
/** @test */
|
||||
|
|
|
|||
|
|
@ -1 +0,0 @@
|
|||
{"tenant_id":"The current tenant id is: acme"}
|
||||
|
|
@ -4,12 +4,14 @@ declare(strict_types=1);
|
|||
|
||||
namespace Stancl\Tenancy\Tests;
|
||||
|
||||
use Symfony\Component\HttpKernel\Exception\HttpException;
|
||||
use Illuminate\Foundation\Http\Exceptions\MaintenanceModeException;
|
||||
use Illuminate\Support\Facades\Route;
|
||||
use Stancl\Tenancy\Database\Concerns\MaintenanceMode;
|
||||
use Stancl\Tenancy\Middleware\CheckTenantForMaintenanceMode;
|
||||
use Stancl\Tenancy\Middleware\InitializeTenancyByDomain;
|
||||
use Stancl\Tenancy\Tests\Etc\Tenant;
|
||||
use Symfony\Component\HttpKernel\Exception\ServiceUnavailableHttpException;
|
||||
|
||||
class MaintenanceModeTest extends TestCase
|
||||
{
|
||||
|
|
@ -32,7 +34,7 @@ class MaintenanceModeTest extends TestCase
|
|||
|
||||
$tenant->putDownForMaintenance();
|
||||
|
||||
$this->expectException(MaintenanceModeException::class);
|
||||
$this->expectException(HttpException::class);
|
||||
$this->withoutExceptionHandling()
|
||||
->get('http://acme.localhost/foo');
|
||||
}
|
||||
|
|
|
|||
|
|
@ -4,18 +4,33 @@ declare(strict_types=1);
|
|||
|
||||
namespace Stancl\Tenancy\Tests;
|
||||
|
||||
use Closure;
|
||||
use Exception;
|
||||
use Illuminate\Support\Str;
|
||||
use Illuminate\Bus\Queueable;
|
||||
use Spatie\Valuestore\Valuestore;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Stancl\Tenancy\Tests\Etc\User;
|
||||
use Stancl\JobPipeline\JobPipeline;
|
||||
use Stancl\Tenancy\Tests\Etc\Tenant;
|
||||
use Illuminate\Support\Facades\Event;
|
||||
use Illuminate\Queue\SerializesModels;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
use Stancl\Tenancy\Events\TenancyEnded;
|
||||
use Stancl\Tenancy\Jobs\CreateDatabase;
|
||||
use Illuminate\Queue\InteractsWithQueue;
|
||||
use Stancl\Tenancy\Events\TenantCreated;
|
||||
use Illuminate\Database\Schema\Blueprint;
|
||||
use Illuminate\Queue\Events\JobProcessed;
|
||||
use Illuminate\Queue\Events\JobProcessing;
|
||||
use Illuminate\Contracts\Queue\ShouldQueue;
|
||||
use Illuminate\Foundation\Bus\Dispatchable;
|
||||
use Illuminate\Queue\Events\JobProcessing;
|
||||
use Illuminate\Queue\InteractsWithQueue;
|
||||
use Illuminate\Queue\SerializesModels;
|
||||
use Illuminate\Support\Facades\Event;
|
||||
use Spatie\Valuestore\Valuestore;
|
||||
use Stancl\Tenancy\Bootstrappers\QueueTenancyBootstrapper;
|
||||
use PDO;
|
||||
use Stancl\Tenancy\Events\TenancyInitialized;
|
||||
use Stancl\Tenancy\Listeners\BootstrapTenancy;
|
||||
use Stancl\Tenancy\Tests\Etc\Tenant;
|
||||
use Stancl\Tenancy\Listeners\RevertToCentralContext;
|
||||
use Stancl\Tenancy\Bootstrappers\QueueTenancyBootstrapper;
|
||||
use Stancl\Tenancy\Bootstrappers\DatabaseTenancyBootstrapper;
|
||||
|
||||
class QueueTest extends TestCase
|
||||
{
|
||||
|
|
@ -31,13 +46,68 @@ class QueueTest extends TestCase
|
|||
config([
|
||||
'tenancy.bootstrappers' => [
|
||||
QueueTenancyBootstrapper::class,
|
||||
DatabaseTenancyBootstrapper::class,
|
||||
],
|
||||
'queue.default' => 'redis',
|
||||
]);
|
||||
|
||||
Event::listen(TenancyInitialized::class, BootstrapTenancy::class);
|
||||
Event::listen(TenancyEnded::class, RevertToCentralContext::class);
|
||||
|
||||
$this->valuestore = Valuestore::make(__DIR__ . '/Etc/tmp/queuetest.json')->flush();
|
||||
$this->createValueStore();
|
||||
}
|
||||
|
||||
public function tearDown(): void
|
||||
{
|
||||
$this->valuestore->flush();
|
||||
}
|
||||
|
||||
protected function createValueStore(): void
|
||||
{
|
||||
$valueStorePath = __DIR__ . '/Etc/tmp/queuetest.json';
|
||||
|
||||
if (! file_exists($valueStorePath)) {
|
||||
// The directory sometimes goes missing as well when the file is deleted in git
|
||||
if (! is_dir(__DIR__ . '/Etc/tmp')) {
|
||||
mkdir(__DIR__ . '/Etc/tmp');
|
||||
}
|
||||
|
||||
file_put_contents($valueStorePath, '');
|
||||
}
|
||||
|
||||
$this->valuestore = Valuestore::make($valueStorePath)->flush();
|
||||
}
|
||||
|
||||
protected function withFailedJobs()
|
||||
{
|
||||
Schema::connection('central')->create('failed_jobs', function (Blueprint $table) {
|
||||
$table->increments('id');
|
||||
$table->string('uuid')->unique();
|
||||
$table->text('connection');
|
||||
$table->text('queue');
|
||||
$table->longText('payload');
|
||||
$table->longText('exception');
|
||||
$table->timestamp('failed_at')->useCurrent();
|
||||
});
|
||||
}
|
||||
|
||||
protected function withUsers()
|
||||
{
|
||||
Schema::create('users', function (Blueprint $table) {
|
||||
$table->increments('id');
|
||||
$table->string('name');
|
||||
$table->string('email')->unique();
|
||||
$table->string('password');
|
||||
$table->rememberToken();
|
||||
$table->timestamps();
|
||||
});
|
||||
}
|
||||
|
||||
protected function withTenantDatabases()
|
||||
{
|
||||
Event::listen(TenantCreated::class, JobPipeline::make([CreateDatabase::class])->send(function (TenantCreated $event) {
|
||||
return $event->tenant;
|
||||
})->toListener());
|
||||
}
|
||||
|
||||
/** @test */
|
||||
|
|
@ -49,7 +119,7 @@ class QueueTest extends TestCase
|
|||
|
||||
tenancy()->initialize($tenant);
|
||||
|
||||
Event::fake([JobProcessing::class]);
|
||||
Event::fake([JobProcessing::class, JobProcessed::class]);
|
||||
|
||||
dispatch(new TestJob($this->valuestore));
|
||||
|
||||
|
|
@ -79,21 +149,95 @@ class QueueTest extends TestCase
|
|||
});
|
||||
}
|
||||
|
||||
/** @test */
|
||||
public function tenancy_is_initialized_inside_queues()
|
||||
/**
|
||||
* @test
|
||||
*
|
||||
* @testWith [true]
|
||||
* [false]
|
||||
*/
|
||||
public function tenancy_is_initialized_inside_queues(bool $shouldEndTenancy)
|
||||
{
|
||||
$tenant = Tenant::create([
|
||||
'id' => 'acme',
|
||||
]);
|
||||
$this->withTenantDatabases();
|
||||
$this->withFailedJobs();
|
||||
|
||||
$tenant = Tenant::create();
|
||||
|
||||
tenancy()->initialize($tenant);
|
||||
|
||||
dispatch(new TestJob($this->valuestore));
|
||||
$this->withUsers();
|
||||
|
||||
$user = User::create(['name' => 'Foo', 'email' => 'foo@bar.com', 'password' => 'secret']);
|
||||
|
||||
$this->valuestore->put('userName', 'Bar');
|
||||
|
||||
dispatch(new TestJob($this->valuestore, $user));
|
||||
|
||||
$this->assertFalse($this->valuestore->has('tenant_id'));
|
||||
|
||||
if ($shouldEndTenancy) {
|
||||
tenancy()->end();
|
||||
}
|
||||
|
||||
$this->artisan('queue:work --once');
|
||||
|
||||
$this->assertSame('The current tenant id is: acme', $this->valuestore->get('tenant_id'));
|
||||
$this->assertSame(0, DB::connection('central')->table('failed_jobs')->count());
|
||||
|
||||
$this->assertSame('The current tenant id is: ' . $tenant->id, $this->valuestore->get('tenant_id'));
|
||||
|
||||
$tenant->run(function () use ($user) {
|
||||
$this->assertSame('Bar', $user->fresh()->name);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* @test
|
||||
*
|
||||
* @testWith [true]
|
||||
* [false]
|
||||
*/
|
||||
public function tenancy_is_initialized_when_retrying_jobs(bool $shouldEndTenancy)
|
||||
{
|
||||
if (! Str::startsWith(app()->version(), '8')) {
|
||||
$this->markTestSkipped('queue:retry tenancy is only supported in Laravel 8');
|
||||
}
|
||||
|
||||
$this->withFailedJobs();
|
||||
$this->withTenantDatabases();
|
||||
|
||||
$tenant = Tenant::create();
|
||||
|
||||
tenancy()->initialize($tenant);
|
||||
|
||||
$this->withUsers();
|
||||
|
||||
$user = User::create(['name' => 'Foo', 'email' => 'foo@bar.com', 'password' => 'secret']);
|
||||
|
||||
$this->valuestore->put('userName', 'Bar');
|
||||
$this->valuestore->put('shouldFail', true);
|
||||
|
||||
dispatch(new TestJob($this->valuestore, $user));
|
||||
|
||||
$this->assertFalse($this->valuestore->has('tenant_id'));
|
||||
|
||||
if ($shouldEndTenancy) {
|
||||
tenancy()->end();
|
||||
}
|
||||
|
||||
$this->artisan('queue:work --once');
|
||||
|
||||
$this->assertSame(1, DB::connection('central')->table('failed_jobs')->count());
|
||||
$this->assertNull($this->valuestore->get('tenant_id')); // job failed
|
||||
|
||||
$this->artisan('queue:retry all');
|
||||
$this->artisan('queue:work --once');
|
||||
|
||||
$this->assertSame(0, DB::connection('central')->table('failed_jobs')->count());
|
||||
|
||||
$this->assertSame('The current tenant id is: ' . $tenant->id, $this->valuestore->get('tenant_id')); // job succeeded
|
||||
|
||||
$tenant->run(function () use ($user) {
|
||||
$this->assertSame('Bar', $user->fresh()->name);
|
||||
});
|
||||
}
|
||||
|
||||
/** @test */
|
||||
|
|
@ -127,13 +271,31 @@ class TestJob implements ShouldQueue
|
|||
/** @var Valuestore */
|
||||
protected $valuestore;
|
||||
|
||||
public function __construct(Valuestore $valuestore)
|
||||
/** @var User|null */
|
||||
protected $user;
|
||||
|
||||
public function __construct(Valuestore $valuestore, User $user = null)
|
||||
{
|
||||
$this->valuestore = $valuestore;
|
||||
$this->user = $user;
|
||||
}
|
||||
|
||||
public function handle()
|
||||
{
|
||||
if ($this->valuestore->get('shouldFail')) {
|
||||
$this->valuestore->put('shouldFail', false);
|
||||
|
||||
throw new Exception('failing');
|
||||
}
|
||||
|
||||
if ($this->user) {
|
||||
assert($this->user->getConnectionName() === 'tenant');
|
||||
}
|
||||
|
||||
$this->valuestore->put('tenant_id', 'The current tenant id is: ' . tenant('id'));
|
||||
|
||||
if ($userName = $this->valuestore->get('userName')) {
|
||||
$this->user->update(['name' => $userName]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -4,17 +4,21 @@ declare(strict_types=1);
|
|||
|
||||
namespace Stancl\Tenancy\Tests;
|
||||
|
||||
use Illuminate\Database\Schema\Blueprint;
|
||||
use Illuminate\Support\Facades\Event;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
use Illuminate\Support\Str;
|
||||
use PDO;
|
||||
use Stancl\JobPipeline\JobPipeline;
|
||||
use Stancl\Tenancy\Bootstrappers\DatabaseTenancyBootstrapper;
|
||||
use Stancl\Tenancy\Database\DatabaseManager;
|
||||
use Stancl\Tenancy\Events\TenancyEnded;
|
||||
use Stancl\Tenancy\Events\TenancyInitialized;
|
||||
use Stancl\Tenancy\Events\TenantCreated;
|
||||
use Stancl\Tenancy\Exceptions\TenantDatabaseAlreadyExistsException;
|
||||
use Stancl\Tenancy\Jobs\CreateDatabase;
|
||||
use Stancl\Tenancy\Listeners\BootstrapTenancy;
|
||||
use Stancl\Tenancy\Listeners\RevertToCentralContext;
|
||||
use Stancl\Tenancy\TenantDatabaseManagers\MySQLDatabaseManager;
|
||||
use Stancl\Tenancy\TenantDatabaseManagers\PermissionControlledMySQLDatabaseManager;
|
||||
use Stancl\Tenancy\TenantDatabaseManagers\PostgreSQLDatabaseManager;
|
||||
|
|
@ -102,6 +106,52 @@ class TenantDatabaseManagerTest extends TestCase
|
|||
];
|
||||
}
|
||||
|
||||
/** @test */
|
||||
public function the_tenant_connection_is_fully_removed()
|
||||
{
|
||||
config([
|
||||
'tenancy.boostrappers' => [
|
||||
DatabaseTenancyBootstrapper::class,
|
||||
],
|
||||
]);
|
||||
|
||||
Event::listen(TenantCreated::class, JobPipeline::make([CreateDatabase::class])->send(function (TenantCreated $event) {
|
||||
return $event->tenant;
|
||||
})->toListener());
|
||||
|
||||
Event::listen(TenancyInitialized::class, BootstrapTenancy::class);
|
||||
Event::listen(TenancyEnded::class, RevertToCentralContext::class);
|
||||
|
||||
$tenant = Tenant::create();
|
||||
|
||||
$this->assertSame(['central'], array_keys(app('db')->getConnections()));
|
||||
$this->assertArrayNotHasKey('tenant', config('database.connections'));
|
||||
|
||||
tenancy()->initialize($tenant);
|
||||
|
||||
$this->createUsersTable();
|
||||
|
||||
$this->assertSame(['central', 'tenant'], array_keys(app('db')->getConnections()));
|
||||
$this->assertArrayHasKey('tenant', config('database.connections'));
|
||||
|
||||
tenancy()->end();
|
||||
|
||||
$this->assertSame(['central'], array_keys(app('db')->getConnections()));
|
||||
$this->assertNull(config('database.connections.tenant'));
|
||||
}
|
||||
|
||||
protected function createUsersTable()
|
||||
{
|
||||
Schema::create('users', function (Blueprint $table) {
|
||||
$table->increments('id');
|
||||
$table->string('name');
|
||||
$table->string('email')->unique();
|
||||
$table->string('password');
|
||||
$table->rememberToken();
|
||||
$table->timestamps();
|
||||
});
|
||||
}
|
||||
|
||||
/** @test */
|
||||
public function db_name_is_prefixed_with_db_path_when_sqlite_is_used()
|
||||
{
|
||||
|
|
@ -144,7 +194,11 @@ class TenantDatabaseManagerTest extends TestCase
|
|||
]);
|
||||
tenancy()->initialize($tenant);
|
||||
|
||||
$this->assertSame($tenant->database()->getName(), config('database.connections.' . config('database.default') . '.schema'));
|
||||
$schemaConfig = version_compare(app()->version(), '9.0', '>=') ?
|
||||
config('database.connections.' . config('database.default') . '.search_path') :
|
||||
config('database.connections.' . config('database.default') . '.schema');
|
||||
|
||||
$this->assertSame($tenant->database()->getName(), $schemaConfig);
|
||||
$this->assertSame($originalDatabaseName, config(['database.connections.pgsql.database']));
|
||||
}
|
||||
|
||||
|
|
@ -217,5 +271,6 @@ class TenantDatabaseManagerTest extends TestCase
|
|||
/** @test */
|
||||
public function path_used_by_sqlite_manager_can_be_customized()
|
||||
{
|
||||
$this->markTestIncomplete();
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -48,8 +48,12 @@ abstract class TestCase extends \Orchestra\Testbench\TestCase
|
|||
protected function getEnvironmentSetUp($app)
|
||||
{
|
||||
if (file_exists(__DIR__ . '/../.env')) {
|
||||
if (method_exists(\Dotenv\Dotenv::class, 'createImmutable')) {
|
||||
\Dotenv\Dotenv::createImmutable(__DIR__ . '/..')->load();
|
||||
} else {
|
||||
\Dotenv\Dotenv::create(__DIR__ . '/..')->load();
|
||||
}
|
||||
}
|
||||
|
||||
$app['config']->set([
|
||||
'database.default' => 'central',
|
||||
|
|
@ -83,6 +87,7 @@ abstract class TestCase extends \Orchestra\Testbench\TestCase
|
|||
'public',
|
||||
's3',
|
||||
],
|
||||
'filesystems.disks.s3.bucket' => 'foo',
|
||||
'tenancy.redis.tenancy' => env('TENANCY_TEST_REDIS_TENANCY', true),
|
||||
'database.redis.client' => env('TENANCY_TEST_REDIS_CLIENT', 'phpredis'),
|
||||
'tenancy.redis.prefixed_connections' => ['default'],
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue