Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
40 changes: 27 additions & 13 deletions src/Commands/CreateDatabase.php
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
namespace BlitzPHP\Database\Commands;

use BlitzPHP\Database\Connection\SQLite;
use BlitzPHP\Database\Database;
use BlitzPHP\Database\Exceptions\CreatorException;
use InvalidArgumentException;

class CreateDatabase extends DatabaseCommand
Expand Down Expand Up @@ -46,7 +46,13 @@ class CreateDatabase extends DatabaseCommand
*/
public function handle()
{
[$group, $config] = $this->connectionInfo(on_test() ? 'tests' : null);

if (empty($name = $this->argument('name'))) {
$name = $config['database'];
}

if (empty($name)) {
$name = $this->prompt('Nom de la base de données', null, static function ($val) {
if (empty($val)) {
throw new InvalidArgumentException('Veuillez entrer le nom de la base de données.');
Expand All @@ -56,12 +62,10 @@ public function handle()
});
}

[$group, $config] = $this->resolver->connectionInfo(on_test() ? 'tests' : null);

$config['database'] = '';
$config['debug'] = false;

$db = $this->resolver->connect($config);
$db = $this->db($config);

// Specialement pour SQLite3
if ($db instanceof SQLite) {
Expand All @@ -75,7 +79,7 @@ public function handle()
$name = str_replace(['.db', '.sqlite'], '', $name) . ".{$ext}";
}

$config['driver'] = 'pdosqlite';
$config['driver'] = 'sqlite';
$config['database'] = $name;

if ($name !== ':memory:') {
Expand All @@ -91,22 +95,32 @@ public function handle()
}

// Connection a un nouveau SQLite3 pour creer la bd
$db = $this->resolver->connect($config, false);
$db = $this->db($config, false);
$db->connect();

if (! is_file($db->getDatabase()) && $name !== ':memory:') {
// @codeCoverageIgnoreStart
$this->error('Echec de la création de la base de données');

return;
// @codeCoverageIgnoreEnd
}
} elseif (! Database::creator($db)->createDatabase($name)) {
// @codeCoverageIgnoreStart
$this->error('Echec de la création de la base de données');
} else {
try {
if (! $this->dbManager->creator($db)->createDatabase($name)) {
$this->error('Echec de la création de la base de données');

return;
// @codeCoverageIgnoreEnd
return;
}
} catch (CreatorException $e) {
$previous = $e->getPrevious();
$self = $previous === null ? $this : $this->badge();

$self->error($e->getMessage());
if (null !== $previous) {
$this->error($previous->getMessage());
}

return;
}
}

$this->success("Base de données \"{$name}\" créée avec succès.");
Expand Down
14 changes: 10 additions & 4 deletions src/Commands/DatabaseCommand.php
Original file line number Diff line number Diff line change
Expand Up @@ -27,16 +27,22 @@ abstract class DatabaseCommand extends Command
*/
protected string $group = 'Base de données';

/**
* @deprecated
*/
protected ConnectionResolverInterface $resolver;

protected DatabaseManager $dbManager;

public function __construct(protected ContainerInterface $container)
{
$this->resolver = $container->get(ConnectionResolverInterface::class);
$this->dbManager = $this->container->get(DatabaseManager::class);
$this->resolver = $this->dbManager;
}

protected function db(array|string|null $group = null, bool $shared = true): BaseConnection
{
return $this->resolver->connect($group, $shared);
return $this->dbManager->connect($group, $shared);
}

/**
Expand All @@ -46,7 +52,7 @@ protected function db(array|string|null $group = null, bool $shared = true): Bas
*/
public function connectionInfo(array|string|null $group = null): array
{
return $this->resolver->connectionInfo($group);
return $this->dbManager->connectionInfo($group);
}

/**
Expand All @@ -67,7 +73,7 @@ public function runner(string $namespace, ?string $group = null): Runner
}

return new Runner(
$this->container->get(DatabaseManager::class),
$this->dbManager,
$group,
$files,
config('migrations'),
Expand Down
35 changes: 16 additions & 19 deletions src/Commands/TableInfo.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,8 @@

namespace BlitzPHP\Database\Commands;

use BlitzPHP\Database\Result\BaseResult;
use BlitzPHP\Database\Connection\BaseConnection;
use BlitzPHP\Database\Query\Result;
use InvalidArgumentException;
use PDO;

Expand Down Expand Up @@ -72,10 +73,12 @@ class TableInfo extends DatabaseCommand

private string $prefix = '';

private BaseConnection $db;

public function handle()
{
try {
$this->db = $this->resolver->connection($this->option('group', config('database.connection', 'default')));
$this->db = $this->db($this->option('group'));
} catch (InvalidArgumentException $e) {
$this->fail($e->getMessage());

Expand Down Expand Up @@ -109,15 +112,7 @@ public function handle()
$limitFieldValue = (int) $this->option('limit-field-value', 15);

while (! in_array($tableName, $tables, true)) {
$tabs = $tables;
$tables = [];

foreach ($tabs as $key => $tab) {
$tables[$key + 1] = $tab;
}

$tableNameNo = $this->choice("Voici les tables disponible dans votre base de données. \n Quelle table souhaitez-vous afficher?", $tables);
$tableName = $tables[$tableNameNo] ?? null;
$tableName = $this->choice("Voici les tables disponible dans votre base de données. \nQuelle table souhaitez-vous afficher?", $tables);
}

if (true === $this->option('metadata')) {
Expand All @@ -133,13 +128,15 @@ public function handle()

private function showDBConfig(): void
{
$config = $this->db->getConfig();

$this->table([[
'hostname' => $this->db->hostname,
'hostname' => $config['hostname'],
'database' => $this->db->getDatabase(),
'username' => $this->db->username,
'username' => $config['username'],
'driver' => $this->db->getPlatform(),
'prefix' => $this->prefix,
'port' => $this->db->port,
'port' => $config['port'],
]]);
}

Expand All @@ -158,7 +155,7 @@ private function showDataOfTable(string $tableName, int $limitRows, int $limitFi
$this->newLine()->io->blackBgYellow("Données de la table \"{$tableName}\":", true);

$this->removeDBPrefix();
$thead = $this->db->getFieldNames($tableName);
$thead = $this->db->getColumnNames($tableName);
$this->restoreDBPrefix();

// Si on a un champ id, on trie en fonction de lui.
Expand Down Expand Up @@ -189,15 +186,15 @@ private function makeTbodyForShowAllTables(array $tables): array
$this->removeDBPrefix();

foreach ($tables as $id => $tableName) {
$table = $this->db->protectIdentifiers($tableName);
/** @var BaseResult $db */
$table = $this->db->escapeIdentifiers($tableName);
/** @var Result $db */
$db = $this->db->query("SELECT * FROM {$table}");

$this->tbody[] = [
'ID' => $id + 1,
'Nom de la table' => $tableName,
'Nombre d\'enregistrement' => $db->numRows(),
'Nombre de champs' => $db->countField(),
'Nombre de champs' => $db->countColumn(),
];
}

