Skip to content

Commit

Permalink
Add PicoDatabaseUtilSqlite
Browse files Browse the repository at this point in the history
  • Loading branch information
kamshory committed Oct 26, 2024
1 parent 3c3ab91 commit 13c32e9
Show file tree
Hide file tree
Showing 8 changed files with 532 additions and 127 deletions.
5 changes: 3 additions & 2 deletions manual/includes/_sqlite.md
Original file line number Diff line number Diff line change
Expand Up @@ -197,6 +197,7 @@ $sqlite->delete('users', $conditions);

use MagicObject\Database\PicoSqlite;
use MagicObject\MagicObject;
use MagicObject\Util\Database\PicoDatabaseUtilSqlite;

require_once dirname(__DIR__) . "/vendor/autoload.php";

Expand Down Expand Up @@ -386,8 +387,8 @@ try
$album = new Album(null, $database);

// create table if not exists
$tableStructure = $database->showCreateTable($album, true);

$util = new PicoDatabaseUtilSqlite();
$tableStructure = $util->showCreateTable($album, true);
$database->query($tableStructure);

$album->setAlbumId("1235");
Expand Down
5 changes: 3 additions & 2 deletions manual/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -10214,6 +10214,7 @@ <h3>Entity with PicoSqlite</h3>

use MagicObject\Database\PicoSqlite;
use MagicObject\MagicObject;
use MagicObject\Util\Database\PicoDatabaseUtilSqlite;

require_once dirname(__DIR__) . "/vendor/autoload.php";

Expand Down Expand Up @@ -10403,8 +10404,8 @@ <h3>Entity with PicoSqlite</h3>
$album = new Album(null, $database);

// create table if not exists
$tableStructure = $database-&gt;showCreateTable($album, true);

$util = new PicoDatabaseUtilSqlite();
$tableStructure = $util-&gt;showCreateTable($album, true);
$database-&gt;query($tableStructure);

$album-&gt;setAlbumId("1235");
Expand Down
97 changes: 0 additions & 97 deletions src/Database/PicoSqlite.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,8 @@

namespace MagicObject\Database;

use MagicObject\MagicObject;
use PDO;
use PDOException;
use ReflectionClass;
use ReflectionProperty;

/**
* Class PicoSqlite
Expand Down Expand Up @@ -184,100 +181,6 @@ public function delete($tableName, $conditions) {

return $stmt->execute();
}

/**
* Generates a SQL CREATE TABLE query based on the provided class annotations.
*
* This function inspects the given class for its properties and their annotations
* to construct a SQL statement that can be used to create a corresponding table in a database.
* It extracts the table name from the `@Table` annotation and processes each property
* to determine the column definitions from the `@Column` annotations.
*
* @param MagicObject $entity The instance of the class whose properties will be used
* to generate the table structure.
* @param bool $ifNotExists If true, the query will include an "IF NOT EXISTS" clause.
* @return string The generated SQL CREATE TABLE query.
*
* @throws ReflectionException If the class does not exist or is not accessible.
*/
function showCreateTable($entity, $ifNotExists = false) {
$tableInfo = $entity->tableInfo();
$tableName = $tableInfo->getTableName();

// Start building the CREATE TABLE query
if($ifNotExists)
{
$condition = " IF NOT EXISTS";
}
else
{
$condition = "";
}
$query = "CREATE TABLE$condition $tableName (\n";

// Define primary key
$primaryKey = null;

$pKeys = $tableInfo->getPrimaryKeys();
if(isset($pKeys) && is_array($pKeys) && !empty($pKeys))
{
$pKeyArr = [];
$pkVals = array_values($pKeys);
foreach($pkVals as $pk)
{
$pKeyArr[] = $pk['name'];
}
$primaryKey = implode(", ", $pKeyArr);
}

foreach ($tableInfo->getColumns() as $column) {

$columnName = $column['name'];
$columnType = $column['type'];
$length = isset($column['length']) ? $column['length'] : null;
$nullable = (isset($column['nullable']) && $column['nullable'] === 'true') ? 'NULL' : 'NOT NULL';
$defaultValue = isset($column['defaultValue']) ? "DEFAULT '{$column['defaultValue']}'" : '';

// Convert column type for SQL
$columnType = strtolower($columnType); // Convert to lowercase for case-insensitive comparison

if (strpos($columnType, 'varchar') !== false) {
$sqlType = "VARCHAR($length)";
} elseif ($columnType === 'int') {
$sqlType = 'INT';
} elseif ($columnType === 'float') {
$sqlType = 'FLOAT';
} elseif ($columnType === 'text') {
$sqlType = 'TEXT';
} elseif ($columnType === 'longtext') {
$sqlType = 'LONGTEXT';
} elseif ($columnType === 'date') {
$sqlType = 'DATE';
} elseif ($columnType === 'timestamp') {
$sqlType = 'TIMESTAMP';
} elseif ($columnType === 'tinyint(1)') {
$sqlType = 'TINYINT(1)';
} else {
$sqlType = 'VARCHAR(255)'; // Fallback type
}

// Add to query
$query .= " $columnName $sqlType $nullable,\n";

}

// Remove the last comma and add primary key constraint
$query = rtrim($query, ",\n") . "\n";

if ($primaryKey) {
$query = rtrim($query, ",\n");
$query .= ",\n PRIMARY KEY ($primaryKey)\n";
}

$query .= ");";

return str_replace("\n", "\r\n", $query);
}


}
24 changes: 12 additions & 12 deletions src/Util/Database/PicoDatabaseUtilMySql.php
Original file line number Diff line number Diff line change
Expand Up @@ -50,12 +50,12 @@ class PicoDatabaseUtilMySql extends PicoDatabaseUtilBase implements PicoDatabase
* Retrieves a list of columns for a specified table.
*
* @param PicoDatabase $database Database connection.
* @param string $picoTableName Table name.
* @param string $tableName Table name.
* @return array An array of column details.
*/
public function getColumnList($database, $picoTableName)
public function getColumnList($database, $tableName)
{
$sql = "SHOW COLUMNS FROM $picoTableName";
$sql = "SHOW COLUMNS FROM $tableName";
return $database->fetchAll($sql);
}

