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.

111 lines
2.7 KiB

  1. #!/bin/bash
  2. ## compose: no-hooks
  3. ## Load action gets a first argument a FILE/DIRECTORY/URL holding the necessary files.
  4. ##
  5. ##
  6. if [ -z "$SERVICE_DATASTORE" ]; then
  7. echo "This script is meant to be run through 'compose' to work properly." >&2
  8. exit 1
  9. fi
  10. version=0.1
  11. usage="$exname [-h|--help] DBNAME"
  12. help="
  13. USAGE:
  14. $usage
  15. DESCRIPTION:
  16. Read stdin and content to related postgres service in the database
  17. DBNAME. If DBNAME is not provided, it'll take the default database
  18. from the ${DARKCYAN}postgres-database${NORMAL} relation of current
  19. service.
  20. EXAMPLES:
  21. $exname < foo.sql
  22. $exname mydb2 < foo.sql
  23. "
  24. dbname=
  25. output=
  26. while [ "$1" ]; do
  27. case "$1" in
  28. "--help"|"-h")
  29. print_help >&2
  30. exit 0
  31. ;;
  32. "--force"|"-f")
  33. force=yes
  34. ;;
  35. --*|-*)
  36. err "Unexpected optional argument '$1'"
  37. print_usage >&2
  38. exit 1
  39. ;;
  40. *)
  41. [ -z "$dbname" ] && { dbname=$1 ; shift ; continue ; }
  42. err "Unexpected positional argument '$1'"
  43. print_usage >&2
  44. exit 1
  45. ;;
  46. esac
  47. shift
  48. done
  49. if [ -z "$dbname" ]; then
  50. ##
  51. ## Fetch default dbname in relation to postgres-database
  52. ##
  53. ## XXXvlab: can't get real config here
  54. if ! read-0 ts _ _ < <(get_service_relation "$SERVICE_NAME" "postgres-database"); then
  55. err "Couldn't find relation ${DARKCYAN}postgres-database${NORMAL}."
  56. exit 1
  57. fi
  58. relation_dir=$(get_relation_data_dir "$SERVICE_NAME" "$ts" "postgres-database") || {
  59. err "Failed to find relation dir"
  60. exit 1
  61. }
  62. postgres_config=$(cat "$relation_dir"/data) || exit 2
  63. dbname="$(e "$postgres_config" | shyaml get-value dbname)" || {
  64. err "Couldn't retrieve information of ${DARKCYAN}postgres-database${NORMAL}'s relation."
  65. exit 1
  66. }
  67. dbuser="$(e "$postgres_config" | shyaml get-value user)" || {
  68. err "Couldn't retrieve information of ${DARKCYAN}postgres-database${NORMAL}'s relation."
  69. exit 1
  70. }
  71. password="$(e "$postgres_config" | shyaml get-value password)" || {
  72. err "Couldn't retrieve information of ${DARKCYAN}postgres-database${NORMAL}'s relation."
  73. exit 1
  74. }
  75. fi
  76. set -e
  77. containers="$(get_running_containers_for_service "$RELATION_TARGET_SERVICE")"
  78. if [ -z "$containers" ]; then
  79. err "No containers running for service $DARKYELLOW$service$NORMAL."
  80. exit 1
  81. fi
  82. ## XXXvlab: taking first container is probably not a good idea
  83. container_id="$(echo "$containers" | head -n 1)"
  84. docker exec -i -u 0 \
  85. -e PGUSER="$dbuser" \
  86. -e PGPASSWORD="$password" \
  87. "${container_id}" psql -qAt "$dbname"