Expand Down Expand Up @@ -254,7 +251,7 @@ private function showFieldMetaData(string $tableName): void
$this->newLine()->io->blackBgYellow("Liste des informations de métadonnées dans la table \"{$tableName}\"\u{a0}:", true);

$this->removeDBPrefix();
$fields = $this->db->getFieldData($tableName);
$fields = $this->db->getColumnData($tableName);
$this->restoreDBPrefix();

foreach ($fields as $row) {
Expand Down
3 changes: 2 additions & 1 deletion src/Connection/MySQL.php
Original file line number Diff line number Diff line change
Expand Up @@ -155,11 +155,12 @@ public function _listColumns(string $table): array
foreach ($rows as $row) {
$column = new stdClass();
$column->name = $row->Field;
$column->type = $row->Type;
$column->nullable = $row->Null === 'YES';
$column->default = $row->Default;
$column->primary_key = $row->Key === 'PRI';

sscanf($row->Type, '%[a-z](%d)', $column->type, $column->max_length);

$columns[] = $column;
}

Expand Down
2 changes: 1 addition & 1 deletion src/Creator/BaseCreator.php
Original file line number Diff line number Diff line change
Expand Up @@ -266,7 +266,7 @@ public function createDatabase(string $dbName, bool $ifNotExists = false): bool
try {
$result = $this->db->statement(sprintf(
$ifNotExists ? $this->createDatabaseIfStr : $this->createDatabaseStr,
$this->db->escapeIdentifier($dbName),
$this->db->escapeIdentifiers($dbName),
$this->charset,
$this->collation,
));
Expand Down
2 changes: 1 addition & 1 deletion src/Exceptions/DatabaseException.php
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,6 @@ class DatabaseException extends Error implements ExceptionInterface

protected static function t(string $message, array $args = []): string
{
return sprintf($message, $args);
return sprintf($message, ...$args);
}
}