从Hive表生成DDL,并将每个DDL写入不同的.txt文件

时间:2019-05-31 20:59:15

标签: php python sql linux hive

我正在尝试学习如何为Hive的给定数据库中的所有表自动创建DDL。

例如,我有一个名为abc_db的数据库。我编写了一个Hive脚本,将所有表写入一个名为abc_db.txt的文件中。文件中的输出是abc_db内的所有表逐行显示。

 `hive -e 'show tables in abc_db' > abc_db.tx`t

我希望能够遍历其所有表并将每个表的DDL及其各自的表名写入我的目录。

这是我的起点:

hive -e "show tables in abc_db" > d.txt

cat d.txt | while read LINE;
do
  echo "## Table Name:" $LINE
  mkdir $LINE
  cd $LINE
  eval "hive -e 'show create table in $LINE' | grep -v ^$ | grep -v Logging | grep -v tab_name | tee $LINE.tables.txt"
done

鉴于以上信息,关于如何自动从表中生成所有DDL并将每个DDL写入单独文件的任何想法或起点?

1 个答案:

答案 0 :(得分:1)

根据需要进行调整。将源模式(处理模式中的所有表)和输出目录作为参数。

脚本:gen-ddl

#!/bin/bash
SCHEMA="$1"
OUTDIR="$2"
if [[ $# -ne 2 ]]; then
  echo "Usage: $0 <schema-name> <out-dir>"
  exit 1
fi
mkdir -p "$OUTDIR"
TABLES=$(hive -e "show tables in $SCHEMA;")
for TABLE in $TABLES; do
  DDL_FILE="$OUTDIR/$TABLE-create-ddl.sql"
  echo -e "Generating DDL ...\n... table: $TABLE\n... file:  $DDL_FILE"
  hive -e "show create table $SCHEMA.$TABLE" > "$DDL_FILE"
done
echo "Done."

用法:

$ ./gen-ddl <schema-name> <out-dir>