From eaa4772dc5b62629183f84b740baca959b4b3918 Mon Sep 17 00:00:00 2001 From: Murilo Elias Date: Sun, 29 Sep 2024 03:32:45 -0300 Subject: [PATCH] [fixes] - function declaration moved to database constructor --- bin/maestro | 125 ------------------------ composer.json | 2 +- example/AuthCode.php | 22 ----- example/Hr.php | 10 -- example/MaestroDb.php | 21 ----- example/Post.php | 14 --- example/Social.php | 10 -- example/TaggedUser.php | 14 --- example/User.php | 46 --------- src/Core/Synchronizer.php | 159 ------------------------------- tests/DatabaseManagerTest.php | 141 --------------------------- tests/DeleteTest.php | 112 ---------------------- tests/InsertTest.php | 104 -------------------- tests/ManagerTest.php | 104 -------------------- tests/SelectTest.php | 173 ---------------------------------- tests/UpdateTest.php | 131 ------------------------- 16 files changed, 1 insertion(+), 1187 deletions(-) delete mode 100755 bin/maestro delete mode 100644 example/AuthCode.php delete mode 100644 example/Hr.php delete mode 100644 example/MaestroDb.php delete mode 100644 example/Post.php delete mode 100644 example/Social.php delete mode 100644 example/TaggedUser.php delete mode 100644 example/User.php delete mode 100644 src/Core/Synchronizer.php delete mode 100644 tests/DatabaseManagerTest.php delete mode 100644 tests/DeleteTest.php delete mode 100644 tests/InsertTest.php delete mode 100644 tests/ManagerTest.php delete mode 100644 tests/SelectTest.php delete mode 100644 tests/UpdateTest.php diff --git a/bin/maestro b/bin/maestro deleted file mode 100755 index 276ea73..0000000 --- a/bin/maestro +++ /dev/null @@ -1,125 +0,0 @@ -#!/usr/bin/env php - [options] - -Commands: - sync-schema Synchronize the database schema with the given schema class - sync-database Synchronize the database with the given database class - initiate-database Initiate the database with the given database class - -Options: - -h, --help Show this help message - -EOL; - -function showUsage($message = null) -{ - global $usage; - if ($message) { - echo $message . PHP_EOL . PHP_EOL; - } - echo $usage; - exit(1); -} - -if ($argc < 2) { - showUsage('Error: No command provided.'); -} - -$command = $argv[1]; - -switch ($command) { - case 'sync-schema': - if ($argc < 3) { - showUsage('Error: No schema class provided.'); - } - - $schemaClass = $argv[2]; - - if (!class_exists($schemaClass)) { - showUsage("Error: Schema class '$schemaClass' does not exist."); - } - - try { - $manager = new Manager(); - $schema = new $schemaClass(); - $sqlStatements = $manager->synchronizeSchema($schema); - if (!empty($sqlStatements)) { - echo "Schema synchronized successfully. SQL statements executed:" . PHP_EOL; - foreach ($sqlStatements as $sql) { - echo $sql . PHP_EOL; - } - } else { - echo "No changes detected. Schema is up to date." . PHP_EOL; - } - } catch (Exception $e) { - echo "Error: " . $e->getMessage() . PHP_EOL; - exit(1); - } - break; - - case 'sync-database': - if ($argc < 3) { - showUsage('Error: No database class provided.'); - } - - $databaseClass = $argv[2]; - - if (!class_exists($databaseClass)) { - showUsage("Error: Database class '$databaseClass' does not exist."); - } - - try { - $manager = new Manager(); - $database = new $databaseClass(); - $sqlStatements = $manager->synchronizeDatabase($database); - if (!empty($sqlStatements)) { - echo "Database synchronized successfully. SQL statements executed:" . PHP_EOL; - foreach ($sqlStatements as $sql) { - echo $sql . PHP_EOL; - } - } else { - echo "No changes detected. Database is up to date." . PHP_EOL; - } - } catch (Exception $e) { - echo "Error: " . $e->getMessage() . PHP_EOL; - exit(1); - } - break; - - case 'initiate-database': - // if ($argc < 3) { - // showUsage('Error: No database class provided.'); - // } - - // $databaseClass = $argv[2]; - - // if (!class_exists($databaseClass)) { - // showUsage("Error: Database class '$databaseClass' does not exist."); - // } - - // try { - // $manager = new Manager(); - // $database = new $databaseClass(); - // $manager->initiateDatabase($database); - // } catch (Exception $e) { - // echo "Error: " . $e->getMessage() . PHP_EOL; - // exit(1); - // } - break; - - case '-h': - case '--help': - default: - showUsage(); - break; -} - -exit(0); diff --git a/composer.json b/composer.json index 789374d..db6cea6 100644 --- a/composer.json +++ b/composer.json @@ -40,5 +40,5 @@ "require-dev": { "phpunit/phpunit": "^11.2" }, - "minimum-stability": "dev" + "minimum-stability": "stable" } diff --git a/example/AuthCode.php b/example/AuthCode.php deleted file mode 100644 index d73af28..0000000 --- a/example/AuthCode.php +++ /dev/null @@ -1,22 +0,0 @@ -code = $code; - } -} diff --git a/example/Hr.php b/example/Hr.php deleted file mode 100644 index ca08371..0000000 --- a/example/Hr.php +++ /dev/null @@ -1,10 +0,0 @@ -nickname = $nickname; - $this->email = $email; - $this->password = $password; - $this->active = $active; - $this->createdIn = $createdIn; - } -} diff --git a/src/Core/Synchronizer.php b/src/Core/Synchronizer.php deleted file mode 100644 index 0786351..0000000 --- a/src/Core/Synchronizer.php +++ /dev/null @@ -1,159 +0,0 @@ -manager = new Manager(); - $this->pdo = PDOConnection::getInstance(); - } - - public function synchronize(Database $ormDb): void - { - $ormVector = $this->vectorizeORM($ormDb); - $dbVector = $this->vectorizeDatabase($this->pdo); - $differences = $this->compareVectors($ormVector, $dbVector); - $queries = $this->generateSQLQueries($differences); - - echo var_dump($ormVector, $dbVector, $differences, $queries); - return; - - // $this->executeQueries($queries, $this->pdo); - } - - private function vectorizeORM(Database $ormDb): array - { - $vector = []; - - foreach ($ormDb::getSchemas() as $schemaName => $schema) { - foreach ($schema::getTables() as $tableName => $table) { - $columns = $table::tableColumns(); - foreach ($columns as $columnName => $column) { - $vector[$schemaName][$tableName][$columnName] = [ - 'type' => $column['type'], - 'default' => $column['default'], - 'not_null' => $column['not_null'], - 'is_unique' => $column['is_unique'], - ]; - } - } - } - - return $vector; - } - - private function vectorizeDatabase(PDO $pdo): array - { - $vector = []; - - $query = "SELECT c.table_schema, c.table_name, c.column_name, c.data_type, c.column_default, c.is_nullable, tc.constraint_type - FROM information_schema.columns c - LEFT JOIN information_schema.key_column_usage kcu - ON c.table_schema = kcu.table_schema - AND c.table_name = kcu.table_name - AND c.column_name = kcu.column_name - LEFT JOIN information_schema.table_constraints tc - ON kcu.constraint_name = tc.constraint_name - AND kcu.table_schema = tc.table_schema - AND kcu.table_name = tc.table_name - AND tc.constraint_type = 'UNIQUE' - WHERE c.table_schema NOT IN ('information_schema', 'pg_catalog') - ORDER BY c.table_schema, c.table_name, c.ordinal_position;"; - $stmt = $pdo->query($query); - - while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) { - $schemaName = $row['table_schema']; - $tableName = $row['table_name']; - $columnName = $row['column_name']; - - $vector[$schemaName][$tableName][$columnName] = [ - 'type' => $row['data_type'], - 'default' => $row['column_default'], - 'not_null' => $row['is_nullable'] === 'NO', - 'is_unique' => $row['constraint_type'] === 'UNIQUE', - ]; - } - - return $vector; - } - - private function compareVectors(array $ormVector, array $dbVector): array - { - $differences = []; - - foreach ($ormVector as $schemaName => $schema) { - foreach ($schema as $tableName => $table) { - if (!isset($dbVector[$schemaName][$tableName])) { - $differences[] = [ - 'action' => 'create_table', - 'table' => $tableName, - ]; - continue; - } - - $dbTable = $dbVector[$schemaName][$tableName]; - foreach ($table as $columnName => $column) { - if (!isset($dbTable[$columnName])) { - $differences[] = [ - 'action' => 'add_column', - 'schema' => $schemaName, - 'table' => $tableName, - 'column' => $columnName, - 'definition' => $column - ]; - } - } - } - } - - return $differences; - } - - private function generateSQLQueries(array $differences): array - { - $queries = []; - - foreach ($differences as $difference) { - switch ($difference['action']) { - case 'create_table': - $queries[] = $this->manager->createTable($difference['table']); - break; - case 'add_column': - $queries[] = $this->generateAddColumnSQL( - $difference['schema'], - $difference['table'], - $difference['column'], - $difference['definition'] - ); - break; - } - } - - return $queries; - } - - private function generateAddColumnSQL(string $schema, string $table, string $column, array $definition): string - { - $type = Utils::getPostgresType(is_array($definition['type']) ? $definition['type'][0] : $definition['type']); - $notNull = $definition['not_null'] ? 'NOT NULL' : 'NULL'; - $default = $definition['default'] ? "DEFAULT {$definition['default']}" : ''; - - return "ALTER TABLE \"$schema\".\"$table\" ADD COLUMN \"$column\" $type $notNull $default;"; - } - - private function executeQueries(array $queries, PDO $pdo): void - { - foreach ($queries as $query) { - $this->manager->executeQuery($pdo, $query); - } - } -} diff --git a/tests/DatabaseManagerTest.php b/tests/DatabaseManagerTest.php deleted file mode 100644 index dd56330..0000000 --- a/tests/DatabaseManagerTest.php +++ /dev/null @@ -1,141 +0,0 @@ -pdo = $this->createMock(PDO::class); - $this->manager = new Manager(); - } - - public function testCreateDatabase() - { - $database = new \Maestro\Example\MaestroDb(); - $sql = $this->manager->createDatabase($database); - - $expectedSql = [ - "CREATE SCHEMA IF NOT EXISTS \"hr\";", - "CREATE SCHEMA IF NOT EXISTS \"social\";", - "CREATE TABLE IF NOT EXISTS \"hr\".\"user\" (\n\tid SERIAL PRIMARY KEY,\n\tnickname TEXT NOT NULL UNIQUE,\n\temail TEXT NOT NULL UNIQUE,\n\tpassword TEXT NOT NULL,\n\tactive BOOLEAN NOT NULL DEFAULT TRUE,\n\tcreated_in TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,\n\tupdated_in TIMESTAMP NULL,\n\tinactivated_in TIMESTAMP NULL\n);", - "CREATE TABLE IF NOT EXISTS \"social\".\"post\" (\n\tid SERIAL PRIMARY KEY,\n\tuser_id INTEGER NULL,\n\tpost_content TEXT NULL\n);", - "CREATE TABLE IF NOT EXISTS \"social\".\"tagged_user\" (\n\tid SERIAL PRIMARY KEY,\n\tpost_id INTEGER NULL,\n\tuser_id INTEGER NULL\n);", - "ALTER TABLE \"social\".\"post\" ADD CONSTRAINT fk_post_user_id FOREIGN KEY (\"user_id\") REFERENCES \"hr\".\"user\"(\"id\");", - "ALTER TABLE \"social\".\"tagged_user\" ADD CONSTRAINT fk_tagged_user_post_id FOREIGN KEY (\"post_id\") REFERENCES \"social\".\"post\"(\"id\");", - "ALTER TABLE \"social\".\"tagged_user\" ADD CONSTRAINT fk_tagged_user_user_id FOREIGN KEY (\"user_id\") REFERENCES \"hr\".\"user\"(\"id\");" - ]; - - $this->assertEquals($expectedSql, $sql); - } - - public function testCreateTablesForSchema() - { - $schema = new Hr(); - $sql = $this->manager->createTablesForSchema($schema); - - $expectedSql = [ - "CREATE TABLE IF NOT EXISTS \"hr\".\"user\" (\n\tid SERIAL PRIMARY KEY,\n\tnickname TEXT NOT NULL UNIQUE,\n\temail TEXT NOT NULL UNIQUE,\n\tpassword TEXT NOT NULL,\n\tactive BOOLEAN NOT NULL DEFAULT TRUE,\n\tcreated_in TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,\n\tupdated_in TIMESTAMP NULL,\n\tinactivated_in TIMESTAMP NULL\n);" - ]; - - $this->assertEquals($expectedSql, $sql); - } - - public function testCreateTable() - { - $table = User::class; - $sql = $this->manager->createTable($table); - - $expectedSql = "CREATE TABLE IF NOT EXISTS \"hr\".\"user\" (\n\tid SERIAL PRIMARY KEY,\n\tnickname TEXT NOT NULL UNIQUE,\n\temail TEXT NOT NULL UNIQUE,\n\tpassword TEXT NOT NULL,\n\tactive BOOLEAN NOT NULL DEFAULT TRUE,\n\tcreated_in TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,\n\tupdated_in TIMESTAMP NULL,\n\tinactivated_in TIMESTAMP NULL\n);"; - - $this->assertEquals($expectedSql, $sql); - } - - public function testCreateSchema() - { - $sql = $this->manager->createSchema(Hr::class); - - $expectedSql = "CREATE SCHEMA IF NOT EXISTS \"hr\";"; - $this->assertEquals($expectedSql, $sql); - } - - public function testCreateForeignKeyConstraints() - { - $table = TaggedUser::class; - $constraints = $this->manager->createForeignKeyConstraints($table); - - $expectedConstraints = [ - "ALTER TABLE \"social\".\"tagged_user\" ADD CONSTRAINT fk_tagged_user_post_id FOREIGN KEY (\"post_id\") REFERENCES \"social\".\"post\"(\"id\");", - "ALTER TABLE \"social\".\"tagged_user\" ADD CONSTRAINT fk_tagged_user_user_id FOREIGN KEY (\"user_id\") REFERENCES \"hr\".\"user\"(\"id\");" - ]; - - $this->assertEquals($expectedConstraints, $constraints); - } - - public function testGetSchemaNameFromTable() - { - $table = User::class; - $schemaName = $this->manager->getSchemaNameFromTable($table); - - $expectedSchemaName = "hr"; - $this->assertEquals($expectedSchemaName, $schemaName); - } - - public function testIsPropertyNotNull() - { - $reflectionClass = new \ReflectionClass(User::class); - $propertyName = "nickname"; - - $isNotNull = $this->manager->isPropertyNotNull($reflectionClass, $propertyName); - $this->assertTrue($isNotNull); - } - - public function testGetPropertyDefaultValue() - { - $reflectionClass = new \ReflectionClass(User::class); - $propertyName = "createdIn"; - - $defaultValue = $this->manager->getPropertyDefaultValue($reflectionClass, $propertyName); - $this->assertEquals("CURRENT_TIMESTAMP", $defaultValue); - } - - public function testFormatDefaultValue() - { - $stringValue = "test"; - $booleanValueTrue = true; - $booleanValueFalse = false; - $intValue = 123; - - $this->assertEquals("'test'", $this->manager->formatDefaultValue($stringValue)); - $this->assertEquals("TRUE", $this->manager->formatDefaultValue($booleanValueTrue)); - $this->assertEquals("FALSE", $this->manager->formatDefaultValue($booleanValueFalse)); - $this->assertEquals("123", $this->manager->formatDefaultValue($intValue)); - } - - public function testGetColumnType() - { - $type = "string"; - $expectedColumnType = "TEXT"; - - $this->assertEquals($expectedColumnType, $this->manager->getColumnType($type)); - } - - public function testExecuteQuery() - { - $sql = "SELECT * FROM users LIMIT 1"; - $this->pdo->method('exec')->willReturn(1); - $stmt = $this->manager->executeQuery($this->pdo, $sql); - - $this->assertIsArray($stmt); - } -} diff --git a/tests/DeleteTest.php b/tests/DeleteTest.php deleted file mode 100644 index b61408f..0000000 --- a/tests/DeleteTest.php +++ /dev/null @@ -1,112 +0,0 @@ - 'email@example.com']; - - $delete->from($table::getTableName())->where($conditions); - - $expectedSql = "DELETE FROM user WHERE email = :where_email"; - $expectedParams = [':where_email' => "'email@example.com'"]; - - $this->assertEquals($expectedSql, $delete->getSql()); - $this->assertEquals($expectedParams, $delete->getParameters()); - } - - public function testDeleteWithInClause() - { - $delete = new Delete(SqlBehavior::SQL_NO_PREDICT); - $table = User::class; - $conditions = ['id' => [1, 2, 3]]; - - $delete->from($table::getTableName())->in($conditions); - - $expectedSql = "DELETE FROM user WHERE id IN(:in_id_0,:in_id_1,:in_id_2)"; - $expectedParams = [':in_id_0' => 1, ':in_id_1' => 2, ':in_id_2' => 3]; - - $this->assertEquals($expectedSql, $delete->getSql()); - $this->assertEquals($expectedParams, $delete->getParameters()); - } - - public function testDeleteWithMultipleConditions() - { - $delete = new Delete(SqlBehavior::SQL_NO_PREDICT); - $table = User::class; - $conditions = ['email' => 'email@example.com', 'active' => false]; - - $delete->from($table::getTableName())->where($conditions); - - $expectedSql = "DELETE FROM user WHERE email = :where_email AND active = :where_active"; - $expectedParams = [':where_email' => "'email@example.com'", ':where_active' => 'false']; - - $this->assertEquals($expectedSql, $delete->getSql()); - $this->assertEquals($expectedParams, $delete->getParameters()); - } - - public function testDeleteWithoutConditions() - { - $delete = new Delete(SqlBehavior::SQL_NO_PREDICT); - $table = User::class; - - $delete->from($table::getTableName()); - - $expectedSql = "DELETE FROM user"; - $expectedParams = []; - - $this->assertEquals($expectedSql, $delete->getSql()); - $this->assertEquals($expectedParams, $delete->getParameters()); - } - - public function testMultipleInConditions() - { - $delete = new Delete(SqlBehavior::SQL_NO_PREDICT); - $table = User::class; - $conditions = [ - 'id' => [1, 2, 3], - 'group_id' => [10, 20, 30] - ]; - - $delete->from($table::getTableName())->in($conditions); - - $expectedSql = "DELETE FROM user WHERE id IN(:in_id_0,:in_id_1,:in_id_2) AND group_id IN(:in_group_id_0,:in_group_id_1,:in_group_id_2)"; - $expectedParams = [ - ':in_id_0' => 1, - ':in_id_1' => 2, - ':in_id_2' => 3, - ':in_group_id_0' => 10, - ':in_group_id_1' => 20, - ':in_group_id_2' => 30 - ]; - - $this->assertEquals($expectedSql, $delete->getSql()); - $this->assertEquals($expectedParams, $delete->getParameters()); - } - - public function testDeleteWithTimestampCondition() - { - $delete = new Delete(SqlBehavior::SQL_NO_PREDICT); - $table = User::class; - $date = new Timestamp(); - $conditions = ['created_at' => $date]; - - $delete->from($table::getTableName())->where($conditions); - - $expectedSql = "DELETE FROM user WHERE created_at = :where_created_at"; - $expectedParams = [':where_created_at' => "'{$date}'"]; - - $this->assertEquals($expectedSql, $delete->getSql()); - $this->assertEquals($expectedParams, $delete->getParameters()); - } -} diff --git a/tests/InsertTest.php b/tests/InsertTest.php deleted file mode 100644 index aa8b6bf..0000000 --- a/tests/InsertTest.php +++ /dev/null @@ -1,104 +0,0 @@ - 'nickname', 'email' => 'email@example.com', 'password' => 'password']; - - $insert->into($table::getTableName())->values($data); - - $expectedSql = "INSERT INTO user (nickname, email, password) VALUES (:nickname, :email, :password)"; - $expectedParams = [':nickname' => 'nickname', ':email' => 'email@example.com', ':password' => 'password']; - - $this->assertEquals($expectedSql, $insert->getSql()); - $this->assertEquals($expectedParams, $insert->getParameters()); - } - - public function testInsertWithMissingFields() - { - $insert = new Insert(SqlBehavior::SQL_NO_PREDICT); - $table = User::class; - $data = ['nickname' => 'nickname', 'email' => 'email@example.com']; - - $insert->into($table::getTableName())->values($data); - - $expectedSql = "INSERT INTO user (nickname, email) VALUES (:nickname, :email)"; - $expectedParams = [':nickname' => 'nickname', ':email' => 'email@example.com']; - - $this->assertEquals($expectedSql, $insert->getSql()); - $this->assertEquals($expectedParams, $insert->getParameters()); - } - - public function testInsertWithAllFields() - { - $insert = new Insert(SqlBehavior::SQL_NO_PREDICT); - $table = User::class; - $data = [ - 'nickname' => 'nickname', - 'email' => 'email@example.com', - 'password' => 'password', - 'active' => true, - 'created_in' => 'CURRENT_TIMESTAMP', - 'updated_in' => '2022-01-01 00:00:00', - 'inactivated_in' => null - ]; - - $insert->into($table::getTableName())->values($data); - - $expectedSql = "INSERT INTO user (nickname, email, password, active, created_in, updated_in, inactivated_in) VALUES (:nickname, :email, :password, :active, :created_in, :updated_in, :inactivated_in)"; - $expectedParams = [ - ':nickname' => 'nickname', - ':email' => 'email@example.com', - ':password' => 'password', - ':active' => true, - ':created_in' => 'CURRENT_TIMESTAMP', - ':updated_in' => '2022-01-01 00:00:00', - ':inactivated_in' => null - ]; - - $this->assertEquals($expectedSql, $insert->getSql()); - $this->assertEquals($expectedParams, $insert->getParameters()); - } - - public function testInsertWithTimestamp() - { - $insert = new Insert(SqlBehavior::SQL_NO_PREDICT); - $table = User::class; - $date = new Timestamp(); - $data = ['nickname' => 'nickname', 'email' => 'email@example.com', 'created_at' => $date]; - - $insert->into($table::getTableName())->values($data); - - $expectedSql = "INSERT INTO user (nickname, email, created_at) VALUES (:nickname, :email, :created_at)"; - $expectedParams = [':nickname' => 'nickname', ':email' => 'email@example.com', ':created_at' => $date]; - - $this->assertEquals($expectedSql, $insert->getSql()); - $this->assertEquals($expectedParams, $insert->getParameters()); - } - - public function testInsertWithNullValue() - { - $insert = new Insert(SqlBehavior::SQL_NO_PREDICT); - $table = User::class; - $data = ['nickname' => 'nickname', 'email' => null, 'password' => 'password']; - - $insert->into($table::getTableName())->values($data); - - $expectedSql = "INSERT INTO user (nickname, email, password) VALUES (:nickname, :email, :password)"; - $expectedParams = [':nickname' => 'nickname', ':email' => null, ':password' => 'password']; - - $this->assertEquals($expectedSql, $insert->getSql()); - $this->assertEquals($expectedParams, $insert->getParameters()); - } -} diff --git a/tests/ManagerTest.php b/tests/ManagerTest.php deleted file mode 100644 index edc65da..0000000 --- a/tests/ManagerTest.php +++ /dev/null @@ -1,104 +0,0 @@ -pdoMock = $this->createMock(\PDO::class); - PDOConnection::getInstance($this->pdoMock); - $this->manager = new Manager(); - } - - public function testCreateTable() - { - $tableClass = Hr::getTables()['user']; - $createTableSql = $this->manager->createTable($tableClass); - - $expectedSql = 'CREATE TABLE IF NOT EXISTS "hr"."user" ( - id SERIAL PRIMARY KEY, - nickname TEXT NOT NULL UNIQUE, - email TEXT NOT NULL UNIQUE, - password TEXT NOT NULL, - active BOOLEAN NOT NULL DEFAULT TRUE, - created_in TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, - updated_in TIMESTAMP NULL, - inactivated_in TIMESTAMP NULL - );'; - - $this->assertEquals(trim(preg_replace('/\s+/', ' ', $expectedSql)), trim(preg_replace('/\s+/', ' ', $createTableSql))); - } - - public function testAddColumnToTable() - { - $schema = new Hr(); - - $dbSchema = [ - 'user' => [ - ['column_name' => 'id', 'data_type' => 'integer'], - ['column_name' => 'nickname', 'data_type' => 'text'], - ], - ]; - - $definedSchema = $this->manager->getSchemaComparator()->getDefinedSchema($schema); - $differences = $this->manager->getSchemaComparator()->compareSchemas($dbSchema, $definedSchema); - - $sqlStatements = $this->manager->generateSqlStatements($differences, $schema); - - $expectedSql = 'ALTER TABLE "hr"."user" ADD COLUMN email TEXT;'; - $this->assertContains($expectedSql, $sqlStatements); - } - - public function testRemoveColumnFromTable() - { - $schema = new Hr(); - - $dbSchema = [ - 'user' => [ - ['column_name' => 'id', 'data_type' => 'integer'], - ['column_name' => 'nickname', 'data_type' => 'text'], - ['column_name' => 'unused_column', 'data_type' => 'text'], - ], - ]; - - $definedSchema = $this->manager->getSchemaComparator()->getDefinedSchema($schema); - $differences = $this->manager->getSchemaComparator()->compareSchemas($dbSchema, $definedSchema); - - $sqlStatements = $this->manager->generateSqlStatements($differences, $schema); - - $expectedSql = 'ALTER TABLE "hr"."user" DROP COLUMN unused_column;'; - $this->assertContains($expectedSql, $sqlStatements); - } - - public function testDropTable() - { - $schema = new Hr(); - - $dbSchema = [ - 'user' => [ - ['column_name' => 'id', 'data_type' => 'integer'], - ['column_name' => 'nickname', 'data_type' => 'text'], - ], - 'old_table' => [ - ['column_name' => 'id', 'data_type' => 'integer'], - ], - ]; - - $definedSchema = $this->manager->getSchemaComparator()->getDefinedSchema($schema); - $differences = $this->manager->getSchemaComparator()->compareSchemas($dbSchema, $definedSchema); - - $sqlStatements = $this->manager->generateSqlStatements($differences, $schema); - - $expectedSql = 'DROP TABLE "hr"."old_table";'; - $this->assertContains($expectedSql, $sqlStatements); - } -} diff --git a/tests/SelectTest.php b/tests/SelectTest.php deleted file mode 100644 index 37e8072..0000000 --- a/tests/SelectTest.php +++ /dev/null @@ -1,173 +0,0 @@ -from(['user' => 'user'], ['nickname', 'email'])->where(['active' => true]); - - $expectedSql = "SELECT user.nickname, user.email FROM user WHERE active = :where_active"; - $expectedParams = [':where_active' => true]; - - $this->assertEquals($expectedSql, $select->getSql()); - $this->assertEquals($expectedParams, $select->getParameters()); - } - - public function testSelectWithInClause() - { - $select = new Select(SqlBehavior::SQL_NO_PREDICT); - $select->from(['user' => 'user'], ['nickname', 'email'])->in(['id' => [1, 2, 3]]); - - $expectedSql = "SELECT user.nickname, user.email FROM user WHERE id IN(:in_id_0,:in_id_1,:in_id_2)"; - $expectedParams = [':in_id_0' => 1, ':in_id_1' => 2, ':in_id_2' => 3]; - - $this->assertEquals($expectedSql, $select->getSql()); - $this->assertEquals($expectedParams, $select->getParameters()); - } - - public function testSelectWithMultipleConditions() - { - $select = new Select(SqlBehavior::SQL_NO_PREDICT); - $select->from(['user' => 'user'], ['nickname', 'email'])->where(['active' => true, 'verified' => true]); - - $expectedSql = "SELECT user.nickname, user.email FROM user WHERE active = :where_active AND verified = :where_verified"; - $expectedParams = [':where_active' => true, ':where_verified' => true]; - - $this->assertEquals($expectedSql, $select->getSql()); - $this->assertEquals($expectedParams, $select->getParameters()); - } - - public function testMultipleInConditions() - { - $select = new Select(SqlBehavior::SQL_NO_PREDICT); - $table = User::class; - $columns = ['nickname', 'email']; - $conditions = [ - 'id' => [1, 2, 3], - 'group_id' => [10, 20, 30] - ]; - - $select->from([$table::getTableName() => 'user'], $columns)->in($conditions); - - $expectedSql = "SELECT user.nickname, user.email FROM user WHERE id IN(:in_id_0,:in_id_1,:in_id_2) AND group_id IN(:in_group_id_0,:in_group_id_1,:in_group_id_2)"; - $expectedParams = [ - ':in_id_0' => 1, - ':in_id_1' => 2, - ':in_id_2' => 3, - ':in_group_id_0' => 10, - ':in_group_id_1' => 20, - ':in_group_id_2' => 30 - ]; - - $this->assertEquals($expectedSql, $select->getSql()); - $this->assertEquals($expectedParams, $select->getParameters()); - } - - public function testSelectWithoutConditions() - { - $select = new Select(SqlBehavior::SQL_NO_PREDICT); - $select->from(['user' => 'user'], ['nickname', 'email']); - - $expectedSql = "SELECT user.nickname, user.email FROM user"; - $expectedParams = []; - - $this->assertEquals($expectedSql, $select->getSql()); - $this->assertEquals($expectedParams, $select->getParameters()); - } - - public function testSelectWithFunctions() - { - $select = new Select(SqlBehavior::SQL_NO_PREDICT); - $table = User::class; - $columns = ['nickname', 'email', 'count' => new Expression('COUNT(*)')]; - $conditions = ['active' => true]; - - $select->from([$table::getTableName() => 'user'], $columns)->where($conditions); - - $expectedSql = "SELECT user.nickname, user.email, COUNT(*) AS count FROM user WHERE active = :where_active"; - $expectedParams = [':where_active' => true]; - - $this->assertEquals($expectedSql, $select->getSql()); - $this->assertEquals($expectedParams, $select->getParameters()); - } - - public function testSelectWithJoin() - { - $select = new Select(SqlBehavior::SQL_NO_PREDICT); - $table = User::class; - $columns = ['nickname', 'email']; - $conditions = ['user.active' => true]; - - $select->from(['user' => $table::getTableName()], $columns) - ->join(['profile' => 'profile'], 'user.id = profile.user_id', ['bio']) - ->where($conditions); - - $expectedSql = "SELECT user.nickname, user.email, profile.bio FROM user AS user INNER JOIN profile AS profile ON user.id = profile.user_id WHERE user.active = :where_user_active"; - $expectedParams = [':where_user_active' => 'true']; - - $this->assertEquals($expectedSql, $select->getSql()); - $this->assertEquals($expectedParams, $select->getParameters()); - } - - public function testSelectWithLeftJoin() - { - $select = new Select(SqlBehavior::SQL_NO_PREDICT); - $table = User::class; - $columns = ['nickname', 'email']; - $conditions = ['user.active' => true]; - - $select->from(['user' => $table::getTableName()], $columns) - ->join(['profile' => 'profile'], 'user.id = profile.user_id', ['bio'], 'LEFT') - ->where($conditions); - - $expectedSql = "SELECT user.nickname, user.email, profile.bio FROM user AS user LEFT JOIN profile AS profile ON user.id = profile.user_id WHERE user.active = :where_user_active"; - $expectedParams = [':where_user_active' => true]; - - $this->assertEquals($expectedSql, $select->getSql()); - $this->assertEquals($expectedParams, $select->getParameters()); - } - - public function testSelectWithMultipleJoins() - { - $select = new Select(SqlBehavior::SQL_NO_PREDICT); - $table = User::class; - $columns = ['nickname', 'email']; - $conditions = ['user.active' => true]; - - $select->from(['user' => $table::getTableName()], $columns) - ->join(['profile' => 'profile'], 'user.id = profile.user_id', ['bio']) - ->join(['account' => 'account'], 'user.id = account.user_id', ['balance']) - ->where($conditions); - - $expectedSql = "SELECT user.nickname, user.email, profile.bio, account.balance FROM user AS user INNER JOIN profile AS profile ON user.id = profile.user_id INNER JOIN account AS account ON user.id = account.user_id WHERE user.active = :where_user_active"; - $expectedParams = [':where_user_active' => true]; - - $this->assertEquals($expectedSql, $select->getSql()); - $this->assertEquals($expectedParams, $select->getParameters()); - } - - public function testSelectWithOrderBy() - { - $select = new Select(SqlBehavior::SQL_NO_PREDICT); - $table = User::class; - $columns = ['nickname', 'email']; - $conditions = ['active' => true]; - - $select->from([$table::getTableName() => 'user'], $columns)->where($conditions)->order('nickname', 'ASC'); - - $expectedSql = "SELECT user.nickname, user.email FROM user WHERE active = :where_active ORDER BY nickname ASC"; - $expectedParams = [':where_active' => true]; - - $this->assertEquals($expectedSql, $select->getSql()); - $this->assertEquals($expectedParams, $select->getParameters()); - } -} diff --git a/tests/UpdateTest.php b/tests/UpdateTest.php deleted file mode 100644 index cb8e387..0000000 --- a/tests/UpdateTest.php +++ /dev/null @@ -1,131 +0,0 @@ - 'updated_nickname']; - $conditions = ['email' => 'email@example.com']; - - $update->table($table::getTableName())->set('nickname', 'updated_nickname')->where($conditions); - - $expectedSql = "UPDATE {$table::getTableName()} SET nickname = :nickname WHERE email = :where_email"; - $expectedParams = [':nickname' => 'updated_nickname', ':where_email' => "'email@example.com'"]; - - $this->assertEquals($expectedSql, $update->getSql()); - $this->assertEquals($expectedParams, $update->getParameters()); - } - - public function testUpdateWithInClause() - { - $update = new Update(SqlBehavior::SQL_NO_PREDICT); - $table = User::class; - $data = ['nickname' => 'updated_nickname']; - $conditions = ['id' => [1, 2, 3]]; - - $update->table($table::getTableName())->set('nickname', 'updated_nickname')->in($conditions); - - $expectedSql = "UPDATE {$table::getTableName()} SET nickname = :nickname WHERE id IN(:in_id_0,:in_id_1,:in_id_2)"; - $expectedParams = [':nickname' => 'updated_nickname', ':in_id_0' => 1, ':in_id_1' => 2, ':in_id_2' => 3]; - - $this->assertEquals($expectedSql, $update->getSql()); - $this->assertEquals($expectedParams, $update->getParameters()); - } - - public function testUpdateWithMultipleConditions() - { - $update = new Update(SqlBehavior::SQL_NO_PREDICT); - $table = User::class; - $data = ['nickname' => 'updated_nickname']; - $conditions = ['email' => 'email@example.com', 'active' => true]; - - $update->table($table::getTableName())->set('nickname', 'updated_nickname')->where($conditions); - - $expectedSql = "UPDATE {$table::getTableName()} SET nickname = :nickname WHERE email = :where_email AND active = :where_active"; - $expectedParams = [':nickname' => 'updated_nickname', ':where_email' => "'email@example.com'", ':where_active' => true]; - - $this->assertEquals($expectedSql, $update->getSql()); - $this->assertEquals($expectedParams, $update->getParameters()); - } - - public function testMultipleInConditions() - { - $update = new Update(SqlBehavior::SQL_NO_PREDICT); - $table = User::class; - $data = ['nickname' => 'updated_nickname']; - $conditions = [ - 'id' => [1, 2, 3], - 'group_id' => [10, 20, 30] - ]; - - $update->table($table::getTableName())->set('nickname', 'updated_nickname')->in($conditions); - - $expectedSql = "UPDATE {$table::getTableName()} SET nickname = :nickname WHERE id IN(:in_id_0,:in_id_1,:in_id_2) AND group_id IN(:in_group_id_0,:in_group_id_1,:in_group_id_2)"; - $expectedParams = [ - ':nickname' => 'updated_nickname', - ':in_id_0' => 1, ':in_id_1' => 2, ':in_id_2' => 3, - ':in_group_id_0' => 10, ':in_group_id_1' => 20, ':in_group_id_2' => 30 - ]; - - $this->assertEquals($expectedSql, $update->getSql()); - $this->assertEquals($expectedParams, $update->getParameters()); - } - - public function testUpdateWithoutConditions() - { - $update = new Update(SqlBehavior::SQL_NO_PREDICT); - $table = User::class; - $data = ['nickname' => 'updated_nickname']; - - $update->table($table::getTableName())->set('nickname', 'updated_nickname'); - - $expectedSql = "UPDATE {$table::getTableName()} SET nickname = :nickname"; - $expectedParams = [':nickname' => 'updated_nickname']; - - $this->assertEquals($expectedSql, $update->getSql()); - $this->assertEquals($expectedParams, $update->getParameters()); - } - - public function testUpdateWithTimestamp() - { - $update = new Update(SqlBehavior::SQL_NO_PREDICT); - $table = User::class; - $date = new Timestamp(); - $data = ['updated_at' => $date]; - $conditions = ['email' => 'email@example.com']; - - $update->table($table::getTableName())->set('updated_at', $date)->where($conditions); - - $expectedSql = "UPDATE {$table::getTableName()} SET updated_at = :updated_at WHERE email = :where_email"; - $expectedParams = [':updated_at' => $date, ':where_email' => "'email@example.com'"]; - - $this->assertEquals($expectedSql, $update->getSql()); - $this->assertEquals($expectedParams, $update->getParameters()); - } - - public function testUpdateMultipleSetClauses() - { - $update = new Update(SqlBehavior::SQL_NO_PREDICT); - $table = User::class; - $data = ['nickname' => 'updated_nickname', 'active' => false]; - $conditions = ['email' => 'email@example.com']; - - $update->table($table::getTableName())->set('nickname', 'updated_nickname')->set('active', false)->where($conditions); - - $expectedSql = "UPDATE {$table::getTableName()} SET nickname = :nickname, active = :active WHERE email = :where_email"; - $expectedParams = [':nickname' => 'updated_nickname', ':active' => false, ':where_email' => '\'email@example.com\'']; - - $this->assertEquals($expectedSql, $update->getSql()); - $this->assertEquals($expectedParams, $update->getParameters()); - } -}