I’m working on a c++ desktop application involving database management, and i’m facing few issues on how to start/stop the postgres server automatically after the application starts/stops.
we could register the service during the installation as "automatic" but if the application is off it would be a waste of resources.
manually it could be done via the svc manager or the command line (pg_ctl -D … start), but desktop applications do it automatically.
the general ideas i’ve been able to find on the internet were to register it as a service then start/stop it manually or run it from inside the code by running the command.
i would be very grateful if anybody could point me to a guide on the proper way to do it, or tell me how it’s done.
2
Answers
Registering as a service is not a good idea, because:
This is not your way if you want to run PostgreSQL built into your application.
Using
pg_ctl
is better. Your best bet would be to use the "standard" library, i.e. libpq to control the server. But lipq doesn’t have such an API, because regular applications SHOULD NOT control a shared server.I think, more correct way is to do this, like pg_ctl.
You can look at the pg_ctl code: https://github.com/postgres/postgres/blob/master/src/bin/pg_ctl/pg_ctl.c#L924
No magic there and starting process is simple:
Function, which runs executable just use command interpreter to run Postgres executable: https://github.com/postgres/postgres/blob/master/src/bin/pg_ctl/pg_ctl.c#L440
P.S.:
Another possible option is to use SQLite, which is designed for embedding.
I recommend you to look at "embedded-postgres-binaries" GitHub project which provides small-size binaries that have been then used by other projects (referred in README.md) to provide embedded support for Java, Rust, Go and JavaScript (Node.JS) languages.
There is still no easy-to-use support for C++ (yet) but these integrations mainly consists in starting the PostgreSQL server engine as a forked process with your own tuned light configuration from your application code and connecting to socket to submit commands and requests.
The "portable" binaries are published as artefacts in a Maven repository, but quite easy to retrieve.