星期二, 10月 21, 2008

[Note]以 bash script 為 sqlite database 產生 C/C++ struct

最近寫的一個 bash script,用來幫你把 sqlite database 裡的 table schema 轉成 C/C++ struct。
這裡只處理 text 與 integer 型態,text 轉成 wstring/string,integer 則轉為 int。轉換的工具是使用 awk/sed。

只要稍稍改動一下,也適用在其他語言上。

#!/bin/bash
if test -z "$1"
then
echo "You need to specify the database file name."
exit -1
fi

db=$1
dbname=`basename $1 .db`
tables=`sqlite3 $db ".table"`
output="db_${dbname}_schema.h"

touch $output

cat >> $output << EOF
#ifndef __db_${dbname}_schema_h__
#define __db_${dbname}_schema_h__

#include <string>

#ifdef _UNICODE
typedef std::wstring db_string;
#else
typedef std::string db_string;
#endif

EOF

for table in $tables
do
echo "typedef struct {" >> $output
sqlite3 $db ".schema $table" | awk '/^\ /{printf("%s %s;",$2,$1);}' | sed -e 's/,/\ /g' | sed -e 's/text/db_string /g' | sed -e 's/integer/int /g' >> $output
struct_name=`echo $table | awk -f cap.awk`
echo "}$struct_name;" >> $output
echo "" >> $output
done

cat >> $output << EOF
#endif
EOF

# call "astyle" to format the code. Beside "astyle", you can use "indent".
astyle $output

exit 0

沒有留言: