milesasylum/schnoop-schema

Schnoop Schema 是一个用于描述 MySQL 数据库模式的 PHP 类集合。

v0.3.3 2024-08-26 02:20 UTC

This package is auto-updated.

Last update: 2024-08-26 02:21:43 UTC


README

Tests Coverage Status Latest Stable Version Total Downloads License

Schnoop Schema 是一个用于描述 MySQL 数据库模式并提供该模式的 DDL 语句的 PHP 类集合。

它的目的是作为一个代码生成器,通过使 PHP 脚本更容易创建 DDL 语句来创建表、存储过程等。

此包不与数据库服务器交互,但对于需要交互的实现,请查看 milesasylum/Schnoop

使用 Schnoop-Scheme,您可以描述以下数据库定义

  • 数据库
    • 索引
    • 外键
    • 触发器
  • 函数
  • 存储过程

免责声明:不建议在生产环境中使用此包 - 它仅适用于开发环境以辅助代码生成。

示例

创建数据库

<?php

use MilesAsylum\SchnoopSchema\MySQL\Database\Database;

$database = new Database('schnoop_db');
$database->setDefaultCollation('utf8mb4_general_ci');
$database->setDelimiter('$$');
$database->setDropPolicy(Database::DDL_DROP_POLICY_DROP_IF_EXISTS);
echo $database->getCreateStatement();
/*
DROP DATABASE IF EXISTS `schnoop_db`$$
CREATE DATABASE `schnoop_db` DEFAULT COLLATION 'utf8mb4_general_ci'$$
*/

创建表

<?php

use MilesAsylum\SchnoopSchema\MySQL\Table\Table;

// Create Table.
$table = new Table('schnoop_tbl');
$table->setEngine(Table::ENGINE_INNODB);
$table->setDefaultCollation('utf8mb4_general_ci');

向表中添加列

<?php

// ...
use MilesAsylum\SchnoopSchema\MySQL\Column\Column;
use MilesAsylum\SchnoopSchema\MySQL\DataType\IntType;
use MilesAsylum\SchnoopSchema\MySQL\DataType\VarCharType;
use MilesAsylum\SchnoopSchema\MySQL\DataType\TimestampType;

// ...

// Add an ID column.
$idType = new IntType();
$idType->setSigned(false);
$idColumn = new Column('id', $idType);
$idColumn->setAutoIncrement(true);
$idColumn->setNullable(false);
$table->addColumn($idColumn);

// Add a name column.
$nameType = new VarCharType(50);
$nameType->setCollation('ascii_general_ci');
$nameColumn = new Column('name', $nameType);
$table->addColumn($nameColumn);

// Add an updated-at column.
$updatedAtType = new TimestampType();
$updatedAtType->setPrecision(2);
$updatedAtColumn = new Column('updated_at', $updatedAtType);
$updatedAtColumn->setOnUpdateCurrentTimestamp(true);
$updatedAtColumn->setNullable(false);
$table->addColumn($updatedAtColumn);

向表中添加索引

<?php

// ...
use MilesAsylum\SchnoopSchema\MySQL\Constraint\PrimaryKey;
use MilesAsylum\SchnoopSchema\MySQL\Constraint\Index;
use MilesAsylum\SchnoopSchema\MySQL\Constraint\IndexedColumn;

// ...

// Add a primary key
$pkIndex = new PrimaryKey();
$pkIndex->addIndexedColumn(
    new IndexedColumn($idColumn->getName())
);
$table->addIndex($pkIndex);

// Add an index on the first 8 characters of the name column.
$nameIndexedColumn = new IndexedColumn($nameColumn->getName());
$nameIndexedColumn->setLength(8);
$nameIndex = new Index('name_idx');
$nameIndex->addIndexedColumn($nameIndexedColumn);
$table->addIndex($nameIndex);

待办事项

  • 添加对视图的支持。