Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

95 rindas
2.4KB

  1. <?php
  2. namespace Framework\Database\Connection;
  3. use Framework\Database\Migration\MysqlMigration;
  4. use Framework\Database\QueryBuilder\MysqlQueryBuilder;
  5. use InvalidArgumentException;
  6. use Pdo;
  7. class MysqlConnection extends Connection
  8. {
  9. private Pdo $pdo;
  10. private string $database;
  11. public function __construct(array $config)
  12. {
  13. [
  14. 'host' => $host,
  15. 'port' => $port,
  16. 'database' => $database,
  17. 'username' => $username,
  18. 'password' => $password,
  19. ] = $config;
  20. if (empty($host) || empty($database) || empty($username)) {
  21. throw new InvalidArgumentException('Connection incorrectly configured');
  22. }
  23. $this->database = $database;
  24. $this->pdo = new Pdo("mysql:host={$host};port={$port};dbname={$database}", $username, $password);
  25. }
  26. public function pdo(): Pdo
  27. {
  28. return $this->pdo;
  29. }
  30. public function query(): MysqlQueryBuilder
  31. {
  32. return new MysqlQueryBuilder($this);
  33. }
  34. public function createTable(string $table): MysqlMigration
  35. {
  36. return new MysqlMigration($this, $table, 'create');
  37. }
  38. public function alterTable(string $table): MysqlMigration
  39. {
  40. return new MysqlMigration($this, $table, 'alter');
  41. }
  42. public function getTables(): array
  43. {
  44. $statement = $this->pdo->prepare('SHOW TABLES');
  45. $statement->execute();
  46. $results = $statement->fetchAll(PDO::FETCH_NUM);
  47. $results = array_map(fn($result) => $result[0], $results);
  48. return $results;
  49. }
  50. public function hasTable(string $name): bool
  51. {
  52. $tables = $this->getTables();
  53. return in_array($name, $tables);
  54. }
  55. public function dropTables(): int
  56. {
  57. $statement = $this->pdo->prepare("
  58. SELECT CONCAT('DROP TABLE IF EXISTS `', table_name, '`')
  59. FROM information_schema.tables
  60. WHERE table_schema = '{$this->database}';
  61. ");
  62. $statement->execute();
  63. $dropTableClauses = $statement->fetchAll(PDO::FETCH_NUM);
  64. $dropTableClauses = array_map(fn($result) => $result[0], $dropTableClauses);
  65. $clauses = [
  66. 'SET FOREIGN_KEY_CHECKS = 0',
  67. ...$dropTableClauses,
  68. 'SET FOREIGN_KEY_CHECKS = 1',
  69. ];
  70. $statement = $this->pdo->prepare(join(';', $clauses) . ';');
  71. return $statement->execute();
  72. }
  73. }

Powered by TurnKey Linux.