Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
112 commits
Select commit Hold shift + click to select a range
0fb8734
Add migration_helper reldb
reicda Jul 10, 2024
bded6a8
Merge branch 'feature/relational-db' of https://github.com/OpenSlides…
reicda Aug 27, 2024
000c23a
Add first migration
reicda Sep 3, 2024
aa56a49
adjusted meta repo
reicda Sep 4, 2024
4f60aec
adjusted meta repo
reicda Sep 4, 2024
40fa60f
Update requirements_production.txt
reicda Sep 4, 2024
d0fdb6d
renamed and optimized files
reicda Sep 4, 2024
64d2642
updated meta
reicda Sep 4, 2024
842fddb
adjust meta
reicda Sep 4, 2024
a3d766a
Merge branch 'RelDB-Migration' of https://github.com/reicda/openslide…
reicda Sep 4, 2024
f86ac4c
adjust meta
reicda Sep 5, 2024
bc9d26a
restructured for test framework
reicda Sep 27, 2024
37c9522
restructued for test framework
reicda Sep 27, 2024
92a1ef9
exclude deleted models
reicda Sep 30, 2024
2713c46
Merge remote-tracking branch 'upstream/feature/relational-db' into HEAD
luisa-beerboom Jan 21, 2025
ded2ab3
Fix
luisa-beerboom Jan 21, 2025
948f571
Automatically open conn pool
luisa-beerboom Jan 21, 2025
f14b382
Comment out migration for now
luisa-beerboom Jan 21, 2025
389abb8
merge upstream/feature-relational
hjanott Sep 19, 2025
1c6d317
extend migration test
hjanott Sep 23, 2025
74fa6e8
properly check table creation and deletion
hjanott Oct 10, 2025
58ea990
update meta
hjanott Oct 14, 2025
12932b9
adapt backend to new meta
hjanott Oct 14, 2025
27879af
base pre_migration for vote service
hjanott Oct 14, 2025
f69b3ba
* fix exception on schema_checks
hjanott Oct 16, 2025
32dc90f
rework migration route
hjanott Nov 11, 2025
7f5f9f8
prod create schema
hjanott Nov 13, 2025
542acef
wait for database
hjanott Nov 13, 2025
dc9bcd0
worn out password
hjanott Nov 13, 2025
3637e2d
again
hjanott Nov 13, 2025
1c275c5
more logs
hjanott Nov 13, 2025
88a058c
ls debug
hjanott Nov 13, 2025
f90d9f0
add pyyaml to production requirements
hjanott Nov 13, 2025
c85105b
add logger
hjanott Nov 13, 2025
e62dcf7
update migration index
hjanott Nov 13, 2025
da31001
fixes
hjanott Nov 13, 2025
7a775bd
use extended database and update meta
hjanott Nov 14, 2025
f599418
poll method
hjanott Nov 14, 2025
1507cc8
skip inexistent fields again
hjanott Nov 14, 2025
c23d7f2
add error handling for too long values
hjanott Nov 14, 2025
903a350
extend error message
hjanott Nov 14, 2025
1e9cb83
shorten too long action worker names
hjanott Nov 17, 2025
6e0615e
debug index prepared statement
hjanott Nov 17, 2025
a173c89
prepared statements debugging
hjanott Nov 17, 2025
4a4c280
set prepared statements to none
hjanott Nov 17, 2025
e0c7e3e
improve exception
hjanott Nov 18, 2025
95c9467
use field type instead of data type for json fields
hjanott Nov 18, 2025
646763c
fix faulty import
hjanott Nov 18, 2025
fea6ddd
Revert logging.
hjanott Nov 19, 2025
0c3689d
Revert "set prepared statements to none"
hjanott Nov 19, 2025
d676cf5
Revert "prepared statements debugging"
hjanott Nov 19, 2025
bb0ac85
Revert "debug index prepared statement"
hjanott Nov 19, 2025
5cc6181
Revert "add logger"
hjanott Nov 19, 2025
c63e0dd
git revert adding extended database
hjanott Nov 19, 2025
2378201
reapply meta
hjanott Nov 19, 2025
c0f6fb7
Revert "adapt backend to new meta"
hjanott Nov 19, 2025
0f8fb2c
revert vote stuff
hjanott Nov 19, 2025
de3cbd8
update make file
hjanott Nov 19, 2025
a60b154
remove vote service pre migration
hjanott Nov 19, 2025
70374ef
improve migrate thread stream and tests
hjanott Nov 19, 2025
ad9db8c
utilize only last line from stream
hjanott Nov 19, 2025
cc0a08c
improve progress message
hjanott Nov 19, 2025
e502a5e
non empty
hjanott Nov 19, 2025
ee08402
line break for output
hjanott Nov 19, 2025
67e98c0
return exception to stats route
hjanott Nov 19, 2025
afc0d20
Revert "Revert "set prepared statements to none""
hjanott Nov 20, 2025
f8dcdf4
* more numbers in stats route
hjanott Nov 21, 2025
6e25f6f
cleanup and documentation and small fixes
hjanott Nov 25, 2025
05bcd47
requested changes
hjanott Nov 26, 2025
a114c3e
eliminate unwanted decimal zeroes in vote_weight and default_vote_weight
hjanott Nov 26, 2025
7038e4f
set vote weight to 0.000001 instead
hjanott Nov 27, 2025
5280e53
increase last rel migration
hjanott Nov 28, 2025
e1b6c7e
merge upstream feature rel-db
hjanott Dec 8, 2025
954cc89
* extend migration states
hjanott Dec 8, 2025
d2fd1e0
proper origin collections
hjanott Dec 9, 2025
dee2244
delete version rows in one statement
hjanott Dec 9, 2025
54017ad
Merge upstream feature rel-db
hjanott Dec 10, 2025
29c4ea8
update id sequences
hjanott Dec 10, 2025
9715bf4
remove poll_id from example votes again
hjanott Dec 10, 2025
8d7b816
use new migration table and view names
hjanott Dec 10, 2025
6dae774
Set up shadow copies for non initial migration
hjanott Dec 11, 2025
69ae686
insert data into shadow copy
hjanott Dec 11, 2025
dcda9e2
increase last non rel index
hjanott Dec 12, 2025
947913e
extend shadow copy handling
hjanott Dec 12, 2025
d4941a3
Merge feature/relational-db
hjanott Dec 15, 2025
167feec
fix production
hjanott Dec 15, 2025
e2ad978
lint
hjanott Dec 15, 2025
93a26b0
debugging workflow
hjanott Dec 15, 2025
ce5f134
assign prod as target for docker-compose.prod.yml
hjanott Dec 15, 2025
08bdcf3
adding recursive submodule checkout
hjanott Dec 15, 2025
4f7bc31
fix for reset
hjanott Dec 15, 2025
021079c
Update openslides_backend/migrations/README.md
hjanott Dec 15, 2025
31fa08a
pass argument
hjanott Dec 15, 2025
cb98b17
* use migration tables for initial migration
hjanott Jan 8, 2026
e1ad0a3
* centralize MODELS in InternalHelper
hjanott Jan 17, 2026
68b0f34
Apply suggestions from code review
hjanott Jan 17, 2026
2fda0f8
Update openslides_backend/migrations/README.md
hjanott Jan 17, 2026
230a766
update from feature branch
hjanott Jan 20, 2026
0802db4
update meta
hjanott Jan 20, 2026
29d81e5
generate models
hjanott Jan 20, 2026
968ecd6
use minimum non rel index
hjanott Jan 20, 2026
11ebb50
drop all triggers instead of replacing
hjanott Jan 20, 2026
e1ffc6d
recreate trigger also on intermediate tables
hjanott Jan 20, 2026
9731c2e
update meta
hjanott Jan 21, 2026
183545c
generically update sequential_number sequences
hjanott Jan 21, 2026
ffe171d
allow only backendManage and dev instances to create schema in entryp…
hjanott Jan 21, 2026
fd8adfd
use double parenthesis
hjanott Jan 21, 2026
8fbf9f5
delete migrations core
hjanott Jan 21, 2026
9b3590f
use advisory locks instead
hjanott Jan 21, 2026
771b34d
more elaborate debug output
hjanott Jan 21, 2026
deaf0fa
filter for relkind instead of output
hjanott Jan 21, 2026
42e7bb8
implicit unlock of advisory lock
hjanott Jan 21, 2026
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 10 additions & 3 deletions .github/docker-compose/docker-compose.prod.yml
Original file line number Diff line number Diff line change
@@ -1,7 +1,10 @@
version: "3"
services:
backend-action:
build: ../..
build:
context: ../..
target: "prod"
args:
CONTEXT: "prod"
image: openslides-backend
ports:
- "9002:9002"
Expand All @@ -14,7 +17,11 @@ services:
secrets:
- postgres_password
backend-presenter:
build: ../..
build:
context: ../..
target: "prod"
args:
CONTEXT: "prod"
image: openslides-backend
ports:
- "9003:9003"
Expand Down
3 changes: 3 additions & 0 deletions .github/workflows/continuous_integration.yml
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,8 @@ jobs:

