30

go模板-代码生成器

 4 years ago
source link: http://www.cnblogs.com/li-peng/p/12972016.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

能用程序去做的事,就不要用手,编写自己的代码生成器就是用来解放你的双手,替你做一些重复性的工作。

上篇帖子写了模板的基础go模板详说 ,有了基础就要做点什么东西,把所学到的东西应用起来才能更好的进步。于是用模板写了一个代码生成器,用于把数据库的表转换成 gostruct ,目前支持 MySQLPostgreSQL 。这篇帖子写实现的思路和一些具体的代码实现。

Github地址: yggdrasill

看一下效果

r2qeEzb.gif

大概的思路:

go

组织元数据

这里的 元数据 也就是数据库的表信息,由于 MySQLPostgreSQL 得到表和列信息的实现方式不同,但是最终的数据结构是一致的,就写了一个统一的接口来获取元数据信息。

uMrUJna.png!web

MySQL

MySQLinformation_schema.tables 得到一个数据库下的所有表

select table_name from information_schema.tables where table_schema = ? and table_type = 'base table';

如果只想查询指写的表,只需添加 table_name in 查询条件就行。

表的列信息从 information_schema.columns 获取

select column_name, is_nullable, if(column_type = 'tinyint(1)', 'boolean', data_type), column_type like '%unsigned%' from information_schema.columns where table_schema = ? and  table_name = ? order by ordinal_position;

PostgreSQL

PostgreSQL 也是从 information_schema.tables 获取表信息,不同的是,不需要指定数据库的名字,但 MySql 需要,感觉还是 PostgreSQL 更合理一些,因为在连接数据库的 dsn 里已经指定了要操作的 db

select table_name from information_schema.tables where table_schema = 'public';

表的列信息从 information_schema.columns 获取

select column_name, is_nullable, data_type, false
from information_schema.columns where table_schema = 'public' and table_name = $1 order by ordinal_position;

类型转换

从数据库里获取完表和列的信息后,就要把数据库的类型转换成 go 相关的类型。

需要考虑的是是否有些类型要特殊处理,或自定义,特殊处理后的类型是否需要在 import 里加上具体的导入。

方法 getGoType 把得到的数据库类型进行对比,返回go的类型。

aERZf2I.png!web

模板

先看一下模板的代码,里面的知识点上篇帖子都有说过

JnqQNzU.png!web

主要就是包名称、是否有import、结构体信息

import 应该是会用到的,有用到时间类型就需要 import time ,还有前面说的,注意自定义的类型的导入。

还有一点就是这个 Tag ,由于模板的功能还不够丰富,就完全用方法去实现了

b6ZBnuz.png!web

看一下生成的效果

IZJJVrV.png!web

也可以根据你的业务对这个库进行扩展,由于项目不让用 orm 完全手写 sql ,我就根据自己的业务进行了扩展,把 dao 层的也实现了。

auAbumZ.png!web

一定要用模板实现么?当然不是,可以用你喜欢的方式去实现,只是正好阅读了模板的官方文档,就用他做了实现。

Github地址: yggdrasill


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK