mirror of
https://github.com/archtechx/tenancy.git
synced 2025-12-12 18:44:03 +00:00
* Update url binding bootstrapper test * Fix parent::temporarySignedRoute() call * Add universal route tests for all identification types * Improve determineContextFromRequest() * Add setting `TenancyUrlGenerator::$prefixRouteNames` to true in TSP stub * Delete seemingly redundant test (making one route universal won't make all routes universal in any case) * Use collection syntax in ReregisterUniversalRoutes * Improve comments * Add domain identification MW annotation * Update condition in GloballyUsable * Set `tenancy.bootstrappers` instead of adding the bootstrappers using `tenancy.bootstrappers.x`, move test * Revert GloballyUsable condition change * Delete assigning bootstrappers to tenancy.bootstrappers.x * Exclude cache prefixing bootstrapper from the initial configuration * Fix test * Unset bypass parameter * Set static kernel identification-related properties in TestCase * Update bootstrapper name in annotation * Move unset() into a condition * Update TenancyUrlGenerator condition * Set static properties without instantiating Tenancy * Fix unsetting bypass parameter * formatting changes * add a comment * improve docblock * add docblock to TenancyUrlGenerator [ci skip] * docblock changes [ci skip] * Update TenancyUrlGenerator (rename variable, allow bypassing prefixing temporarySignedRoute name) * Improve determineContextFromRequest * Only return the new url generator instance when extending 'url' in UrlBindingBootstrapper * Check route's MW groups for the path ID MW * Remove extra imports from config * Rename MiddlewareContext to Context, add condition for skipping ID MW * Set only the needed bootstrappers in TestCase * Fix code style (php-cs-fixer) * Remove condition * Use correct return type * Fix PHPStan issue * Update comment * Check for tenant parameter instead of prefix * Update shouldBeSkipped condition for universal routes * Don't remove the 'universal' MW group after route re-registration, update test * Fix code style (php-cs-fixer) * Fix typo * Add test for mixing placement of access prevention and identification MW * Add test for mixing placement of access prevention and identification MW * Update docblock * Add setting the session and key resolvers in UrlBindingBootstrapper (required with LW file uploads) * Update stub * Update variable name in route reregistering action * Add trailing comma * Fix code style (php-cs-fixer) * Require routes using path identification to be flagged as tenant in order to be recognized as tenant routes * Add tenant flag while re-registering routes * Update determineContextFromRequest condition (wip) * Fix code style (php-cs-fixer) * Update the middleware context logic so that universal routes have to be flagged as tenant instead of just having ID MW * Update path identification condition * Fix re-registering the LW localized route (add 'tenant' MW) * Update docblock * Simplify LW route re-registration * Add comment * Update comment * Simplify determineContextFromRequest, add comment * Improve stub * Add skipRoute method + test * Fix typo * Update assets/TenancyServiceProvider.stub.php * Update src/Concerns/DealsWithEarlyIdentification.php * Fix typo Co-authored-by: Samuel Štancl <samuel.stancl@gmail.com> * Improve comment * Update test structure * Restructure Fortify test * code style * Fix typo * Update ReregisterUniversalRoutes annotation * Only prefix route name if it wasn't already prefixed * Add todo@docs * Delete `Tenancy::$kernelAccessPreventionSkipped` and related logic * Delete test tenant cleanup * Test MW group unpacking, restructure and improve test * Test that tenancy isn't initialized after visiting a central route with the tenant parameter * Delete "in both central and tenant contexts" from test names * Test that re-registering works with controllers too * Set misc route properties during re-registering * Determine context instead of guessing, update universal route tests * Use randomly generated tenant ID instead of hardcoding `acme` * Remove setting route validators * Rename and update determine context method, add comments * Update ForgetTenantParameter annotation * Add comment * Delete comment, delete variable assignment * Update early domain identification test * Improve domain identification tests (test defaulting accurately) * Improve readability * Simplify domain early ID test * Use randomly generated tenant instead of 'acme' * Simplify request data ID test, use random tenant instead of 'acme' * Simplify defaulting domain identification test * Use RouteFacade alias for the Route facade, improve test code * Add defaulting to the request data and path ID tests * Merge path identification tenant parameter removal tests, clean up * Correct wording Co-authored-by: Samuel Štancl <samuel.stancl@gmail.com> * Delete debugging things from UniversalRouteTest * Update annotation * Add `// Creates a matrix` * Improve comment wording * Add MiddlewareUsableWithUniversalRoutes, refactor code accordingly * Fix code style (php-cs-fixer) * Delete debugging leftovers * Delete unused import * Update universal route GloballyUsable condition * Don't implement the universal route interface in access prevention MW * Check if request host is in the central domains in domain ID MW * Test universal routes with domain identification without access prevent MW * Test that universal routes work only with identification MW implementing the universal route interface * Fix code style (php-cs-fixer) * Rename GloballyUsable to UsableWithEarlyIdentification * Fix annotation * Update requestHasTenant annotations * Update comment * Add `with()` comments * Add with() comments where missing * Rename interface, update/add comments * Rename exception, update its default message * Fix code style (php-cs-fixer) * Fix interface name * Delete redundant code from subdomain ID MW * Change domainOrSubdomain ID MW so that instead of passing the identification to other MWs, it happens in the domainOrSubdomain MW * Test domainOrSubdomain identification with universal routes * Fix code style (php-cs-fixer) * Rename universal routes interface * Fix code style (php-cs-fixer) * Try explaining forgetting the tenant parameter better * update interface name reference * uncouple example from query parameters * Update ForgetTenantParameter.php * Update ForgetTenantParameter annotation * Check both routeHasMiddleware and routeHasIdentificationMiddleware in the route MW detection test * Hardcode tenant subdomain * Delete redundant event listening code * Delete unused imports * Delete misuse of `tenancy()->getMiddlewareContext()` from conditions * Delete unused variable * Update comment * Correct request data identification test (defaulting) * Fix defaulting in path id test * Move default route context configuration in domian id test * Rename and update the tenant parameter test * Delete extra tenant parameter test * Use `tenant-domain.test` instead of `127.0.0.2` * Add `default_to_universal_routes` config key * Deal with defaulting to universal routes in the reregistering action * Update logic to make defaulting to universal routes possible * Test defaulting to universal routes * Fix code style (php-cs-fixer) * Delete extra tests * Delete "without access prevention" from datasets * Add defaulting to universal routes to datasets * Override universal flag by central/tenant flag * Add universal flag overriding test * Update "a route can be universal in both route modes" so that the name corresponds with the tested thing * Ignore the PHPStan error * Reset `InitializeTenancyByPath::$onFail` in PathIdentificationTest * Simplify expression * Use 'Tenancy (not) initialized.' in instead of `tenant()?->getTenantKey()` for better assertions * Properly test removing tenant parameter * Reset static properties in tests * Correct comments in EarlyIdentificationTest * Add comment * Add detail to annotation * Throw exception if payload isn't string or null in request data ID MW * Fix code style (php-cs-fixer) * Delete static `$kernelIdentificationSkipped` property, use `$request->attributes` instead * Use 'default_route_mode' instead of 'default_to_tenant/universal_routes' * Fix code style (php-cs-fixer) * Make path identification MW, tenantParameterName and tenantRouteNamePrefix configurable in ReregisterUniversalRoutes * Delete unused import * Add `$passTenantParameterToRoute` to TenancyUrlGenerator * Use `$passTenantParameterToRoute` in BootstrapperTest * Bypass tenant parameter passing * Improve TenancyUrlGenerator so that both ID methods work * Fix code style (php-cs-fixer) * Improve TenancyUrlGenerator readability * Add modifyBehavior() to TenancyUrlGenerator * Fix code style (php-cs-fixer) * Improve comment * Toggle route name prefixing in path/request data ID MW (route-level identification) * Fix code style (php-cs-fixer) * Add path identification MW config key, add `getTenantParameterName()` to ForgetTenantParameter * Fix code style (php-cs-fixer) * Fix modifyBehavior and routeBehaviorModificationBypassed * Add type to `$parameters` parameter * Split modifyBehavior into two methods, don't pass name and parameters by reference * Update UrlBindingBootstrapper annotation * Correct naming in tests (request data -> query string identification) * Add info to annotation * Pass arrays to the behavior modification methods instead of `mixed` * Fix default value of static property in Fortify bootstrapper * Fix code style (php-cs-fixer) * Correct annotation * Enable prefixing routes directly using path identification MW * Test re-registration of routes with path ID MW * Prefix names of routes directly using path ID MW * Fix code style (php-cs-fixer) * Add Livewire v3 integration example to TSP stub * Prefix route name only if it's not prefixed already * Rename ReregisterUniversalRoutes to ReregisterRoutesAsTenant * Fix code style (php-cs-fixer) * Improve ReregisterRoutesAsTenant * Add/update TenancyUrlGenerator docblocks * Update action name in comments/test names * Update reregister action annotation * Delete unused imports * Improve comments * Make method protected * Improve TenancyUrlGenerator code * Test bypass parameter removal * Fix comment * Update annotation * Improve shouldReregisterRoute * Fix typo, delete redundant comment * Improve skipRoute * Improve shouldBeSkipped * Add and test `$passTenantParameterToRoutes` * add a comment * Fix typo in comment * Pass array as $parameters in prepareRouteInputs * Make path_identification_middleware an array * Fix code style (php-cs-fixer) * Fix ReregisterRouteAsTenant * Move tenantParameterName and tenantRouteNamePrefix getting to PathIdentificationManager * Make PathIdentificationManager properties `Closure|null` * Fix code style (php-cs-fixer) * Fix PathIdentificationManager * Update comments * Use foreach for dataset definition * Extract repetitive inGlobalStack and routeHasMiddleware calls * Refactor PathIdentificationManager * Update TenancyUrlGenerator annotation * Add $skippedRoutes, refactor ReregisterRoutesAsTenant * Improve reregisterRoute * Update re-register action annotation * update test name * Make PathIdentificationManager methods static again, update comments * Add test comment * Update ForgetTenantParameter annotation * Improve route re-registration condition, add comment * Change "re-register" to "clone" * minor code improvements --------- Co-authored-by: lukinovec <lukinovec@gmail.com> Co-authored-by: Samuel Štancl <samuel.stancl@gmail.com> Co-authored-by: PHP CS Fixer <phpcsfixer@example.com>
494 lines
18 KiB
PHP
494 lines
18 KiB
PHP
<?php
|
|
|
|
declare(strict_types=1);
|
|
|
|
use Illuminate\Database\Schema\Blueprint;
|
|
use Illuminate\Support\Facades\DB;
|
|
use Illuminate\Support\Facades\Event;
|
|
use Illuminate\Support\Facades\Schema;
|
|
use Illuminate\Support\Str;
|
|
use Stancl\JobPipeline\JobPipeline;
|
|
use Stancl\Tenancy\Bootstrappers\DatabaseTenancyBootstrapper;
|
|
use Stancl\Tenancy\Database\Contracts\StatefulTenantDatabaseManager;
|
|
use Stancl\Tenancy\Database\DatabaseManager;
|
|
use Stancl\Tenancy\Events\TenancyEnded;
|
|
use Stancl\Tenancy\Events\TenancyInitialized;
|
|
use Stancl\Tenancy\Events\TenantCreated;
|
|
use Stancl\Tenancy\Database\Exceptions\TenantDatabaseAlreadyExistsException;
|
|
use Stancl\Tenancy\Jobs\CreateDatabase;
|
|
use Stancl\Tenancy\Listeners\BootstrapTenancy;
|
|
use Stancl\Tenancy\Listeners\RevertToCentralContext;
|
|
use Stancl\Tenancy\Database\TenantDatabaseManagers\MicrosoftSQLDatabaseManager;
|
|
use Stancl\Tenancy\Database\TenantDatabaseManagers\MySQLDatabaseManager;
|
|
use Stancl\Tenancy\Database\TenantDatabaseManagers\PermissionControlledMySQLDatabaseManager;
|
|
use Stancl\Tenancy\Database\TenantDatabaseManagers\PostgreSQLDatabaseManager;
|
|
use Stancl\Tenancy\Database\TenantDatabaseManagers\PostgreSQLSchemaManager;
|
|
use Stancl\Tenancy\Database\TenantDatabaseManagers\SQLiteDatabaseManager;
|
|
use Stancl\Tenancy\Tests\Etc\Tenant;
|
|
|
|
beforeEach(function () {
|
|
SQLiteDatabaseManager::$path = null;
|
|
});
|
|
|
|
test('databases can be created and deleted', function ($driver, $databaseManager) {
|
|
Event::listen(TenantCreated::class, JobPipeline::make([CreateDatabase::class])->send(function (TenantCreated $event) {
|
|
return $event->tenant;
|
|
})->toListener());
|
|
|
|
config()->set([
|
|
"tenancy.database.managers.$driver" => $databaseManager,
|
|
]);
|
|
|
|
$name = 'db' . pest()->randomString();
|
|
|
|
$manager = app($databaseManager);
|
|
|
|
if ($manager instanceof StatefulTenantDatabaseManager) {
|
|
$manager->setConnection($driver);
|
|
}
|
|
|
|
expect($manager->databaseExists($name))->toBeFalse();
|
|
|
|
$tenant = Tenant::create([
|
|
'tenancy_db_name' => $name,
|
|
'tenancy_db_connection' => $driver,
|
|
]);
|
|
|
|
expect($manager->databaseExists($name))->toBeTrue();
|
|
$manager->deleteDatabase($tenant);
|
|
expect($manager->databaseExists($name))->toBeFalse();
|
|
})->with('database_managers');
|
|
|
|
test('dbs can be created when another driver is used for the central db', function () {
|
|
expect(config('database.default'))->toBe('central');
|
|
|
|
Event::listen(TenantCreated::class, JobPipeline::make([CreateDatabase::class])->send(function (TenantCreated $event) {
|
|
return $event->tenant;
|
|
})->toListener());
|
|
|
|
$database = 'db' . pest()->randomString();
|
|
|
|
$mysqlmanager = app(MySQLDatabaseManager::class);
|
|
$mysqlmanager->setConnection('mysql');
|
|
|
|
expect($mysqlmanager->databaseExists($database))->toBeFalse();
|
|
Tenant::create([
|
|
'tenancy_db_name' => $database,
|
|
'tenancy_db_connection' => 'mysql',
|
|
]);
|
|
|
|
expect($mysqlmanager->databaseExists($database))->toBeTrue();
|
|
|
|
$postgresManager = app(PostgreSQLDatabaseManager::class);
|
|
$postgresManager->setConnection('pgsql');
|
|
|
|
$database = 'db' . pest()->randomString();
|
|
expect($postgresManager->databaseExists($database))->toBeFalse();
|
|
|
|
Tenant::create([
|
|
'tenancy_db_name' => $database,
|
|
'tenancy_db_connection' => 'pgsql',
|
|
]);
|
|
|
|
expect($postgresManager->databaseExists($database))->toBeTrue();
|
|
});
|
|
|
|
test('the tenant connection is fully removed', function () {
|
|
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();
|
|
|
|
expect(array_keys(app('db')->getConnections()))->toBe(['central', 'tenant_host_connection']);
|
|
pest()->assertArrayNotHasKey('tenant', config('database.connections'));
|
|
|
|
tenancy()->initialize($tenant);
|
|
|
|
createUsersTable();
|
|
|
|
expect(array_keys(app('db')->getConnections()))->toBe(['central', 'tenant']);
|
|
pest()->assertArrayHasKey('tenant', config('database.connections'));
|
|
|
|
tenancy()->end();
|
|
|
|
expect(array_keys(app('db')->getConnections()))->toBe(['central']);
|
|
expect(config('database.connections.tenant'))->toBeNull();
|
|
});
|
|
|
|
test('db name is prefixed with db path when sqlite is used', function () {
|
|
if (file_exists(database_path('foodb'))) {
|
|
unlink(database_path('foodb')); // cleanup
|
|
}
|
|
config([
|
|
'database.connections.fooconn.driver' => 'sqlite',
|
|
]);
|
|
|
|
$tenant = Tenant::create([
|
|
'tenancy_db_name' => 'foodb',
|
|
'tenancy_db_connection' => 'fooconn',
|
|
]);
|
|
app(DatabaseManager::class)->createTenantConnection($tenant);
|
|
|
|
expect(database_path('foodb'))->toBe(config('database.connections.tenant.database'));
|
|
});
|
|
|
|
test('schema manager uses schema to separate tenant dbs', function () {
|
|
config([
|
|
'tenancy.database.managers.pgsql' => \Stancl\Tenancy\Database\TenantDatabaseManagers\PostgreSQLSchemaManager::class,
|
|
'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);
|
|
|
|
$originalDatabaseName = config(['database.connections.pgsql.database']);
|
|
|
|
$tenant = Tenant::create([
|
|
'tenancy_db_connection' => 'pgsql',
|
|
]);
|
|
tenancy()->initialize($tenant);
|
|
|
|
$schemaConfig = config('database.connections.' . config('database.default') . '.search_path');
|
|
|
|
expect($schemaConfig)->toBe($tenant->database()->getName());
|
|
expect(config(['database.connections.pgsql.database']))->toBe($originalDatabaseName);
|
|
});
|
|
|
|
test('a tenants database cannot be created when the database already exists', function () {
|
|
Event::listen(TenantCreated::class, JobPipeline::make([CreateDatabase::class])->send(function (TenantCreated $event) {
|
|
return $event->tenant;
|
|
})->toListener());
|
|
|
|
$name = 'foo' . Str::random(8);
|
|
$tenant = Tenant::create([
|
|
'tenancy_db_name' => $name,
|
|
]);
|
|
|
|
$manager = $tenant->database()->manager();
|
|
expect($manager->databaseExists($tenant->database()->getName()))->toBeTrue();
|
|
|
|
pest()->expectException(TenantDatabaseAlreadyExistsException::class);
|
|
$tenant2 = Tenant::create([
|
|
'tenancy_db_name' => $name,
|
|
]);
|
|
});
|
|
|
|
test('tenant database can be created and deleted on a foreign server', function () {
|
|
config([
|
|
'tenancy.database.managers.mysql' => PermissionControlledMySQLDatabaseManager::class,
|
|
'database.connections.mysql2' => [
|
|
'driver' => 'mysql',
|
|
'host' => 'mysql2', // important line
|
|
'port' => 3306,
|
|
'database' => 'main',
|
|
'username' => 'root',
|
|
'password' => 'password',
|
|
'unix_socket' => env('DB_SOCKET', ''),
|
|
'charset' => 'utf8mb4',
|
|
'collation' => 'utf8mb4_unicode_ci',
|
|
'prefix' => '',
|
|
'prefix_indexes' => true,
|
|
'strict' => true,
|
|
'engine' => null,
|
|
'options' => extension_loaded('pdo_mysql') ? array_filter([
|
|
PDO::MYSQL_ATTR_SSL_CA => env('MYSQL_ATTR_SSL_CA'),
|
|
]) : [],
|
|
],
|
|
]);
|
|
|
|
Event::listen(TenantCreated::class, JobPipeline::make([CreateDatabase::class])->send(function (TenantCreated $event) {
|
|
return $event->tenant;
|
|
})->toListener());
|
|
|
|
$name = 'foo' . Str::random(8);
|
|
$tenant = Tenant::create([
|
|
'tenancy_db_name' => $name,
|
|
'tenancy_db_connection' => 'mysql2',
|
|
]);
|
|
|
|
/** @var PermissionControlledMySQLDatabaseManager $manager */
|
|
$manager = $tenant->database()->manager();
|
|
|
|
expect($manager->databaseExists($name))->toBeTrue(); // mysql2
|
|
|
|
$manager->setConnection('mysql');
|
|
expect($manager->databaseExists($name))->toBeFalse(); // check that the DB doesn't exist in 'mysql'
|
|
|
|
$manager->setConnection('mysql2'); // set the connection back
|
|
$manager->deleteDatabase($tenant);
|
|
|
|
expect($manager->databaseExists($name))->toBeFalse();
|
|
});
|
|
|
|
test('tenant database can be created on a foreign server by using the host from tenant config', function () {
|
|
config([
|
|
'tenancy.database.managers.mysql' => MySQLDatabaseManager::class,
|
|
'tenancy.database.template_tenant_connection' => 'mysql', // This will be overridden by tenancy_db_host
|
|
'database.connections.mysql2' => [
|
|
'driver' => 'mysql',
|
|
'host' => 'mysql2',
|
|
'port' => 3306,
|
|
'database' => 'main',
|
|
'username' => 'root',
|
|
'password' => 'password',
|
|
'unix_socket' => env('DB_SOCKET', ''),
|
|
'charset' => 'utf8mb4',
|
|
'collation' => 'utf8mb4_unicode_ci',
|
|
'prefix' => '',
|
|
'prefix_indexes' => true,
|
|
'strict' => true,
|
|
'engine' => null,
|
|
'options' => extension_loaded('pdo_mysql') ? array_filter([
|
|
PDO::MYSQL_ATTR_SSL_CA => env('MYSQL_ATTR_SSL_CA'),
|
|
]) : [],
|
|
],
|
|
]);
|
|
|
|
Event::listen(TenantCreated::class, JobPipeline::make([CreateDatabase::class])->send(function (TenantCreated $event) {
|
|
return $event->tenant;
|
|
})->toListener());
|
|
|
|
$name = 'foo' . Str::random(8);
|
|
$tenant = Tenant::create([
|
|
'tenancy_db_name' => $name,
|
|
'tenancy_db_host' => 'mysql2',
|
|
]);
|
|
|
|
/** @var MySQLDatabaseManager $manager */
|
|
$manager = $tenant->database()->manager();
|
|
|
|
expect($manager->databaseExists($name))->toBeTrue();
|
|
});
|
|
|
|
test('database credentials can be provided to PermissionControlledMySQLDatabaseManager by specifying a connection', function () {
|
|
config([
|
|
'tenancy.database.managers.mysql' => PermissionControlledMySQLDatabaseManager::class,
|
|
'tenancy.database.template_tenant_connection' => 'mysql',
|
|
'database.connections.mysql2' => [
|
|
'driver' => 'mysql',
|
|
'host' => 'mysql2',
|
|
'port' => 3306,
|
|
'database' => 'main',
|
|
'username' => 'root',
|
|
'password' => 'password',
|
|
'unix_socket' => env('DB_SOCKET', ''),
|
|
'charset' => 'utf8mb4',
|
|
'collation' => 'utf8mb4_unicode_ci',
|
|
'prefix' => '',
|
|
'prefix_indexes' => true,
|
|
'strict' => true,
|
|
'engine' => null,
|
|
'options' => extension_loaded('pdo_mysql') ? array_filter([
|
|
PDO::MYSQL_ATTR_SSL_CA => env('MYSQL_ATTR_SSL_CA'),
|
|
]) : [],
|
|
],
|
|
]);
|
|
|
|
// Create a new random database user with privileges to use with mysql2 connection
|
|
$username = 'dbuser' . Str::random(4);
|
|
$password = Str::random('8');
|
|
$mysql2DB = DB::connection('mysql2');
|
|
$mysql2DB->statement("CREATE USER `{$username}`@`%` IDENTIFIED BY '{$password}';");
|
|
$mysql2DB->statement("GRANT ALL PRIVILEGES ON *.* TO `{$username}`@`%` identified by '{$password}' WITH GRANT OPTION;");
|
|
$mysql2DB->statement("FLUSH PRIVILEGES;");
|
|
|
|
DB::purge('mysql2'); // forget the mysql2 connection so that it uses the new credentials the next time
|
|
|
|
config(['database.connections.mysql2.username' => $username]);
|
|
config(['database.connections.mysql2.password' => $password]);
|
|
|
|
Event::listen(TenantCreated::class, JobPipeline::make([CreateDatabase::class])->send(function (TenantCreated $event) {
|
|
return $event->tenant;
|
|
})->toListener());
|
|
|
|
$name = 'foo' . Str::random(8);
|
|
$usernameForNewDB = 'user_for_new_db' . Str::random(4);
|
|
$passwordForNewDB = Str::random(8);
|
|
$tenant = Tenant::create([
|
|
'tenancy_db_name' => $name,
|
|
'tenancy_db_connection' => 'mysql2',
|
|
'tenancy_db_username' => $usernameForNewDB,
|
|
'tenancy_db_password' => $passwordForNewDB,
|
|
]);
|
|
|
|
/** @var PermissionControlledMySQLDatabaseManager $manager */
|
|
$manager = $tenant->database()->manager();
|
|
|
|
expect($manager->database()->getConfig('username'))->toBe($username); // user created for the HOST connection
|
|
expect($manager->userExists($usernameForNewDB))->toBeTrue();
|
|
expect($manager->databaseExists($name))->toBeTrue();
|
|
});
|
|
|
|
test('tenant database can be created by using the username and password from tenant config', function () {
|
|
Event::listen(TenantCreated::class, JobPipeline::make([CreateDatabase::class])->send(function (TenantCreated $event) {
|
|
return $event->tenant;
|
|
})->toListener());
|
|
|
|
config([
|
|
'tenancy.database.managers.mysql' => MySQLDatabaseManager::class,
|
|
'tenancy.database.template_tenant_connection' => 'mysql',
|
|
]);
|
|
|
|
// Create a new random database user with privileges to use with `mysql` connection
|
|
$username = 'dbuser' . Str::random(4);
|
|
$password = Str::random('8');
|
|
$mysqlDB = DB::connection('mysql');
|
|
$mysqlDB->statement("CREATE USER `{$username}`@`%` IDENTIFIED BY '{$password}';");
|
|
$mysqlDB->statement("GRANT ALL PRIVILEGES ON *.* TO `{$username}`@`%` identified by '{$password}' WITH GRANT OPTION;");
|
|
$mysqlDB->statement("FLUSH PRIVILEGES;");
|
|
|
|
DB::purge('mysql2'); // forget the mysql2 connection so that it uses the new credentials the next time
|
|
|
|
// Remove `mysql` credentials to make sure we will be using the credentials from the tenant config
|
|
config(['database.connections.mysql.username' => null]);
|
|
config(['database.connections.mysql.password' => null]);
|
|
|
|
$name = 'foo' . Str::random(8);
|
|
$tenant = Tenant::create([
|
|
'tenancy_db_name' => $name,
|
|
'tenancy_db_username' => $username,
|
|
'tenancy_db_password' => $password,
|
|
]);
|
|
|
|
/** @var MySQLDatabaseManager $manager */
|
|
$manager = $tenant->database()->manager();
|
|
|
|
expect($manager->database()->getConfig('username'))->toBe($username); // user created for the HOST connection
|
|
expect($manager->databaseExists($name))->toBeTrue();
|
|
});
|
|
|
|
test('path used by sqlite manager can be customized', function () {
|
|
Event::listen(TenantCreated::class, JobPipeline::make([CreateDatabase::class])->send(function (TenantCreated $event) {
|
|
return $event->tenant;
|
|
})->toListener());
|
|
|
|
// Set custom path for SQLite file
|
|
SQLiteDatabaseManager::$path = $customPath = database_path('custom_' . Str::random(8));
|
|
|
|
if (! is_dir($customPath)) {
|
|
// Create custom directory
|
|
mkdir($customPath);
|
|
}
|
|
|
|
$name = Str::random(8). '.sqlite';
|
|
Tenant::create([
|
|
'tenancy_db_name' => $name,
|
|
'tenancy_db_connection' => 'sqlite',
|
|
]);
|
|
|
|
expect(file_exists($customPath . '/' . $name))->toBeTrue();
|
|
|
|
SQLiteDatabaseManager::$path = null;
|
|
});
|
|
|
|
test('the tenant connection template can be specified either by name or as a connection array', function () {
|
|
Event::listen(TenantCreated::class, JobPipeline::make([CreateDatabase::class])->send(function (TenantCreated $event) {
|
|
return $event->tenant;
|
|
})->toListener());
|
|
|
|
config([
|
|
'tenancy.database.managers.mysql' => MySQLDatabaseManager::class,
|
|
'tenancy.database.template_tenant_connection' => 'mysql',
|
|
]);
|
|
|
|
$name = 'foo' . Str::random(8);
|
|
$tenant = Tenant::create([
|
|
'tenancy_db_name' => $name,
|
|
]);
|
|
|
|
/** @var MySQLDatabaseManager $manager */
|
|
$manager = $tenant->database()->manager();
|
|
expect($manager->databaseExists($name))->toBeTrue();
|
|
expect($manager->database()->getConfig('host'))->toBe('mysql');
|
|
|
|
config([
|
|
'tenancy.database.template_tenant_connection' => [
|
|
'driver' => 'mysql',
|
|
'url' => null,
|
|
'host' => 'mysql2',
|
|
'port' => '3306',
|
|
'database' => 'main',
|
|
'username' => 'root',
|
|
'password' => 'password',
|
|
'unix_socket' => '',
|
|
'charset' => 'utf8mb4',
|
|
'collation' => 'utf8mb4_unicode_ci',
|
|
'prefix' => '',
|
|
'prefix_indexes' => true,
|
|
'strict' => true,
|
|
'engine' => null,
|
|
'options' => [],
|
|
],
|
|
]);
|
|
|
|
$tenant = Tenant::create([
|
|
'tenancy_db_name' => $name,
|
|
]);
|
|
|
|
/** @var MySQLDatabaseManager $manager */
|
|
$manager = $tenant->database()->manager();
|
|
expect($manager->databaseExists($name))->toBeTrue(); // tenant connection works
|
|
expect($manager->database()->getConfig('host'))->toBe('mysql2');
|
|
});
|
|
|
|
test('partial tenant connection templates get merged into the central connection template', function () {
|
|
Event::listen(TenantCreated::class, JobPipeline::make([CreateDatabase::class])->send(function (TenantCreated $event) {
|
|
return $event->tenant;
|
|
})->toListener());
|
|
|
|
config([
|
|
'database.connections.central.url' => 'example.com',
|
|
'tenancy.database.template_tenant_connection' => [
|
|
'url' => null,
|
|
'host' => 'mysql2',
|
|
],
|
|
]);
|
|
|
|
$name = 'foo' . Str::random(8);
|
|
$tenant = Tenant::create([
|
|
'tenancy_db_name' => $name,
|
|
]);
|
|
|
|
/** @var MySQLDatabaseManager $manager */
|
|
$manager = $tenant->database()->manager();
|
|
expect($manager->databaseExists($name))->toBeTrue(); // tenant connection works
|
|
expect($manager->database()->getConfig('host'))->toBe('mysql2');
|
|
expect($manager->database()->getConfig('url'))->toBeNull();
|
|
});
|
|
|
|
// Datasets
|
|
dataset('database_managers', [
|
|
['mysql', MySQLDatabaseManager::class],
|
|
['mysql', PermissionControlledMySQLDatabaseManager::class],
|
|
['sqlite', SQLiteDatabaseManager::class],
|
|
['pgsql', PostgreSQLDatabaseManager::class],
|
|
['pgsql', PostgreSQLSchemaManager::class],
|
|
['sqlsrv', MicrosoftSQLDatabaseManager::class]
|
|
]);
|
|
|
|
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();
|
|
});
|
|
}
|