Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
149 changes: 149 additions & 0 deletions docs/examples/ViewsAndTriggersExample.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,149 @@
<?php
declare(strict_types=1);

use Migrations\BaseMigration;

/**
* Example migration demonstrating views and triggers support.
*
* This migration shows how to create and drop database views and triggers
* using the CakePHP Migrations plugin.
*/
class ViewsAndTriggersExample extends BaseMigration
{
/**
* Change Method.
*
* Write your reversible migrations using this method.
*
* More information on writing migrations is available here:
* https://book.cakephp.org/migrations/4/en/index.html
*/
public function change(): void
{
// Create a users table
$users = $this->table('users');
$users->addColumn('username', 'string', ['limit' => 100])
->addColumn('email', 'string', ['limit' => 255])
->addColumn('status', 'string', ['limit' => 20, 'default' => 'active'])
->addColumn('created', 'datetime')
->create();

// Create a posts table
$posts = $this->table('posts');
$posts->addColumn('user_id', 'integer')
->addColumn('title', 'string', ['limit' => 255])
->addColumn('body', 'text')
->addColumn('published', 'boolean', ['default' => false])
->addColumn('created', 'datetime')
->addForeignKey('user_id', 'users', 'id', ['delete' => 'CASCADE'])
->create();

// Create a view showing active users with their post counts
// Note: Views are created through a dummy table object
$this->createView(
'active_users_with_posts',
'SELECT u.id, u.username, u.email, COUNT(p.id) as post_count
FROM users u
LEFT JOIN posts p ON u.id = p.user_id
WHERE u.status = \'active\'
GROUP BY u.id, u.username, u.email'
);

// Create a materialized view (PostgreSQL only)
// On other databases, this will create a regular view
$this->createView(
'published_posts_summary',
'SELECT user_id, COUNT(*) as published_count
FROM posts
WHERE published = 1
GROUP BY user_id',
['materialized' => true]
);

// Create an audit log table for triggers
$auditLog = $this->table('audit_log');
$auditLog->addColumn('table_name', 'string', ['limit' => 100])
->addColumn('action', 'string', ['limit' => 20])
->addColumn('record_id', 'integer')
->addColumn('created', 'datetime')
->create();

// Create a trigger to log user insertions
// Note: The trigger definition syntax varies by database

// For MySQL:
$this->createTrigger(
'users',
'log_user_insert',
'INSERT',
"INSERT INTO audit_log (table_name, action, record_id, created)
VALUES ('users', 'INSERT', NEW.id, NOW())",
['timing' => 'AFTER']
);

// For PostgreSQL, you would need to create a function first:
// $this->execute("
// CREATE OR REPLACE FUNCTION log_user_insert_func()
// RETURNS TRIGGER AS $$
// BEGIN
// INSERT INTO audit_log (table_name, action, record_id, created)
// VALUES ('users', 'INSERT', NEW.id, NOW());
// RETURN NEW;
// END;
// $$ LANGUAGE plpgsql;
// ");
//
// $this->createTrigger(
// 'users',
// 'log_user_insert',
// 'INSERT',
// 'log_user_insert_func()', // Function name for PostgreSQL
// ['timing' => 'AFTER']
// );

// Create a trigger for updates with multiple events
$this->createTrigger(
'posts',
'log_post_changes',
['UPDATE', 'DELETE'],
"INSERT INTO audit_log (table_name, action, record_id, created)
VALUES ('posts', 'CHANGE', OLD.id, NOW())",
['timing' => 'BEFORE']
);
}

/**
* Migrate Up.
*
* If you need more control, you can use up() and down() methods instead.
*/
public function up(): void
{
// Example of creating a view in up() method
$this->createView(
'simple_user_list',
'SELECT id, username FROM users'
);
}

/**
* Migrate Down.
*/
public function down(): void
{
// Drop views
$this->dropView('simple_user_list');
$this->dropView('active_users_with_posts');
$this->dropView('published_posts_summary', ['materialized' => true]);

// Drop triggers
$this->dropTrigger('users', 'log_user_insert');
$this->dropTrigger('posts', 'log_post_changes');

// Drop tables
$this->table('audit_log')->drop()->save();
$this->table('posts')->drop()->save();
$this->table('users')->drop()->save();
}
}
60 changes: 60 additions & 0 deletions src/BaseMigration.php
Original file line number Diff line number Diff line change
Expand Up @@ -498,6 +498,66 @@ public function shouldExecute(): bool
return true;
}

/**
* Creates a view.
*
* This is a convenience method that creates a dummy table to associate the view with.
* Views are not directly associated with tables, but the Table class is used to
* manage the migration actions.
*
* @param string $viewName View name
* @param string $definition SQL SELECT statement for the view
* @param array<string, mixed> $options View options
* @return void
*/
public function createView(string $viewName, string $definition, array $options = []): void
{
$table = $this->table($viewName);
$table->createView($viewName, $definition, $options)->save();
}

