Klimbo
Klimbo

Reputation: 1448

Is it possible to create PostgreSQL Databases with dynamic names with the help of Golang?

I use Go on my backend. I try to write a function which takes database name and creates PostgreSQL Database with this name. After this function should create tables in this DB (I have already created an sql script for this task)

So the main problem is that I don't understand how to write a function which will create a PostgreSQL Database. I had a thought to create one .sql file and somehow pass database name to this file (for example find string in .sql file, which looks like {{dbname}} and replace it with db name), but may be there is a better way?

Here is my .sql file which should create tables in new PostgreSQL Database

create table "reviews"
(
  review_id  uuid  not null
    constraint review_pk
      primary key,
  user_id  uuid  not null,
  rating  float,
  comment text,
  date  date  not null
);

create unique index reviews_review_id_uindex
  on "reviews" (review_id);

create unique index reviews_user_id_uindex
  on "reviews" (user_id);

create table "sections"
(
  section_id  uuid  not null
    constraint section_pk
      primary key,
  title  text  not null,
  color  text,
  created_at date not null,
  updated_at  date  not null,
  deleted boolean default false
);

create unique index sections_section_id_uindex
  on "sections" (section_id);

Upvotes: 5

Views: 9159

Answers (1)

monirz
monirz

Reputation: 544

Try this,

 package main

import (
  "database/sql"
   "log"

   _ "github.com/lib/pq"
)

func main() {
    conninfo := "user=postgres password=yourpassword 
    host=127.0.0.1 sslmode=disable"
    db, err := sql.Open("postgres", conninfo)

if err != nil {
    log.Fatal(err)
}
dbName := "testdb"
_, err = db.Exec("create database " + dbName)
if err != nil {
    //handle the error
    log.Fatal(err)
}

//Then execute your query for creating table
   _, err = db.Exec("CREATE TABLE example ( id integer, 
   username varchar(255) )")

   if err != nil {
       log.Fatal(err)
   }

}

Note: All query statements don't support parameters in postgress, like ("create database $1", "testdb") won't work.

Upvotes: 7

Related Questions