Skip to content

Commit

Permalink
Fixing database driver
Browse files Browse the repository at this point in the history
  • Loading branch information
kamshory committed Nov 13, 2024
1 parent 6c77d51 commit a9a0fe2
Show file tree
Hide file tree
Showing 8 changed files with 66 additions and 39 deletions.
30 changes: 28 additions & 2 deletions src/Database/PicoDatabase.php
Original file line number Diff line number Diff line change
Expand Up @@ -440,6 +440,32 @@ private function getDbType($databaseType) // NOSONAR
}
}

/**
* Determines the database driver based on the provided database type.
*
* This function takes a string representing the database type and returns
* the corresponding database driver constant from the `PicoDatabaseType` class.
* It supports SQLite, PostgreSQL, and MySQL/MariaDB types.
*
* @param string $databaseType The type of the database (e.g., 'sqlite', 'postgres', 'pgsql', 'mysql', 'mariadb').
*
* @return string The corresponding database driver constant, one of:
* - `sqlite`
* - `pgsql`
* - `mysql`
*/
private function getDbDriver($databaseType)
{
if (stripos($databaseType, 'sqlite') !== false) {
return PicoDatabaseType::DATABASE_TYPE_SQLITE;
} else if (stripos($databaseType, 'postgre') !== false || stripos($databaseType, 'pgsql') !== false) {
return PicoDatabaseType::DATABASE_TYPE_PGSQL;
} else {
return PicoDatabaseType::DATABASE_TYPE_MYSQL;
}
}


