1
0

postgresql.sh 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. #!/bin/sh
  2. PSQL="/usr/bin/psql"
  3. free_megs() {
  4. fsdir=$1
  5. while [ ! -d "$fsdir" ]; do
  6. fsdir=$(dirname $fsdir)
  7. done
  8. df -m $fsdir | while read fs bl us av cap mnt; do [ "$av" = "Available" ] || echo $av; done
  9. }
  10. pg_init_data() {
  11. # make sure we got at least 50MB of free space
  12. [ $(free_megs $1) -lt 50 ] && return 1
  13. pg_ctl initdb -U postgres -D $1
  14. }
  15. pg_server_ready() {
  16. t=0
  17. while [ $t -le 90 ]; do
  18. pg_ctl status -U postgres -D $1 2>/dev/null >/dev/null && return 0
  19. t=$((t+1))
  20. sleep 1
  21. done
  22. return 1
  23. }
  24. # $1: dbname, $2: username, $3: password
  25. pg_require_db() {
  26. pg_test_db $@ && return 0
  27. ( echo "CREATE DATABASE $1;"
  28. echo -n "CREATE USER $2"
  29. [ "$3" ] && echo -n " WITH PASSWORD '$3'"
  30. echo ";"
  31. echo "GRANT ALL PRIVILEGES ON DATABASE \"$1\" to $2;" ) |
  32. $PSQL -U postgres -d template1 -e
  33. return $?
  34. }
  35. pg_test_db() {
  36. PGPASSWORD=$3
  37. echo "SHOW ALL;" | $PSQL -U $2 -d $1 -q 2>/dev/null >/dev/null
  38. return $?
  39. }
  40. uci_require_db() {
  41. local dbname dbuser dbpass
  42. config_get dbname $1 name
  43. config_get dbuser $1 user
  44. config_get dbpass $1 pass
  45. pg_require_db $dbname $dbuser $dbpass
  46. }
  47. [ "$1" = "init" ] && {
  48. . /lib/functions.sh
  49. pg_server_ready $2 || exit 1
  50. config_load postgresql
  51. config_foreach uci_require_db postgres-db
  52. }