Skip to content

Commit

Permalink
[release] - database function declaration & minor fixes
Browse files Browse the repository at this point in the history
  • Loading branch information
iloElias committed Sep 29, 2024
1 parent 64e3f26 commit 35d721e
Show file tree
Hide file tree
Showing 12 changed files with 54 additions and 64 deletions.
6 changes: 0 additions & 6 deletions .env

This file was deleted.

4 changes: 2 additions & 2 deletions composer.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"name": "ilias/maestro",
"type": "library",
"version": "1.1.1",
"version": "1.2.2",
"description": "A PHP object-oriented postgres database manager",
"keywords": [
"postgres",
Expand Down Expand Up @@ -35,7 +35,7 @@
}
],
"require": {
"ilias/dotenv": "1.0.0"
"ilias/dotenv": "^1.0"
},
"require-dev": {
"phpunit/phpunit": "^11.2"
Expand Down
10 changes: 0 additions & 10 deletions example/Hr.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,19 +2,9 @@

namespace Maestro\Example;
use Ilias\Maestro\Abstract\Schema;
use Ilias\Maestro\Types\Postgres;

final class Hr extends Schema
{
public User $user;
public AuthCode $authCode;

public function __construct()
{
self::declareFunction(
'generate_four_digit_auth_code',
Postgres::TEXT,
'CREATE OR REPLACE FUNCTION generate_four_digit_auth_code() RETURNS TEXT AS $$ BEGIN RETURN CAST(FLOOR(1000 + RANDOM() * 9000) AS TEXT); END; $$ LANGUAGE plpgsql;'
);
}
}
12 changes: 11 additions & 1 deletion example/MaestroDb.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,19 @@
namespace Maestro\Example;

use Ilias\Maestro\Abstract\Database;
use Ilias\Maestro\Types\Postgres;

final class MaestroDb extends Database
{
public Hr $hr;
// public Social $social;
public Social $social;

public function __construct()
{
self::declareFunction(
'generate_four_digit_auth_code',
Postgres::TEXT,
'CREATE OR REPLACE FUNCTION generate_four_digit_auth_code() RETURNS TEXT AS $$ BEGIN RETURN CAST(FLOOR(1000 + RANDOM() * 9000) AS TEXT); END; $$ LANGUAGE plpgsql;'
);
}
}
2 changes: 2 additions & 0 deletions example/Post.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,12 @@
namespace Maestro\Example;

use Ilias\Maestro\Abstract\Table;
use Ilias\Maestro\Types\Serial;

final class Post extends Table
{
public Social $schema;
public Serial $id;
public User $userId;
public string $postContent;
}
2 changes: 2 additions & 0 deletions example/TaggedUser.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,12 @@
namespace Maestro\Example;

use Ilias\Maestro\Abstract\Table;
use Ilias\Maestro\Types\Serial;

final class TaggedUser extends Table
{
public Social $schema;
public Serial $id;
public Post $postId;
public User $userId;
}
1 change: 1 addition & 0 deletions test.php → maestro.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

use Ilias\Maestro\Core\Manager;
use Ilias\Maestro\Types\Timestamp;
use Ilias\Maestro\Utils\Utils;
use Maestro\Example\MaestroDb;
use Maestro\Example\User;

Expand Down
21 changes: 18 additions & 3 deletions src/Abstract/Database.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,14 @@

namespace Ilias\Maestro\Abstract;

use Ilias\Maestro\Database\DatabaseFunction;

abstract class Database extends \stdClass
{
use Sanitizable;

private static array $functions = [];

public static function getDatabaseName(): string
{
return static::class;
Expand All @@ -24,19 +29,29 @@ public static function getSchemas(): array
return $schemas;
}

public static function declareFunction(string $name, string $returnType, string $sqlDefinition)
{
self::$functions[$name] = new DatabaseFunction($name, $returnType, $sqlDefinition);
}

public static function getFunctions(): array
{
return self::$functions;
}

public static function dumpDatabase()
{
$databaseMap = [];
$schemas = self::getSchemas();
foreach ($schemas as $schema) {
$databaseMap[$schema::tableSanitizedName()] = $schema::dumpSchema();
$databaseMap[$schema::sanitizedName()] = $schema::dumpSchema();
}
return [self::tableSanitizedName() => $databaseMap];
return [self::sanitizedName() => $databaseMap];
}

public static function prettyPrint()
{
$databaseName = self::tableSanitizedName();
$databaseName = self::sanitizedName();
echo "Database: $databaseName (Class: " . self::getDatabaseName() . ")\n";

$schemas = self::getSchemas();
Expand Down
2 changes: 1 addition & 1 deletion src/Abstract/Sanitizable.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@

trait Sanitizable
{
public static function tableSanitizedName(): string
public static function sanitizedName(): string
{
$spreadClassName = explode("\\", static::class);
return Utils::sanitizeForPostgres($spreadClassName[count($spreadClassName) - 1]);
Expand Down
18 changes: 1 addition & 17 deletions src/Abstract/Schema.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,17 +2,11 @@

namespace Ilias\Maestro\Abstract;

use Ilias\Maestro\Database\DatabaseFunction;
use Ilias\Maestro\Utils\Utils;

abstract class Schema extends \stdClass
{
use Sanitizable;
private static array $functions = [];
public static function getSchemaName(): string
{
return static::class;
}

public static function getTables(): array
{
Expand All @@ -29,22 +23,12 @@ public static function getTables(): array
return $tables;
}

public static function declareFunction(string $name, string $returnType, string $sqlDefinition)
{
self::$functions[$name] = new DatabaseFunction($name, $returnType, $sqlDefinition);
}

public static function getFunctions(): array
{
return self::$functions;
}

public static function dumpSchema(): array
{
$tablesMap = [];
$tables = self::getTables();
foreach ($tables as $table) {
$tablesMap[$table::tableSanitizedName()] = $table::dumpTable();
$tablesMap[$table::sanitizedName()] = $table::dumpTable();
}
return $tablesMap;
}
Expand Down
15 changes: 4 additions & 11 deletions src/Abstract/Table.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ abstract class Table extends \stdClass

public static function tableName(): string
{
return self::tableSanitizedName();
return self::sanitizedName();
}

public function __toString()
Expand All @@ -26,7 +26,7 @@ public static function getTableSchemaAddress(): string
$reflection = new \ReflectionClass(static::class);
$schemaNamespace = explode('\\', $reflection->getProperty("schema")->getType()->getName());
$tableSchema = Utils::sanitizeForPostgres($schemaNamespace[array_key_last($schemaNamespace)]);
$tableName = self::tableSanitizedName();
$tableName = self::sanitizedName();
return "\"{$tableSchema}\".\"{$tableName}\"";
}

Expand All @@ -35,7 +35,7 @@ final public static function tableFullAddress(): string
$reflection = new \ReflectionClass(static::class);
$schemaNamespace = explode('\\', $reflection->getProperty("schema")->getType()->getName());
$tableSchema = Utils::sanitizeForPostgres($schemaNamespace[array_key_last($schemaNamespace)]);
$tableName = self::tableSanitizedName();
$tableName = self::sanitizedName();
return "\"{$tableSchema}\".\"{$tableName}\"";
}

Expand Down Expand Up @@ -99,18 +99,11 @@ final public static function tableIdentifier(): array
public static function tableCreationInfo(): array
{
return [
'tableName' => static::tableSanitizedName(),
'tableName' => static::sanitizedName(),
'columns' => static::tableColumns()
];
}

public static function tableSanitizedName(): string
{
$reflect = new \ReflectionClass(static::class);
return strtolower($reflect->getShortName());
}


public static function dumpTable(): array
{
return self::tableColumns();
Expand Down
25 changes: 12 additions & 13 deletions src/Core/Manager.php
Original file line number Diff line number Diff line change
Expand Up @@ -49,15 +49,14 @@ public function createDatabase(Database $database, bool $executeOnComplete = tru
$schemasSql = [];
$tablesSql = [];
$constraintsSql = [];
$functionsSql = [];
$functionsSql = $this->createDatabaseFunctions($database);
$schemas = $database::getSchemas();

foreach ($schemas as $schemaClass) {
$schemasSql[] = $this->createSchema($schemaClass);
[$create, $constraints] = $this->createSchemaTables($schemaClass);
$tablesSql = array_merge($tablesSql, $create);
$constraintsSql = array_merge($constraintsSql, ...$constraints);
$functionsSql = array_merge($functionsSql, $this->createSchemaFunctions($schemaClass));
}

$sql = array_merge($schemasSql, $tablesSql, $constraintsSql, $functionsSql);
Expand All @@ -84,12 +83,12 @@ public function createSchema(string|Schema $schema): string
throw new NotFinalExceptions("The " . Utils::sanitizeForPostgres($schema) . " class was not identified as \"final\".");
}
try {
$schemaName = call_user_func("{$schema}::tableSanitizedName");
$schemaName = call_user_func("{$schema}::sanitizedName");
return $this->strictType === Maestro::SQL_STRICT
? "CREATE SCHEMA IF NOT EXISTS \"{$schemaName}\";"
: "CREATE SCHEMA \"{$schemaName}\";";
} catch (Throwable) {
throw new InvalidArgumentException('The tableSanitizedName method was not implemented in the provided schema class.');
throw new InvalidArgumentException('The sanitizedName method was not implemented in the provided schema class.');
}
}
throw new InvalidArgumentException('The provided $schema is not a real schema. Use <SchemaClass>::class to get the full schema namespace.');
Expand Down Expand Up @@ -127,16 +126,16 @@ public function createSchemaTables(string|Schema $schema): array
public function createTable(string $table): string
{
if (!Utils::isFinalClass($table)) {
throw new NotFinalExceptions("The " . $table::tableSanitizedName() . " class was not identified as \"final\"");
throw new NotFinalExceptions("The " . $table::sanitizedName() . " class was not identified as \"final\"");
}

$reflectionClass = new \ReflectionClass($table);
$tableName = $table::tableSanitizedName();
$schemaName = $this->schemaNameFromTable($table);
$tableName = $table::sanitizedName();
$columns = $table::tableColumns();
$primaryColumn = $table::tableIdentifier();
$uniqueColumns = $table::tableUniqueColumns();
$notNullColumns = $this->getNotNullProperties($reflectionClass);
$schemaName = $this->schemaNameFromTable($table);

$columnDefs = [];

Expand Down Expand Up @@ -185,11 +184,11 @@ public function createTable(string $table): string
* @param string|Schema $schema
* @return array
*/
public function createSchemaFunctions(string|Schema $schema): array
public function createDatabaseFunctions(string|Database $database): array
{
$functionsSql = [];
new $schema();
$functions = $schema::getFunctions();
new $database();
$functions = $database::getFunctions();

foreach ($functions as $function) {
$functionsSql[] = $function->getSqlDefinition();
Expand Down Expand Up @@ -232,15 +231,15 @@ public function getColumnType(mixed $type): string
public function createForeignKeyConstraints(string $table): array
{
$schemaName = $this->schemaNameFromTable($table);
$tableName = $table::tableSanitizedName();
$tableName = $table::sanitizedName();
$columns = $table::tableColumns();
$constraints = [];

foreach ($columns as $name => $type) {
if (is_subclass_of($type, Table::class)) {
$referencedTable = $type::tableSanitizedName();
$referencedTable = $type::sanitizedName();
$referencedSchema = $this->schemaNameFromTable($type);
$sanitizedName = Utils::sanitizeForPostgres($name);
$sanitizedName = Utils::toSnakeCase($name);
$constraints[] = "ALTER TABLE \"{$schemaName}\".\"{$tableName}\" ADD CONSTRAINT fk_{$tableName}_{$sanitizedName} FOREIGN KEY (\"{$sanitizedName}\") REFERENCES \"{$referencedSchema}\".\"{$referencedTable}\"(\"id\");";
}
}
Expand Down

0 comments on commit 35d721e

Please sign in to comment.