转载于:http://www.cnblogs.com/gomysql/p/6007013.html

大家都知道在MySQL里面是非常easy的,show create table table_name 就搞定了,在gpdb里面就没这么容易,在查询大量资料以后终于找到了方法。那就是自己定义一个函数去获取,函数中可以嵌套python代码,非常的方便。但是资料中的代码有大量错误,在经过几番调试以后终于可以使用了。

1. 创建语言

CREATE PROCEDURAL LANGUAGE plpythonu; -- 已经创建了可忽略

2. 创建函数(代码如下):

create or replace function get_table_structure(tablename text)    # 表名格式为 tableschema.table_namereturns text
as $$try:table_name = tablename.lower().split('.')[1]talbe_schema=tablename.lower().split('.')[0]except (IndexError):return 'Please in put "tableschema.table_name"'get_table_oid="select oid,reloptions,relkind from pg_class where oid='%s'::regclass"%(tablename)try:rv_oid=plpy.execute(get_table_oid,5)      #plpy.execute(query [, max-rows])if not rv_oid:return 'Did not find any relation named"'+tablename +'".'except (Error):return 'Did not find any relation named"'+tablename +'".'table_oid=rv_oid[0]['oid']rv_reloptions=rv_oid[0]['reloptions'] # 访问方法特定的选项,使用"keyword=value"格式的字符串
rv_relkind=rv_oid[0]['relkind']create_sql="";table_kind='table';if rv_relkind !='r' and rv_relkind !='v':  # r:普通表, v:视图, c:复合类型, t:表, o:内部 AO 节点文件, plpy.error('%s is not table or view'%(tablename));elif rv_relkind=='v':get_view_def="select pg_get_viewdef(%s,'t') as viewdef;" % (table_oid)rv_viewdef=plpy.execute(get_view_def);create_sql='create view %s as \n' % (tablename)create_sql += rv_viewdef[0]['viewdef']+'\n';table_kind='view'else:
#获取行
get_columns="select a.attname,pg_catalog.format_type(a.atttypid,a.atttypmod),\(select substring(pg_catalog.pg_get_expr(d.adbin,d.adrelid) for 128) \from pg_catalog.pg_attrdef d where d.adrelid=a.attrelid and d.adnum=a.attnum and a.atthasdef) \as default,a.attnotnull as isnull from pg_catalog.pg_attribute \a where a.attrelid= %s and a.attnum >0 and not a.attisdropped order by a.attnum;" % (table_oid);rv_columns=plpy.execute(get_columns)#获取分布键get_table_distribution1="select attrnums from pg_catalog.gp_distribution_policy t where localoid = '" + table_oid + "' "rv_distribution1=plpy.execute(get_table_distribution1,500)rv_distribution2=''if rv_distribution1 and rv_distribution1[0]['attrnums']:get_table_distribution2="select attname from pg_attribute where attrelid='"+table_oid+"' and attnum in (" + str(rv_distribution1[0]['attrnums']).strip('{').strip('}').strip('[').strip(']')+")"rv_distribution2=plpy.execute(get_table_distribution2,500)create_sql='create table %s (\n' % (tablename)
#获取索引
get_index="select pg_get_indexdef(indexrelid) as indexdef from pg_index where indrelid=%s" % (table_oid);rv_index=plpy.execute(get_index);get_parinfo1="select attname as columnname from pg_attribute where attnum =(select paratts[0] from pg_partition where parrelid=%s) and attrelid=%s;"%(table_oid,table_oid);get_parinfo2=""" select pp.parrelid,prl.parchildrelid,case when pp.parkind='h'::"char" then 'hash'::text when pp.parkind='r'::"char" then 'range'::text when pp.parkind='l'::"char" then 'list'::text else null::text end as partitiontype,pg_get_partition_rule_def(prl.oid,true) as partitionboundary from pg_partition pp,pg_partition_rule prl where pp.paristemplate=false and pp.parrelid = %s and prl.paroid = pp.oid order by prl.parname; """ % (table_oid)v_par_parent=plpy.execute(get_parinfo1);v_par_info=plpy.execute(get_parinfo2);max_column_len=10max_type_len=4max_modifiers_len=4max_default_len=4for i in rv_columns:if i['attname']:if max_column_len < i['attname'].__len__():max_column_len=i['attname'].__len__()if i['format_type']:if max_type_len < i['format_type'].__len__():max_type_len=i['format_type'].__len__()if i['default']:if max_type_len < i['default'].__len__():max_default_len=i['default'].__len__()first=Truefor i in rv_columns:if first==True:split_char=' ';first=Falseelse:split_char=',';if i['attname']:create_sql += " " + split_char + i['attname'].ljust(max_column_len+6)+''else:create_sql += "" + split_char + ' '.ljust(max_column_len+6)if i['format_type']:create_sql += ' ' + i['format_type'].ljust(max_type_len +2)else:create_sql += ' ' + ' '.ljust(max_type_len+2)if i['isnull'] and i['isnull']:create_sql += ' ' + ' not null '.ljust(8)if i['default']:create_sql += ' default ' + i['default'].ljust(max_default_len+6)create_sql += "\n"create_sql += ")"if rv_reloptions:create_sql +=" with ("+str(rv_reloptions).strip('{').strip('}').strip('[').strip(']') +")\n"create_sql = create_sql.replace("'",'')if rv_distribution2:create_sql += 'Distributed by ('for i in rv_distribution2:create_sql += i['attname'] + ','create_sql =create_sql.strip(',')+')'elif rv_distribution1:create_sql += 'Distributed randomly\n'if v_par_parent:partitiontype=v_par_info[0]['partitiontype'];create_sql +='\nPARTITION BY '+ partitiontype + "("+v_par_parent[0]['columnname']+")\n(\n";for i in v_par_info:create_sql +=" " +i['partitionboundary']+',\n';create_sql=create_sql.strip(',\n');create_sql+="\n)"create_sql+=";\n\n"for i in rv_index:create_sql += i['indexdef']+';\n'get_table_comment="select 'comment on %s %s is '''|| COALESCE (description,'')|| '''' as comment from pg_description where objoid=%s and objsubid=0;" % (table_kind,tablename,table_oid)get_column_comment="select 'comment on column %s.'||b.attname ||' is ''' || COALESCE(a.description,'')|| ''' ' as comment from pg_catalog.pg_description a,pg_catalog.pg_attribute b where objoid=%s and a.objoid=b.attrelid and a.objsubid=b.attnum;" % (tablename,table_oid)rv_table_comment=plpy.execute(get_table_comment);rv_column_comment=plpy.execute(get_column_comment);for i in rv_table_comment:create_sql += i['comment']+';\n'for i in rv_column_comment:create_sql +=i['comment']+';\n'return create_sql;$$ LANGUAGE plpythonu;

