获得mysql、postgresql元数据信息
源于最近新的需求需要一个新功能,需要获得元数据表的信息,包括comment等,展示在页面上。
mysql
-- 查询当前库有多少个表
select
count(*)
from information_schema.tables
where
table_schema = (select database())
-- 查询所有的表及其元数据信息
select
table_name tableName,
engine,
table_comment tableComment,
create_time createTime
from information_schema.tables
where
table_schema = (select database())
-- 获得表的所有列的元数据信息
select
column_name columnName,
data_type dataType,
column_comment columnComment,
column_key columnKey, extra
from information_schema.columns
where
table_name = 'emp'
and table_schema = (select database())
order by ordinal_position
-- 获得表的引擎和注释
select
table_name tableName,
engine,
table_comment tableComment,
create_time createTime
from information_schema.tables
where
table_schema = (select database())
and table_name = 'emp'
postgresql
postgresql比较特殊一点,因为postgresql使用了namespace的概念,可能同一个库中不同的namesespace有两个表明一样的表:
-- 查询某个命名空间的所有的表名
select tablename from pg_tables where schemaname = 'public'
-- 查询某个命名空间所有的表的注释信息
select
relname as "name",
obj_description(oid) as "comment"
from pg_class
where
obj_description(relnamespace) like '%public%'
-- and relname = 't_yl_hjdm' -- 需要指定某个表的时候给表名的条件
-- 查询某个命名空间的某个表的所有列的元数据信息
-- 两个函数的用法参考官方文档:https://www.postgresql.org/docs/10/functions-info.html
-- 关于存储表和列元数据的信息文档:https://www.postgresql.org/docs/10/catalogs.html
select
col_description(pa.attrelid, pa.attnum) as "comment",
format_type(pa.atttypid, pa.atttypmod) as "type",
pa.attname as "name"
from pg_class as pc, pg_attribute as pa, pg_namespace as pn
where
pa.attrelid = pc.oid
and pn.nspname = 'public'
and pc.relname = 't_yl_hjdm'
and col_description(pa.attrelid, pa.attnum) is not null
参考:
postgresql文档:https://www.postgresql.org/docs/10/index.html