I would like to synchronize the states of multiple databases. I would like to compare the tables in them, and create the missing tables and columns.
There is a library for Php, which has a lot of functions for database manipulation: Phinx Unfortunately there are only examples for creating migrations, but it does not explain, how to use it without that.
How is it possible to query and modify the database structure, without writing migrations?
Phinx makes it ridiculously easy to manage the database migrations for your PHP app. In less than 5 minutes, you can install Phinx using Composer and create your first database migration. Phinx is just about migrations without all the bloat of a database ORM system or application framework.
Running Phinx in a Web App This will create local web server at http://localhost:8000 which will show current migration status by default. To run migrations up, use http://localhost:8000/migrate and to rollback use http://localhost:8000/rollback.
Migrations are a type of version control for your database. They allow a team to modify the database schema and stay up to date on the current schema state. Migrations are typically paired with the Schema Builder to easily manage your application's schema.
The main problem here is sync all the databases, to do that by using phinx
, you should decide which is the most complete database and do the following:
Option 1: Create a "master" migration with each table that should exist, "complete database, one per table.
<?PHP
public function up()
{
$exists = $this->hasTable('xxx');
if (!$exists) {
$this->execute("CREATE TABLE `xxx` (`xxx_id` int(10) NOT NULL AUTO_INCREMENT);");
}
}
public function down()
{
$exists = $this->hasTable('xxx');
if ($exists) {
$table = $this->table('xxx');
if (!$table->hasColumn('name')) {
$table->addColumn("name", "string", ["limit" => 255])->save();
}
$table->drop();
}
}
but creating one migration per table could be a hard job, then ...
Option 2:: You could create the database scripts dynamically by listing tables and adding them into an array:
<?PHP
public function up()
{
$tables = ['xxx', 'yyy'];
foreach ($tables as $curTable) {
$exists = $this->hasTable($curTable);
if (!$exists) {
$this->execute($this->getCreateTable($curTable));
}
}
}
but then you should generate a method called getCreateTable
that receives the table
name and get the structure from the master database.
after that create a routine to do the same with fields but you can get them for each table and nested loop for each field.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With