safronik / db-migrator
检查当前数据库结构
0.1.1
2024-04-25 18:51 UTC
Requires
- php: >=8.0
This package is not auto-updated.
Last update: 2024-09-22 06:18:37 UTC
README
检查并更改现有的 SQL 架构,并按要求的架构修改它
关于
此库帮助从当前架构迁移到指定架构。
安装
首选的安装方法是使用 Composer。运行以下命令安装软件包并将其添加到项目的 composer.json
文件中作为需求
composer require safronik/db-migrator
或者直接下载文件或克隆仓库(在这种情况下,您需要担心自动加载器)
使用方法
限制
在使用之前,您需要做一些事情。
- 首先,您应该实现
DBMigratorGatewayInterface
以创建网关。
namespace Safronik\DBMigrator; use Safronik\DBMigrator\Objects\Table; interface DBMigratorGatewayInterface { public function isTableExists( $table ): bool; public function createTable( Table $table ): bool; public function getTablesNames(): array; public function getTableColumns( string $table ): array; public function getTableIndexes( string $table ): array; public function getTableConstraints( string $table ): array; public function alterTable( $table, array $columns = [], array $indexes = [], array $constraints = [] ): bool; public function dropTable( $table ): bool; }
例如
class DBMigratorGatewayInterfaceImplementation implements \Safronik\DBMigrator\DBMigratorGatewayInterface { // Your implementation of the interface }
- 其次,您应该创建架构提供者或直接向迁移对象提供
Schemas
对象。您可以使用self::getCurrentSchemas()
获取当前架构。
$migrator = new DBMigrator( $migrator_gateway ); $schemas = $migrator->getCurrentSchemas();
无论如何,这里是一个手动创建 Schemas 对象的示例
$schemas = new Schemas([ new Table( 'example_table', // Columns [ new Column([ 'field' => 'id', // Required 'type' => 'INT(11)', // Required 'null' => 'no', 'default' => '' 'extra' => 'AUTO INCREMENT', 'comment' => 'Primary key', ]), new Column([ 'field' => 'value_field', // Required 'type' => 'TEXT', // Required 'null' => 'yes', 'default' => 'null', 'extra' => '', 'comment' => 'Desc', ]), // ... ], // Indexes (optional) [ new Index([ 'key_name' => 'PRIMARY', // Required 'columns' => ['id'], // Required 'unique' => true, 'type' => 'BTREE', 'comment' => 'Primary key', ]), // ... ], // Constraints (optional) [ new Constraint([ 'name' => 'Example constraint', // Required 'column' => 'id', // Required 'reference_table' => 'examples2', // Required 'reference_column' => 'example_id', // Required 'on_update' => '', 'on_delete' => '', ]), // ... ], ) ]);
最后,完成所有这些后,您可以继续操作
$migrator = new DBMigrator( new DBMigratorGatewayInterfaceImplementation() ); $migrator ->setSchemas( $schemas ) ->compareWithCurrentStructure() ->actualizeSchema();
此外,您还可以删除现有的架构
$migrator = new DBMigrator( new DBMigratorGatewayInterfaceImplementation() ); $migrator ->setSchemas( $migrator->getCurrentSchemas() ) ->dropSchema();