1

We create a hive database using expect script and with some other commands.

In the case if we run the expect script again on the machine that hive already created, we get this:

ERROR hive already exists

How can we check if database hive already created before creating it again?

And by this verification we can escape the expect script:

# su - postgres
 Last login: Sun Aug 13 11:12:03 UTC 2017 on pts/0
 -bash-4.2$ psql
 psql (9.2.13)
 Type "help" for help.

postgres=# CREATE DATABASE hive;
ERROR:  database "hive" already exists

My expect script: (from my bash script)

set timeout -1

#exec the scripts

spawn timeout 60 ssh root@IP
expect "#"
spawn su - postgres
expect "$"
send "psql\n"
expect "=#"
send "CREATE DATABASE hive;\n"
.
.
.
.

Other example:

postgres=# CREATE DATABASE [IF NOT EXISTS] hive;
ERROR:  syntax error at or near "["
LINE 1: CREATE DATABASE [IF NOT EXISTS] hive;
                    ^
peterh
  • 9,488
  • 16
  • 59
  • 88
yael
  • 12,598
  • 51
  • 169
  • 303
  • See also https://stackoverflow.com/q/45659905/4957508 – Jeff Schaller Aug 13 '17 at 15:35
  • I suggest to check the rules, when should you use "the" or "a". It would significantly improve your English (it doesn't make your posts incomprehensible, but anybody having a first language with articles, will have to think about what you tried to say. So you lose a lot of good answers.) – peterh Aug 21 '17 at 16:08

1 Answers1

1

If you would like to use Hive database, try using hive directly (see below)

PostgreSQL answer

Stack overflow Q&A Simulate CREATE DATABASE IF NOT EXISTS for PostgreSQL?

Specify that PostgreSQL doesn't have build in support for IF NOT EXISTS (as hive have)

One of the simple answer mentioned there is: query the database, and only if the query fail - create the database.

psql -U postgres -tc "SELECT 1 FROM pg_database WHERE datname = 'my_db'" | grep -q 1 || psql -U postgres -c "CREATE DATABASE my_db"

Hive answer:

You should use the command with the option [IF NOT EXISTS]:

CREATE DATABASE [IF NOT EXISTS] <database name>

More info

Create Database Statement

Create Database is a statement used to create a database in Hive. A database in Hive is a namespace or a collection of tables. The syntax for this statement is as follows:

CREATE DATABASE|SCHEMA [IF NOT EXISTS] <database name>

Here, IF NOT EXISTS is an optional clause, which notifies the user that a database with the same name already exists. We can use SCHEMA in place of DATABASE in this command. The following query is executed to create a database named userdb:

hive> CREATE DATABASE [IF NOT EXISTS] userdb;

or

hive> CREATE SCHEMA userdb;
Yaron
  • 4,229
  • 2
  • 20
  • 33