steps:
- uses: actions/checkout@v6
with:
submodules: recursive

- name: Create secrets for datastore
run: mkdir secrets && echo -n "openslides" > secrets/postgres_password
Expand Down Expand Up @@ -64,6 +66,7 @@ jobs:
- uses: actions/checkout@v6
with:
path: openslides-backend
submodules: recursive

- name: Set env vars
working-directory: openslides-backend/requirements
Expand Down
5 changes: 5 additions & 0 deletions Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,11 @@ check-all: validate-models-yml check-models check-initial-data-json check-exampl

# Models

generate-schema:
make -C meta/dev generate-relational-schema

generate-db: | generate-schema create-database-with-schema

generate-models:
python cli/generate_models.py $(MODELS_PATH)
black openslides_backend/models/models.py
Expand Down
29 changes: 12 additions & 17 deletions cli/generate_models.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,7 @@
from textwrap import dedent
from typing import Any, Optional

from cli.util.util import (
ROOT,
assert_equal,
open_output,
open_yml_file,
parse_arguments,
)
from cli.util.util import ROOT, assert_equal, open_output, parse_arguments
from meta.dev.src.helper_get_names import (
FieldSqlErrorType,
HelperGetNames,
Expand Down Expand Up @@ -76,8 +70,6 @@
"""
)

MODELS: dict[str, dict[str, Any]] = {}


def main() -> None:
"""
Expand All @@ -101,10 +93,8 @@ def main() -> None:
to: some_model/some_attribute_id
"""
args = parse_arguments(SOURCE)
global MODELS
MODELS = open_yml_file(args.filename)

InternalHelper.MODELS = MODELS
InternalHelper.read_models_yml(SOURCE)

# Load and parse models.yml
with open_output(DESTINATION, args.check) as dest:
Expand All @@ -114,7 +104,7 @@ def main() -> None:
+ ", ".join(mixin.__name__ for mixin in MODEL_MIXINS.values())
+ "\n"
)
for collection, fields in MODELS.items():
for collection, fields in InternalHelper.MODELS.items():
if collection.startswith("_"):
continue
model = Model(collection, fields)
Expand All @@ -132,7 +122,7 @@ def get_model_field(collection: str, field_name: str) -> str | dict:
Helper function the get a specific model field. Used to create generic relations.
"""

model = MODELS.get(collection)
model = InternalHelper.MODELS.get(collection)
if model is None:
raise ValueError(f"Collection {collection} does not exist.")
value = model.get(field_name)
Expand Down Expand Up @@ -376,16 +366,21 @@ def get_view_field_state_write_fields(
else:
write_fields = (table_name, field1, field2, [])
elif "generic-relation-list" in (field_type, foreign_type):
write_fields = self.get_write_fields_for_generic(own, foreign_fields)
write_fields = self.get_write_fields_for_generic(
own, foreign_fields, primary
)

assert error == "", error

return is_view_field, primary, write_fields

def get_write_fields_for_generic(
self, own: TableFieldType, foreign_fields: list[TableFieldType]
self, own: TableFieldType, foreign_fields: list[TableFieldType], primary: bool
) -> tuple[str, str, str, list[str]] | None:
table_name = HelperGetNames.get_gm_table_name(own)
if primary:
table_name = HelperGetNames.get_gm_table_name(own)
else:
table_name = HelperGetNames.get_gm_table_name(foreign_fields[0])
field1 = f"{own.table}_{own.ref_column}"
field2 = own.intermediate_column
return (
Expand Down
2 changes: 1 addition & 1 deletion data/example-data.json
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
{
"_migration_index": 74,
"_migration_index": 100,
"gender":{
"1":{
"id": 1,
Expand Down
2 changes: 1 addition & 1 deletion data/initial-data.json
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
{
"_migration_index": 74,
"_migration_index": 100,
"gender":{
"1":{
"id": 1,
Expand Down
11 changes: 5 additions & 6 deletions dev/entrypoint.sh
Original file line number Diff line number Diff line change
Expand Up @@ -3,20 +3,19 @@
printf "enter entrypoint.sh"
set -e

printf "\nOpenslides Database:\n"
printf "\nOpenslides DBMS:\n"
printf "Export env variables for database.\n"
source scripts/export_database_variables.sh

meta/dev/scripts/wait-for-database.sh
printf "Database is started.\n"
printf "DBMS is started.\n"

printf "Create schema.\n"
python cli/create_schema.py
printf "\n"

# TODO: Re-add this code
# printf "\nMigrations:\n"
# python openslides_backend/migrations/migrate.py finalize
# printf "\n"
printf "\nMigrations:\n"
python openslides_backend/migrations/migrate.py finalize
printf "\n"

exec "$@"
23 changes: 13 additions & 10 deletions docs/migration_route.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,20 +3,23 @@
Migrations are available via the internal route `/internal/migrations/` with the following payload:
```js
{
"cmd": "migrate" | "finalize" | "reset" | "clear-collectionfield-tables" | "stats" | "progress",
"cmd": "migrate" | "finalize" | "reset" | "stats",
"verbose": bool
}
```

All commands except `progress` are directly translated the the respective method calls to the datastore module as well as the `verbose` flag. While a migration is running (either via `migrate` or `finalize`), no other commands are permitted except `progress`. The `progress` command is an additional command only available in the backend which reports the progress of a long-running migration (which is executed in a thread).
While a migration is running (either via `migrate` or `finalize`), no other commands are permitted except `stats`. The `stats` command reports the progress of a long-running migration (which is executed in a thread).

The output of all commands except `stats` is the following (for a successful request):
```js
enum MigrationState {
MIGRATION_RUNNING = "migration_running"
MIGRATION_REQUIRED = "migration_required"
MIGRATION_RUNNING = "migration_running"
MIGRATION_FAILED = "migration_failed"
FINALIZATION_REQUIRED = "finalization_required"
NO_MIGRATION_REQUIRED = "no_migration_required"
FINALIZATION_RUNNING = "finalization_running"
FINALIZED = "finalized"
FINALIZATION_FAILED = "finalization_failed"
}

{
Expand All @@ -30,20 +33,20 @@ enum MigrationState {
```
`output` always contains the full output of the migration command up to this point. `exception` contains the thrown exception, if any, which can only be the case if the command is finished (meaning `status != "migration_running"`). After issuing a migration command, it is waited a short period of time for the thread to finish, so the status can be all of these things for any command (e.g. after calling `migrate`, the returned status can be either `MIGRATION_RUNNING` if the migrations did not finish directly or `FINALIZATION_REQUIRED` if the migration is already done).

The output of migration commands is stored until a new migration command is issued, meaning repeated `progress` requests after a finished command will always return the same result with the full output.

The `stats` return value is the following:
```js
{
"success": True,
"stats": {
"status": MigrationState,
"output": str, // Optional
"exception": str, // Optional
"current_migration_index": int,
"target_migration_index": int,
"positions": int,
"events": int,
"partially_migrated_positions": int,
"fully_migrated_positions": int
"migratable_models": {
"count": int,
"migrated": int
}
}
}
```
Expand Down
6 changes: 6 additions & 0 deletions entrypoint.sh
Original file line number Diff line number Diff line change
@@ -1,9 +1,15 @@
#!/bin/bash

printf "enter entrypoint.sh"
set -e

printf "\nOpenslides DBMS:\n"
printf "Export env variables for database.\n"
source scripts/export_database_variables.sh

if [ ! $ANONYMOUS_ONLY ]; then
meta/dev/scripts/wait-for-database.sh
printf "DBMS is started.\n"
fi

printf "Create schema.\n"
Expand Down
2 changes: 1 addition & 1 deletion meta
Submodule meta updated 61 files
+47 −27 .github/workflows/continuous_integration.yml
+1 −1 .github/workflows/create-prs-for-updates.yml
+21 −2 .github/workflows/pick-to-staging.yml
+0 −54 .github/workflows/staging-to-main.yml
+72 −1 README.md
+30 −0 collection-meta.yml
+36 −0 collections/action_worker.yml
+96 −0 collections/agenda_item.yml
+96 −0 collections/assignment.yml
+34 −0 collections/assignment_candidate.yml
+38 −0 collections/chat_group.yml
+35 −0 collections/chat_message.yml
+103 −0 collections/committee.yml
+23 −0 collections/gender.yml
+150 −0 collections/group.yml
+38 −0 collections/history_entry.yml
+25 −0 collections/history_position.yml
+32 −0 collections/import_preview.yml
+68 −0 collections/list_of_speakers.yml
+67 −0 collections/mediafile.yml
+1,210 −0 collections/meeting.yml
+118 −0 collections/meeting_mediafile.yml
+102 −0 collections/meeting_user.yml
+280 −0 collections/motion.yml
+54 −0 collections/motion_block.yml
+55 −0 collections/motion_category.yml
+58 −0 collections/motion_change_recommendation.yml
+34 −0 collections/motion_comment.yml
+50 −0 collections/motion_comment_section.yml
+30 −0 collections/motion_editor.yml
+150 −0 collections/motion_state.yml
+30 −0 collections/motion_submitter.yml
+27 −0 collections/motion_supporter.yml
+48 −0 collections/motion_workflow.yml
+30 −0 collections/motion_working_group_speaker.yml
+65 −0 collections/option.yml
+175 −0 collections/organization.yml
+30 −0 collections/organization_tag.yml
+40 −0 collections/personal_note.yml
+27 −0 collections/point_of_order_category.yml
+177 −0 collections/poll.yml
+34 −0 collections/poll_candidate.yml
+28 −0 collections/poll_candidate_list.yml
+81 −0 collections/projection.yml
+204 −0 collections/projector.yml
+48 −0 collections/projector_countdown.yml
+24 −0 collections/projector_message.yml
+81 −0 collections/speaker.yml
+34 −0 collections/structure_level.yml
+51 −0 collections/structure_level_list_of_speakers.yml
+29 −0 collections/tag.yml
+162 −0 collections/theme.yml
+63 −0 collections/topic.yml
+197 −0 collections/user.yml
+46 −0 collections/vote.yml
+1,612 −1,605 dev/sql/schema_relational.sql
+21 −13 dev/src/generate_sql_schema.py
+18 −7 dev/src/helper_get_names.py
+47 −0 dev/src/join_models_yml.py
+49 −11 dev/src/validate.py
+2,594 −2,611 models.yml
4 changes: 2 additions & 2 deletions openslides_backend/action/actions/meeting/import_.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
from typing import Any

from openslides_backend.action.actions.meeting.mixins import MeetingPermissionMixin
from openslides_backend.migrations import get_backend_migration_index
from openslides_backend.migrations.migration_helper import MigrationHelper
from openslides_backend.models.base import model_registry
from openslides_backend.models.checker import Checker, CheckException
from openslides_backend.models.fields import (
Expand Down Expand Up @@ -753,7 +753,7 @@ def check_data_migration_index(self, instance: dict[str, Any]) -> None:
Check for valid migration index.
"""
start_migration_index = instance["meeting"].pop("_migration_index")
backend_migration_index = get_backend_migration_index()
backend_migration_index = MigrationHelper.get_backend_migration_index()
if backend_migration_index < start_migration_index:
raise ActionException(
f"Your data migration index '{start_migration_index}' is higher than the migration index of this backend '{backend_migration_index}'! Please, update your backend!"
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
from collections.abc import Iterable
from typing import Any

from openslides_backend.migrations.migration_helper import MigrationHelper

from ....i18n.translator import Translator
from ....i18n.translator import translate as _
from ....models.base import json_dict_to_non_json_data_types
Expand Down Expand Up @@ -142,10 +144,7 @@ def build_write_request(
def create_action_result_element(
self, instance: dict[str, Any]
) -> ActionResultElement | None:
backend_migration_index = 1
# TODO set to fixed value because of lacking migrations
# needs to be readded in some shape or form
# backend_migration_index = get_backend_migration_index()
backend_migration_index = MigrationHelper.get_backend_migration_index()
result = {
"data_migration_index": self.data_migration_index,
"backend_migration_index": backend_migration_index,
Expand Down
18 changes: 11 additions & 7 deletions openslides_backend/http/views/action_view.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,10 @@
from ...action.action_handler import ActionHandler
from ...action.action_worker import handle_action_in_worker_thread
from ...i18n.translator import Translator
from ...migrations import assert_migration_index
from ...migrations.migration_handler import MigrationHandler
from ...migrations.migration_helper import MigrationHelper
from ...migrations.migration_manager import MigrationManager
from ...services.auth.interface import AUTHENTICATION_HEADER, COOKIE_NAME
from ...services.postgresql.db_connection_handling import get_new_os_conn
from ...shared.env import DEV_PASSWORD
from ...shared.exceptions import AuthenticationException, ServerError
from ...shared.interfaces.wsgi import RouteResponse
Expand All @@ -31,8 +32,9 @@ class ActionView(BaseView):
def action_route(self, request: Request) -> RouteResponse:
self.logger.debug("Start dispatching action request.")

assert_migration_index()

with get_new_os_conn() as conn:
with conn.cursor() as curs:
MigrationHelper.assert_migration_index(curs)
# Get user id.
user_id, access_token = self.get_user_id_from_headers(
request.headers, request.cookies
Expand All @@ -56,7 +58,9 @@ def action_route(self, request: Request) -> RouteResponse:
def internal_action_route(self, request: Request) -> RouteResponse:
self.logger.debug("Start dispatching internal action request.")

assert_migration_index()
with get_new_os_conn() as conn:
with conn.cursor() as curs:
MigrationHelper.assert_migration_index(curs)
self.check_internal_auth_password(request)

handler = ActionHandler(self.env, self.services, self.logging)
Expand All @@ -71,8 +75,8 @@ def internal_action_route(self, request: Request) -> RouteResponse:
def migrations_route(self, request: Request) -> RouteResponse:
self.logger.debug("Start executing migrations request.")
self.check_internal_auth_password(request)
handler = MigrationHandler(self.env, self.services, self.logging)
response = handler.handle_request(request.json)
manager = MigrationManager(self.env, self.services, self.logging)
response = manager.handle_request(request.json)
self.logger.debug("Migrations request finished successfully.")
return {"success": True, **response}, None

Expand Down
7 changes: 5 additions & 2 deletions openslides_backend/http/views/presenter_view.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
from ...migrations import assert_migration_index
from ...migrations.migration_helper import MigrationHelper
from ...presenter.presenter import PresenterHandler
from ...services.postgresql.db_connection_handling import get_new_os_conn
from ...shared.interfaces.wsgi import RouteResponse
from ..request import Request
from .base_view import BaseView, route
Expand All @@ -17,7 +18,9 @@ class PresenterView(BaseView):
def presenter_route(self, request: Request) -> RouteResponse:
self.logger.debug("Start dispatching presenter request.")

assert_migration_index()
with get_new_os_conn() as conn:
with conn.cursor() as curs:
MigrationHelper.assert_migration_index(curs)

# Handle request.
handler = PresenterHandler(
Expand Down
35 changes: 12 additions & 23 deletions openslides_backend/migrations/README.md
Original file line number Diff line number Diff line change
@@ -1,32 +1,21 @@
# Migrations for the Datastore
# TODO revise this file
# Migrations for the Database

The `migrate.py` script is the main entrypoint to execute migrations. The migrations itself are in the `migrations` folder. Each file can be arbitrarily named but must include a class called `Migration` that can be found by the loader. Note that all docker related files in this folder are only for **developing** migrations, not execute them. For execution in the dev mode, see the actual backend target for the dockerfile (`target dev`) and `dev/entrypoint.sh`.
The migrations will create shadow copies with `{name}_mig` of all tables to be migrated and rereference all triggers and references to those. Migration will be done on the `_mig`-tables. In the finalization step the original tables are deleted and the shadow copies put into place.
Collections in READ_MODELS will prevent writing on corresponding tables for all parrallel processes.
Collections in WRITE_MODELS will additionally prevent reading on corresponding tables for all parrallel processes.

There are three ways to execute migrations:

## 1) Developing migrations
This is done within the dockersetup in this folder. Note that the datastore needs to be checked out with the name `openslides-datastore-service` next to the backend repository.

- checkout the current datastore (in ../../openslides-datastore-service) and the current backend.
- `make dev`: Starts the compose setup -> A shell opens with the ability to run `migrate.py` and auxillary scripts.
- You can exit from it with `exit` and shut down the docker setup with `make stop-dev`
- You can write migrations in the backend and also adjust the Datastore at the same time since both are mounted into the container.

The following scripts can be used to make snapshots and trying out new migrations
The migrations themselves are in the `migrations` folder. Each file must start with a four digit number and can include certain functions that can be found by the loader. A psycopg cursor object will be passed as function parameter.
* data_definition: should do necessary schema changes
* data_manipulation: should pass the altered original data from the table to table_mig
* cleanup: should do all cleanups that aren't done automatically like deleting additional temporary tables. This step happens during finalization before all automatic changes.

#### Scripts for setting initial data
Only the current dataset is exported, so after a (re-)import, only one position exists in the datastore. Also note that importing clears the old content

- `export-data-only.sh` [to:export.json]
- `import-data-only.sh` [from:export.json]

#### Scripts for the full backup (Does a DB dump)
- `export-events.sh` [to:export.sql]
- `import-events.sh` [from:export.sql]

#### Downloading example data
- `fetch-example-data.sh` [to:example-data.json]
There are three ways to execute migrations:

## 1) The `migrate.py` script is the cli entrypoint to execute migrations.
Use python `migrate.py -h` to see all available commands.

## 2) Migrations in dev mode

Expand Down
Loading
Loading