Expand All @@ -67,20 +67,20 @@ public function getColumnList($database, $picoTableName)
* "DROP TABLE IF EXISTS". It also handles the definition of primary keys if present.
*
* @param PicoTableInfo $tableInfo The information about the table, including column details and primary keys.
* @param string $picoTableName The name of the table for which the structure is being generated.
* @param string $tableName The name of the table for which the structure is being generated.
* @param bool $createIfNotExists Whether to add "IF NOT EXISTS" in the CREATE statement (default is false).
* @param bool $dropIfExists Whether to add "DROP TABLE IF EXISTS" before the CREATE statement (default is false).
* @param string|null $engine The storage engine to use for the table (optional, default is null).
* @param string|null $charset The character set to use for the table (optional, default is null).
* @return string The SQL statement to create the table, including column definitions and primary keys.
*/
public function dumpStructure($tableInfo, $picoTableName, $createIfNotExists = false, $dropIfExists = false, $engine = 'InnoDB', $charset = 'utf8mb4')
public function dumpStructure($tableInfo, $tableName, $createIfNotExists = false, $dropIfExists = false, $engine = 'InnoDB', $charset = 'utf8mb4')
{
$query = array();
$columns = array();
if($dropIfExists)
{
$query[] = "-- DROP TABLE IF EXISTS `$picoTableName`;";
$query[] = "-- DROP TABLE IF EXISTS `$tableName`;";
$query[] = "";
}
$createStatement = "";
Expand All @@ -93,7 +93,7 @@ public function dumpStructure($tableInfo, $picoTableName, $createIfNotExists = f

$autoIncrementKeys = $this->getAutoIncrementKey($tableInfo);

$query[] = "$createStatement `$picoTableName` (";
$query[] = "$createStatement `$tableName` (";

foreach($tableInfo->getColumns() as $column)
{
Expand All @@ -106,7 +106,7 @@ public function dumpStructure($tableInfo, $picoTableName, $createIfNotExists = f
if(isset($pk) && is_array($pk) && !empty($pk))
{
$query[] = "";
$query[] = "ALTER TABLE `$picoTableName`";
$query[] = "ALTER TABLE `$tableName`";
foreach($pk as $primaryKey)
{
$query[] = "\tADD PRIMARY KEY (`$primaryKey[name]`)";
Expand All @@ -119,7 +119,7 @@ public function dumpStructure($tableInfo, $picoTableName, $createIfNotExists = f
if(isset($autoIncrementKeys) && is_array($autoIncrementKeys) && in_array($column[parent::KEY_NAME], $autoIncrementKeys))
{
$query[] = "";
$query[] = "ALTER TABLE `$picoTableName` \r\n\tMODIFY ".trim($this->createColumn($column), " \r\n\t ")." AUTO_INCREMENT";
$query[] = "ALTER TABLE `$tableName` \r\n\tMODIFY ".trim($this->createColumn($column), " \r\n\t ")." AUTO_INCREMENT";
$query[] = ";";
}
}
Expand Down Expand Up @@ -199,13 +199,13 @@ public function fixDefaultValue($defaultValue, $type)
* columns based on the provided column definitions.
*
* @param array $columns An associative array where keys are column names and values are column details.
* @param string $picoTableName The name of the table where the record will be inserted.
* @param string $tableName The name of the table where the record will be inserted.
* @param MagicObject $record The data record to be inserted, which provides a method to retrieve values.
*
* @return string The generated SQL INSERT statement.
* @throws Exception If the record cannot be processed or if there are no values to insert.
*/
public function dumpRecord($columns, $picoTableName, $record)
public function dumpRecord($columns, $tableName, $record)
{
$value = $record->valueArray();
$rec = array();
Expand All @@ -219,7 +219,7 @@ public function dumpRecord($columns, $picoTableName, $record)
$queryBuilder = new PicoDatabaseQueryBuilder(PicoDatabaseType::DATABASE_TYPE_MYSQL);
$queryBuilder->newQuery()
->insert()
->into($picoTableName)
->into($tableName)
->fields(array_keys($rec))
->values(array_values($rec));

Expand Down
22 changes: 11 additions & 11 deletions src/Util/Database/PicoDatabaseUtilPostgreSql.php
Original file line number Diff line number Diff line change
Expand Up @@ -54,13 +54,13 @@ class PicoDatabaseUtilPostgreSql extends PicoDatabaseUtilBase implements PicoDat
* and default values.
*
* @param PicoDatabase $database The database connection instance.
* @param string $picoTableName The name of the table to retrieve column information from.
* @param string $tableName The name of the table to retrieve column information from.
* @return array An array of associative arrays containing details about each column,
* where each associative array includes 'column_name', 'data_type',
* 'is_nullable', and 'column_default'.
* @throws Exception If the database connection fails or the query cannot be executed.
*/
public function getColumnList($database, $picoTableName)
public function getColumnList($database, $tableName)
{
$schema = $database->getDatabaseCredentials()->getDatabaseSchema();
if(!isset($schema) || empty($schema))
Expand All @@ -69,7 +69,7 @@ public function getColumnList($database, $picoTableName)
}
$sql = "SELECT column_name, data_type, is_nullable, column_default
FROM information_schema.columns
WHERE table_schema = '$schema' AND table_name = '$picoTableName'";
WHERE table_schema = '$schema' AND table_name = '$tableName'";
return $database->fetchAll($sql);
}

Expand All @@ -81,18 +81,18 @@ public function getColumnList($database, $picoTableName)
* "DROP TABLE IF EXISTS". It also handles the definition of primary keys if present.
*
* @param PicoTableInfo $tableInfo The information about the table, including column details and primary keys.
* @param string $picoTableName The name of the table for which the structure is being generated.
* @param string $tableName The name of the table for which the structure is being generated.
* @param bool $createIfNotExists Whether to add "IF NOT EXISTS" in the CREATE statement (default is false).
* @param bool $dropIfExists Whether to add "DROP TABLE IF EXISTS" before the CREATE statement (default is false).
* @param string|null $engine The storage engine to use for the table (optional, default is null).
* @param string|null $charset The character set to use for the table (optional, default is null).
* @return string The SQL statement to create the table, including column definitions and primary keys.
*/
public function dumpStructure($tableInfo, $picoTableName, $createIfNotExists = false, $dropIfExists = false, $engine = null, $charset = null)
public function dumpStructure($tableInfo, $tableName, $createIfNotExists = false, $dropIfExists = false, $engine = null, $charset = null)
{
$query = [];
if ($dropIfExists) {
$query[] = "-- DROP TABLE IF EXISTS \"$picoTableName\";";
$query[] = "-- DROP TABLE IF EXISTS \"$tableName\";";
$query[] = "";
}

Expand All @@ -103,7 +103,7 @@ public function dumpStructure($tableInfo, $picoTableName, $createIfNotExists = f

$autoIncrementKeys = $this->getAutoIncrementKey($tableInfo);

$query[] = "$createStatement \"$picoTableName\" (";
$query[] = "$createStatement \"$tableName\" (";

foreach ($tableInfo->getColumns() as $column) {
$query[] = $this->createColumn($column);
Expand All @@ -114,7 +114,7 @@ public function dumpStructure($tableInfo, $picoTableName, $createIfNotExists = f
$pk = $tableInfo->getPrimaryKeys();
if (isset($pk) && is_array($pk) && !empty($pk)) {
$query[] = "";
$query[] = "ALTER TABLE \"$picoTableName\"";
$query[] = "ALTER TABLE \"$tableName\"";
foreach ($pk as $primaryKey) {
$query[] = "\tADD PRIMARY KEY (\"$primaryKey[name]\")";
}
Expand Down Expand Up @@ -195,13 +195,13 @@ public function fixDefaultValue($defaultValue, $type)
* columns based on the provided column definitions.
*
* @param array $columns An associative array where keys are column names and values are column details.
* @param string $picoTableName The name of the table where the record will be inserted.
* @param string $tableName The name of the table where the record will be inserted.
* @param MagicObject $record The data record to be inserted, which provides a method to retrieve values.
*
* @return string The generated SQL INSERT statement.
* @throws Exception If the record cannot be processed or if there are no values to insert.
*/
public function dumpRecord($columns, $picoTableName, $record)
public function dumpRecord($columns, $tableName, $record)
{
$value = $record->valueArray();
$rec = [];
Expand All @@ -214,7 +214,7 @@ public function dumpRecord($columns, $picoTableName, $record)
$queryBuilder = new PicoDatabaseQueryBuilder(PicoDatabaseType::DATABASE_TYPE_POSTGRESQL);
$queryBuilder->newQuery()
->insert()
->into($picoTableName)
->into($tableName)
->fields(array_keys($rec))
->values(array_values($rec));

Expand Down
Loading

0 comments on commit 13c32e9

Please sign in to comment.