How to use "env" stanza?

I am creating a web application on dune (with opium).
I want to change the value to connect to the database for dev, test and production.

I think for that can use env stanza. like this…

(env
    (dev
     (env-vars
       (DB_HOST localhost)
       (DB_PORT 5432)
       (DB_NAME sample)
       (DB_PASSWORD "password")
     )
    )
    (test
     (env-vars
       (DB_HOST localhost)
       (DB_PORT 5432)
       (DB_NAME sample)
       (DB_PASSWORD "password")
     )
    )
    (production
     (env-vars
       (DB_HOST localhost)
       (DB_PORT 5432)
       (DB_NAME sample)
       (DB_PASSWORD "password")
     )
    )
)

But how can use this data in OCaml code?
I assumed these values are set in environment variable.
Therefore i tryed following code.

print_endline (Sys.getenv "DB_HOST");

But no date set in environment.(Not_found exception)

Are you running your program with dune exec?

Yes. I execute dune exec bin/main.exe
and the env stanza is written in bin/dune

Hi !
You wrote the correct syntax, maybe you have an environment-related problem? Try:

(env
    (_
     (env-vars
       (DB_HOST localhost)
       (DB_PORT 5432)
       (DB_NAME sample)
       (DB_PASSWORD "password")
     )
    )
)

The underscore means “any environment”. Does it work for you ?
But I think env-vars modify environment variables only at build/compilation time (should be confirmed by someone who knows or by dune documentation), not at runtime, that is why you have this problem to my opinion.
If you use pgocaml or another library to connect to a db, I am convinced this code will do what you expect.

@ruyblast
Thank you for your reply.
I tested “any environment” (_), but same problem…
I created following codes and tested.

dune file is:

(env
    (_
     (env-vars
       (DB_HOST localhost)
       (DB_PORT 5432)
       (DB_NAME sample)
       (DB_PASSWORD "password")
     )
    )
)
(executable
 (public_name sample)
 (name main)
 (libraries sample))

and main.ml

let () =
  print_endline (Sys.getenv "DB_HOST");

and i execute:

[koji:sample]$ dune exec bin/main.exe
Fatal error: exception Not_found

Is there a problem with the execution method?

maybe looking in the dune log file (found in the _build directory) might be enlightening.

I found solution.
env stanza must be written in dune-workspace.

Interesting, looks like it’s also usable in the project root directory dune file: https://dune.readthedocs.io/en/stable/quick-start.html?highlight=env#setting-the-ocaml-compilation-flags-globally

Yes i thought so …(dune version 2.5.1)
I am OCaml beginner and my English skill is not good.
Therefore it is really hard and complicated to learn OCaml.

Ah OK. For what it’s worth I found your English quite readable. Keep going, you will get OCaml :slight_smile:

1 Like