piped target added for multiple select
[brisk.git] / sql / builder.sh
1 #! /bin/bash
2
3 #
4 #  all this part is from mopshop and we will use it to construct the brisk database
5 #
6 DBHOST=127.0.0.1
7 DBUSER=brisk
8 DBBASE=brisk
9 DBPASS=briskpass
10 PFX="bsk_"
11
12 if [ -f $HOME/.brisk_install ]; then
13    . $HOME/.brisk_install
14 fi
15
16 sqlexe () {
17     local sht
18     sht=$1
19     
20     if [ $sht -eq 1 ];  then 
21         sed "s/#PFX#/$PFX/g" | psql -a -h $DBHOST -U $DBUSER $DBBASE 2>&1 | egrep 'ERROR|^-- MESG' 
22     else
23         sed "s/#PFX#/$PFX/g" | psql -a -h $DBHOST -U $DBUSER $DBBASE
24     fi
25
26     return 0
27 }
28
29 one_or_all() {
30     if [ "$1" = "" ]; then
31         cat sql.d/*.sql
32     else
33         cat "$1"
34     fi
35 }
36
37 #
38 # MAIN
39 #
40 sht=0
41 if [ -f $HOME/.db.conf ]; then
42     source $HOME/.db.conf
43 fi
44
45 if [ "$1" = "-s" ]; then
46     shift
47     sht=1
48 fi
49
50 if [ "$1" = "create" ]; then
51     echo "su root" 
52     su root -c "su postgres -c \"echo \\\"DBUser passwd: $DBPASS\\\" ; createuser -S -D -R -P $DBUSER && createdb -E utf8 -O $DBUSER $DBBASE\"" 
53 elif [ "$1" = "destroy" ]; then
54     echo "su root" 
55     su root -c "su postgres -c \"dropdb $DBBASE && dropuser $DBUSER\"" 
56 elif [ "$1" = "clean" ]; then
57     ( echo "-- MESG: clean start" ; one_or_all $2 | grep -i '^drop' | tac ; echo "-- MESG: clean end" ;   ) | sqlexe $sht
58 elif [ "$1" = "build" ]; then
59     ( echo "-- MESG: build start" ; one_or_all $2 | grep -iv '^drop' ; echo "-- MESG: build end" ;   ) | sqlexe $sht
60 elif [ "$1" = "rebuild" ]; then
61     ( echo "-- MESG: clean start" ; one_or_all $2 | grep -i '^drop' | tac ; echo "-- MESG: clean end" ; \
62       echo "-- MESG: build start" ; one_or_all $2 | grep -iv '^drop' ; echo "-- MESG: build end" ;   ) \
63         | sqlexe $sht
64 elif [ "$1" = "psql" ]; then
65    psql -h $DBHOST -U $DBUSER $DBBASE $@
66 elif [ "$1" = "piped" ]; then
67    psql -h $DBHOST -U $DBUSER $DBBASE -t -q -A -F '|' $@
68 elif [ "$1" = "dump" ]; then
69    if [ $# -eq 1 ]; then
70       pg_dump -a --inserts -h $DBHOST -U $DBUSER $DBBASE
71    else
72       pg_dump -a --inserts -h $DBHOST -U $DBUSER $DBBASE > $2
73    fi
74 elif [ "$1" = "dumpall" ]; then
75    if [ $# -eq 1 ]; then
76       pg_dump -h $DBHOST -U $DBUSER $DBBASE
77    else
78       pg_dump -h $DBHOST -U $DBUSER $DBBASE > $2
79    fi
80 elif [ "$1" = "add" ]; then
81    cat "$2" | psql -h $DBHOST -U $DBUSER $DBBASE
82 else
83     echo " USAGE"
84     echo "   ./builder create"
85     echo "   ./builder destroy"
86     echo "   ./builder clean"
87     echo "   ./builder build"
88     echo "   ./builder rebuild"
89     echo "   ./builder psql"
90     echo "   ./builder piped"
91     echo "   ./builder add <filesql>"
92     echo "   ./builder dump [dumpfile]"
93     echo "   ./builder dumpall [dumpfile]"
94     echo "   ./builder all"
95     echo "   ./builder help"
96 fi