/**
* Drops a view.
*
* @param string $viewName View name
* @param array<string, mixed> $options View options
* @return void
*/
public function dropView(string $viewName, array $options = []): void
{
$table = $this->table($viewName);
$table->dropView($viewName, $options)->save();
}

/**
* Creates a trigger on a table.
*
* @param string $tableName Table name
* @param string $triggerName Trigger name
* @param string|array<string> $event Event(s) that fire the trigger (INSERT, UPDATE, DELETE)
* @param string $definition Trigger body/definition
* @param array<string, mixed> $options Trigger options
* @return void
*/
public function createTrigger(string $tableName, string $triggerName, string|array $event, string $definition, array $options = []): void
{
$table = $this->table($tableName);
$table->createTrigger($triggerName, $event, $definition, $options)->save();
}

/**
* Drops a trigger from a table.
*
* @param string $tableName Table name
* @param string $triggerName Trigger name
* @return void
*/
public function dropTrigger(string $tableName, string $triggerName): void
{
$table = $this->table($tableName);
$table->dropTrigger($triggerName)->save();
}

/**
* Makes sure the version int is within range for valid datetime.
* This is required to have a meaningful order in the overview.
Expand Down
38 changes: 38 additions & 0 deletions src/Db/Action/CreateTrigger.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
<?php
declare(strict_types=1);

/**
* MIT License
* For full license information, please view the LICENSE file that was distributed with this source code.
*/

namespace Migrations\Db\Action;

use Migrations\Db\Table\TableMetadata;
use Migrations\Db\Table\Trigger;

class CreateTrigger extends Action
{
/**
* Constructor
*
* @param \Migrations\Db\Table\TableMetadata $table The table metadata
* @param \Migrations\Db\Table\Trigger $trigger The trigger to create
*/
public function __construct(
TableMetadata $table,
protected Trigger $trigger,
) {
parent::__construct($table);
}

/**
* Gets the trigger
*
* @return \Migrations\Db\Table\Trigger
*/
public function getTrigger(): Trigger
{
return $this->trigger;
}
}
38 changes: 38 additions & 0 deletions src/Db/Action/CreateView.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
<?php
declare(strict_types=1);

/**
* MIT License
* For full license information, please view the LICENSE file that was distributed with this source code.
*/

namespace Migrations\Db\Action;

use Migrations\Db\Table\TableMetadata;
use Migrations\Db\Table\View;

class CreateView extends Action
{
/**
* Constructor
*
* @param \Migrations\Db\Table\TableMetadata $table The table metadata
* @param \Migrations\Db\Table\View $view The view to create
*/
public function __construct(
TableMetadata $table,
protected View $view,
) {
parent::__construct($table);
}

/**
* Gets the view
*
* @return \Migrations\Db\Table\View
*/
public function getView(): View
{
return $this->view;
}
}
37 changes: 37 additions & 0 deletions src/Db/Action/DropTrigger.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
<?php
declare(strict_types=1);

/**
* MIT License
* For full license information, please view the LICENSE file that was distributed with this source code.
*/

namespace Migrations\Db\Action;

use Migrations\Db\Table\TableMetadata;

class DropTrigger extends Action
{
/**
* Constructor
*
* @param \Migrations\Db\Table\TableMetadata $table The table metadata
* @param string $triggerName The name of the trigger to drop
*/
public function __construct(
TableMetadata $table,
protected string $triggerName,
) {
parent::__construct($table);
}

/**
* Gets the trigger name
*
* @return string
*/
public function getTriggerName(): string
{
return $this->triggerName;
}
}
49 changes: 49 additions & 0 deletions src/Db/Action/DropView.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
<?php
declare(strict_types=1);

/**
* MIT License
* For full license information, please view the LICENSE file that was distributed with this source code.
*/

namespace Migrations\Db\Action;

use Migrations\Db\Table\TableMetadata;

class DropView extends Action
{
/**
* Constructor
*
* @param \Migrations\Db\Table\TableMetadata $table The table metadata
* @param string $viewName The name of the view to drop
* @param bool $materialized Whether this is a materialized view (PostgreSQL only)
*/
public function __construct(
TableMetadata $table,
protected string $viewName,
protected bool $materialized = false,
) {
parent::__construct($table);
}

/**
* Gets the view name
*
* @return string
*/
public function getViewName(): string
{
return $this->viewName;
}

/**
* Gets whether this is a materialized view
*
* @return bool
*/
public function getMaterialized(): bool
{
return $this->materialized;
}
}
Loading