1# Copyright 2016 OpenMarket Ltd
2#
3# Licensed under the Apache License, Version 2.0 (the "License");
4# you may not use this file except in compliance with the License.
5# You may obtain a copy of the License at
6#
7#     http://www.apache.org/licenses/LICENSE-2.0
8#
9# Unless required by applicable law or agreed to in writing, software
10# distributed under the License is distributed on an "AS IS" BASIS,
11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12# See the License for the specific language governing permissions and
13# limitations under the License.
14import json
15import logging
16
17from synapse.storage.prepare_database import get_statements
18
19logger = logging.getLogger(__name__)
20
21
22ALTER_TABLE = """
23ALTER TABLE events ADD COLUMN sender TEXT;
24ALTER TABLE events ADD COLUMN contains_url BOOLEAN;
25"""
26
27
28def run_create(cur, database_engine, *args, **kwargs):
29    for statement in get_statements(ALTER_TABLE.splitlines()):
30        cur.execute(statement)
31
32    cur.execute("SELECT MIN(stream_ordering) FROM events")
33    rows = cur.fetchall()
34    min_stream_id = rows[0][0]
35
36    cur.execute("SELECT MAX(stream_ordering) FROM events")
37    rows = cur.fetchall()
38    max_stream_id = rows[0][0]
39
40    if min_stream_id is not None and max_stream_id is not None:
41        progress = {
42            "target_min_stream_id_inclusive": min_stream_id,
43            "max_stream_id_exclusive": max_stream_id + 1,
44            "rows_inserted": 0,
45        }
46        progress_json = json.dumps(progress)
47
48        sql = (
49            "INSERT into background_updates (update_name, progress_json)"
50            " VALUES (?, ?)"
51        )
52
53        cur.execute(sql, ("event_fields_sender_url", progress_json))
54
55
56def run_upgrade(cur, database_engine, *args, **kwargs):
57    pass
58