From 0b8d011a0180a1e30743aec9112686fa4b13397b Mon Sep 17 00:00:00 2001 From: Jagepard Date: Thu, 18 Dec 2025 18:52:52 +0300 Subject: [PATCH 1/2] change DSN to connection --- docs.md | 13 +++--- src/QB.php | 24 +++++----- src/Repository.php | 110 +++++++++++++++++++++++++-------------------- src/Schema.php | 2 +- 4 files changed, 81 insertions(+), 68 deletions(-) diff --git a/docs.md b/docs.md index 0934fb2..6763b11 100644 --- a/docs.md +++ b/docs.md @@ -79,7 +79,7 @@ ### Class: Rudra\Model\QB | Visibility | Function | |:-----------|:---------| -| public | `__construct( $dsn)`
Initializes the database driver based on the provided DSN or a default DSN from the container.
If no DSN is provided and none is available in the container, a LogicException is thrown.
The driver is selected based on the database type specified in the DSN's driver attribute.
-------------------------
Инициализирует драйвер базы данных на основе предоставленного DSN или DSN по умолчанию из контейнера.
Если DSN не предоставлен и отсутствует в контейнере, выбрасывается исключение LogicException.
Драйвер выбирается на основе типа базы данных, указанного в атрибуте драйвера DSN. | +| public | `__construct( $connection)`
Initializes the database driver based on the provided connection or a default connection from the container.
If no connection is provided and none is available in the container, a LogicException is thrown.
The driver is selected based on the database type specified in the connection's driver attribute.
-------------------------
Инициализирует драйвер базы данных на основе предоставленного connection или connection по умолчанию из контейнера.
Если connection не предоставлен и отсутствует в контейнере, выбрасывается исключение LogicException.
Драйвер выбирается на основе типа базы данных, указанного в атрибуте драйвера connection. | | public | `select(string $fields): self`
| | public | `concat(string $fieldName, string $alias, ?string $orderBy): self`
| | public | `from(string $table): self`
| @@ -116,11 +116,12 @@ ### Class: Rudra\Model\Repository | Visibility | Function | |:-----------|:---------| -| public | `__construct(?string $table, ?PDO $dsn)`
Initializes the class with a table name, DSN (Data Source Name), and sets up dependencies.
The DSN is either provided directly or retrieved from the Rudra container.
If the DSN is not an instance of PDO, a LogicException is thrown.
-------------------------
Инициализирует класс с именем таблицы, DSN (Data Source Name) и настраивает зависимости.
DSN может быть предоставлен напрямую или извлечен из контейнера Rudra.
Если DSN не является экземпляром PDO, выбрасывается исключение LogicException. | +| public | `__construct(?string $table, ?PDO $connection)`
Initializes the class with a table name, connection, and sets up dependencies.
The connection is either provided directly or retrieved from the Rudra container.
If the connection is not an instance of PDO, a LogicException is thrown.
-------------------------
Инициализирует класс с именем таблицы, connection и настраивает зависимости.
connection может быть предоставлен напрямую или извлечен из контейнера Rudra.
Если connection не является экземпляром PDO, выбрасывается исключение LogicException. | | public | `__call( $method, array $parameters)`
Handles calls to undefined methods by throwing a LogicException.
This method is invoked when an attempt is made to call a non-existent method on the object.
-------------------------
Обрабатывает вызовы неопределённых методов, выбрасывая исключение LogicException.
Этот метод вызывается, когда происходит попытка вызвать несуществующий метод у объекта. | -| public | `qb(): Rudra\Model\QB`
Returns an instance of the Query Builder (QB).
If the QB instance is not yet initialized, it creates a new instance using the DSN.
This method implements lazy initialization to ensure the QB instance is created only when needed.
-------------------------
Возвращает экземпляр Query Builder (QB).
Если экземпляр QB ещё не инициализирован, создаётся новый экземпляр с использованием DSN.
Этот метод реализует ленивую инициализацию, чтобы гарантировать создание экземпляра QB только при необходимости. | -| public | `onDsn(PDO $dsn): self`
Sets the DSN (Data Source Name) for the database connection and resets the Query Builder instance.
This method allows changing the DSN dynamically and ensures that the Query Builder is re-initialized.
-------------------------
Устанавливает DSN (Data Source Name) для подключения к базе данных и сбрасывает экземпляр Query Builder.
Этот метод позволяет динамически изменять DSN и гарантирует повторную инициализацию Query Builder. | -| public | `withDsn(PDO $dsn): self`
Creates and returns a new instance of the class with the specified DSN.
This method allows changing the DSN while preserving the current table name.
It is useful for creating new instances with different database connections without modifying the original object.
-------------------------
Создает и возвращает новый экземпляр класса с указанным DSN.
Этот метод позволяет изменить DSN, сохраняя текущее имя таблицы.
Он полезен для создания новых экземпляров с разными подключениями к базе данных без изменения исходного объекта. | +| public | `qb(): Rudra\Model\QB`
Returns an instance of the Query Builder (QB).
If the QB instance is not yet initialized, it creates a new instance using the connection.
This method implements lazy initialization to ensure the QB instance is created only when needed.
-------------------------
Возвращает экземпляр Query Builder (QB).
Если экземпляр QB ещё не инициализирован, создаётся новый экземпляр с использованием connection.
Этот метод реализует ленивую инициализацию, чтобы гарантировать создание экземпляра QB только при необходимости. | +| public | `connection(): PDO`
Returns the current PDO instance used by the repository.
-------------------------
Возвращает текущий экземпляр PDO, используемый репозиторием. | +| public | `onConnection(PDO $connection): self`
Sets the connection for the database connection and resets the Query Builder instance.
This method allows changing the connection dynamically and ensures that the Query Builder is re-initialized.
-------------------------
Устанавливает connection для подключения к базе данных и сбрасывает экземпляр Query Builder.
Этот метод позволяет динамически изменять connection и гарантирует повторную инициализацию Query Builder. | +| public | `withConnectionn(PDO $connection): self`
Creates and returns a new instance of the class with the specified connection.
This method allows changing the connection while preserving the current table name.
It is useful for creating new instances with different database connections without modifying the original object.
-------------------------
Создает и возвращает новый экземпляр класса с указанным connection.
Этот метод позволяет изменить connection, сохраняя текущее имя таблицы.
Он полезен для создания новых экземпляров с разными подключениями к базе данных без изменения исходного объекта. | | public | `qBuilder( $queryString, array $queryParams): array`
Executes a custom SQL query and returns the result as an associative array.
The method prepares the query, executes it with optional parameters, and fetches all results.
-------------------------
Выполняет пользовательский SQL-запрос и возвращает результат в виде ассоциативного массива.
Метод подготавливает запрос, выполняет его с необязательными параметрами и извлекает все результаты. | | public | `getAllPerPage(Rudra\Pagination $pagination, ?string $fields)`
| | public | `find( $id): array\|false`
| @@ -135,7 +136,7 @@ | protected static | `createStmtString(array $fields)`
Generates two strings for an SQL INSERT statement: one for column names and one for placeholders.
The method takes an array of fields and constructs two comma-separated lists:
- A list of column names.
- A list of placeholders (prefixed with colons) for parameter binding.
These strings can be directly used in the SQL INSERT query.
-------------------------
Генерирует две строки для SQL-запроса INSERT:
- Список имен столбцов.
- Список плейсхолдеров (с префиксом двоеточия) для связывания параметров.
Эти строки могут быть напрямую использованы в SQL-запросе INSERT. | | public | `getColumns()`
Retrieves the column information for the current table based on the database driver.
The method executes a query specific to the database type (MySQL, PostgreSQL, or SQLite)
to fetch the column details of the table.
-------------------------
Получает информацию о столбцах текущей таблицы в зависимости от типа базы данных.
Метод выполняет запрос, специфичный для используемой СУБД (MySQL, PostgreSQL или SQLite),
чтобы получить сведения о столбцах таблицы. | | public | `getFields(?string $fields)`
Retrieves the list of fields (columns) for the current table.
If no specific fields are provided, the method fetches all column names based on the database driver.
Otherwise, it splits the provided comma-separated string of fields into an array.
-------------------------
Получает список полей (столбцов) для текущей таблицы.
Если конкретные поля не указаны, метод извлекает все имена столбцов в зависимости от типа базы данных.
В противном случае он разделяет предоставленную строку полей, разделённых запятыми, на массив. | -| public | `search(string $search, string $column, ?string $fields)`
Searches for records in the database based on a search term and column.
The method prepares and executes a query to retrieve records where the specified column matches the search term.
Results are ordered by ID in descending order and limited to 10 records.
-------------------------
Выполняет поиск записей в базе данных на основе поискового запроса и указанного столбца.
Метод подготавливает и выполняет запрос для получения записей, где указанный столбец соответствует поисковому запросу.
Результаты сортируются по ID в порядке убывания и ограничиваются 10 записями. | +| public | `search(string $search, string $column, ?string $fields): array`
Searches for records in the database based on a search term and column.
The method prepares and executes a query to retrieve records where the specified column matches the search term.
Results are ordered by ID in descending order and limited to 10 records.
-------------------------
Выполняет поиск записей в базе данных на основе поискового запроса и указанного столбца.
Метод подготавливает и выполняет запрос для получения записей, где указанный столбец соответствует поисковому запросу.
Результаты сортируются по ID в порядке убывания и ограничиваются 10 записями. | | public | `toggle()`
| | public | `cache(array $params, $cacheTime)`
Caches the result of a method call to a JSON file for a specified duration.
If the cached file exists and is still valid (based on cache time), the cached data is returned.
Otherwise, the method executes the specified method, caches its result, and returns the data.
-------------------------
Кэширует результат вызова метода в JSON-файл на определённый период времени.
Если кэшированный файл существует и всё ещё действителен (на основе времени кэширования), возвращаются кэшированные данные.
В противном случае метод выполняет указанный метод, кэширует его результат и возвращает данные. | | public | `clearCache(string $type)`
Clears cached files of a specified type or all types.
The method removes JSON cache files from the 'database' or 'view' directories,
or clears both directories if 'all' is specified.
-------------------------
Очищает кэшированные файлы указанного типа или всех типов.
Метод удаляет JSON-файлы кэша из директорий 'database' или 'view',
или очищает обе директории, если указано значение 'all'. | diff --git a/src/QB.php b/src/QB.php index 715dbae..ac7db79 100755 --- a/src/QB.php +++ b/src/QB.php @@ -21,26 +21,26 @@ class QB private string $query = ''; /** - * Initializes the database driver based on the provided DSN or a default DSN from the container. - * If no DSN is provided and none is available in the container, a LogicException is thrown. - * The driver is selected based on the database type specified in the DSN's driver attribute. + * Initializes the database driver based on the provided connection or a default connection from the container. + * If no connection is provided and none is available in the container, a LogicException is thrown. + * The driver is selected based on the database type specified in the connection's driver attribute. * ------------------------- - * Инициализирует драйвер базы данных на основе предоставленного DSN или DSN по умолчанию из контейнера. - * Если DSN не предоставлен и отсутствует в контейнере, выбрасывается исключение LogicException. - * Драйвер выбирается на основе типа базы данных, указанного в атрибуте драйвера DSN. + * Инициализирует драйвер базы данных на основе предоставленного connection или connection по умолчанию из контейнера. + * Если connection не предоставлен и отсутствует в контейнере, выбрасывается исключение LogicException. + * Драйвер выбирается на основе типа базы данных, указанного в атрибуте драйвера connection. * - * @param $dsn + * @param $connection * @throws LogicException */ - public function __construct($dsn = null) + public function __construct($connection = null) { - $dsn = $dsn ?? Rudra::get('DSN') ?? throw new LogicException("DSN is mot installed"); + $connection = $connection ?? Rudra::get('connection') ?? throw new LogicException("connection is mot installed"); - if ($dsn->getAttribute(\PDO::ATTR_DRIVER_NAME) === "mysql") { + if ($connection->getAttribute(\PDO::ATTR_DRIVER_NAME) === "mysql") { $this->driver = new MySQL; - } elseif ($dsn->getAttribute(\PDO::ATTR_DRIVER_NAME) === "pgsql") { + } elseif ($connection->getAttribute(\PDO::ATTR_DRIVER_NAME) === "pgsql") { $this->driver = new PgSQL; - } elseif ($dsn->getAttribute(\PDO::ATTR_DRIVER_NAME) === "sqlite") { + } elseif ($connection->getAttribute(\PDO::ATTR_DRIVER_NAME) === "sqlite") { $this->driver = new SQLite; } } diff --git a/src/Repository.php b/src/Repository.php index e235a26..3e18c88 100755 --- a/src/Repository.php +++ b/src/Repository.php @@ -19,32 +19,32 @@ class Repository { public ?string $table; private Rudra $rudra; - private \PDO $dsn; + private \PDO $connection; private QB $qb; /** - * Initializes the class with a table name, DSN (Data Source Name), and sets up dependencies. - * The DSN is either provided directly or retrieved from the Rudra container. - * If the DSN is not an instance of PDO, a LogicException is thrown. + * Initializes the class with a table name, connection, and sets up dependencies. + * The connection is either provided directly or retrieved from the Rudra container. + * If the connection is not an instance of PDO, a LogicException is thrown. * ------------------------- - * Инициализирует класс с именем таблицы, DSN (Data Source Name) и настраивает зависимости. - * DSN может быть предоставлен напрямую или извлечен из контейнера Rudra. - * Если DSN не является экземпляром PDO, выбрасывается исключение LogicException. + * Инициализирует класс с именем таблицы, connection и настраивает зависимости. + * connection может быть предоставлен напрямую или извлечен из контейнера Rudra. + * Если connection не является экземпляром PDO, выбрасывается исключение LogicException. * * @param string|null $table - * @param \PDO|null $dsn + * @param \PDO|null $connection * @return void * @throws LogicException */ - public function __construct(?string $table, ?\PDO $dsn = null) + public function __construct(?string $table, ?\PDO $connection = null) { $this->table = $table; $this->rudra = Rudra::run(); - $this->dsn = $dsn ?? $this->rudra->get('DSN'); - $this->qb = new QB($this->dsn); + $this->connection = $connection ?? $this->rudra->get('connection'); + $this->qb = new QB($this->connection); - if (!$this->dsn instanceof \PDO) { - throw new LogicException('DSN must be an instance of PDO'); + if (!$this->connection instanceof \PDO) { + throw new LogicException('connection must be an instance of PDO'); } } @@ -67,11 +67,11 @@ public function __call($method, array $parameters = []) /** * Returns an instance of the Query Builder (QB). - * If the QB instance is not yet initialized, it creates a new instance using the DSN. + * If the QB instance is not yet initialized, it creates a new instance using the connection. * This method implements lazy initialization to ensure the QB instance is created only when needed. * ------------------------- * Возвращает экземпляр Query Builder (QB). - * Если экземпляр QB ещё не инициализирован, создаётся новый экземпляр с использованием DSN. + * Если экземпляр QB ещё не инициализирован, создаётся новый экземпляр с использованием connection. * Этот метод реализует ленивую инициализацию, чтобы гарантировать создание экземпляра QB только при необходимости. * * @return QB @@ -79,45 +79,57 @@ public function __call($method, array $parameters = []) public function qb(): QB { if ($this->qb === null) { - $this->qb = new QB($this->dsn); + $this->qb = new QB($this->connection); } return $this->qb; } /** - * Sets the DSN (Data Source Name) for the database connection and resets the Query Builder instance. - * This method allows changing the DSN dynamically and ensures that the Query Builder is re-initialized. + * Returns the current PDO instance used by the repository. * ------------------------- - * Устанавливает DSN (Data Source Name) для подключения к базе данных и сбрасывает экземпляр Query Builder. - * Этот метод позволяет динамически изменять DSN и гарантирует повторную инициализацию Query Builder. + * Возвращает текущий экземпляр PDO, используемый репозиторием. * - * @param \PDO $dsn + * @return \PDO + */ + public function connection(): \PDO + { + return $this->connection; + } + + /** + * Sets the connection for the database connection and resets the Query Builder instance. + * This method allows changing the connection dynamically and ensures that the Query Builder is re-initialized. + * ------------------------- + * Устанавливает connection для подключения к базе данных и сбрасывает экземпляр Query Builder. + * Этот метод позволяет динамически изменять connection и гарантирует повторную инициализацию Query Builder. + * + * @param \PDO $connection * @return self */ - public function onDsn(\PDO $dsn): self + public function onConnection(\PDO $connection): self { - $this->dsn = $dsn; + $this->connection = $connection; $this->qb = null; return $this; } /** - * Creates and returns a new instance of the class with the specified DSN. - * This method allows changing the DSN while preserving the current table name. + * Creates and returns a new instance of the class with the specified connection. + * This method allows changing the connection while preserving the current table name. * It is useful for creating new instances with different database connections without modifying the original object. * ------------------------- - * Создает и возвращает новый экземпляр класса с указанным DSN. - * Этот метод позволяет изменить DSN, сохраняя текущее имя таблицы. + * Создает и возвращает новый экземпляр класса с указанным connection. + * Этот метод позволяет изменить connection, сохраняя текущее имя таблицы. * Он полезен для создания новых экземпляров с разными подключениями к базе данных без изменения исходного объекта. * - * @param \PDO $dsn + * @param \PDO $connection * @return self */ - public function withDsn(\PDO $dsn): self + public function withConnectionn(\PDO $connection): self { - return new static($this->table, $dsn); + return new static($this->table, $connection); } /** @@ -133,7 +145,7 @@ public function withDsn(\PDO $dsn): self */ public function qBuilder($queryString, array $queryParams = []): array { - $stmt = $this->dsn->prepare($queryString); + $stmt = $this->connection->prepare($queryString); $stmt->execute($queryParams); return $stmt->fetchAll(\PDO::FETCH_ASSOC); @@ -162,7 +174,7 @@ public function getAllPerPage(Pagination $pagination, string $fields = null) */ public function find($id): array|false { - $stmt = $this->dsn->prepare(" + $stmt = $this->connection->prepare(" SELECT * FROM {$this->table} WHERE id = :id "); @@ -195,7 +207,7 @@ public function getAll(string $sort = 'id ASC', string $fields = null) public function numRows() { $table = $this->table; - $count = $this->dsn->query("SELECT COUNT(*) FROM {$table}"); + $count = $this->connection->query("SELECT COUNT(*) FROM {$table}"); return $count->fetchColumn(); } @@ -208,7 +220,7 @@ public function numRows() public function findBy($field, $value) { $table = $this->table; - $stmt = $this->dsn->prepare(" + $stmt = $this->connection->prepare(" SELECT * FROM {$table} WHERE {$field} = :val "); @@ -222,7 +234,7 @@ public function findBy($field, $value) public function lastInsertId() { - return $this->dsn->lastInsertId(); + return $this->connection->lastInsertId(); } /** @@ -236,7 +248,7 @@ public function update(array $fields) $stmtString = $this->updateStmtString($fields); $fields['id'] = $id; - $query = $this->dsn->prepare(" + $query = $this->connection->prepare(" UPDATE {$this->table} SET {$stmtString} WHERE id =:id"); @@ -253,7 +265,7 @@ public function create(array $fields) $table = $this->table; $stmtString = $this->createStmtString($fields); - $query = $this->dsn->prepare(" + $query = $this->connection->prepare(" INSERT INTO {$table} ({$stmtString[0]}) VALUES ({$stmtString[1]})"); @@ -268,7 +280,7 @@ public function create(array $fields) public function delete($id) { $table = $this->table; - $query = $this->dsn->prepare("DELETE FROM {$table} WHERE id = :id"); + $query = $this->connection->prepare("DELETE FROM {$table} WHERE id = :id"); $query->execute([':id' => $id]); $this->clearCache(); } @@ -340,15 +352,15 @@ public function getColumns() { $table = $this->table; - if ($this->dsn->getAttribute(\PDO::ATTR_DRIVER_NAME) === "mysql") { - $query = $this->dsn->query("SHOW COLUMNS FROM {$table}"); - } elseif ($this->dsn->getAttribute(\PDO::ATTR_DRIVER_NAME) === "pgsql") { - $query = $this->dsn->query("SELECT column_name, data_type + if ($this->connection->getAttribute(\PDO::ATTR_DRIVER_NAME) === "mysql") { + $query = $this->connection->query("SHOW COLUMNS FROM {$table}"); + } elseif ($this->connection->getAttribute(\PDO::ATTR_DRIVER_NAME) === "pgsql") { + $query = $this->connection->query("SELECT column_name, data_type FROM information_schema.columns WHERE table_name = '{$table}'" ); - } elseif ($this->dsn->getAttribute(\PDO::ATTR_DRIVER_NAME) === "sqlite") { - $query = $this->dsn->query("PRAGMA table_info('{$table}')" + } elseif ($this->connection->getAttribute(\PDO::ATTR_DRIVER_NAME) === "sqlite") { + $query = $this->connection->query("PRAGMA table_info('{$table}')" ); } @@ -370,15 +382,15 @@ public function getColumns() public function getFields(string $fields = null) { if (!isset($fields)) { - if ($this->dsn->getAttribute(\PDO::ATTR_DRIVER_NAME) === "mysql") { + if ($this->connection->getAttribute(\PDO::ATTR_DRIVER_NAME) === "mysql") { foreach ($this->getColumns() as $column) { $fields[] = $column['Field']; } - } elseif ($this->dsn->getAttribute(\PDO::ATTR_DRIVER_NAME) === "pgsql") { + } elseif ($this->connection->getAttribute(\PDO::ATTR_DRIVER_NAME) === "pgsql") { foreach ($this->getColumns() as $column) { $fields[] = $column['column_name']; } - } elseif ($this->dsn->getAttribute(\PDO::ATTR_DRIVER_NAME) === "sqlite") { + } elseif ($this->connection->getAttribute(\PDO::ATTR_DRIVER_NAME) === "sqlite") { foreach ($this->getColumns() as $column) { $fields[] = $column['name']; } @@ -408,7 +420,7 @@ public function search(string $search, string $column, ?string $fields = null): { $table = $this->table; $fields = $fields ?: implode(',', $this->getFields()); - $driver = $this->dsn->getAttribute(\PDO::ATTR_DRIVER_NAME); + $driver = $this->connection->getAttribute(\PDO::ATTR_DRIVER_NAME); // Формируем выражение для приведения к строке $searchExpr = match ($driver) { @@ -418,7 +430,7 @@ public function search(string $search, string $column, ?string $fields = null): default => "$column", // fallback (если вдруг другая СУБД) }; - $query = $this->dsn->prepare(" + $query = $this->connection->prepare(" SELECT {$fields} FROM {$table} WHERE {$searchExpr} LIKE :search ORDER BY id DESC diff --git a/src/Schema.php b/src/Schema.php index f23dbd8..bdbd6fb 100644 --- a/src/Schema.php +++ b/src/Schema.php @@ -47,6 +47,6 @@ public static function create(string $table, callable $callback): self public function execute(): bool { $sql = $this->qb->close()->get(); - return Rudra::get("DSN")->prepare($sql)->execute(); + return Rudra::get("connection")->prepare($sql)->execute(); } } From f0bae43de24748942066e458f1ec8303fd1753cc Mon Sep 17 00:00:00 2001 From: Jagepard Date: Thu, 18 Dec 2025 18:53:15 +0300 Subject: [PATCH 2/2] fix --- src/QB.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/QB.php b/src/QB.php index ac7db79..2c78de2 100755 --- a/src/QB.php +++ b/src/QB.php @@ -34,7 +34,7 @@ class QB */ public function __construct($connection = null) { - $connection = $connection ?? Rudra::get('connection') ?? throw new LogicException("connection is mot installed"); + $connection = $connection ?? Rudra::get('connection') ?? throw new LogicException("connection is not installed"); if ($connection->getAttribute(\PDO::ATTR_DRIVER_NAME) === "mysql") { $this->driver = new MySQL;