Version 0.7.0 beta - update for database functionality

This commit is contained in:
Stephan Kasdorf
2019-01-27 16:20:25 +01:00
parent a2bb8a2f48
commit 7bc5198d31
14 changed files with 1477 additions and 31 deletions

View File

@@ -1,6 +1,6 @@
# Nibiru
### Rapid Prototyping PHP Framework
Version 0.6.1 beta
Version 0.7.0 beta
## Introduction
<div style="word-spacing: 2px; letter-spacing: 0.1px; font-size: 12px; margin-bottom: 15px;">Nibiru is a rapid prototyping framework written in PHP and based on the MVC design pattern. Now one may say that writing <br>
@@ -76,7 +76,6 @@ Engine Implementation.</div>
<li>Minor bugfixing</li>
</ul>
<h1>Previous version</h1>
<p>Version 0.4.0 beta 28.08.2018</p>
<ul>
<li>Minor update concerning the autoloading class in the core, now it is also possible to give a loading order through the configuration</li>
@@ -85,7 +84,13 @@ Engine Implementation.</div>
<li>Update for multidatabase support, see the documentation on http://www.nibiru-framework.com</li>
</ul>
<h1>Update</h1>
<h1>Bugfixing</h1>
<p>Version 0.6.1 beta 04.01.2019</p>
<ul>
<li>Bugfix for the pagination in the core files, used not to work on more then three pages, is now fixed.</li>
</ul>
<h1>Previous version</h1>
<p>Version 0.6.0 beta 05.12.2018</p>
<ul>
<li>Added a Pagination to the core it now can be used like in the template file Example, the class just needs to be extended by the module that should have a pageination (e.g. a Blog Module)</li>
@@ -95,11 +100,25 @@ Engine Implementation.</div>
<li>A soap extension will not be part of the system anymore, since that is just a bad habit, so this will be replaced with a REST api.</li>
</ul>
<h1>Bugfixing</h1>
<p>Version 0.6.1 beta 04.01.2019</p>
<h1>Update</h1>
<p>Version 0.7.0 beta 27.01.2018</p>
<ul>
<li>Bugfix for the pagination in the core files, used not to work on more then three pages, is now fixed.</li>
<li>Class generator for the database models can now be used, and are configured in the settings file</li>
<li>A bug in the debug core class has been corrected</li>
<li>Implemented the pgsql driver from PHP</li>
<li>Added a configuration parameter for useing either the ODBC, or the PGSQL-PHP database driver</li>
<li>It is possible to now generate the database models even if they already exisit, by configuring overwrite in the configuration</li>
<li>Added multithreading for postgres</li>
<li>Added charset configuration for the database settings</li>
<li>Added a class mask file in the settings folder in order to have the chance to pre-configure the autmatic generated database model files.</li>
</ul>
<h1>TODO</h1>
<p>Version 0.7.1 beta</p>
<ul>
<li>Add autoated class generator for MySQL database models</li>
</ul>
<div style="word-spacing: 2px; letter-spacing: 0.1px; font-size: 15px; margin-bottom: 15px;">The start is done, have success with PHP prototyping, and always remember to have fun!</div>
Author: Stephan Kasdorf<br><br>

View File

@@ -32,6 +32,7 @@ dbmodel = "/../../application/model/"
module = "/../../application/module/"
interfaces = "/../../application/interfaces/"
trait = "/../../application/trait/"
entriesperpage = 4
background.img[] = "public/img/nibiru3.jpg"
smarty.css[] = "public/css/v3/roboto.css"
smarty.css[] = "public/css/v3/toolkit-inverse.css"
@@ -57,12 +58,24 @@ username = "YOURUSER"
password = "YOURPASSWORD"
hostname = "SERVERHOST"
basename = "DATABASENAME"
driver = "mysql"
port = "3306"
;;driver = "mysql"
;;port = "3306"
;;Postgres UNIXodbc
;;driver = "PSQL"
;;port = "5432"
;;readonly = "No"
driver = "psql"
port = "5432"
readonly = "No"
multithreading = 4
encoding = "UTF-8"
[GENERATOR]
odbc = false
database = true
database.overwrite = false
controller = true
config-section = "DATABASE"
folder-out = "/../../application/model/"
modeltemplate = "/../../application/settings/db/db.class.mask"
[SECURITY]
password_hash = "YOURPWHASH"

View File

@@ -0,0 +1,36 @@
<?php
namespace Nibiru\Model\[FOLDERNAME];
use Nibiru\Adapter\[ADAPTER]\Db;
use Nibiru\Pdo;
/**
* Created by PhpStorm.
* User: kasdorf
* Date: 10.11.17
* Time: 09:38
*/
class [CLASSNAME] extends Db
{
const TABLE = array(
'table' => '[TABLE]',
'fields' => [FIELDARRAY]
);
public function __construct()
{
[ADAPTER]::settingsSection('[DBSECTION]');
self::initTable( self::TABLE );
}
public function getTableInfo()
{
return self::TABLE;
}
public function insertArrayIntoTable($dataset = array())
{
// TODO: Implement insertArrayIntoTable() method.
}
}

View File

@@ -339,4 +339,20 @@ abstract class Db implements IDb
$result = Postgres::query("SELECT * FROM information_schema.columns WHERE table_schema = 'public' AND table_name = '" . self::getTable()['table'] . "';");
return $result;
}
public function loadPasswordByUsername( $user_name = false )
{
//TODO: Implement the postgres query
}
/**
* @desc select a row by the selected fieldset ( field and where value )
* @param array $field
* @return mixed
*/
public function selectRowByFieldWhere( $field = array() )
{
//TODO: Implement the posgtes query
//return Pdo::fetchRowInArrayByWhere(self::$table['table'], $field['field'], $field['value']);
}
}

