Simplify database selection

Do not require every script that sources stackrc to also
source lib/databases.

* Move use_databases() to functions
* Set DATABASE_TYPE in stackrc
* Allow setting DATABASE_TYPE in localrc to work
  (use_database() essentially just sets DATABASE_TYPE at this stage
  so continuing to use it is equivalent)
* Validate DATABASE_TYPE in stack.sh.
* Change sudo to postgresql user to go through root to eliminate
  password prompt
* fix use_database error condition

Change-Id: Ibb080c76e6cd7c6eebbb641a894d54b1dde78ca6
diff --git a/functions b/functions
index 92c8a5f..8ab3eef 100644
--- a/functions
+++ b/functions
@@ -841,6 +841,22 @@
     fi
 }
 
+# Set the database backend to use
+# When called from stackrc/localrc DATABASE_BACKENDS has not been
+# initialized yet, just save the configuration selection and call back later
+# to validate it.
+#  $1 The name of the database backend to use (mysql, postgresql, ...)
+function use_database {
+    if [[ -z "$DATABASE_BACKENDS" ]]; then
+        # The backends haven't initialized yet, just save the selection for now
+        DATABASE_TYPE=$1
+        return
+    fi
+    use_exclusive_service DATABASE_BACKENDS DATABASE_TYPE $1 && return 0
+    ret=$?
+    return $ret
+}
+
 # Toggle enable/disable_service for services that must run exclusive of each other
 #  $1 The name of a variable containing a space-separated list of services
 #  $2 The name of a variable in which to store the enabled service's name