MatrixSynapse/synapse/storage/schema/main/delta/30/as_users.py

73 lines
2.6 KiB
Python
Raw Normal View History

2016-02-11 15:10:00 +01:00
# Copyright 2016 OpenMarket Ltd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import logging
from typing import Dict, Iterable, List, Tuple, cast
2016-02-11 15:10:00 +01:00
2018-07-09 08:09:20 +02:00
from synapse.config.appservice import load_appservices
from synapse.config.homeserver import HomeServerConfig
from synapse.storage.database import LoggingTransaction
from synapse.storage.engines import BaseDatabaseEngine
2016-02-11 15:10:00 +01:00
logger = logging.getLogger(__name__)
def run_create(cur: LoggingTransaction, database_engine: BaseDatabaseEngine) -> None:
2016-02-11 15:10:00 +01:00
# NULL indicates user was not registered by an appservice.
try:
cur.execute("ALTER TABLE users ADD COLUMN appservice_id TEXT")
except Exception:
# Maybe we already added the column? Hope so...
pass
2016-02-11 15:10:00 +01:00
def run_upgrade(
cur: LoggingTransaction,
database_engine: BaseDatabaseEngine,
config: HomeServerConfig,
) -> None:
2016-02-11 15:10:00 +01:00
cur.execute("SELECT name FROM users")
rows = cast(Iterable[Tuple[str]], cur.fetchall())
2016-02-11 15:10:00 +01:00
config_files = []
try:
config_files = config.appservice.app_service_config_files
2016-02-11 15:10:00 +01:00
except AttributeError:
logger.warning("Could not get app_service_config_files from config")
appservices = load_appservices(config.server.server_name, config_files)
2016-02-11 15:10:00 +01:00
owned: Dict[str, List[str]] = {}
2016-02-11 15:10:00 +01:00
for row in rows:
user_id = row[0]
for appservice in appservices:
if appservice.is_exclusive_user(user_id):
if user_id in owned.keys():
logger.error(
"user_id %s was owned by more than one application"
2019-06-20 11:32:02 +02:00
" service (IDs %s and %s); assigning arbitrarily to %s"
% (user_id, owned[user_id], appservice.id, owned[user_id])
2016-02-11 15:10:00 +01:00
)
2016-03-10 16:12:19 +01:00
owned.setdefault(appservice.id, []).append(user_id)
for as_id, user_ids in owned.items():
n = 100
2019-06-20 11:32:02 +02:00
user_chunks = (user_ids[i : i + 100] for i in range(0, len(user_ids), n))
2016-03-10 16:12:19 +01:00
for chunk in user_chunks:
cur.execute(
"UPDATE users SET appservice_id = ? WHERE name IN (%s)"
% (",".join("?" for _ in chunk),),
2019-06-20 11:32:02 +02:00
[as_id] + chunk,
2016-03-10 16:12:19 +01:00
)