data.rst 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416
  1. .. _host-data:
  2. Postgres database
  3. =====================
  4. This document describes how to get the postgres database ready to use and maintain it (do migrations / changes to the structure).
  5. .. note:: This is about a stable database, useful for longer development work or production. A super quick way to get a postgres database running with Docker is described in :ref:`tut_toy_schedule`. In :ref:`docker-compose` we use both postgres and redis.
  6. We also spend a few words on coding with database transactions in mind.
  7. .. contents:: Table of contents
  8. :local:
  9. :depth: 2
  10. Getting ready to use
  11. ----------------------
  12. Notes:
  13. * We assume ``flexmeasures`` for your database and username here. You can use anything you like, of course.
  14. * The name ``flexmeasures_test`` for the test database is good to keep this way, as automated tests are looking for that database / user / password.
  15. Install
  16. ^^^^^^^^^^^^^
  17. We believe FlexMeasures works with Postgres above version 9 and we ourselves have run it with versions up to 14.
  18. On Linux:
  19. .. code-block:: bash
  20. $ # On Ubuntu and Debian, you can install postgres like this:
  21. $ sudo apt-get install postgresql-12 # replace 12 with the version available in your packages
  22. $ pip install psycopg2-binary
  23. $ # On Fedora, you can install postgres like this:
  24. $ sudo dnf install postgresql postgresql-server
  25. $ sudo postgresql-setup --initdb --unit postgresql
  26. On Windows:
  27. * Download postgres here: https://www.enterprisedb.com/downloads/postgres-postgresql-downloads
  28. * Install and remember your ``postgres`` user password
  29. * Add the lib and bin directories to your Windows path: http://bobbyong.com/blog/installing-postgresql-on-windoes/
  30. * ``conda install psycopg2``
  31. On Macos:
  32. .. code-block:: bash
  33. $ brew update
  34. $ brew doctor
  35. $ # Need to specify postgres version, in this example we use 13
  36. $ brew install postgresql@13
  37. $ brew link postgresql@13 --force
  38. $ # Start postgres (you can change /usr/local/var/postgres to any directory you like)
  39. $ pg_ctl -D /usr/local/var/postgres -l logfile start
  40. Using Docker Compose:
  41. Alternatively, you can use Docker Compose to run a postgres database. You can use the following ``docker-compose.yml`` as a starting point:
  42. .. code-block:: yaml
  43. version: '3.7'
  44. services:
  45. postgres:
  46. image: postgres:latest
  47. restart: always
  48. environment:
  49. POSTGRES_USER: flexmeasures
  50. POSTGRES_PASSWORD: this-is-your-secret-choice
  51. POSTGRES_DB: flexmeasures
  52. ports:
  53. - 5432:5432
  54. volumes:
  55. - ./postgres-data:/var/lib/postgresql/data
  56. network_mode: host
  57. To run this, simply type ``docker-compose up`` in the directory where you saved the ``docker-compose.yml`` file. Pass the ``-d`` flag to run it in the background.
  58. This will create a postgres database in a directory ``postgres-data`` in your current working directory. You can change the password and database name to your liking. You can also change the port mapping to e.g. ``5433:5432`` if you already have a postgres database running on your host machine.
  59. Make sure postgres represents datetimes in UTC timezone
  60. ^^^^^^^^^^^^^
  61. (Otherwise, pandas can get confused with daylight saving time.)
  62. Luckily, many web hosters already have ``timezone= 'UTC'`` set correctly by default,
  63. but local postgres installations often use ``timezone='localtime'``.
  64. In any case, check both your local installation and the server, like this:
  65. Find the ``postgres.conf`` file. Mine is at ``/etc/postgresql/9.6/main/postgresql.conf``.
  66. You can also type ``SHOW config_file;`` in a postgres console session (as superuser) to find the config file.
  67. Find the ``timezone`` setting and set it to 'UTC'.
  68. Then restart the postgres server.
  69. .. tabs::
  70. .. tab:: Linux
  71. .. code-block:: bash
  72. $ sudo service postgresql restart
  73. .. tab:: Macos
  74. .. code-block:: bash
  75. $ pg_ctl -D /usr/local/var/postgres -l logfile restart
  76. .. note:: If you are using Docker to run postgres, the ``timezone`` setting is already set to ``UTC`` by default.
  77. Create "flexmeasures" and "flexmeasures_test" databases and users
  78. ^^^^^^^^^^^^^
  79. From the terminal:
  80. Open a console (use your Windows key and type ``cmd``\ ).
  81. Proceed to create a database as the postgres superuser (using your postgres user password):
  82. .. code-block:: bash
  83. $ sudo -i -u postgres
  84. $ createdb -U postgres flexmeasures
  85. $ createdb -U postgres flexmeasures_test
  86. $ createuser --pwprompt -U postgres flexmeasures # enter your password
  87. $ createuser --pwprompt -U postgres flexmeasures_test # enter "flexmeasures_test" as password
  88. $ exit
  89. .. note:: In case you encounter the following "FAILS: sudo: unknown user postgres" you need to create "postgres" OS user with sudo rights first - better done via System preferences -> Users & Groups.
  90. Or, from within Postgres console:
  91. .. code-block:: sql
  92. CREATE USER flexmeasures WITH PASSWORD 'this-is-your-secret-choice';
  93. CREATE DATABASE flexmeasures WITH OWNER = flexmeasures;
  94. CREATE USER flexmeasures_test WITH PASSWORD 'flexmeasures_test';
  95. CREATE DATABASE flexmeasures_test WITH OWNER = flexmeasures_test;
  96. Finally, test if you can log in as the flexmeasures user:
  97. .. code-block:: bash
  98. $ psql -U flexmeasures --password -h 127.0.0.1 -d flexmeasures
  99. .. code-block:: sql
  100. \q
  101. Add Postgres Extensions to your database(s)
  102. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  103. To find the nearest sensors, FlexMeasures needs some extra Postgres support.
  104. Add the following extensions while logged in as the postgres superuser:
  105. .. code-block:: bash
  106. $ sudo -u postgres psql
  107. .. code-block:: sql
  108. \connect flexmeasures
  109. CREATE EXTENSION cube;
  110. CREATE EXTENSION earthdistance;
  111. .. note:: Lines from above should be run seperately
  112. If you have it, connect to the ``flexmeasures_test`` database and repeat creating these extensions there. Then ``exit``.
  113. Configure FlexMeasures app for that database
  114. ^^^^^^^^^^^^^
  115. Write:
  116. .. code-block:: python
  117. SQLALCHEMY_DATABASE_URI = "postgresql://flexmeasures:<password>@127.0.0.1/flexmeasures"
  118. into the config file you are using, e.g. ~/.flexmeasures.cfg
  119. Get structure (and some data) into place
  120. ^^^^^^^^^^^^^
  121. You need data to enjoy the benefits of FlexMeasures or to develop features for it. In this section, there are some ways to get started.
  122. Import from another database
  123. """"""""""""""""""""""""""""""
  124. Here is a short recipe to import data from a FlexMeasures database (e.g. a demo database) into your local system.
  125. On the to-be-exported database:
  126. .. code-block:: bash
  127. $ flexmeasures db-ops dump
  128. .. note:: Only the data gets dumped here.
  129. Then, we create the structure in our database anew, based on the data model given by the local codebase:
  130. .. code-block:: bash
  131. $ flexmeasures db-ops reset
  132. Then we import the data dump we made earlier:
  133. .. code-block:: bash
  134. $ flexmeasures db-ops restore <DATABASE DUMP FILENAME>
  135. A potential ``alembic_version`` error should not prevent other data tables from being restored.
  136. You can also choose to import a complete db dump into a freshly created database, of course.
  137. .. note:: To make sure passwords will be decrypted correctly when you authenticate, set the same SECURITY_PASSWORD_SALT value in your config as the one that was in use when the dumped passwords were encrypted!
  138. Create data manually
  139. """""""""""""""""""""""
  140. First, you can get the database structure with:
  141. .. code-block:: bash
  142. $ flexmeasures db upgrade
  143. .. note:: If you develop code (and might want to make changes to the data model), you should also check out the maintenance section about database migrations.
  144. You can create users with the ``add user`` command. Check it out:
  145. .. code-block:: bash
  146. $ flexmeasures add account --help
  147. $ flexmeasures add user --help
  148. You can create some pre-determined asset types and data sources with this command:
  149. .. code-block:: bash
  150. $ flexmeasures add initial-structure
  151. You can also create assets in the FlexMeasures UI.
  152. On the command line, you can add many things. Check what data you can add yourself:
  153. .. code-block:: bash
  154. $ flexmeasures add --help
  155. For instance, you can create forecasts for your existing metered data with this command:
  156. .. code-block:: bash
  157. $ flexmeasures add forecasts --help
  158. Check out it's ``--help`` content to learn more. You can set which assets and which time window you want to forecast. Of course, making forecasts takes a while for a larger dataset.
  159. You can also simply queue a job with this command (and run a worker to process the :ref:`redis-queue`).
  160. Just to note, there are also commands to get rid of data. Check:
  161. .. code-block:: bash
  162. $ flexmeasures delete --help
  163. Check out the :ref:`cli` documentation for more details.
  164. Visualize the data model
  165. --------------------------
  166. You can visualise the data model like this:
  167. .. code-block:: bash
  168. $ make show-data-model
  169. This will generate a picture based on the model code.
  170. You can also generate picture based on the actual database, see inside the Makefile.
  171. .. note:: If you encounter "error: externally-managed-environment" when running `make test` and you do it in venv, try `pip cache purge` or use pipx.
  172. Maintenance
  173. ----------------
  174. Maintenance is supported with the alembic tool. It reacts automatically
  175. to almost all changes in the SQLAlchemy code. With alembic, multiple databases,
  176. such as development, staging and production databases can be kept in sync.
  177. Make first migration
  178. ^^^^^^^^^^^^^^^^^^^^^^^
  179. Run these commands from the repository root directory (read below comments first):
  180. .. code-block:: bash
  181. $ flexmeasures db init
  182. $ flexmeasures db migrate
  183. $ flexmeasures db upgrade
  184. The first command (\ ``flexmeasures db init``\ ) is only needed here once, it initialises the alembic migration tool.
  185. The second command generates the SQL for your current db model and the third actually gives you the db structure.
  186. With every migration, you get a new migration step in ``migrations/versions``. Be sure to add that to ``git``\ ,
  187. as future calls to ``flexmeasures db upgrade`` will need those steps, and they might happen on another computer.
  188. Hint: You can edit these migrations steps, if you want.
  189. Make another migration
  190. ^^^^^^^^^^^^^^^^^^^^^^^
  191. Just to be clear that the ``db init`` command is needed only at the beginning - you usually do, if your model changed:
  192. .. code-block:: bash
  193. $ flexmeasures db migrate --message "Please explain what you did, it helps for later"
  194. $ flexmeasures db upgrade
  195. Get database structure updated
  196. ^^^^^^^^^^^^^^^^^^^^^^^
  197. The goal is that on any other computer, you can always execute
  198. .. code-block:: bash
  199. $ flexmeasures db upgrade
  200. to have the database structure up-to-date with all migrations.
  201. Working with the migration history
  202. ^^^^^^^^^^^^^^^^^^^^^^^
  203. The history of migrations is at your fingertips:
  204. .. code-block:: bash
  205. $ flexmeasures db current
  206. $ flexmeasures db history
  207. You can move back and forth through the history:
  208. .. code-block:: bash
  209. $ flexmeasures db downgrade
  210. $ flexmeasures db upgrade
  211. Both of these accept a specific revision id parameter, as well.
  212. Check out database status
  213. ^^^^^^^^^^^^^^^^^^^^^^^
  214. Log in into the database:
  215. .. code-block:: bash
  216. $ psql -U flexmeasures --password -h 127.0.0.1 -d flexmeasures
  217. with the password from flexmeasures/development_config.py. Check which tables are there:
  218. .. code-block:: sql
  219. \dt
  220. To log out:
  221. .. code-block:: sql
  222. \q
  223. Transaction management
  224. -----------------------
  225. It is really useful (and therefore an industry standard) to bundle certain database actions within a transaction. Transactions are atomic - either the actions in them all run or the transaction gets rolled back. This keeps the database in a sane state and really helps having expectations during debugging.
  226. Please see the package ``flexmeasures.data.transactional`` for details on how a FlexMeasures developer should make use of this concept.
  227. If you are writing a script or a view, you will find there the necessary structural help to bundle your work in a transaction.