4 Commits

Author SHA1 Message Date
80e889946b improved Maintenance for MySQL and SQLite DB type 2025-10-13 23:26:19 +02:00
cf59109a47 extend compatibility for SQLite3 2025-10-01 01:12:46 +02:00
ae59ffaa97 added getListOrganize for created new model 2025-06-15 19:07:42 +02:00
616dc01c21 added namespace for created new model,
added method getListByID for new model,
added type of object for import method,
extends definition tor checkDBTable,
fixed typo in parameters of method existsColumn
2025-06-12 07:48:08 +02:00
4 changed files with 100 additions and 20 deletions

View File

@ -4,7 +4,7 @@
"description": "This library extends the builtin PDO object by several useful features. ", "description": "This library extends the builtin PDO object by several useful features. ",
"type": "library", "type": "library",
"readme": "README.md", "readme": "README.md",
"keywords": ["db", "model", "pdo"], "keywords": ["db", "model", "pdo", "mysql", "sqlite"],
"authors": [ "authors": [
{ {
"name": "Igor Mino", "name": "Igor Mino",

View File

@ -21,12 +21,14 @@ class Creator {
public function interact() { public function interact() {
$name = $this->readline('New model name: '); $name = $this->readline('New model name: ');
$table = $this->readline('Table name: '); $table = strtolower($name);
$entity = $this->readline('Entity name: '); $table = $this->readline('Table name ['.$table.']: ', $table);
$entity = $this->readline('Entity name ['.$table.']: ', $table);
$namespace = $this->readline('Namespace [App\Models]: ', 'App\Models');
if (strlen($entity) <= 0) { if (strlen($entity) <= 0) {
$entity = $table; $entity = $table;
} }
$model_filepath = $this->rootDir().'/models/'.$name.'.php'; $model_filepath = $this->rootDir().'/Models/'.$name.'.php';
if ($this->readline("Create MODEL class '$model_filepath'? (y - yes, other - no) ") != 'y') { if ($this->readline("Create MODEL class '$model_filepath'? (y - yes, other - no) ") != 'y') {
echo "Creating of MODEL class is skipped\n"; echo "Creating of MODEL class is skipped\n";
return false; return false;
@ -47,11 +49,11 @@ class Creator {
} }
} }
$table_columns = $this->dbh->getTableColumns($table); $table_columns = $this->dbh->getTableColumns($table);
$suc = $this->modelSave($model_filepath, $name, $table, $entity, $table_columns['pks'], $table_columns['columns'], $table_columns['types']); $suc = $this->modelSave($model_filepath, $name, $table, $entity, $table_columns['pks'], $table_columns['columns'], $table_columns['types'], $namespace);
echo $suc ? "MODEL class created" : 'Error: MODEL class not created'; echo $suc ? "MODEL class created" : 'Error: MODEL class not created';
} }
private function modelSave($filepath, $name, $tablename, $entity, $pks, $columns, $types) { private function modelSave($filepath, $name, $tablename, $entity, $pks, $columns, $types, $namespace) {
if (is_array($pks) && count($pks) > 1) { if (is_array($pks) && count($pks) > 1) {
$primary_key_name = "array('".implode("', '", $pks)."')"; $primary_key_name = "array('".implode("', '", $pks)."')";
$columns = array_merge($pks, $columns); $columns = array_merge($pks, $columns);
@ -93,6 +95,7 @@ class Creator {
$data[\'changed_dt\'] = date(\'Y-m-d H:i:s\'); $data[\'changed_dt\'] = date(\'Y-m-d H:i:s\');
}' }'
: ''; : '';
$namespace_str = strlen($namespace) > 0 ? "\nnamespace $namespace;\n" : '';
$content = '<?'."php $content = '<?'."php
/* /*
TPsoft.org 2000-".date('Y')." TPsoft.org 2000-".date('Y')."
@ -101,7 +104,7 @@ class Creator {
Milestones: Milestones:
".date('Y-m-d H:i')." Created ".date('Y-m-d H:i')." Created
*/ */
".$namespace_str."
class ".$name." extends \TPsoft\DBmodel\DBmodel { class ".$name." extends \TPsoft\DBmodel\DBmodel {
public $"."tables = array( public $"."tables = array(
@ -149,6 +152,19 @@ class ".$name." extends \TPsoft\DBmodel\DBmodel {
->toArray(); ->toArray();
} }
public function getListOrganize($"."cola_name, $"."search = array(), $"."reverse = false, $"."concat_or = false) {
$"."all = $"."this->getList($"."search, $"."reverse, $"."concat_or);
$"."ret = array();
if (is_array($"."all)) foreach ($"."all as $"."key => $"."row) {
$"."ret[$"."row[$"."cola_name]] = $"."row;
}
return $"."ret;
}
public function getListByID($"."search = array(), $"."reverse = false, $"."concat_or = false) {
return $"."this->getListOrganize($primary_key_name, $"."search, $"."reverse, $"."concat_or);
}
public function ".$entity_one."Combo($"."col_key, $"."col_value, $"."add_empty = false) { public function ".$entity_one."Combo($"."col_key, $"."col_value, $"."add_empty = false) {
return $"."this->search('".$entity."') return $"."this->search('".$entity."')
->toCombo($"."col_key, $"."col_value, $"."add_empty); ->toCombo($"."col_key, $"."col_value, $"."add_empty);

View File

@ -154,6 +154,11 @@ class DBmodel
return $where; return $where;
} }
public function getDBtype()
{
return $this->dbh->getAttribute(\PDO::ATTR_DRIVER_NAME);
}
public function existTable($table_id) public function existTable($table_id)
{ {
$query = sprintf( $query = sprintf(
@ -269,11 +274,14 @@ class DBmodel
return false; return false;
} }
if (count($primary_key_names) > 1) return true; if (count($primary_key_names) > 1) return true;
$last_id = $this->getLastInsertID();
/*
if (method_exists($this->dbh, 'getLastInsertID')) { if (method_exists($this->dbh, 'getLastInsertID')) {
$last_id = $this->getLastInsertID(); $last_id = $this->getLastInsertID();
} else { } else {
$last_id = $this->getOne('SELECT last_insert_id()'); $last_id = $this->getOne('SELECT last_insert_id()');
} }
*/
return $last_id; return $last_id;
} }
@ -304,12 +312,14 @@ class DBmodel
$query = sprintf( $query = sprintf(
'UPDATE %s' 'UPDATE %s'
. ' SET %s' . ' SET %s'
. ' WHERE %s' . ' WHERE %s',
. ' LIMIT 1',
$table, $table,
$set, $set,
$this->buildWherePrimaryKey($table_id, $primary_key) $this->buildWherePrimaryKey($table_id, $primary_key)
); );
if ($this->getDBtype() == 'mysql') {
$query .= ' LIMIT 1';
}
$this->_debug('[DBmodel][record][UPDATE]: ' . $query); $this->_debug('[DBmodel][record][UPDATE]: ' . $query);
$ret = $this->query($query); $ret = $this->query($query);
if ($ret === false) { if ($ret === false) {
@ -331,11 +341,13 @@ class DBmodel
} }
$query = sprintf( $query = sprintf(
'DELETE FROM %s' 'DELETE FROM %s'
. ' WHERE %s' . ' WHERE %s',
. ' LIMIT 1',
$table, $table,
$this->buildWherePrimaryKey($table_id, $primary_key) $this->buildWherePrimaryKey($table_id, $primary_key)
); );
if ($this->getDBtype() == 'mysql') {
$query .= ' LIMIT 1';
}
$this->_debug('[DBmodel][record][DELETE]: ' . $query); $this->_debug('[DBmodel][record][DELETE]: ' . $query);
$ret = $this->query($query); $ret = $this->query($query);
if ($ret === false) { if ($ret === false) {
@ -548,6 +560,15 @@ class DBmodel
} }
public function getTableColumns($table_name) { public function getTableColumns($table_name) {
$db_type = $this->getDBtype();
switch ($db_type) {
case 'mysql': return $this->getTableColumnsMYSQL($table_name);
case 'sqlite': return $this->getTableColumnsSQLITE($table_name);
default: new \Exception('Unknown DB type: ' . $db_type);
}
}
public function getTableColumnsMYSQL($table_name) {
$desc = $this->getAll(sprintf('DESC %s', $table_name)); $desc = $this->getAll(sprintf('DESC %s', $table_name));
$desc = $this->arrayKeysToLowerCase($desc); $desc = $this->arrayKeysToLowerCase($desc);
$pks = array(); $pks = array();
@ -567,6 +588,26 @@ class DBmodel
return array('pks' => $pks, 'columns' => $columns, 'types' => $types); return array('pks' => $pks, 'columns' => $columns, 'types' => $types);
} }
public function getTableColumnsSQLITE($table_name) {
$desc = $this->getAll(sprintf('PRAGMA table_info(%s)', $table_name));
$desc = $this->arrayKeysToLowerCase($desc);
$pks = array();
$columns = array();
foreach ($desc as $d) {
$colname = $d['name'];
$types[$colname] = $d['type'];
if ($d['pk'] == 1) {
$pks[] = $colname;
if (strtoupper($d['type']) != 'INTEGER') {
$columns[] = $colname;
}
} else {
$columns[] = $colname;
}
}
return array('pks' => $pks, 'columns' => $columns, 'types' => $types);
}
/* ---------------------------------------------------- /* ----------------------------------------------------
* HELPER METHODS * HELPER METHODS
*/ */
@ -851,7 +892,7 @@ class DBmodel
return $this->allowNextError(); return $this->allowNextError();
} }
public function import($objModel) public function import(DBmodel $objModel)
{ {
if (is_null($objModel)) return false; if (is_null($objModel)) return false;
if ( if (

View File

@ -81,25 +81,48 @@ class Maintenance
public function existsTable($table_name) public function existsTable($table_name)
{ {
return $this->testDB( $db_type = $this->dbh->getDBtype();
'SHOW TABLES LIKE "' . $table_name . '"', switch ($db_type) {
$table_name case 'mysql':
); return $this->testDB(
'SHOW TABLES LIKE "' . $table_name . '"',
$table_name
);
case 'sqlite':
return $this->testDB(
'SELECT name FROM sqlite_master WHERE TYPE = "table" AND name LIKE "' . $table_name . '"',
$table_name
);
default:
new \Exception('Unknown DB type: ' . $db_type);
}
} }
public function checkDBTable($table_name, $definition) public function checkDBTable($table_name, $definition, $after_definition = '')
{ {
if (strlen($table_name) <= 0) { if (strlen($table_name) <= 0) {
$this->lastMessage = 'Table ' . strtoupper($table_name) . ' - invalid index'; $this->lastMessage = 'Table ' . strtoupper($table_name) . ' - invalid index';
return Maintenance::ABNORMAL; return Maintenance::ABNORMAL;
} }
$check_query = '';
$db_type = $this->dbh->getDBtype();
switch ($db_type) {
case 'mysql':
$check_query = 'SHOW TABLES LIKE "' . $table_name . '"';
break;
case 'sqlite':
$check_query = 'SELECT name FROM sqlite_master WHERE TYPE = "table" AND name LIKE "' . $table_name . '"';
break;
default:
new \Exception('Unknown DB type: ' . $db_type);
}
$status = $this->checkDB( $status = $this->checkDB(
// TEST query // TEST query
'SHOW TABLES LIKE "' . $table_name . '"', $check_query,
// TEST output // TEST output
$table_name, $table_name,
// FIX query // FIX query
'CREATE TABLE `' . $table_name . '` (' . $definition . ')' 'CREATE TABLE `' . $table_name . '` (' . $definition . ') ' . $after_definition
); );
$this->lastMessage = 'Table ' . strtoupper($table_name) . ' (' . $table_name . ')'; $this->lastMessage = 'Table ' . strtoupper($table_name) . ' (' . $table_name . ')';
return $status; return $status;
@ -146,7 +169,7 @@ class Maintenance
public function checkDBRetype($table_name, $column, $new_type, $definition) public function checkDBRetype($table_name, $column, $new_type, $definition)
{ {
if (!$this->existsColumn($table_name, $column_old)) { if (!$this->existsColumn($table_name, $column)) {
return Maintenance::ABNORMAL; return Maintenance::ABNORMAL;
} }
$status = $this->checkDB( $status = $this->checkDB(