Skip to content

Commit

Permalink
Merge pull request #237 from bowphp/5.x-refactoring-for-perf
Browse files Browse the repository at this point in the history
[5.x] Parse data on validation custom message and Add performance for PGSQL
  • Loading branch information
papac authored May 22, 2023
2 parents 0b55ba3 + 0ac3e09 commit 8f03bd1
Show file tree
Hide file tree
Showing 14 changed files with 275 additions and 120 deletions.
173 changes: 125 additions & 48 deletions src/Database/Barry/Model.php
Original file line number Diff line number Diff line change
Expand Up @@ -306,8 +306,11 @@ public static function create(array $data): Model
}

// Check if the primary key existe on updating data
if (!array_key_exists($model->primary_key, $data)) {
if ($model->auto_increment && static::$builder->getAdapterName() !== "pgsql") {
if (
!array_key_exists($model->primary_key, $data)
&& static::$builder->getAdapterName() !== "pgsql"
) {
if ($model->auto_increment) {
$id_value = [$model->primary_key => null];
$data = array_merge($id_value, $data);
} elseif ($model->primary_key_type == 'string') {
Expand All @@ -319,11 +322,7 @@ public static function create(array $data): Model

// Override the olds model attributes
$model->setAttributes($data);

if ($model->save() == 1) {
// Throw the onCreated event
$model->fireEvent('onCreated');
}
$model->save();

return $model;
}
Expand All @@ -349,7 +348,33 @@ public static function paginate(int $page_number, int $current = 0, ?int $chunk
*/
public static function deleted(callable $cb): void
{
$env = static::formatEventName('onDeleted');
$env = static::formatEventName('model.deleted');

event()->once($env, $cb);
}

/**
* Allows to associate listener
*
* @param callable $cb
* @throws
*/
public static function deleting(callable $cb): void
{
$env = static::formatEventName('model.deleted');

event()->once($env, $cb);
}

/**
* Allows to associate a listener
*
* @param callable $cb
* @throws
*/
public static function creating(callable $cb): void
{
$env = static::formatEventName('model.creating');

event()->once($env, $cb);
}
Expand All @@ -362,7 +387,20 @@ public static function deleted(callable $cb): void
*/
public static function created(callable $cb): void
{
$env = static::formatEventName('onCreated');
$env = static::formatEventName('model.created');

event()->once($env, $cb);
}

/**
* Allows to associate a listener
*
* @param callable $cb
* @throws
*/
public static function updating(callable $cb): void
{
$env = static::formatEventName('model.updating');

event()->once($env, $cb);
}
Expand All @@ -375,7 +413,7 @@ public static function created(callable $cb): void
*/
public static function updated(callable $cb): void
{
$env = static::formatEventName('onUpdated');
$env = static::formatEventName('model.updated');

event()->once($env, $cb);
}
Expand Down Expand Up @@ -432,50 +470,70 @@ public static function query(): Builder
}

/**
* Save aliases on insert action
* Create the new row
*
* @param Builder $model
* @return int
* @throws
*/
public function save()
private function writeRows(Builder $builder)
{
$model = static::query();
// Fire the creating event
$this->fireEvent('model.creating');

/**
* Get the current primary key value
*/
$primary_key_value = $this->getKeyValue();

// If primary key value is null, we are going to start the creation of new row
if ($primary_key_value == null) {
// Insert information in the database
$row_affected = $model->insert($this->attributes);
// Insert information in the database
$row_affected = $builder->insert($this->attributes);

// We get a last insertion id value
if (static::$builder->getAdapterName() == 'pgsql') {
// We get a last insertion id value
if (static::$builder->getAdapterName() == 'pgsql') {
if ($this->auto_increment) {
$sequence = $this->table . "_" . $this->primary_key . '_seq';
$primary_key_value = static::$builder->getPdo()->lastInsertId($sequence);
} else {
$primary_key_value = static::$builder->getPdo()->lastInsertId();
}
} else {
$primary_key_value = static::$builder->getPdo()->lastInsertId();
}

$primary_key_value = !is_numeric($primary_key_value) ? $primary_key_value : (int) $primary_key_value;
if (is_null($primary_key_value)) {
$primary_key_value = $this->attributes[$this->primary_key] ?? null;
}

// Set the primary key value
$this->attributes[$this->primary_key] = $primary_key_value;
$this->original = $this->attributes;
$primary_key_value = !is_numeric($primary_key_value) ? $primary_key_value : (int) $primary_key_value;

if ($row_affected == 1) {
$this->fireEvent('onCreated');
}
// Set the primary key value
$this->attributes[$this->primary_key] = $primary_key_value;
$this->original = $this->attributes;

return $row_affected;
if ($row_affected == 1) {
$this->fireEvent('model.created');
}

return $row_affected;
}

/**
* Save aliases on insert action
*
* @return int
* @throws
*/
public function save()
{
$builder = static::query();

// Get the current primary key value
$primary_key_value = $this->getKeyValue();

// If primary key value is null, we are going to start the creation of new row
if (is_null($primary_key_value)) {
return $this->writeRows($builder);
}

$primary_key_value = $this->transtypeKeyValue($primary_key_value);

// Check the existent in database
if (!$model->exists($this->primary_key, $primary_key_value)) {
if (!$builder->exists($this->primary_key, $primary_key_value)) {
return 0;
}

Expand All @@ -495,11 +553,15 @@ public function save()
$update_data = $this->original;
}

$updated = $model->where($this->primary_key, $primary_key_value)->update($update_data);
// Fire the updating event
$this->fireEvent('model.updating');

// Execute update model
$updated = $builder->where($this->primary_key, $primary_key_value)->update($update_data);

// Fire the updated event if there are affected row
if ($updated) {
$this->fireEvent('onUpdated');
$this->fireEvent('model.updated');
}

return $updated;
Expand All @@ -515,16 +577,14 @@ private function transtypeKeyValue(mixed $primary_key_value): mixed
{
// Transtype value to the define primary key type
if ($this->primary_key_type == 'int') {
$primary_key_value = (int) $primary_key_value;
} elseif ($this->primary_key_type == 'float') {
$primary_key_value = (float) $primary_key_value;
} elseif ($this->primary_key_type == 'double') {
$primary_key_value = (float) $primary_key_value;
} else {
$primary_key_value = (string) $primary_key_value;
return (int) $primary_key_value;
}

return $primary_key_value;
if ($this->primary_key_type == 'float' || $this->primary_key_type == 'double') {
return (float) $primary_key_value;
}

return (string) $primary_key_value;
}

/**
Expand All @@ -538,8 +598,9 @@ public function update(array $attributes): int
{
$primary_key_value = $this->getKeyValue();

// return 0 if the primary key is not define for update
if ($primary_key_value == null) {
return 0;
return false;
}

$model = static::query();
Expand All @@ -558,9 +619,12 @@ public function update(array $attributes): int
}
}

// Fire the updating event
$this->fireEvent('model.updating');

// When the data for updating list is empty, we load the original data
if (count($data_for_updating) == 0) {
$this->fireEvent('onUpdated');
$this->fireEvent('model.updated');
return true;
}

Expand All @@ -569,7 +633,7 @@ public function update(array $attributes): int

// Fire the updated event if there are affected row
if ($updated) {
$this->fireEvent('onUpdated');
$this->fireEvent('model.updated');
}

return $updated;
Expand All @@ -595,12 +659,15 @@ public function delete(): int
return 0;
}

// Fire the deleting event
$this->fireEvent('model.deleting');

// We apply the delete action
$deleted = $model->where($this->primary_key, $primary_key_value)->delete();

// Fire the deleted event if there are affected row
if ($deleted) {
$this->fireEvent('onDeleted');
$this->fireEvent('model.deleted');
}

return $deleted;
Expand Down Expand Up @@ -642,6 +709,16 @@ public function getKey(): string
return $this->primary_key;
}

/**
* Retrieves the primary key key
*
* @return string
*/
public function getKeyType(): string
{
return $this->primary_key_type;
}

/**
* Used to update the timestamp.
*
Expand Down
6 changes: 4 additions & 2 deletions src/Database/Barry/Traits/EventTrait.php
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,9 @@ trait EventTrait
*/
private static function formatEventName(string $event): string
{
return str_replace('\\', '', strtolower(Str::snake(static::class))) . '.' . Str::snake($event);
$class_name = str_replace('\\', '', strtolower(Str::snake(static::class)));

return sprintf("%s.%s", $class_name, strtolower($event));
}

/**
Expand All @@ -26,7 +28,7 @@ private static function formatEventName(string $event): string
*/
private function fireEvent(string $event): void
{
$env = $this->formatEventName($event);
$env = static::formatEventName($event);

if (event()->bound($env)) {
event()->emit($env, $this);
Expand Down
28 changes: 28 additions & 0 deletions src/Database/Connection/Adapter/PostgreSQLAdapter.php
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,30 @@ public function connection(): void
// Formatting connection parameters
$dsn = sprintf("pgsql:host=%s;port=%s;dbname=%s", $hostname, $port, $this->config['database']);

if (isset($this->config['sslmode'])) {
$dsn .= ';sslmode=' . $this->config['sslmode'];
}

if (isset($this->config['sslrootcert'])) {
$dsn .= ';sslrootcert=' . $this->config['sslrootcert'];
}

if (isset($this->config['sslcert'])) {
$dsn .= ';sslcert=' . $this->config['sslcert'];
}

if (isset($this->config['sslkey'])) {
$dsn .= ';sslkey=' . $this->config['sslkey'];
}

if (isset($this->config['sslcrl'])) {
$dsn .= ';sslcrl=' . $this->config['sslcrl'];
}

if (isset($this->config['application_name'])) {
$dsn .= ';application_name=' . $this->config['application_name'];
}

$username = $this->config["username"];
$password = $this->config["password"];

Expand All @@ -71,5 +95,9 @@ public function connection(): void

// Build the PDO connection
$this->pdo = new PDO($dsn, $username, $password, $options);

if ($this->config["charset"]) {
$this->pdo->query('SET NAMES \'' . $this->config["charset"] . '\'');
}
}
}
11 changes: 8 additions & 3 deletions src/Database/Migration/Compose/PgsqlCompose.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,14 +6,19 @@

trait PgsqlCompose
{
/**
* Define the query for create the custom type
*
* @var array
*/
protected array $custom_types = [];

/**
* Generate the custom type for pgsql
* Get the custom type for pgsql
*
* @return array
*/
public function generateCustomTypes(): array
public function getCustomTypeQueries(): array
{
return $this->custom_types;
}
Expand Down Expand Up @@ -94,7 +99,7 @@ private function composeAddPgsqlColumn(string $name, array $description): string

// Bind auto increment action
if ($increment) {
$type = 'SERIAL';
$type = in_array($raw_type, ["INT", "TINYINT", "SMALLINT"]) ? "SERIAL" : "BIGSERIAL";
}

// Set column as primary key
Expand Down
2 changes: 1 addition & 1 deletion src/Database/Migration/Migration.php
Original file line number Diff line number Diff line change
Expand Up @@ -119,7 +119,7 @@ final public function create(string $table, callable $cb): Migration
return $this->executeSqlQuery($sql);
}

foreach ($generator->generateCustomTypes() as $sql) {
foreach ($generator->getCustomTypeQueries() as $sql) {
try {
$this->executeSqlQuery($sql);
} catch (\Exception $exception) {
Expand Down
Loading

0 comments on commit 8f03bd1

Please sign in to comment.