/**
* Create a connection string.
*
Expand All @@ -464,12 +490,12 @@ private function constructConnectionString($withDatabase = true)
$emptyValue .= $emptyName ? "{database_name}" : "";
throw new InvalidDatabaseConfiguration("Invalid database configuration. $emptyValue. Please check your database configuration!");
}
return $this->databaseCredentials->getDriver() . ':host=' . $this->databaseCredentials->getHost() . '; port=' . ((int) $this->databaseCredentials->getPort()) . '; dbname=' . $this->databaseCredentials->getDatabaseName();
return $this->getDbDriver($this->databaseCredentials->getDriver()) . ':host=' . $this->databaseCredentials->getHost() . '; port=' . ((int) $this->databaseCredentials->getPort()) . '; dbname=' . $this->databaseCredentials->getDatabaseName();
} else {
if ($invalidParam1) {
throw new InvalidDatabaseConfiguration("Invalid database configuration. $emptyValue. Please check your database configuration!");
}
return $this->databaseCredentials->getDriver() . ':host=' . $this->databaseCredentials->getHost() . '; port=' . ((int) $this->databaseCredentials->getPort());
return $this->getDbDriver($this->databaseCredentials->getDriver()) . ':host=' . $this->databaseCredentials->getHost() . '; port=' . ((int) $this->databaseCredentials->getPort());
}
}

Expand Down
2 changes: 1 addition & 1 deletion src/Database/PicoDatabaseCredentials.php
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@
class PicoDatabaseCredentials extends SecretObject
{
/**
* Database driver (e.g., 'mysql', 'postgresql', 'mariadb).
* Database driver (e.g., 'mysql', 'pgsql', 'mariadb', 'sqlite').
*
* @var string
*/
Expand Down
16 changes: 8 additions & 8 deletions src/Util/Database/EntityUtil.php
Original file line number Diff line number Diff line change
Expand Up @@ -29,10 +29,10 @@ public static function getPropertyColumn($entity)
$tableInfo = $entity->tableInfo();
if($tableInfo == null)
{
return array();
return [];
}
$columns = $tableInfo->getColumns();
$propertyColumns = array();
$propertyColumns = [];
foreach($columns as $prop=>$column)
{
$propertyColumns[$prop] = $column['name'];
Expand All @@ -51,10 +51,10 @@ public static function getPropertyJoinColumn($entity)
$tableInfo = $entity->tableInfo();
if($tableInfo == null)
{
return array();
return [];
}
$joinColumns = $tableInfo->getJoinColumns();
$propertyColumns = array();
$propertyColumns = [];
foreach($joinColumns as $prop=>$column)
{
$propertyColumns[$prop] = $column['name'];
Expand All @@ -71,7 +71,7 @@ public static function getPropertyJoinColumn($entity)
*/
public static function getEntityData($data, $map)
{
$newData = array();
$newData = [];
if(isset($data))
{
if(is_array($data))
Expand Down Expand Up @@ -99,7 +99,7 @@ public static function getEntityData($data, $map)
*/
private static function fromArray($data, $map)
{
$newData = array();
$newData = [];
foreach($map as $key=>$value)
{
if(isset($data[$value]))
Expand All @@ -119,7 +119,7 @@ private static function fromArray($data, $map)
*/
private static function fromStdClass($data, $map)
{
$newData = array();
$newData = [];
foreach($map as $key=>$value)
{
if(isset($data->{$value}))
Expand All @@ -139,7 +139,7 @@ private static function fromStdClass($data, $map)
*/
private static function fromMagicObject($data, $map)
{
$newData = array();
$newData = [];
foreach($map as $key=>$value)
{
$newData[$key] = $data->get($value);
Expand Down
2 changes: 1 addition & 1 deletion src/Util/Database/PicoDatabaseUtil.php
Original file line number Diff line number Diff line change
Expand Up @@ -109,7 +109,7 @@ public static function sortableFromParams($params)
*/
public static function valuesFromParams($params)
{
$ret = array();
$ret = [];
if(self::isArray($params))
{
foreach($params as $param)
Expand Down
16 changes: 8 additions & 8 deletions src/Util/Database/PicoDatabaseUtilBase.php
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ class PicoDatabaseUtilBase
public function getAutoIncrementKey($tableInfo)
{
$autoIncrement = $tableInfo->getAutoIncrementKeys();
$autoIncrementKeys = array();
$autoIncrementKeys = [];
if(is_array($autoIncrement) && !empty($autoIncrement))
{
foreach($autoIncrement as $col)
Expand Down Expand Up @@ -61,7 +61,7 @@ public function dumpData($columns, $picoTableName, $data, $maxRecord = 100, $cal
// Handle case where fetching data is not required
if($data->getFindOption() & MagicObject::FIND_OPTION_NO_FETCH_DATA && $maxRecord > 0 && isset($callbackFunction) && is_callable($callbackFunction))
{
$records = array();
$records = [];
$stmt = $data->getPDOStatement();
// Fetch records in batches
while($data = $stmt->fetch(PDO::FETCH_ASSOC, PDO::FETCH_ORI_NEXT))
Expand All @@ -81,7 +81,7 @@ public function dumpData($columns, $picoTableName, $data, $maxRecord = 100, $cal
call_user_func($callbackFunction, $sql);
}
// Reset the records buffer
$records = array();
$records = [];
}
}
// Handle any remaining records
Expand Down Expand Up @@ -211,7 +211,7 @@ public function createMapTemplate($databaseSource, $databaseTarget, $target)
{
$targetColumns = array_keys($this->showColumns($databaseTarget, $target));
$sourceColumns = array_keys($this->showColumns($databaseSource, $target));
$map = array();
$map = [];
foreach($targetColumns as $column)
{
if(!in_array($column, $sourceColumns))
Expand Down Expand Up @@ -306,7 +306,7 @@ public function importDataTable($databaseSource, $databaseTarget, $tableNameSour
->select("*")
->from($sourceTable);
$stmt = $databaseSource->query($queryBuilderSource);
$records = array();
$records = [];
while($data = $stmt->fetch(PDO::FETCH_ASSOC, PDO::FETCH_ORI_NEXT))
{
$data = $this->processDataMapping($data, $columns, $tableInfo->getMap());
Expand All @@ -322,7 +322,7 @@ public function importDataTable($databaseSource, $databaseTarget, $tableNameSour
call_user_func($callbackFunction, $sql, $tableNameSource, $tableNameTarget);
}
// reset buffer
$records = array();
$records = [];
}
}
if(!empty($records) && isset($callbackFunction) && is_callable($callbackFunction))
Expand Down Expand Up @@ -542,7 +542,7 @@ public function fixFloatData($data, $name, $value)
public function insert($tableName, $data)
{
// Collect all unique columns from the data records
$columns = array();
$columns = [];
foreach ($data as $record) {
$columns = array_merge($columns, array_keys($record));
}
Expand All @@ -557,7 +557,7 @@ public function insert($tableName, $data)
implode(",\r\n", array_fill(0, count($data), $placeholders));

// Prepare values for binding
$values = array();
$values = [];
foreach ($data as $record) {
foreach ($columns as $column) {
// Use null if the value is not set
Expand Down
12 changes: 6 additions & 6 deletions src/Util/Database/PicoDatabaseUtilMySql.php
Original file line number Diff line number Diff line change
Expand Up @@ -76,8 +76,8 @@ public function getColumnList($database, $tableName)
*/
public function dumpStructure($tableInfo, $tableName, $createIfNotExists = false, $dropIfExists = false, $engine = 'InnoDB', $charset = 'utf8mb4')
{
$query = array();
$columns = array();
$query = [];
$columns = [];
if($dropIfExists)
{
$query[] = "-- DROP TABLE IF EXISTS `$tableName`;";
Expand Down Expand Up @@ -144,7 +144,7 @@ public function dumpStructure($tableInfo, $tableName, $createIfNotExists = false
*/
public function createColumn($column)
{
$col = array();
$col = [];
$col[] = "\t";
$col[] = "`".$column[parent::KEY_NAME]."`";
$col[] = $column['type'];
Expand Down Expand Up @@ -208,7 +208,7 @@ public function fixDefaultValue($defaultValue, $type)
public function dumpRecord($columns, $tableName, $record)
{
$value = $record->valueArray();
$rec = array();
$rec = [];
foreach($value as $key=>$val)
{
if(isset($columns[$key]))
Expand Down Expand Up @@ -242,7 +242,7 @@ public function showColumns($database, $tableName)
$sql = "SHOW COLUMNS FROM $tableName";
$result = $database->fetchAll($sql, PDO::FETCH_ASSOC);

$columns = array();
$columns = [];
foreach($result as $row)
{
$columns[$row['Field']] = $row['Type'];
Expand Down Expand Up @@ -273,7 +273,7 @@ public function autoConfigureImportData($config)
$databaseTarget->connect();
$tables = $config->getTable();

$existingTables = array();
$existingTables = [];
foreach($tables as $tb)
{
$existingTables[] = $tb->getTarget();
Expand Down
17 changes: 9 additions & 8 deletions src/Util/Database/PicoDatabaseUtilSqlite.php
Original file line number Diff line number Diff line change
Expand Up @@ -170,7 +170,7 @@ private function getPkeyArrayFinal($pKeyArr, $pKeyArrUsed)
* @param array $pKeyArrUsed The array to store used primary key names.
* @return array An array containing the determined SQL data type and the updated primary key array.
*/
private function determineSqlType($column, $autoIncrementKeys = null, $length = 255, $pKeyArrUsed = array())
private function determineSqlType($column, $autoIncrementKeys = null, $length = 255, $pKeyArrUsed = [])
{
$columnName = $column[parent::KEY_NAME];
$columnType = strtolower($column['type']); // Assuming 'type' holds the column type
Expand Down Expand Up @@ -200,7 +200,8 @@ private function determineSqlType($column, $autoIncrementKeys = null, $length =
$sqlType = strtoupper($columnType);
if ($sqlType !== 'TINYINT(1)' && $sqlType !== 'FLOAT' && $sqlType !== 'TEXT' &&
$sqlType !== 'LONGTEXT' && $sqlType !== 'DATE' && $sqlType !== 'TIMESTAMP' &&
$sqlType !== 'BLOB') {
$sqlType !== 'BLOB')
{
$sqlType = 'VARCHAR(255)'; // Fallback type for unknown types
}
}
Expand Down Expand Up @@ -234,7 +235,7 @@ public function getColumnList($database, $tableName)
$stmt = $database->query("PRAGMA table_info($tableName)");

// Fetch and display the column details
$rows = array();
$rows = [];
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$rows[] = array(
"Field" => $row['name'],
Expand Down Expand Up @@ -265,8 +266,8 @@ public function getColumnList($database, $tableName)
*/
public function dumpStructure($tableInfo, $tableName, $createIfNotExists = false, $dropIfExists = false, $engine = 'InnoDB', $charset = 'utf8mb4')
{
$query = array();
$columns = array();
$query = [];
$columns = [];
if($dropIfExists)
{
$query[] = "-- DROP TABLE IF EXISTS $tableName;";
Expand All @@ -289,7 +290,7 @@ public function dumpStructure($tableInfo, $tableName, $createIfNotExists = false
$columns[] = $this->createColumn($column);
}
$query[] = implode(",\r\n", $columns);
$query[] = ") ENGINE=$engine DEFAULT CHARSET=$charset;";
$query[] = ") ";

$pk = $tableInfo->getPrimaryKeys();
if(isset($pk) && is_array($pk) && !empty($pk))
Expand Down Expand Up @@ -333,7 +334,7 @@ public function dumpStructure($tableInfo, $tableName, $createIfNotExists = false
*/
public function createColumn($column)
{
$col = array();
$col = [];
$col[] = "\t";
$col[] = "".$column[parent::KEY_NAME]."";
$col[] = $column['type'];
Expand Down Expand Up @@ -444,7 +445,7 @@ public function autoConfigureImportData($config)
$databaseTarget->connect();
$tables = $config->getTable();

$existingTables = array();
$existingTables = [];
foreach($tables as $tb)
{
$existingTables[] = $tb->getTarget();
Expand Down
10 changes: 5 additions & 5 deletions src/Util/Database/PicoSqlParser.php
Original file line number Diff line number Diff line change
Expand Up @@ -96,7 +96,7 @@ public function parseTable($sql) // NOSONAR
preg_match($rg_tb, $sql, $result);
$tableName = $result['tb'];

$fld_list = [];
$fldList = [];
$primaryKey = null;
$columnList = [];

Expand Down Expand Up @@ -132,7 +132,7 @@ public function parseTable($sql) // NOSONAR
{
$def = null;
}
$fld_list[] = [
$fldList[] = [
self::KEY_COLUMN_NAME => $columnName,
self::KEY_TYPE => trim($rg_fld2_result['ftype']),
self::KEY_LENGTH => $length,
Expand All @@ -148,7 +148,7 @@ public function parseTable($sql) // NOSONAR
}

if ($primaryKey !== null) {
foreach ($fld_list as &$column) //NOSONAR
foreach ($fldList as &$column) //NOSONAR
{
if ($column[self::KEY_COLUMN_NAME] === $primaryKey) {
$column[self::KEY_PRIMARY_KEY] = true;
Expand All @@ -160,7 +160,7 @@ public function parseTable($sql) // NOSONAR
$x = preg_replace('/(PRIMARY|UNIQUE) KEY\s+[a-zA-Z_0-9\s]+/', '', $f);
$x = str_replace(['(', ')'], '', $x);
$pkeys = array_map('trim', explode(',', $x));
foreach ($fld_list as &$column) {
foreach ($fldList as &$column) {
if ($this->inArray($pkeys, $column[self::KEY_COLUMN_NAME])) {
$column[self::KEY_PRIMARY_KEY] = true;
}
Expand All @@ -169,7 +169,7 @@ public function parseTable($sql) // NOSONAR
}
return [
'tableName' => $tableName,
'columns' => $fld_list,
'columns' => $fldList,
'primaryKey' => $primaryKey
];
}
Expand Down

0 comments on commit a9a0fe2

Please sign in to comment.