为什么须要数据字典

通过Navicat等数据库管理工具,咱们也能看到数据表的结构设计,然而,如果咱们把全副的数据表的结构设计都做成可在线预览的,会不会更加清晰清朗呢,而且也更加容易比照发现问题和及时优化,更有效率。

生成数据字典的形式

这里我次要利用showdoc在线文档实现数据字典的在线查看,次要说两种实现形式:别离是官网shell脚本和我写的PHP脚本;

  • 官网shell脚本:仅反对在Linux服务器中运行,官网的文档地址:https://www.showdoc.com.cn/page/312209902620725
  • 我写的PHP脚本:不论是在Linux还是在Windows等操作系统中都反对,而且更加灵便可控

官网的脚本运行形式也比较简单,看看文档即明确,我上面次要说一下我写的PHP脚本的思路和运行形式,也就是利用showdoc提供的凋谢API接口实现将数据结构的信息以Markdown的格局上传到指定我的项目,文档地址:https://www.showdoc.com.cn/page/102098

要害信息配置

因为连贯数据库的配置信息以及须要上传的我的项目地址也不同,所以这些信息须要独自配置,具体我也不多说了,看上面代码及正文信息即可

// 数据库连贯配置信息private $host = '127.0.0.1';private $user_name = 'root';private $password = 'root';private $db_name = 'test';private $port = 3306;private $conn;// showdoc文档API密钥配置,获取办法:https://www.showdoc.com.cn/page/741656402509783private $api_key = '6b0ddb543b53f5002f6033cb2b00cec01908536369';private $api_token = '9da3190d0dda1118de0e8bde08907fc51712469974';

连贯和敞开MySQL数据库

为了不便疾速跨平台应用,我应用的都是PHP原生的写法,所以,连贯数据库以及查问数据都是应用原生的PHP写法,利用PHP类的语法个性,在构造函数中连贯数据库并且在析构函数中敞开连贯。