3. 进行测试

testdb=# SELECT get_table_structure('public.tb1_partition_range_yyyymmdd');get_table_structure
-------------------------------------------------------------------------------------------------------------------create table public.tb1_partition_range_yyyymmdd (                                                                id               numeric                                                                                        ,yyyymmdd         date                                                                                           ) with (appendonly=true, compresslevel=5)                                                                         Distributed by (id)                                                                                               PARTITION BY range(yyyymmdd)                                                                                      (                                                                                                                 PARTITION p20120811 START ('2012-08-11'::date) END ('2012-08-12'::date) WITH (appendonly=true, compresslevel=5), PARTITION p20120812 START ('2012-08-12'::date) END ('2012-08-13'::date) WITH (appendonly=true, compresslevel=5)  );                                                                                                                CREATE INDEX idx_yyyymmdd ON tb1_partition_range_yyyymmdd USING btree (yyyymmdd);                                 (1 row)

【greenplum】 获取表结构,实现类似mysql show create table 功能相关推荐

  1. MySQL中create table as VS create table like

    create table as:说明:复制表结构和数据用法:create table new_table as select * from old_table;create table new_tab ...

  2. MySql 、Oracle 获取表结构和字段信息

    MySql获取表结构信息 SELECTTABLE_NAME,TABLE_COMMENT FROMinformation_schema.`TABLES` WHERETABLE_SCHEMA = 'dm' ...

  3. 【MySQL】如何使用SQL语句获取表结构和获取全部表名

    目录 一.业务背景 二.如何获取全部表名 三.如何获取表结构 四.总结 一.业务背景 在实际的业务需求中,我们经常需要拿到数据库的全部表名,展示在后台中或者输出到文件里. 具体到业务中的需求比如: 导 ...

  4. Java--通过JDBC元数据获取表结构(ResultSetMetaData元数据的使用)

    最近在线上联调,由于我们没有数据库的可视化工具,和其他公司比对数据和表结构总是十分麻烦.后来我看到组长通过元数据来获取表结构和值.之后我自学了一下,感觉十分方便,分享给大家. jdbc的元数据有两类. ...

  5. MySQL 的create table as 与like 的使用

    1.MySQL复制相同表结构的方法: -- 1.使用AS复制相同的表结构CREATE TABLE table_name AS SELECT * FROM other_table WHERE 1=2;( ...

  6. C++MYSQL:获取表结构:MYSQL_FEILD

    这里给出获取表的结构的API.把表的字段描述作为列的形式,动态地显示. 在前面的mysql的连接中,提到一个参数是是否返回表的结构信息.可以通过mysql_options来关闭.使用的关键字为: MY ...

  7. 快速生成sparksql创建carbondata表结构(同步mysql或sqlserver数据)脚本

    前言 当实时同步mysql或sqlserver很多表数据到carbondata时,经常要手动调整脚本涉及到的每个表的字段.类型及对应建表语句,耗费大量的机械比对粘贴复制工作时间.精力,下面介绍的脚本能 ...

  8. A.CTable开源框架Mybatis增强自动创建表/更新表结构/实现类似hibernate共通的增删改查-mybatis-enhance-actable

    mybatis-enhance-actable-1.3.1.RELEASE 项目已更新既支持传统Spring项目也支持Springboot项目,同时支持tk.mybatis能够支持更强大的CUDR(为 ...

  9. SQL SERVER 获取表结构信息《转载》

    获取表信息 SELECT      表名       = case when a.colorder=1 then d.name else '' end,      表说明     = case whe ...

最新文章

  1. 22w+的人选择了这款蓝牙耳机
  2. 这样给面试官解释约瑟夫环问题的几种巧妙解法,面试官满意的笑了
  3. maya导入abc动画_三维文件格式知多少 | abc、glTF、fbx、obj、dae、stl、3ds...
  4. 重磅开源!目标检测新网络 DetectoRS:54.7 AP,特征金字塔与空洞卷积的完美结合
  5. Oracle里PO自动售货如何做,Oracle R12采办接收流程(PR-PO-RCV-AP-Payment)
  6. Aggregate functions cannot be used in the select right after the flatAggregate
  7. java list初始值null_关于list集合存储null的问题
  8. Python中使用Redis的批处理工具pipeline(这种方法从底层思考效率还是低于“订阅发布机制”)
  9. 移动开发技术有哪些?
  10. 美国最受欢迎的电商网站,竟然是一家中国公司?
  11. 基于XAMPP的Testlink安装方法
  12. 在本地搭建hyperledger fabric 网络
  13. 安装 | MATLAB2018a (64位) 安装教程及安装包下载链接
  14. 2000G视频资料送带资源账号
  15. ubuntu串口调试工具RS485
  16. vant实现Select效果--单选和多选
  17. 同学们上课,今天我们学习:UI 操作一定要在 UI 线程吗?
  18. 波动方程,达朗贝尔解和亥姆霍兹方程
  19. Mac 搭建Appium自动化测试环境
  20. 计算机动作路径教案,《引导路径动画》教案

热门文章

  1. 永远的友谊_友谊的传递属性-温馨介绍的重要性
  2. 【Java】If you want an embedded database (H2, HSQL or Derby), please put it on the classpath.
  3. WIN32API串口接收数据简单测试
  4. 汉字转拼音之Jpinyin 简单使用
  5. C语言编程————杨辉三角
  6. 学习笔记——深蓝学院点云系列公开课05:3D物体检测的发展与未来
  7. linux硬盘识别过程
  8. 高品质蓝牙耳机排行榜,值得入手的四款蓝牙耳机分享
  9. 【HDR学习】HDR视频相关知识讲解(一)
  10. 怎么样在应用中实现自助报表功能