358
core/a/postgresql.db.php Normal file
View File

@@ -0,0 +1,358 @@
<?php
namespace Nibiru\Adapter\Postgresql;
use Nibiru\Postgresql;
use Nibiru\Factory;
use Nibiru\Adapter\IDb;
/**
* Created by PhpStorm.
* User: kasdorf
* Date: 17.01.18
* Time: 09:01
*/
abstract class Db implements IDb
{
/**
* @desc class parameters
*/
private static $table = array();
private $_multithreatCount = 0;
private $_nextIndex = NULL;
/**
* @desc load the table array from the model in order to have the correct fields and the correct table name
* @param array $tableArray
*/
protected static function initTable( $tableArray = array() )
{
self::setTable( $tableArray );
}
/**
* @desc getter for the table constant array
* @return array
*/
private static function getTable()
{
return self::$table;
}
/**
* @desc setter for the table constant array
* @param array $table
*/
private static function setTable( $table )
{
self::$table = $table;
}
/**
* @desc Selects a rowset by the dataset id
* @param bool $id
* @return array|mixed
* @throws \Exception
*/
public function selectRowsetById($id = false)
{
try
{
return Postgresql::query("SELECT * FROM " . self::getTable()['table'] . " WHERE " . self::getTable()['fields']['id'] . " = " . $id . ";" );
}
catch (\Exception $e)
{
throw new \Exception(print_r($e, true));
}
}
/**
* @desc Selects a columnlist by a given field array from the current selected table
* @param array $fieldarray
* @return array
* @throws \Exception
*/
public function selectColumnByFieldArray( $fieldarray = array() )
{
try
{
$numItems = count($fieldarray);
$i=0;
$fields = "";
foreach($fieldarray as $key=>$field)
{
if(++$i === $numItems)
{
$fields .= $field . " ";
}
else
{
$fields .= $field . ", ";
}
}
return Postgresql::query("SELECT " . $fields . "FROM " . self::getTable()['table'] . ";");
}
catch(\Exception $e)
{
throw new \Exception(print_r($e, true));
}
}
public function insertRowsetById($rowset = array(), $id = false)
{
// TODO: Implement insertRowsetById() method.
}
/**
* @desc Selects a Field by max value, or multiple fields by max value, same with min fields.
* Both can be combined.
* @param string|array $min
* @param string|array $max
* @return array|mixed
*/
public function selectDatasetByMinMax($min = false, $max = false)
{
if($min)
{
$fields = "";
if(is_array($min))
{
$numItems = count($min);
$i = 0;
foreach ($min as $key=>$item)
{
if(++$i === $numItems)
{
$fields .= "MIN(" . $item .") as min_" .$item . " ";
}
else
{
$fields .= "MIN(" . $item .") as min_".$item.", ";
}
}
}
else
{
$fields .= "MIN(".$min.") as min_" . $min . " ";
}
}
if($max)
{
$mfields = "";
if(is_array($max))
{
$numItems = count($max);
$y = 0;
foreach ($max as $key=>$item)
{
if(++$y === $numItems)
{
$mfields .= "MAX(" . $item .") as max_" .$item . " ";
}
else
{
$mfields .= "MAX(" . $item .") as max_".$item.", ";
}
}
}
else
{
$mfields .= "MAX(".$max.") as max_" . $max . " ";
}
}
if(!empty($fields))
{
if(!empty($mfields))
{
$result = Postgresql::query("SELECT " . $fields . ", " . $mfields . " FROM " . self::getTable()['table']);
}
else
{
$result = Postgresql::query("SELECT " . $fields . " FROM " . self::getTable()['table']);
}
}
if(!empty($mfields) && empty($fields))
{
$result = Postgresql::query("SELECT " . $mfields . " FROM " . self::getTable()['table']);
}
return $result;
}
/**
* @desc Gets the next dataset ID for insertation, if the dataset should be iterated and not be related to the last insert id because that one is already
* present it can also be iterated
* @param bool $iterate
* @return int|mixed|null
*/
public function nextInsertIndex($iterate = false)
{
if(!$iterate)
{
$cur = array_shift(Postgresql::query('SELECT MAX(id) AS id FROM ' . self::getTable()['table'] . ';'));
if(empty(array_filter($cur)))
{
$cur["id"] = 1;
}
else
{
$cur["id"]++;
}
$this->_nextIndex = $cur["id"];
}
else
{
$this->_nextIndex++;
}
return $this->_nextIndex;
}
/**
* @desc returns the rowset by the selected field and value array
* @param array $fieldValue
* @return array|mixed
*/
public function selectRowsetByFieldValue( $fieldValue = array() )
{
return Postgresql::fetchRowInArrayByWhere(self::getTable()['table'], $fieldValue['field'], $fieldValue['value']);
}
/**
* @desc selects only one field from the field value array and returns the result
* @param array $fieldValue
* @return array
*/
public function selectFieldByFieldValue( $fieldValue = array() )
{
return Postgresql::query("SELECT " . $fieldValue['field'] . " FROM " . self::getTable()['table'] . " WHERE " . $fieldValue['field'] . " = '" . $fieldValue['value'] . "';");
}
/**
* @desc deletes all content in the table use with caution
*/
public function truncateTable()
{
Postgresql::query('DELETE FROM ' . self::getTable()['table'] . ';');
}
/**
* @desc deletes entry by ID from the database
* @param bool $id
*/
public function deleteEntryById( $id = false )
{
if($id)
{
Postgresql::query('DELETE FROM ' . self::getTable()['table'] . ' WHERE id = ' . $id . ';' );
}
}
/**
* @desc deletes entry by fieldname and value from the database
* @param array $fieldValue
*/
public function deleteEntryByFieldValue( $fieldValue = array() )
{
if(array_key_exists('field', $fieldValue))
{
Postgresql::query("DELETE FROM " . self::getTable()['table'] . " WHERE " . $fieldValue["field"] . " = '" . $fieldValue["value"] . "'" );
}
}
/**
* @desc Loads the complete Table to an array, only use for small tables, otherwise load the table with its limits.
* @param array $sortfield['name'], $sortfield['order'], or as in the followin example:
* q
* @return array
*/
public function loadTableToArray( $sortfield = array() )
{
if(sizeof($sortfield)>0)
{
$name = implode(', ', $sortfield['name']);
$result = Postgresql::query('SELECT * FROM ' . self::getTable()['table'] . ' ORDER BY ' . $name . ' ' . $sortfield['order']. ';');
}
else
{
$result = Postgresql::query('SELECT * FROM ' . self::getTable()['table'] . ';');
}
return $result;
}
public function loadMultithreadCount()
{
if( $this->_multithreatCount < Postgresql::getInstance()->getMultithreading() )
{
$this->_multithreatCount++;
}
else
{
$this->_multithreatCount = 0;
}
return $this->_multithreatCount;
}
/**
* @desc returns the last inserted id from the corresponding table Model
* @return mixed
*/
public function getLastInsertID( $sequences = false )
{
try
{
if(!$sequences)
{
$result = Postgresql::query('SELECT MAX(id) AS id FROM ' . self::getTable()['table'] . ';');
return array_shift($result)["id"];
}
else
{
//Limbas sequence abfragen
Postgresql::query('SELECT last_value AS id FROM seq_' . self::getTable()['table'] . '_id ;');
return array_shift($result)["id"];
}
}
catch (\Exception $e)
{
throw new \Exception(print_r($e, true));
}
}
/**
* @desc gets the row count of a table
* @return mixed
*/
public function insertedRowCount()
{
$result = Postgresql::query("SELECT count(*) as sum FROM " . self::getTable()['table'] . ";");
return array_shift($result)['sum'];
}
/**
* @desc returns all columns as an array from the current table
* @return mixed|void
*/
public function getAllColumnsAsArray()
{
$result = Postgresql::query("SELECT * FROM information_schema.columns WHERE table_schema = 'public' AND table_name = '" . self::getTable()['table'] . "';");
return $result;
}
public function loadPasswordByUsername( $user_name = false )
{
//TODO: Implement the postgress query
}
/**
* @desc select a row by the selected fieldset ( field and where value )
* @param array $field
* @return mixed
*/
public function selectRowByFieldWhere( $field = array() )
{
//TODO: Implement the posgtes query
//return Pdo::fetchRowInArrayByWhere(self::$table['table'], $field['field'], $field['value']);
}
}

