You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

86 lines
1.7 KiB

  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. pg_test_db() {
  25. if [ "$3" ]; then
  26. echo "SHOW ALL;" | env PGPASSWORD="$3" $PSQL -U "$2" -d "$1" -q 2>/dev/null >/dev/null
  27. return $?
  28. else
  29. echo "SHOW ALL;" | $PSQL -w -U "$2" -d "$1" -q 2>/dev/null >/dev/null
  30. return $?
  31. fi
  32. }
  33. pg_include_sql() {
  34. if [ "$3" ]; then
  35. env PGPASSWORD="$3" $PSQL -U "$2" -d "$1" -e -f "$4"
  36. return $?
  37. else
  38. $PSQL -w -U "$2" -d "$1" -e -f "$4"
  39. return $?
  40. fi
  41. }
  42. # $1: dbname, $2: username, $3: password, $4: sql populate script
  43. pg_require_db() {
  44. local ret
  45. pg_test_db $@ && return 0
  46. ( echo "CREATE DATABASE $1;"
  47. echo -n "CREATE USER $2"
  48. [ "$3" ] && echo -n " WITH PASSWORD '$3'"
  49. echo " NOCREATEDB NOSUPERUSER NOCREATEROLE NOINHERIT;"
  50. echo "GRANT ALL PRIVILEGES ON DATABASE \"$1\" TO $2;" ) |
  51. $PSQL -U postgres -d template1 -e
  52. ret=$?
  53. [ "$ret" = "0" ] || return $ret
  54. if [ "$4" ]; then
  55. pg_include_sql "$@"
  56. ret=$?
  57. fi
  58. return $ret
  59. }
  60. uci_require_db() {
  61. local dbname dbuser dbpass dbscript
  62. config_get dbname $1 name
  63. config_get dbuser $1 user
  64. config_get dbpass $1 pass
  65. config_get dbscript $1 script
  66. pg_require_db "$dbname" "$dbuser" "$dbpass" "$dbscript"
  67. }
  68. [ "$1" = "init" ] && {
  69. . /lib/functions.sh
  70. pg_server_ready $2 || exit 1
  71. config_load postgresql
  72. config_foreach uci_require_db postgres-db
  73. }