/** * 构造函数,连贯数据库 * GetMysqlDict constructor. */public function __construct(){    // 创立连贯    $this->conn = new mysqli($this->host, $this->user_name, $this->password, $this->db_name, $this->port);    // 检测连贯    if ($this->conn->connect_error) {        exit("数据库连贯失败: " . $this->conn->connect_error);    }    $this->echoMsg('数据库连贯胜利');}/** * 析构函数,敞开数据库连贯 */public function __destruct(){    $this->conn->close();    $this->echoMsg('已敞开数据库连贯');}

查问表构造信息

连贯上了数据库,那么咱们就能够查问利用Sql语句数据库信息相干信息,利用语句show table status;能够查出以后连贯库的全副数据表信息,而后再查问information_schema.COLUMNS表上具体某个表的数据结构信息,并组装数组返回应用。

/** * 获取数据表列表 * @return array */private function getTableList(){    // 查看所有表信息    $sql = 'show table status;';    $result = $this->conn->query($sql);    // 循环获取表数据    $table_list = array();    while ($row = $result->fetch_assoc()) {        $table_list[] = $row;    }    return $table_list;}/** * 获取表构造信息 * @param string $table * @return array */private function getDictList($table = ''){    // 获取表构造信息(COLUMN_NAME,COLUMN_TYPE,NUMERIC_SCALE,IS_NULLABLE,COLUMN_DEFAULT,COLUMN_COMMENT)    $sql = "select * from information_schema.COLUMNS where table_schema='" . $this->db_name . "' and table_name='" . $table . "';";    $result = $this->conn->query($sql);    $dict_list = array();    while ($row = $result->fetch_assoc()) {        $dict_list[] = $row;    }    return $dict_list;}

通过API接口上传到我的项目

获取到表的数据结构信息,咱们就能够拼装字段信息,并且通过凋谢API接口上传到执行的我的项目中,大家能够看我的一个测试的我的项目https://www.showdoc.com.cn/1383736300665067,大家须要上传到本人的我的项目,只须要依照下面的阐明批改相干配置即可,如果不想上传到showdoc官网的域名,能够本人利用开源代码搭建到本人的服务器上,而后部署好,上传到本人搭建的我的项目中也能够,具体能够查看相干的文档。

/** * 发送接口申请,生成文档 * @param string $title 页面题目(请保障其惟一) * @param string $content 页面内容(反对Markdown和HTML) * @param string $name 目录名(可选参数) * @param int $number 页面序号(默认99,越小越靠前) * @return array */private function apiPost($title = '', $content = '', $name = '', $number = 99){    // 接口地址,如果是本人利用开源搭建的,则接口地址为:http://xx.com/server/index.php?s=/api/item/updateByApi    $url = 'https://www.showdoc.cc/server/api/item/updateByApi';    // 申请参数    $data = array(        'api_key' => $this->api_key,        'api_token' => $this->api_token,        'cat_name' => $name,        'page_title' => $title,        'page_content' => $content,        's_number' => $number    );    // 发送POST申请    $ch = curl_init();    curl_setopt($ch, CURLOPT_POST, 1);    curl_setopt($ch, CURLOPT_HEADER, 0);    curl_setopt($ch, CURLOPT_URL, $url);    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);    curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);    $response = curl_exec($ch);    curl_close($ch);    return json_decode($response, true);}

脚本执行外围解决

下面的数据获取以及上传办法有了,那么就能够将全副的表构造字段进行循环解决,拼装成Markdown的格局,上传到我的项目中。凋谢API接口有申请频率限度,也就是10分钟只能申请1000次,所以,如果单次申请过多的话,须要做频率管制,避免申请失败,未能胜利上传到我的项目中。

/** * 执行入口 */public function run(){    // 获取数据表    $table_list = $this->getTableList();    $this->echoMsg('数据表总数:' . count($table_list));    // 循环表获取构造信息    $request_num = 0;    foreach ($table_list as $table) {        // 频率管制,10分钟内只能申请1000次        if ($request_num >= 1000) {            $request_num = 0;            $this->echoMsg('频率管制,请期待10分钟后持续');            sleep(600);        }        // 获取数据结构        $msg = '表名:' . $table['Name'] . '(' . $table['Comment'] . ')';        // 字典表头信息        $table_dict = '#### ' . $table['Name'] . ' ' . $table['Comment'] . PHP_EOL;        $table_dict .= '| 字段名称 | 类型长度 | 是否NULL | 默认值 | 正文 |' . PHP_EOL;        $table_dict .= '| --- | --- | --- | --- | --- |' . PHP_EOL;        // 获取表字段信息        $dict_list = $this->getDictList($table['Name']);        foreach ($dict_list as $dict) {            $c_name = $dict['COLUMN_NAME'];            $c_type = $dict['COLUMN_TYPE'];            $c_null = $dict['IS_NULLABLE'];            $c_default = $dict['COLUMN_DEFAULT'];            $c_comment = $dict['COLUMN_COMMENT'];            $table_dict .= '| ' . $c_name . ' | ' . $c_type . ' | ' . $c_null . ' | ' . $c_default . ' | ' . $c_comment . ' |' . PHP_EOL;        }        // 利用showdoc文档在线展现数据字典        $response = $this->apiPost($table['Name'], $table_dict);        if ($response['error_code'] == 0) {            $msg .= ' 生成文档胜利';        } else {            $msg .= ' 生成文档失败(' . $response['error_message'] . ')';        }        $request_num++;        $this->echoMsg($msg);    }}

残缺源码

下面的拆分局部,根本曾经把外围的代码都列出来了,然而为了大家更方便快捷的应用以及反馈问题,一键复制残缺源码间接运行,我把代码上传到交友网站了Github,同时,也把残缺源码贴在上面,请叫我当代活雷锋……(我也不容易,别吐槽我用代码占用大量篇幅了)

<?php/** * 主动生成数据字典上传到showdoc我的项目中 * User: gxcuizy * Date: 2021/05/10 0011 * Time: 下午 15:17 * Class GetMysqlDict */class GetMysqlDict{    // 数据库连贯配置信息    private $host = '127.0.0.1';    private $user_name = 'root';    private $password = 'root';    private $db_name = 'test';    private $port = 3306;    private $conn;    // showdoc文档API密钥配置,获取办法:https://www.showdoc.com.cn/page/741656402509783    private $api_key = '6b0ddb543b53f5002f6033cb2b00cec01908536369';    private $api_token = '9da3190d0dda1118de0e8bde08907fc51712469974';    /**     * 构造函数,连贯数据库     * GetMysqlDict constructor.     */    public function __construct()    {        // 创立连贯        $this->conn = new mysqli($this->host, $this->user_name, $this->password, $this->db_name, $this->port);        // 检测连贯        if ($this->conn->connect_error) {            exit("数据库连贯失败: " . $this->conn->connect_error);        }        $this->echoMsg('数据库连贯胜利');    }    /**     * 执行入口     */    public function run()    {        // 获取数据表        $table_list = $this->getTableList();        $this->echoMsg('数据表总数:' . count($table_list));        // 循环表获取构造信息        $request_num = 0;        foreach ($table_list as $table) {            // 频率管制,10分钟内只能申请1000次            if ($request_num >= 1000) {                $request_num = 0;                $this->echoMsg('频率管制,请期待10分钟后持续');                sleep(600);            }            // 获取数据结构            $msg = '表名:' . $table['Name'] . '(' . $table['Comment'] . ')';            // 字典表头信息            $table_dict = '#### ' . $table['Name'] . ' ' . $table['Comment'] . PHP_EOL;            $table_dict .= '| 字段名称 | 类型长度 | 是否NULL | 默认值 | 正文 |' . PHP_EOL;            $table_dict .= '| --- | --- | --- | --- | --- |' . PHP_EOL;            // 获取表字段信息            $dict_list = $this->getDictList($table['Name']);            foreach ($dict_list as $dict) {                $c_name = $dict['COLUMN_NAME'];                $c_type = $dict['COLUMN_TYPE'];                $c_null = $dict['IS_NULLABLE'];                $c_default = $dict['COLUMN_DEFAULT'];                $c_comment = $dict['COLUMN_COMMENT'];                $table_dict .= '| ' . $c_name . ' | ' . $c_type . ' | ' . $c_null . ' | ' . $c_default . ' | ' . $c_comment . ' |' . PHP_EOL;            }            // 利用showdoc文档在线展现数据字典            $response = $this->apiPost($table['Name'], $table_dict);            if ($response['error_code'] == 0) {                $msg .= ' 生成文档胜利';            } else {                $msg .= ' 生成文档失败(' . $response['error_message'] . ')';            }            $request_num++;            $this->echoMsg($msg);        }    }    /**     * 获取数据表列表     * @return array     */    private function getTableList()    {        // 查看所有表信息        $sql = 'show table status;';        $result = $this->conn->query($sql);        // 循环获取表数据        $table_list = array();        while ($row = $result->fetch_assoc()) {            $table_list[] = $row;        }        return $table_list;    }    /**     * 获取表构造信息     * @param string $table     * @return array     */    private function getDictList($table = '')    {        // 获取表构造信息(COLUMN_NAME,COLUMN_TYPE,NUMERIC_SCALE,IS_NULLABLE,COLUMN_DEFAULT,COLUMN_COMMENT)        $sql = "select * from information_schema.COLUMNS where table_schema='" . $this->db_name . "' and table_name='" . $table . "';";        $result = $this->conn->query($sql);        $dict_list = array();        while ($row = $result->fetch_assoc()) {            $dict_list[] = $row;        }        return $dict_list;    }    /**     * 发送接口申请,生成文档     * @param string $title 页面题目(请保障其惟一)     * @param string $content 页面内容(反对Markdown和HTML)     * @param string $name 目录名(可选参数)     * @param int $number 页面序号(默认99,越小越靠前)     * @return array     */    private function apiPost($title = '', $content = '', $name = '', $number = 99)    {        // 接口地址,如果是本人利用开源搭建的,则接口地址为:http://xx.com/server/index.php?s=/api/item/updateByApi        $url = 'https://www.showdoc.cc/server/api/item/updateByApi';        // 申请参数        $data = array(            'api_key' => $this->api_key,            'api_token' => $this->api_token,            'cat_name' => $name,            'page_title' => $title,            'page_content' => $content,            's_number' => $number        );        // 发送POST申请        $ch = curl_init();        curl_setopt($ch, CURLOPT_POST, 1);        curl_setopt($ch, CURLOPT_HEADER, 0);        curl_setopt($ch, CURLOPT_URL, $url);        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);        curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);        $response = curl_exec($ch);        curl_close($ch);        return json_decode($response, true);    }    /**     * 打印输出信息     * @param string $msg     */    private function echoMsg($msg = '')    {        if (!empty($msg)) {            $msg = "[" . date("Y-m-d H:i:s") . "] " . $msg . PHP_EOL;            echo $msg;            @ob_flush();            @flush();        }    }    /**     * 析构函数,敞开数据库连贯     */    public function __destruct()    {        $this->conn->close();        $this->echoMsg('已敞开数据库连贯');    }}// 实例化类并执行$obj = new GetMysqlDict;$obj->run();

最初

任何的工具,都是为了不便你我他,心愿大家能相处更多更好的工具以及方法,更好更快的实现工作内容,大家有什么好的想法也能够和我分享,一起集思广益,发现问题并及时解决,谢谢。