View File

@@ -12,6 +12,10 @@ require_once __DIR__ . '/../c/autoloader.php';
final class Dispatcher
{
const CONFIG_GENERATOR_SECTION = 'GENERATOR';
const GENERATOR_DATABASE = 'database';
const GENERATOR_DB_OVERWRITE = 'database.overwrite';
private static $_instance;
protected function __construct()
@@ -28,6 +32,10 @@ final class Dispatcher
public function run()
{
if(Config::getInstance()->getConfig()[self::CONFIG_GENERATOR_SECTION][self::GENERATOR_DATABASE])
{
new Model( false );
}
Router::getInstance();
Router::getInstance()->route();
Autoloader::getInstance()->runRequireOnce();

129
core/c/model.php Normal file
View File

@@ -0,0 +1,129 @@
<?php
/**
* Created by PhpStorm.
* User: kasdorf
* Date: 08.03.18
* Time: 11:33
*/
namespace Nibiru;
class Model extends Table
{
const PHP_FILE_ENDING = '.php';
public function __construct($argv)
{
parent::__construct($argv);
$this->createOutFolder();
$this->createClassFiles();
}
private function createOutFolder()
{
if(!is_dir($this->getFolderOut()))
{
mkdir($this->getFolderOut(), 0777, true);
chmod($this->getFolderOut(), 0777);
}
}
private function createClassFiles()
{
if($this->getTable()!="")
{
$this->generateClassByTableName( $this->getTable() );
}
else
{
$tables = array_keys($this->getTables());
foreach ($tables as $table)
{
$this->generateClassByTableName( $table );
}
}
}
private function generateClassByTableName( $table = false )
{
if($table)
{
$pclassname = explode('_', $table);
$classname = "";
for($i=0; count($pclassname)>$i; $i++)
{
if($i!=0)
{
$classname .= ucfirst($pclassname[$i]);
}
else
{
$classname = $pclassname[$i];
}
}
if(Config::getInstance()->getConfig()[self::CONFIG_SECTION][self::DB_OVERWRITE_MODELS])
{
unlink($this->getFolderOut() . '/' . $classname . self::PHP_FILE_ENDING);
}
if(!file_exists($this->getFolderOut() . '/' . $classname . self::PHP_FILE_ENDING))
{
fclose( fopen( $this->getFolderOut() . '/' . $classname . self::PHP_FILE_ENDING, 'w') );
$tablefields = $this->getTables()[$table];
$numItems = count($tablefields);
$i = 0;
$fieldarray = "";
foreach($this->getTables()[$table] as $field)
{
if( $i==0 )
{
$fieldarray .= 'array( ' . "\n";
}
if( ++$i === $numItems )
{
$fieldarray .= "\t\t\t\t\t\t\t\t'" . $field . "' => '" . $field . "'"."\n\t\t\t\t\t\t)";
}
else
{
$fieldarray .= "\t\t\t\t\t\t\t\t'" . $field . "' => '" . $field . "',\n";
}
}
$template = str_replace('[FIELDARRAY]', $fieldarray, $this->getModelTemplate());
$template = str_replace('[TABLE]', $table, $template);
$template = str_replace('[CLASSNAME]', ucfirst($classname), $template);
$template = str_replace('[FOLDERNAME]', ucfirst($this->getDatabase()), $template);
$template = str_replace('[DBSECTION]', $this->getConfigSection(), $template);
if($this->getDatabaseDriver()==self::DB_DRIVER_POSTGRESS)
{
if(Config::getInstance()->getConfig()[self::CONFIG_SECTION]['odbc'])
{
$template = str_replace('[ADAPTER]', self::ADAPTER_POSTGRES, $template);
}
else
{
$template = str_replace('[ADAPTER]', self::ADAPTER_POSTGRESQL, $template);
}
}
if($this->getDatabaseDriver()==self::DB_DRIVER_MYSQL)
{
$template = str_replace('[ADAPTER]', self::ADAPTER_MYSQL, $template);
}
if(Config::getInstance()->getConfig()[self::CONFIG_SECTION][self::DB_OVERWRITE_MODELS])
{
file_put_contents($this->getFolderOut() . '/' . $classname . self::PHP_FILE_ENDING, $template);
chmod($this->getFolderOut() . '/' . $classname . self::PHP_FILE_ENDING, 0777);
}
else
{
if(!filesize($this->getFolderOut() . '/' . $classname . self::PHP_FILE_ENDING))
{
file_put_contents($this->getFolderOut() . '/' . $classname . self::PHP_FILE_ENDING, $template);
chmod($this->getFolderOut() . '/' . $classname . self::PHP_FILE_ENDING, 0777);
}
}
}
}
}
}

200
core/c/postgresql.php Normal file
View File

@@ -0,0 +1,200 @@
<?php
namespace Nibiru;
/**
* Created by PhpStorm.
* User: kasdorf
* Date: 08.12.17
* Time: 11:52
*/
class Postgresql extends Psql implements IPostgresql
{
private static $section = false;
public static function settingsSection( $section = IOdbc::SETTINGS_DATABASE )
{
self::$section = $section;
}
private static function getSettingsSection()
{
return self::$section;
}
/**
* @desc does a plain SQL query on a postgres database, and returns the
* result as an array
* @param string $string
* @return array
*/
public static function query($string = IPsql::PLACE_NO_QUERY)
{
$all = array();
$result = \pg_query(parent::getInstance( self::getSettingsSection() )->getConn(), $string);
while($row=\pg_fetch_object($result))
{
$row_values = array();
$key_values = array();
foreach($row as $key=>$item)
{
$row_values[] = $item;
$key_values[] = $key;
}
$all[] = array_combine($key_values, $row_values);
}
return $all;
}
public static function fetchRowInArrayById($tablename = IPsql::PLACE_TABLE_NAME, $id = IPsql::NO_ID)
{
// TODO: Implement fetchRowInArrayById() method.
}
public static function fetchRowInArrayByWhere($tablename = IPsql::PLACE_TABLE_NAME,
$column_name = IPsql::PLACE_COLUMN_NAME,
$parameter_name = IPsql::PLACE_SEARCH_TERM)
{
return self::query("SELECT * FROM " . $tablename . " WHERE " . $column_name . "='" . $parameter_name . "';");
}
public static function getLastInsertedID()
{
// TODO: Implement getLastInsertedID() method.
}
public static function fetchTableFieldsAsArray($tablename = IPsql::PLACE_TABLE_NAME)
{
$columns = array();
$sqlFieldNames = "SELECT column_name FROM information_schema.columns WHERE table_schema = 'public' AND table_name = '" . $tablename . "';";
$result = \pg_query($sqlFieldNames);
$result = \pg_fetch_all_columns($result, 1);
for($i=0;$row=\pg_fetch_object($result, $i);$i++)
{
foreach ($row as $key=>$entry)
{
if(self::FILTER_COLUMN_NAME == $key)
{
$columns[] = $entry;
}
}
}
return $columns;
}
public static function fetchTableAsArray($tablename = IPsql::PLACE_TABLE_NAME)
{
return self::query("SELECT * FROM " . $tablename . ";");
}
public static function updateFieldValueByWhere( $tablename = IPsql::PLACE_TABLE_NAME,
$field_name = IPsql::PLACE_FIELD_NAME,
$field_value = IPsql::PLACE_FIELD_VALUE,
$where_name = IPsql::PLACE_WHERE_NAME,
$where_value = IPsql::PLACE_WHERE_VALUE,
$and_name = IPsql::PLACE_AND_NAME,
$and_value = IPsql::PLACE_AND_VALUE )
{
if(is_string($field_name))
{
if($and_name!=IPsql::PLACE_AND_NAME)
{
$sql_prepare = 'UPDATE ' . $tablename . ' SET ' . $field_name . '=? WHERE ' . $where_name . '=? AND ' . $and_name . '=?;';
$res = \pg_prepare(parent::getInstance( self::getSettingsSection() )->getConn(), "", $sql_prepare);
\pg_execute($res, "", array($field_value, $where_value, $and_value));
}
else
{
$sql_prepare = 'UPDATE ' . $tablename . ' SET ' . $field_name . '=? WHERE ' . $where_name .'=?;';
$res = \pg_prepare(parent::getInstance( self::getSettingsSection() )->getConn(),"", $sql_prepare);
\pg_execute($res, "", array($field_value, $where_value));
}
unset($sql_prepare);
$res = NULL;
}
}
public static function insertArrayIntoTable($tablename = IPsql::PLACE_TABLE_NAME,
$array_name = IPsql::PLACE_ARRAY_NAME,
$encrypted = IPsql::PLACE_DES_ENCRYPT)
{
if(array_key_exists(0, $array_name))
{
foreach( $array_name as $entry )
{
$field_names = array_keys( $entry );
$numItems = sizeof( $field_names );
$i = 0;
$row = " ( ";
foreach( $field_names as $field )
{
if( ++$i === $numItems )
{
$row .= $field;
}
else
{
$row .= $field . ", ";
}
}
$i = 0;
$row .= " ) VALUES ( ";
foreach ( $entry as $field )
{
if( ++$i === $numItems )
{
$row .= "'" . $field . "'";
}
else
{
$row .= "'" . $field . "', ";
}
}
$row .= " )";
$sql = 'INSERT INTO ' . $tablename . $row . ';';
\pg_exec(parent::getInstance( self::getSettingsSection() )->getConn(), $sql);
}
}
else
{
$field_names = array_keys($array_name);
$numItems = sizeof($field_names);
$i = 0;
$row = " ( ";
foreach( $field_names as $field )
{
if( ++$i === $numItems )
{
$row .= $field;
}
else
{
$row .= $field . ", ";
}
}
$row .= " ) VALUES ( ";
$i = 0;
foreach ( $array_name as $entry )
{
if( ++$i === $numItems )
{
$row .= "'" . $entry . "'";
}
else
{
$row .= "'" . $entry . "', ";
}
}
$row .= " )";
$sql = 'INSERT INTO ' . $tablename . $row . ';';
\pg_exec(parent::getInstance( self::getSettingsSection() )->getConn(), $sql);
}
}
public static function truncateTable($tablename = IPsql::PLACE_TABLE_NAME)
{
\pg_exec(parent::getInstance( self::getSettingsSection() )->getConn(), "DELETE FROM " . $tablename . ";");
}
}

140
core/c/psql.php Normal file
View File

@@ -0,0 +1,140 @@
<?php
namespace Nibiru;
/**
* Created by PhpStorm.
* User: kasdorf
* Date: 08.12.17
* Time: 11:02
*/
class Psql extends Mysql implements IPsql
{
use Messages;
protected $_readOnly = false;
private static $_instance;
protected function __construct( $section = false )
{
if( $section )
{
$settings = Config::getInstance()->getConfig()[$section];
}
else
{
$section = Config::getInstance()->getConfig()[self::SETTINGS_DATABASE];
}
$this->_setUsername($settings[self::PLACE_USERNAME]);
$this->_setPassword($settings[self::PLACE_PASSWORD]);
$this->_setDbname($settings[self::PLACE_DATABASE]);
$this->_setDiver($settings[self::PLACE_DRIVER]);
$this->_setHostname($settings[self::PLACE_HOSTNAME]);
$this->_setPort($settings[self::PLACE_PORT]);
$this->_setReadOnly($settings[self::PLACE_READONLY]);
$this->_setEncoding($settings[self::PLACE_ENCODING]);
$this->_setMultithreading($settings[self::PLACE_MULTI_THREADING]);
$this->_setDsn();
$this->_setConn();
}
public static function getInstance( $section = false )
{
$className = get_called_class();
if(self::$_instance==null) self::$_instance = new $className( $section );
return self::$_instance;
}
/**
* @param string $multithreading
*/
private function _setMultithreading( $multithreading )
{
$this->_multithreading = $multithreading;
}
/**
* @param string $dsn
*/
private function _setDsn( )
{
$this->_dsn = 'host=' . $this->getHostname() . ' port=' . $this->getPort() . ' dbname=' . $this->getDbname() . ' user=' . $this->getUsername() . ' password=' . $this->getPassword();
}
/**
* @param string $username
*/
private function _setUsername( $username )
{
$this->_username = $username;
}
/**
* @param string $password
*/
private function _setPassword( $password )
{
$this->_password = $password;
}
/**
* @param mixed $diver
*/
private function _setDiver( $diver )
{
$this->_diver = $diver;
}
/**
* @param string $hostname
*/
private function _setHostname( $hostname )
{
$this->_hostname = $hostname;
}
/**
* @param string $dbname
*/
private function _setDbname( $dbname )
{
$this->_dbname = $dbname;
}
/**
* @param string $conn
*/
private function _setConn( )
{
$this->_conn = \pg_connect( $this->getDsn() );
}
/**
* @param string $port
*/
private function _setPort( $port )
{
$this->_port = $port;
}
/**
* @param boolean $readOnly
*/
protected function _setReadOnly( $readOnly )
{
$this->_readOnly = $readOnly;
}
/**
* @param string $encoding
*/
private function _setEncoding( $encoding )
{
$this->_encoding = $encoding;
}
}

399
core/c/table.php Normal file
View File

@@ -0,0 +1,399 @@
<?php
namespace Nibiru;
/**
* Created by PhpStorm.
* User: kasdorf
* Date: 17.01.18
* Time: 15:52
*/
class Table
{
const CONFIG_SECTION = "GENERATOR";
const DB_CONFIG_SECTION = "DATABASE";
const DB_CONFIG_TEMPLATE = "modeltemplate";
const DB_CONFIG_BASENAME = "basename";
const DB_CONFIG_DRIVER = "driver";
const DB_CONFIG_SECTION_MODEL = "folder-out";
const DB_CONFIG_SECTION_DB = "config-section";
const DB_DRIVER_POSTGRESS = "psql";
const DB_DRIVER_MYSQL = "mysql";
const DB_OVERWRITE_MODELS = "database.overwrite";
const ADAPTER_POSTGRES = "Postgres";
const ADAPTER_POSTGRESQL = "Postgresql";
const ADAPTER_MYSQL = "MySQL";
const PARAMETERS = array(
'--table',
'--help',
'--folder-out',
'--config-section'
);
private $_table = "";
private $_database = "";
private $_folder_out = "";
private $_tables = array();
private $_fields = array();
private $_db_namespace = "";
private $_params = array();
private $_template_file = "";
private $_model_template = "";
private $_config_section = "";
private $_database_driver = "";
public function __construct( $argv )
{
//get parameters
if(is_array($argv))
{
foreach ($argv as $entry)
{
$this->_setParams($entry);
}
}
$this->displayHelp();
$this->_setConfigSection();
$this->_setDatabaseDriver();
$this->_setDatabase();
$this->_setDbNamespace();
$this->_setFolderOut();
$this->_setTable();
$this->_setTemplateFile( Config::getInstance()->getConfig()[self::CONFIG_SECTION][self::DB_CONFIG_TEMPLATE] );
$this->_setModelTemplate();
$this->_setTables();
}
protected function displayHelp()
{
if(array_key_exists('help', $this->getParams()))
{
echo "--------------------------------------------------------------------\n";
echo "\e[48;5;0mAutogenerator for the database model classes in order to gain access\n";
echo "\e[48;5;0mto the database. The following parameters are required: \n";
echo "\e[16;5;0m--------------------------------------------------------------------\n";
echo "\n";
echo "--table=TABLENAME\n";
echo "( will generate only that table and overwrite the Model file )\n";
echo "\n";
echo "--help\n";
echo "( will display this help, and not execute any further )\n";
echo "\n";
echo "--folder-out=PATH-TO-MODEL-FOLDER\n";
echo "( will output the files into that folder )\n";
echo "\n";
echo "--config-section=CONFIGSECTION\n";
echo "( is attached to the settings.env.ini file and\n";
echo "reads that configuration to connect to the database )\n\n";
echo "--------------------------------------------------------------------\n";
echo "\e[48;5;0m \n";
echo "\e[16;5;0m--------------------------------------------------------------------\n";
die();
}
}
/**
* @return string
*/
protected function getDatabaseDriver(): string
{
return $this->_database_driver;
}
/**
* @param string $database_driver
*/
private function _setDatabaseDriver(): void
{
$this->_database_driver = Config::getInstance()->getConfig()[$this->getConfigSection()][self::DB_CONFIG_DRIVER];
}
/**
* @return string
*/
protected function getConfigSection()
{
return $this->_config_section;
}
/**
* @param string $config_section
*/
private function _setConfigSection( )
{
if(array_key_exists('config-section', $this->getParams()))
{
$this->_config_section = $this->getParams()['config-section'];
}
else
{
if(Config::getInstance()->getConfig()[self::CONFIG_SECTION][self::DB_CONFIG_SECTION_DB])
{
$this->_config_section = Config::getInstance()->getConfig()[self::CONFIG_SECTION][self::DB_CONFIG_SECTION_DB];
}
else
{
$this->_config_section = self::DB_CONFIG_SECTION;
}
}
}
/**
* @return string
*/
protected function getDatabase()
{
return $this->_database;
}
/**
* @param string $database
*/
private function _setDatabase( )
{
$this->_database = Config::getInstance()->getConfig()[$this->getConfigSection()][self::DB_CONFIG_BASENAME];
}
/**
* @return string
*/
protected function getFolderOut()
{
return $this->_folder_out;
}
/**
* @param string $folder_out
*/
private function _setFolderOut( )
{
if(array_key_exists(self::DB_CONFIG_SECTION, $this->getParams()))
{
$this->_folder_out = $this->getParams()[self::DB_CONFIG_SECTION_MODEL] . $this->getDatabase();
}
else
{
$this->_folder_out = __DIR__ . Config::getInstance()->getConfig()[self::CONFIG_SECTION][self::DB_CONFIG_SECTION_MODEL] . $this->getDatabase();
}
}
/**
* @return array
*/
protected function getTables()
{
return $this->_tables;
}
/**
* @param array $tables
*/
private function _setTables( )
{
if($this->getDatabaseDriver()==self::DB_DRIVER_POSTGRESS)
{
if(Config::getInstance()->getConfig()[self::CONFIG_SECTION]['odbc'])
{
Postgres::settingsSection( $this->getConfigSection() );
$result = Postgres::query(
'SELECT table_name
FROM information_schema.tables
WHERE table_schema=\'public\'
AND table_type=\'BASE TABLE\';'
);
foreach ($result as $entry)
{
$this->_setFields($entry["table_name"]);
$this->_tables[$entry["table_name"]] = $this->getFields();
}
}
else
{
Postgresql::settingsSection( $this->getConfigSection() );
$result = Postgresql::query(
'SELECT table_name
FROM information_schema.tables
WHERE table_schema=\'public\'
AND table_type=\'BASE TABLE\';'
);
foreach ($result as $entry)
{
$this->_setFields($entry["table_name"]);
$this->_tables[$entry["table_name"]] = $this->getFields();
}
}
}
if($this->getDatabaseDriver()==self::DB_DRIVER_MYSQL)
{
//TODO: Implement the Table array for MySQL
}
}
/**
* @return string
*/
protected function getDbNamespace()
{
return $this->_db_namespace;
}
/**
* @param string $db_namespace
*/
private function _setDbNamespace( )
{
$this->_db_namespace = ucfirst($this->getDatabase());
}
/**
* @return string
*/
protected function getModelTemplate()
{
return $this->_model_template;
}
/**
* @param string $model_template
*/
private function _setModelTemplate( )
{
try
{
if(file_exists($this->getTemplateFile()))
{
$this->_model_template = file_get_contents($this->getTemplateFile());
}
else
{
throw new \Exception('ERROR: no Template file found, please provide one like in the example!');
}
} catch (\Exception $e)
{
echo "\n" . $e->getMessage() . "\n";
}
}
/**
* @return string
*/
public function getTable()
{
return $this->_table;
}
/**
* @param string $table
*/
private function _setTable( )
{
if(array_key_exists('table', $this->getParams()))
{
$this->_table = $this->getParams()['table'];
}
}
/**
* @return array
*/
protected function getFields()
{
return $this->_fields;
}
/**
* @param array $fields
*/
private function _setFields( $table )
{
$this->_fields = array();
if($this->getDatabaseDriver()==self::DB_DRIVER_POSTGRESS)
{
if(Config::getInstance()->getConfig()[self::CONFIG_SECTION]['odbc'])
{
Postgres::settingsSection( $this->getConfigSection() );
$result = Postgres::query(
'SELECT *
FROM information_schema.columns
WHERE table_schema = \'public\'
AND table_name = \'' . $table . '\''
);
foreach( $result as $field )
{
$this->_fields[] = $field['column_name'];
}
}
else
{
Postgresql::settingsSection( $this->getConfigSection() );
$result = Postgresql::query(
'SELECT *
FROM information_schema.columns
WHERE table_schema = \'public\'
AND table_name = \'' . $table . '\''
);
foreach( $result as $field )
{
$this->_fields[] = $field['column_name'];
}
}
}
if($this->getDatabaseDriver()==self::DB_DRIVER_MYSQL)
{
//TODO: Implement the Table array for MySQL
}
}
/**
* @return array
*/
protected function getParams()
{
return $this->_params;
}
/**
* @param array $params
*/
private function _setParams( $param )
{
$keyvalue = explode('--', $param);
if(array_key_exists(1, $keyvalue))
{
$keyvalue = explode("=", $keyvalue[1]);
if(array_key_exists(1, $keyvalue))
{
$this->_params[$keyvalue[0]] = $keyvalue[1];
}
else
{
$this->_params[$keyvalue[0]] = false;
}
}
}
/**
* @return string
*/
protected function getTemplateFile()
{
return $this->_template_file;
}
/**
* @param string $template_file
*/
private function _setTemplateFile( $template_file )
{
if(file_exists(__DIR__ . "/" . $template_file))
{
$this->_template_file = __DIR__ . "/" . $template_file;
}
}
}

View File

@@ -28,16 +28,26 @@ require_once __DIR__ . '/i/mysql.php';
require_once __DIR__ . '/c/mysql.php';
require_once __DIR__ . '/i/pdo.php';
require_once __DIR__ . '/c/pdo.php';
/**
* @desc Database ODBC support
*/
require_once __DIR__ . '/i/odbc.php';
require_once __DIR__ . '/c/odbc.php';
require_once __DIR__ . '/i/postgres.php';
require_once __DIR__ . '/c/postgres.php';
require_once __DIR__ . '/i/psql.php';
require_once __DIR__ . '/c/psql.php';
require_once __DIR__ . '/i/postgresql.php';
require_once __DIR__ . '/c/postgresql.php';
require_once __DIR__ . '/i/db.php';
require_once __DIR__ . '/i/pageination.php';
require_once __DIR__ . '/a/mysql.db.php';
require_once __DIR__ . '/a/postgres.db.php';
require_once __DIR__ . '/a/postgresql.db.php';
require_once __DIR__ . '/f/db.php';
require_once __DIR__ . '/a/pageination.php';
require_once __DIR__ . '/c/table.php';
require_once __DIR__ . '/c/model.php';
/**
* @desc MVC functionality
*/

View File

@@ -10,26 +10,28 @@ namespace Nibiru;
*/
interface IMysql
{
const SETTINGS_DATABASE = "DATABASE";
const SETTINGS_DATABASE = "DATABASE";
const PLACE_NO_QUERY = "NO QUERY";
const NO_ID = false;
const PLACE_TABLE_NAME = "NO TABLENAME";
const PLACE_QUERY_LIMIT = "NO LIMIT";
const PLACE_SORT_ORDER = "NO ORDER";
const PLACE_DSN = "NO CONNECTION STRING";
const PLACE_USERNAME = "username";
const PLACE_PASSWORD = "password";
const PLACE_HOSTNAME = "hostname";
const PLACE_DRIVER = "driver";
const PLACE_DATABASE = "basename";
const PLACE_PORT = "port";
const PLACE_CONNECTION = "NO CONNECTION";
const PLACE_PRIMARY_KEY = "PRI";
const PLACE_COLUMN_NAME = "NO COLUMN NAME";
const PLACE_SEARCH_TERM = "NO SEARCH PARAMETER";
const PLACE_FIELD_NAME = "NO FIELD NAME";
const PLACE_WHERE_VALUE = "NO WHERE VALUE";
const PLACE_DES_ENCRYPT = false;
const PLACE_NO_QUERY = "NO QUERY";
const NO_ID = false;
const PLACE_TABLE_NAME = "NO TABLENAME";
const PLACE_QUERY_LIMIT = "NO LIMIT";
const PLACE_SORT_ORDER = "NO ORDER";
const PLACE_DSN = "NO CONNECTION STRING";
const PLACE_USERNAME = "username";
const PLACE_PASSWORD = "password";
const PLACE_HOSTNAME = "hostname";
const PLACE_DRIVER = "driver";
const PLACE_DATABASE = "basename";
const PLACE_PORT = "port";
const PLACE_MULTI_THREADING = "multithreading";
const PLACE_CONNECTION = "NO CONNECTION";
const PLACE_PRIMARY_KEY = "PRI";
const PLACE_COLUMN_NAME = "NO COLUMN NAME";
const PLACE_SEARCH_TERM = "NO SEARCH PARAMETER";
const PLACE_FIELD_NAME = "NO FIELD NAME";
const PLACE_WHERE_VALUE = "NO WHERE VALUE";
const PLACE_DES_ENCRYPT = false;
const PLACE_ENCODING = "encoding";
}

102
core/i/postgresql.php Normal file
View File

@@ -0,0 +1,102 @@
<?php
namespace Nibiru;
/**
* Created by PhpStorm.
* User: kasdorf
* Date: 08.12.17
* Time: 11:56
*/
interface IPostgresql
{
/**
* @desc set the configuration section for the database to operate on
* @param string $section
* @return false
*/
public static function settingsSection( $section = IOdbc::SETTINGS_DATABASE );
/**
* @desc returns the query by ressult
* @param string $string
*
* @return array()
*/
public static function query( $string = IPsql::PLACE_NO_QUERY );
/**
* @desc returns the row by id
* @param bool $id
*
* @return array()
*/
public static function fetchRowInArrayById( $tablename = IPsql::PLACE_TABLE_NAME, $id = IPsql::NO_ID );
/**
* @desc returns row by column name and search parameter
* @param string $tablename
* @param string $column_name
* @param IMysql $
* @return mixed
*/
public static function fetchRowInArrayByWhere( $tablename = IPsql::PLACE_TABLE_NAME,
$column_name = IPsql::PLACE_COLUMN_NAME,
$parameter_name = IPsql::PLACE_SEARCH_TERM );
/**
* @desc will return the last inserted ID
* @return integer
*/
public static function getLastInsertedID();
/**
* @desc fetch all fieldnames of the parameter tablename to an array
* @param string $tablename
* @return mixed
*/
public static function fetchTableFieldsAsArray( $tablename = IPsql::PLACE_TABLE_NAME );
/**
* @desc will return all entries from the selected tablename
*
* @param string $tablename
*
* @return mixed
*/
public static function fetchTableAsArray( $tablename = IPsql::PLACE_TABLE_NAME );
/**
* @desc update field data by tablename and fieldname, filter by WHERE and AND
* @param string $tablename
* @param string $field_name
* @param string $field_value
* @param string $where_name
* @param string $where_value
* @param string $and_name
* @param string $and_value
* @return mixed
*/
public static function updateFieldValueByWhere( $tablename = IPsql::PLACE_TABLE_NAME,
$field_name = IPsql::PLACE_FIELD_NAME,
$field_value = IPsql::PLACE_FIELD_VALUE,
$where_name = IPsql::PLACE_WHERE_NAME,
$where_value = IPsql::PLACE_WHERE_VALUE,
$and_name = IPsql::PLACE_AND_NAME,
$and_value = IPsql::PLACE_AND_VALUE );
/**
* @desc insert array content into database
* @param string $tablename
* @param string $array_name
* @return mixed
*/
public static function insertArrayIntoTable( $tablename = IPsql::PLACE_TABLE_NAME, $array_name = IPsql::PLACE_ARRAY_NAME, $encrypted = IPsql::PLACE_DES_ENCRYPT );
/**
* @desc truncate a table to zero entries
* @param string $tablename
* @return mixed
*/
public static function truncateTable( $tablename = IPsql::PLACE_TABLE_NAME );
}

14
core/i/psql.php Normal file
View File

@@ -0,0 +1,14 @@
<?php
namespace Nibiru;
/**
* Created by PhpStorm.
* User: kasdorf
* Date: 08.12.17
* Time: 11:05
*/
interface IPsql extends IMysql
{
const PLACE_READONLY = "readonly";
const FILTER_COLUMN_NAME = "COLUMN_NAME";
}