atk4/schema

此软件包已被废弃且不再维护。未建议替代软件包。

敏捷模式

2.3.1 2020-10-13 22:53 UTC

README

https://github.com/atk4/data





Agile Data - SQL Schema Management Add-on

此扩展为 Agile Data 实现了与 SQL 架构交互、执行迁移、在 PHPUnit 中执行数据库测试(其他 ATK 框架所用)以及将“模型”结构同步到数据库的能力。

Build CodeCov GitHub release Code Climate

基本用法

// Add the following code on your setup page / wizard:

$app->add('MigratorConsole')
    ->migrateModels([
        new Model\User($app->db), 
        new Model\Order($app->db),
        new Model\Payment($app->db)
    ]);

用户将看到一个控制台,该控制台将调整数据库以包含模型所需的表/字段。

migrator-console

当然,也可以在没有视觉反馈的情况下执行迁移。

$changes = \atk4\schema\Migration::of(new User($app->db))->run();

如果您需要更精细的迁移,您可以详细定义它们。

// create table
$migrator = \atk4\schema\Migration::of($app->db);
$migrator->table('user')
    ->id()
    ->field('name')
    ->field('address', ['type'=>'text']);
    ->create();

// or alter
$migrator = \atk4\schema\Migration::of($app->db);
$migrator->table('user')
    ->newField('age', ['type'=>'integer'])
    ->alter();

目前 atk4/schema 完全支持 MySQL 和 SQLite 数据库,部分支持 PostgreSQL 和 Oracle。其他 SQL 数据库目前尚未原生支持,但您可以在运行时注册您的迁移器类。

// $dbDriver is the connection driver name
// MyCustomMigrator::class should be extending \atk4\schema\Migration

\atk4\schema\Migration::register($platformClass, MyCustomMigrator::class);

字段声明使用与 ATK Data 相同的类型。

示例

schema\Migration 是一个简单的类,用于使用 DSQL 构建与架构相关的查询。

<?php
$migrator = \atk4\data\schema\Migration::of($connection);
$migrator->table('user')->drop();
$migrator->field('id');
$migrator->field('name', ['type'=>'string']);
$migrator->field('age', ['type'=>'integer']);
$migrator->field('bio');
$migrator->create();

schema\Snapshot(未实现)是一个简单的类,可以记录和恢复表内容

<?php
$s = new \atk4\data\schema\Snapshot($connection);
$tables = $s->getDb($tables);

// do anything with tables

$s->setDb($tables);

与 PHPUnit 集成

现在您可以通过更容易地设置和检查数据库内容来自动化数据库测试。首先,从 \atk4\schema\PhpunitTestCase 扩展您的测试脚本。

接下来,您需要设置您的架构

$q = ['user' => [
    ['name' => 'John', 'surname' => 'Smith'],
    ['name' => 'Steve', 'surname' => 'Jobs'],
]];
$this->setDb($q);

执行任何更改,然后执行

$this->assertEquals($q, $this->getDb('user'));

以确保数据库保持不变。当然,您可以将它与任何其他状态进行比较。

  • 默认情况下自动添加 'id' 字段
  • 为您创建表
  • 检测类型(int、string、date、boolean 等)
  • 如果不传递,则隐藏 ID 值

安装

请将以下内容添加到您的 composer.json 文件中

composer require atk4/schema