Parsing PostgreSQL connection strings in julia 0.3.10

Jul 16, 2015 · 189 words · 1 minute read databasesjuliapostgres

Today I decided to write a function to read a PostgreSQL connection string from an environment variable and to setup the connection. This is a pretty simple function but I couldn’t find a built in way to do this using DBI.jl and PostgreSQL.jl. The main assumption is that the database connection string is an environment variable, which allows you to make database connections without exposing the connection strings in your code. In my case the connection strings don’t actually live as environment variables but are retrieved from Heroku (using something like $(heroku config:get MY_DATABASE_URL -a my-heroku-service)) so that access can always be revoked without needing to force everyone else to change their keys. In any case you earn poor style points if you hardcode your database connection strings.

function loadConnectionString(variable_name)
    if ismatch(r"postgres://[\w]*:[\w]*@[\w|\-|\.]*:[\d]{4}/[\w]*", ENV[variable_name])
        conn_arr = split(replace(ENV[variable_name], "postgres://", ""), r"[/|:|@]")
        return connect(Postgres, conn_arr[3], conn_arr[1], conn_arr[2], conn_arr[5], conn_arr[4])
    else
        warn("The connection string didn't match the expected format.")
    end
end

I didn’t write this for widespread consumption so I didn’t add any sanity checks, for example it would probably good to returns useful error messages if either DBI.jl or PostgreSQL.jl aren’t loaded.