mhd-jalilvand/php-dbml-parser

数据库标记语言(dbml)的PHP解析器

1.0.3 2020-02-17 16:07 UTC

This package is auto-updated.

Last update: 2024-09-18 02:42:02 UTC


README

解析数据库标记语言(DBML)

您可以使用Diagram.io来可视化设计您的数据库图,并将代码写入文件,然后使用此脚本来解析它。

安装和示例代码

composer require mhd-jalilvand/php-dbml-parser
cp  vendor/mhd-jalilvand/php-dbml-parser/example.php example.php
cp  vendor/mhd-jalilvand/php-dbml-parser/tests -r tests
php  example.php
phpunit tests/ParserTest.php

使用方法

tests/test.dbml包含以下示例数据库模式

table posts {
  id int [pk, increment]
  title varchar [not null]
}

table comments {
  id int [pk,increment]
  comment varchar 
  post_id int [not null,ref: > posts.id]
}
table tags{
  id int [pk, increment, not null]
  title varchar [not null]
}

table post_tags{
  id int [pk]
  post_id int
  tag_id int
}




Ref: "tags"."id" < "post_tags"."tag_id"

Ref: "posts"."id" < "post_tags"."post_id"

示例代码

<?php
require 'vendor/autoload.php';
use DbmlParser\Parser;
$parser = new Parser('tests/test.dbml');
foreach($parser->tables as $table){
  echo $table->name.':'.PHP_EOL;
  foreach($table->columns as $column){
    echo "\t".json_encode($column).PHP_EOL;
  }
}
echo 'Relations:'.PHP_EOL;
foreach($parser->relations as $relation){
  echo $relation->table->name.'.'.$relation->column->name;
  echo ' '.$relation->type.' ';
  echo $relation->foreign_table->name.'.'.$relation->foreign_column->name.PHP_EOL;
}

结果

posts:
        {"name":"id","type":"int","PK":true,"NotNull":null,"Increment":true,"comment":null}
        {"name":"title","type":"varchar","PK":null,"NotNull":true,"Increment":null,"comment":null}
comments:
        {"name":"id","type":"int","PK":true,"NotNull":null,"Increment":true,"comment":null}
        {"name":"comment","type":"varchar","PK":null,"NotNull":null,"Increment":null,"comment":null}
        {"name":"post_id","type":"int","PK":null,"NotNull":null,"Increment":null,"comment":null}
tags:
        {"name":"id","type":"int","PK":true,"NotNull":true,"Increment":null,"comment":null}
        {"name":"title","type":"varchar","PK":null,"NotNull":true,"Increment":null,"comment":null}
post_tags:
        {"name":"id","type":"int","PK":true,"NotNull":null,"Increment":null,"comment":null}
        {"name":"post_id","type":"int","PK":null,"NotNull":null,"Increment":null,"comment":null}
        {"name":"tag_id","type":"int","PK":null,"NotNull":null,"Increment":null,"comment":null}
Relations:
tags.id < post_tags.tag_id
posts.id < post_tags.post_id
comments.post_id > posts.id