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/lib/database b/lib/database
index 66fb36f..07e37ae 100644
--- a/lib/database
+++ b/lib/database
@@ -62,15 +62,6 @@
     return 0
 }
 
-# Set the database backend to use
-#  $1 The name of the database backend to use (mysql, postgresql, ...)
-function use_database {
-    use_exclusive_service DATABASE_BACKENDS DATABASE_TYPE $1 && return 0
-    ret=$?
-    echo "Invalid database '$1'"
-    return $ret
-}
-
 # Recreate a given database
 #  $1 The name of the database
 #  $2 The character set/encoding of the database
diff --git a/lib/databases/postgresql b/lib/databases/postgresql
index 81989f2..ee24c8b 100644
--- a/lib/databases/postgresql
+++ b/lib/databases/postgresql
@@ -38,8 +38,8 @@
     start_service postgresql
 
     # If creating the role fails, chances are it already existed. Try to alter it.
-    sudo -u postgres -i psql -c "CREATE ROLE $DATABASE_USER WITH SUPERUSER LOGIN PASSWORD '$DATABASE_PASSWORD'" || \
-    sudo -u postgres -i psql -c "ALTER ROLE $DATABASE_USER WITH SUPERUSER LOGIN PASSWORD '$DATABASE_PASSWORD'"
+    sudo -u root sudo -u postgres -i psql -c "CREATE ROLE $DATABASE_USER WITH SUPERUSER LOGIN PASSWORD '$DATABASE_PASSWORD'" || \
+    sudo -u root sudo -u postgres -i psql -c "ALTER ROLE $DATABASE_USER WITH SUPERUSER LOGIN PASSWORD '$DATABASE_PASSWORD'"
 }
 
 function install_database_postgresql {