-
-
Notifications
You must be signed in to change notification settings - Fork 30.8k
/
migration.py
2843 lines (2476 loc) · 114 KB
/
migration.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""Schema migration helpers."""
from __future__ import annotations
from abc import ABC, abstractmethod
from collections.abc import Callable, Iterable
import contextlib
from dataclasses import dataclass, replace as dataclass_replace
from datetime import timedelta
import logging
from time import time
from typing import TYPE_CHECKING, Any, cast, final
from uuid import UUID
import sqlalchemy
from sqlalchemy import ForeignKeyConstraint, MetaData, Table, func, text, update
from sqlalchemy.engine import CursorResult, Engine
from sqlalchemy.exc import (
DatabaseError,
IntegrityError,
InternalError,
OperationalError,
ProgrammingError,
SQLAlchemyError,
)
from sqlalchemy.orm.session import Session
from sqlalchemy.schema import AddConstraint, CreateTable, DropConstraint
from sqlalchemy.sql.expression import true
from sqlalchemy.sql.lambdas import StatementLambdaElement
from homeassistant.core import HomeAssistant
from homeassistant.util.enum import try_parse_enum
from homeassistant.util.ulid import ulid_at_time, ulid_to_bytes
from .auto_repairs.events.schema import (
correct_db_schema as events_correct_db_schema,
validate_db_schema as events_validate_db_schema,
)
from .auto_repairs.states.schema import (
correct_db_schema as states_correct_db_schema,
validate_db_schema as states_validate_db_schema,
)
from .auto_repairs.statistics.duplicates import (
delete_statistics_duplicates,
delete_statistics_meta_duplicates,
)
from .auto_repairs.statistics.schema import (
correct_db_schema as statistics_correct_db_schema,
validate_db_schema as statistics_validate_db_schema,
)
from .const import (
CONTEXT_ID_AS_BINARY_SCHEMA_VERSION,
EVENT_TYPE_IDS_SCHEMA_VERSION,
LEGACY_STATES_EVENT_ID_INDEX_SCHEMA_VERSION,
STATES_META_SCHEMA_VERSION,
SupportedDialect,
)
from .db_schema import (
BIG_INTEGER_SQL,
CONTEXT_ID_BIN_MAX_LENGTH,
DOUBLE_PRECISION_TYPE_SQL,
LEGACY_STATES_ENTITY_ID_LAST_UPDATED_INDEX,
LEGACY_STATES_EVENT_ID_INDEX,
MYSQL_COLLATE,
MYSQL_DEFAULT_CHARSET,
SCHEMA_VERSION,
STATISTICS_TABLES,
TABLE_STATES,
Base,
Events,
EventTypes,
LegacyBase,
MigrationChanges,
SchemaChanges,
States,
StatesMeta,
Statistics,
StatisticsMeta,
StatisticsRuns,
StatisticsShortTerm,
)
from .models import process_timestamp
from .models.time import datetime_to_timestamp_or_none
from .queries import (
batch_cleanup_entity_ids,
delete_duplicate_short_term_statistics_row,
delete_duplicate_statistics_row,
find_entity_ids_to_migrate,
find_event_type_to_migrate,
find_events_context_ids_to_migrate,
find_states_context_ids_to_migrate,
find_unmigrated_short_term_statistics_rows,
find_unmigrated_statistics_rows,
get_migration_changes,
has_entity_ids_to_migrate,
has_event_type_to_migrate,
has_events_context_ids_to_migrate,
has_states_context_ids_to_migrate,
has_used_states_entity_ids,
has_used_states_event_ids,
migrate_single_short_term_statistics_row_to_timestamp,
migrate_single_statistics_row_to_timestamp,
)
from .statistics import cleanup_statistics_timestamp_migration, get_start_time
from .tasks import RecorderTask
from .util import (
database_job_retry_wrapper,
database_job_retry_wrapper_method,
execute_stmt_lambda_element,
get_index_by_name,
retryable_database_job_method,
session_scope,
)
if TYPE_CHECKING:
from . import Recorder
# Live schema migration supported starting from schema version 42 or newer
# Schema version 41 was introduced in HA Core 2023.4
# Schema version 42 was introduced in HA Core 2023.11
LIVE_MIGRATION_MIN_SCHEMA_VERSION = 42
MIGRATION_NOTE_OFFLINE = (
"Note: this may take several hours on large databases and slow machines. "
"Home Assistant will not start until the upgrade is completed. Please be patient "
"and do not turn off or restart Home Assistant while the upgrade is in progress!"
)
MIGRATION_NOTE_MINUTES = (
"Note: this may take several minutes on large databases and slow machines. "
"Please be patient!"
)
MIGRATION_NOTE_WHILE = "This will take a while; please be patient!"
_EMPTY_ENTITY_ID = "missing.entity_id"
_EMPTY_EVENT_TYPE = "missing_event_type"
_LOGGER = logging.getLogger(__name__)
@dataclass
class _ColumnTypesForDialect:
big_int_type: str
timestamp_type: str
context_bin_type: str
_MYSQL_COLUMN_TYPES = _ColumnTypesForDialect(
big_int_type="INTEGER(20)",
timestamp_type=DOUBLE_PRECISION_TYPE_SQL,
context_bin_type=f"BLOB({CONTEXT_ID_BIN_MAX_LENGTH})",
)
_POSTGRESQL_COLUMN_TYPES = _ColumnTypesForDialect(
big_int_type="INTEGER",
timestamp_type=DOUBLE_PRECISION_TYPE_SQL,
context_bin_type="BYTEA",
)
_SQLITE_COLUMN_TYPES = _ColumnTypesForDialect(
big_int_type="INTEGER",
timestamp_type="FLOAT",
context_bin_type="BLOB",
)
_COLUMN_TYPES_FOR_DIALECT: dict[SupportedDialect | None, _ColumnTypesForDialect] = {
SupportedDialect.MYSQL: _MYSQL_COLUMN_TYPES,
SupportedDialect.POSTGRESQL: _POSTGRESQL_COLUMN_TYPES,
SupportedDialect.SQLITE: _SQLITE_COLUMN_TYPES,
}
def raise_if_exception_missing_str(ex: Exception, match_substrs: Iterable[str]) -> None:
"""Raise if the exception and cause do not contain the match substrs."""
lower_ex_strs = [str(ex).lower(), str(ex.__cause__).lower()]
for str_sub in match_substrs:
for exc_str in lower_ex_strs:
if exc_str and str_sub in exc_str:
return
raise ex
def _get_schema_version(session: Session) -> int | None:
"""Get the schema version."""
res = (
session.query(SchemaChanges.schema_version)
.order_by(SchemaChanges.change_id.desc())
.first()
)
return getattr(res, "schema_version", None)
def get_schema_version(session_maker: Callable[[], Session]) -> int | None:
"""Get the schema version."""
try:
with session_scope(session=session_maker(), read_only=True) as session:
return _get_schema_version(session)
except Exception:
_LOGGER.exception("Error when determining DB schema version")
return None
@dataclass(frozen=True, kw_only=True)
class SchemaValidationStatus:
"""Store schema validation status."""
current_version: int
migration_needed: bool
non_live_data_migration_needed: bool
schema_errors: set[str]
start_version: int
def _schema_is_current(current_version: int) -> bool:
"""Check if the schema is current."""
return current_version == SCHEMA_VERSION
def validate_db_schema(
hass: HomeAssistant, instance: Recorder, session_maker: Callable[[], Session]
) -> SchemaValidationStatus | None:
"""Check if the schema is valid.
This checks that the schema is the current version as well as for some common schema
errors caused by manual migration between database engines, for example importing an
SQLite database to MariaDB.
"""
schema_errors: set[str] = set()
current_version = get_schema_version(session_maker)
if current_version is None:
return None
if is_current := _schema_is_current(current_version):
# We can only check for further errors if the schema is current, because
# columns may otherwise not exist etc.
schema_errors = _find_schema_errors(hass, instance, session_maker)
schema_migration_needed = not is_current
_non_live_data_migration_needed = non_live_data_migration_needed(
instance, session_maker, current_version
)
return SchemaValidationStatus(
current_version=current_version,
non_live_data_migration_needed=_non_live_data_migration_needed,
migration_needed=schema_migration_needed or _non_live_data_migration_needed,
schema_errors=schema_errors,
start_version=current_version,
)
def _find_schema_errors(
hass: HomeAssistant, instance: Recorder, session_maker: Callable[[], Session]
) -> set[str]:
"""Find schema errors."""
schema_errors: set[str] = set()
schema_errors |= statistics_validate_db_schema(instance)
schema_errors |= states_validate_db_schema(instance)
schema_errors |= events_validate_db_schema(instance)
return schema_errors
def live_migration(schema_status: SchemaValidationStatus) -> bool:
"""Check if live migration is possible."""
return (
schema_status.current_version >= LIVE_MIGRATION_MIN_SCHEMA_VERSION
and not schema_status.non_live_data_migration_needed
)
def pre_migrate_schema(engine: Engine) -> None:
"""Prepare for migration.
This function is called before calling Base.metadata.create_all.
"""
inspector = sqlalchemy.inspect(engine)
if inspector.has_table("statistics_meta") and not inspector.has_table(
"statistics_short_term"
):
# Prepare for migration from schema with statistics_meta table but no
# statistics_short_term table
LegacyBase.metadata.create_all(
engine, (LegacyBase.metadata.tables["statistics_short_term"],)
)
def _migrate_schema(
instance: Recorder,
hass: HomeAssistant,
engine: Engine,
session_maker: Callable[[], Session],
schema_status: SchemaValidationStatus,
end_version: int,
) -> SchemaValidationStatus:
"""Check if the schema needs to be upgraded."""
current_version = schema_status.current_version
start_version = schema_status.start_version
if current_version < end_version:
_LOGGER.warning(
"The database is about to upgrade from schema version %s to %s%s",
current_version,
end_version,
(
f". {MIGRATION_NOTE_OFFLINE}"
if current_version < LIVE_MIGRATION_MIN_SCHEMA_VERSION
else ""
),
)
schema_status = dataclass_replace(schema_status, current_version=end_version)
for version in range(current_version, end_version):
new_version = version + 1
_LOGGER.info("Upgrading recorder db schema to version %s", new_version)
_apply_update(instance, hass, engine, session_maker, new_version, start_version)
with session_scope(session=session_maker()) as session:
session.add(SchemaChanges(schema_version=new_version))
# Log at the same level as the long schema changes
# so its clear that the upgrade is done
_LOGGER.warning("Upgrade to version %s done", new_version)
return schema_status
def migrate_schema_non_live(
instance: Recorder,
hass: HomeAssistant,
engine: Engine,
session_maker: Callable[[], Session],
schema_status: SchemaValidationStatus,
) -> SchemaValidationStatus:
"""Check if the schema needs to be upgraded."""
end_version = LIVE_MIGRATION_MIN_SCHEMA_VERSION
return _migrate_schema(
instance, hass, engine, session_maker, schema_status, end_version
)
def migrate_schema_live(
instance: Recorder,
hass: HomeAssistant,
engine: Engine,
session_maker: Callable[[], Session],
schema_status: SchemaValidationStatus,
) -> SchemaValidationStatus:
"""Check if the schema needs to be upgraded."""
end_version = SCHEMA_VERSION
schema_status = _migrate_schema(
instance, hass, engine, session_maker, schema_status, end_version
)
# Repairs are currently done during the live migration
if schema_errors := schema_status.schema_errors:
_LOGGER.warning(
"Database is about to correct DB schema errors: %s",
", ".join(sorted(schema_errors)),
)
statistics_correct_db_schema(instance, schema_errors)
states_correct_db_schema(instance, schema_errors)
events_correct_db_schema(instance, schema_errors)
return schema_status
def _get_migration_changes(session: Session) -> dict[str, int]:
"""Return migration changes as a dict."""
migration_changes: dict[str, int] = {
row[0]: row[1]
for row in execute_stmt_lambda_element(session, get_migration_changes())
}
return migration_changes
def non_live_data_migration_needed(
instance: Recorder,
session_maker: Callable[[], Session],
schema_version: int,
) -> bool:
"""Return True if non-live data migration is needed.
This must only be called if database schema is current.
"""
migration_needed = False
with session_scope(session=session_maker()) as session:
migration_changes = _get_migration_changes(session)
for migrator_cls in NON_LIVE_DATA_MIGRATORS:
migrator = migrator_cls(schema_version, migration_changes)
migration_needed |= migrator.needs_migrate(instance, session)
return migration_needed
def migrate_data_non_live(
instance: Recorder,
session_maker: Callable[[], Session],
schema_status: SchemaValidationStatus,
) -> None:
"""Do non-live data migration.
This must be called after non-live schema migration is completed.
"""
with session_scope(session=session_maker()) as session:
migration_changes = _get_migration_changes(session)
for migrator_cls in NON_LIVE_DATA_MIGRATORS:
migrator = migrator_cls(schema_status.start_version, migration_changes)
migrator.migrate_all(instance, session_maker)
def migrate_data_live(
instance: Recorder,
session_maker: Callable[[], Session],
schema_status: SchemaValidationStatus,
) -> None:
"""Queue live schema migration tasks.
This must be called after live schema migration is completed.
"""
with session_scope(session=session_maker()) as session:
migration_changes = _get_migration_changes(session)
for migrator_cls in LIVE_DATA_MIGRATORS:
migrator = migrator_cls(schema_status.start_version, migration_changes)
migrator.queue_migration(instance, session)
def _create_index(
session_maker: Callable[[], Session], table_name: str, index_name: str
) -> None:
"""Create an index for the specified table.
The index name should match the name given for the index
within the table definition described in the models
"""
table = Table(table_name, Base.metadata)
_LOGGER.debug("Looking up index %s for table %s", index_name, table_name)
# Look up the index object by name from the table is the models
index_list = [idx for idx in table.indexes if idx.name == index_name]
if not index_list:
_LOGGER.debug("The index %s no longer exists", index_name)
return
index = index_list[0]
_LOGGER.debug("Creating %s index", index_name)
_LOGGER.warning(
"Adding index `%s` to table `%s`. %s",
index_name,
table_name,
MIGRATION_NOTE_MINUTES,
)
with session_scope(session=session_maker()) as session:
try:
connection = session.connection()
index.create(connection)
except (InternalError, OperationalError, ProgrammingError) as err:
raise_if_exception_missing_str(err, ["already exists", "duplicate"])
_LOGGER.warning(
"Index %s already exists on %s, continuing", index_name, table_name
)
_LOGGER.warning("Finished adding index `%s` to table `%s`", index_name, table_name)
def _execute_or_collect_error(
session_maker: Callable[[], Session], query: str, errors: list[str]
) -> bool:
"""Execute a query or collect an error."""
with session_scope(session=session_maker()) as session:
try:
session.connection().execute(text(query))
except SQLAlchemyError as err:
errors.append(str(err))
return False
return True
def _drop_index(
session_maker: Callable[[], Session],
table_name: str,
index_name: str,
quiet: bool | None = None,
) -> None:
"""Drop an index from a specified table.
There is no universal way to do something like `DROP INDEX IF EXISTS`
so we will simply execute the DROP command and ignore any exceptions
WARNING: Due to some engines (MySQL at least) being unable to use bind
parameters in a DROP INDEX statement (at least via SQLAlchemy), the query
string here is generated from the method parameters without sanitizing.
DO NOT USE THIS FUNCTION IN ANY OPERATION THAT TAKES USER INPUT.
"""
_LOGGER.warning(
"Dropping index `%s` from table `%s`. %s",
index_name,
table_name,
MIGRATION_NOTE_MINUTES,
)
index_to_drop: str | None = None
with session_scope(session=session_maker()) as session:
index_to_drop = get_index_by_name(session, table_name, index_name)
if index_to_drop is None:
_LOGGER.warning(
"The index `%s` on table `%s` no longer exists", index_name, table_name
)
return
errors: list[str] = []
for query in (
# Engines like DB2/Oracle
f"DROP INDEX {index_name}",
# Engines like SQLite, SQL Server
f"DROP INDEX {table_name}.{index_name}",
# Engines like MySQL, MS Access
f"DROP INDEX {index_name} ON {table_name}",
# Engines like postgresql may have a prefix
# ex idx_16532_ix_events_event_type_time_fired
f"DROP INDEX {index_to_drop}",
):
if _execute_or_collect_error(session_maker, query, errors):
_LOGGER.warning(
"Finished dropping index `%s` from table `%s`", index_name, table_name
)
return
if not quiet:
_LOGGER.warning(
"Failed to drop index `%s` from table `%s`. Schema "
"Migration will continue; this is not a "
"critical operation: %s",
index_name,
table_name,
errors,
)
def _add_columns(
session_maker: Callable[[], Session], table_name: str, columns_def: list[str]
) -> None:
"""Add columns to a table."""
_LOGGER.warning(
"Adding columns %s to table %s. %s",
", ".join(column.split(" ")[0] for column in columns_def),
table_name,
MIGRATION_NOTE_MINUTES,
)
columns_def = [f"ADD {col_def}" for col_def in columns_def]
with session_scope(session=session_maker()) as session:
try:
connection = session.connection()
connection.execute(
text(f"ALTER TABLE {table_name} {', '.join(columns_def)}")
)
except (InternalError, OperationalError, ProgrammingError):
# Some engines support adding all columns at once,
# this error is when they don't
_LOGGER.info("Unable to use quick column add. Adding 1 by 1")
else:
return
for column_def in columns_def:
with session_scope(session=session_maker()) as session:
try:
connection = session.connection()
connection.execute(text(f"ALTER TABLE {table_name} {column_def}"))
except (InternalError, OperationalError, ProgrammingError) as err:
raise_if_exception_missing_str(err, ["already exists", "duplicate"])
_LOGGER.warning(
"Column %s already exists on %s, continuing",
column_def.split(" ")[1],
table_name,
)
def _modify_columns(
session_maker: Callable[[], Session],
engine: Engine,
table_name: str,
columns_def: list[str],
) -> None:
"""Modify columns in a table."""
if engine.dialect.name == SupportedDialect.SQLITE:
_LOGGER.debug(
(
"Skipping to modify columns %s in table %s; "
"Modifying column length in SQLite is unnecessary, "
"it does not impose any length restrictions"
),
", ".join(column.split(" ")[0] for column in columns_def),
table_name,
)
return
_LOGGER.warning(
"Modifying columns %s in table %s. %s",
", ".join(column.split(" ")[0] for column in columns_def),
table_name,
MIGRATION_NOTE_MINUTES,
)
if engine.dialect.name == SupportedDialect.POSTGRESQL:
columns_def = [
f"ALTER {column} TYPE {type_}"
for column, type_ in (col_def.split(" ", 1) for col_def in columns_def)
]
elif engine.dialect.name == "mssql":
columns_def = [f"ALTER COLUMN {col_def}" for col_def in columns_def]
else:
columns_def = [f"MODIFY {col_def}" for col_def in columns_def]
with session_scope(session=session_maker()) as session:
try:
connection = session.connection()
connection.execute(
text(f"ALTER TABLE {table_name} {', '.join(columns_def)}")
)
except (InternalError, OperationalError):
_LOGGER.info("Unable to use quick column modify. Modifying 1 by 1")
else:
return
for column_def in columns_def:
with session_scope(session=session_maker()) as session:
try:
connection = session.connection()
connection.execute(text(f"ALTER TABLE {table_name} {column_def}"))
except (InternalError, OperationalError):
_LOGGER.exception(
"Could not modify column %s in table %s", column_def, table_name
)
raise
def _update_states_table_with_foreign_key_options(
session_maker: Callable[[], Session], engine: Engine
) -> None:
"""Add the options to foreign key constraints.
This is not supported for SQLite because it does not support
dropping constraints.
"""
if engine.dialect.name not in (SupportedDialect.MYSQL, SupportedDialect.POSTGRESQL):
raise RuntimeError(
"_update_states_table_with_foreign_key_options not supported for "
f"{engine.dialect.name}"
)
inspector = sqlalchemy.inspect(engine)
tmp_states_table = Table(TABLE_STATES, MetaData())
alters = [
{
"old_fk": ForeignKeyConstraint(
(), (), name=foreign_key["name"], table=tmp_states_table
),
"columns": foreign_key["constrained_columns"],
}
for foreign_key in inspector.get_foreign_keys(TABLE_STATES)
if foreign_key["name"] # It's not possible to drop an unnamed constraint
and (
# MySQL/MariaDB will have empty options
not foreign_key.get("options")
# Postgres will have ondelete set to None
or foreign_key.get("options", {}).get("ondelete") is None
)
]
if not alters:
return
states_key_constraints = Base.metadata.tables[TABLE_STATES].foreign_key_constraints
for alter in alters:
with session_scope(session=session_maker()) as session:
try:
connection = session.connection()
connection.execute(DropConstraint(alter["old_fk"])) # type: ignore[no-untyped-call]
for fkc in states_key_constraints:
if fkc.column_keys == alter["columns"]:
# AddConstraint mutates the constraint passed to it, we need to
# undo that to avoid changing the behavior of the table schema.
# https://github.com/sqlalchemy/sqlalchemy/blob/96f1172812f858fead45cdc7874abac76f45b339/lib/sqlalchemy/sql/ddl.py#L746-L748
create_rule = fkc._create_rule # noqa: SLF001
add_constraint = AddConstraint(fkc) # type: ignore[no-untyped-call]
fkc._create_rule = create_rule # noqa: SLF001
connection.execute(add_constraint)
except (InternalError, OperationalError):
_LOGGER.exception(
"Could not update foreign options in %s table", TABLE_STATES
)
raise
def _drop_foreign_key_constraints(
session_maker: Callable[[], Session], engine: Engine, table: str, column: str
) -> None:
"""Drop foreign key constraints for a table on specific columns.
This is not supported for SQLite because it does not support
dropping constraints.
"""
if engine.dialect.name not in (SupportedDialect.MYSQL, SupportedDialect.POSTGRESQL):
raise RuntimeError(
f"_drop_foreign_key_constraints not supported for {engine.dialect.name}"
)
inspector = sqlalchemy.inspect(engine)
## Find matching named constraints and bind the ForeignKeyConstraints to the table
tmp_table = Table(table, MetaData())
drops = [
ForeignKeyConstraint((), (), name=foreign_key["name"], table=tmp_table)
for foreign_key in inspector.get_foreign_keys(table)
if foreign_key["name"] and foreign_key["constrained_columns"] == [column]
]
for drop in drops:
with session_scope(session=session_maker()) as session:
try:
connection = session.connection()
connection.execute(DropConstraint(drop)) # type: ignore[no-untyped-call]
except (InternalError, OperationalError):
_LOGGER.exception(
"Could not drop foreign constraints in %s table on %s",
TABLE_STATES,
column,
)
raise
def _restore_foreign_key_constraints(
session_maker: Callable[[], Session],
engine: Engine,
foreign_columns: list[tuple[str, str, str | None, str | None]],
) -> None:
"""Restore foreign key constraints."""
for table, column, foreign_table, foreign_column in foreign_columns:
constraints = Base.metadata.tables[table].foreign_key_constraints
for constraint in constraints:
if constraint.column_keys == [column]:
break
else:
_LOGGER.info("Did not find a matching constraint for %s.%s", table, column)
continue
inspector = sqlalchemy.inspect(engine)
if any(
foreign_key["name"] and foreign_key["constrained_columns"] == [column]
for foreign_key in inspector.get_foreign_keys(table)
):
_LOGGER.info(
"The database already has a matching constraint for %s.%s",
table,
column,
)
continue
if TYPE_CHECKING:
assert foreign_table is not None
assert foreign_column is not None
# AddConstraint mutates the constraint passed to it, we need to
# undo that to avoid changing the behavior of the table schema.
# https://github.com/sqlalchemy/sqlalchemy/blob/96f1172812f858fead45cdc7874abac76f45b339/lib/sqlalchemy/sql/ddl.py#L746-L748
create_rule = constraint._create_rule # noqa: SLF001
add_constraint = AddConstraint(constraint) # type: ignore[no-untyped-call]
constraint._create_rule = create_rule # noqa: SLF001
try:
_add_constraint(session_maker, add_constraint, table, column)
except IntegrityError:
_LOGGER.exception(
(
"Could not update foreign options in %s table, will delete "
"violations and try again"
),
table,
)
_delete_foreign_key_violations(
session_maker, engine, table, column, foreign_table, foreign_column
)
_add_constraint(session_maker, add_constraint, table, column)
def _add_constraint(
session_maker: Callable[[], Session],
add_constraint: AddConstraint,
table: str,
column: str,
) -> None:
"""Add a foreign key constraint."""
_LOGGER.warning(
"Adding foreign key constraint to %s.%s. "
"Note: this can take several minutes on large databases and slow "
"machines. Please be patient!",
table,
column,
)
with session_scope(session=session_maker()) as session:
try:
connection = session.connection()
connection.execute(add_constraint)
except (InternalError, OperationalError):
_LOGGER.exception("Could not update foreign options in %s table", table)
raise
def _delete_foreign_key_violations(
session_maker: Callable[[], Session],
engine: Engine,
table: str,
column: str,
foreign_table: str,
foreign_column: str,
) -> None:
"""Remove rows which violate the constraints."""
if engine.dialect.name not in (SupportedDialect.MYSQL, SupportedDialect.POSTGRESQL):
raise RuntimeError(
f"_delete_foreign_key_violations not supported for {engine.dialect.name}"
)
_LOGGER.warning(
"Rows in table %s where %s references non existing %s.%s will be %s. "
"Note: this can take several minutes on large databases and slow "
"machines. Please be patient!",
table,
column,
foreign_table,
foreign_column,
"set to NULL" if table == foreign_table else "deleted",
)
result: CursorResult | None = None
if table == foreign_table:
# In case of a foreign reference to the same table, we set invalid
# references to NULL instead of deleting as deleting rows may
# cause additional invalid references to be created. This is to handle
# old_state_id referencing a missing state.
if engine.dialect.name == SupportedDialect.MYSQL:
while result is None or result.rowcount > 0:
with session_scope(session=session_maker()) as session:
# The subquery (SELECT {foreign_column} from {foreign_table}) is
# to be compatible with old MySQL versions which do not allow
# referencing the table being updated in the WHERE clause.
result = session.connection().execute(
text(
f"UPDATE {table} as t1 " # noqa: S608
f"SET {column} = NULL "
"WHERE ("
f"t1.{column} IS NOT NULL AND "
"NOT EXISTS "
"(SELECT 1 "
f"FROM (SELECT {foreign_column} from {foreign_table}) AS t2 "
f"WHERE t2.{foreign_column} = t1.{column})) "
"LIMIT 100000;"
)
)
elif engine.dialect.name == SupportedDialect.POSTGRESQL:
while result is None or result.rowcount > 0:
with session_scope(session=session_maker()) as session:
# PostgreSQL does not support LIMIT in UPDATE clauses, so we
# update matches from a limited subquery instead.
result = session.connection().execute(
text(
f"UPDATE {table} " # noqa: S608
f"SET {column} = NULL "
f"WHERE {column} in "
f"(SELECT {column} from {table} as t1 "
"WHERE ("
f"t1.{column} IS NOT NULL AND "
"NOT EXISTS "
"(SELECT 1 "
f"FROM {foreign_table} AS t2 "
f"WHERE t2.{foreign_column} = t1.{column})) "
"LIMIT 100000);"
)
)
return
if engine.dialect.name == SupportedDialect.MYSQL:
while result is None or result.rowcount > 0:
with session_scope(session=session_maker()) as session:
result = session.connection().execute(
# We don't use an alias for the table we're deleting from,
# support of the form `DELETE FROM table AS t1` was added in
# MariaDB 11.6 and is not supported by MySQL. MySQL and older
# MariaDB instead support the from `DELETE t1 from table AS t1`
# which is undocumented for MariaDB.
text(
f"DELETE FROM {table} " # noqa: S608
"WHERE ("
f"{table}.{column} IS NOT NULL AND "
"NOT EXISTS "
"(SELECT 1 "
f"FROM {foreign_table} AS t2 "
f"WHERE t2.{foreign_column} = {table}.{column})) "
"LIMIT 100000;"
)
)
elif engine.dialect.name == SupportedDialect.POSTGRESQL:
while result is None or result.rowcount > 0:
with session_scope(session=session_maker()) as session:
# PostgreSQL does not support LIMIT in DELETE clauses, so we
# delete matches from a limited subquery instead.
result = session.connection().execute(
text(
f"DELETE FROM {table} " # noqa: S608
f"WHERE {column} in "
f"(SELECT {column} from {table} as t1 "
"WHERE ("
f"t1.{column} IS NOT NULL AND "
"NOT EXISTS "
"(SELECT 1 "
f"FROM {foreign_table} AS t2 "
f"WHERE t2.{foreign_column} = t1.{column})) "
"LIMIT 100000);"
)
)
@database_job_retry_wrapper("Apply migration update", 10)
def _apply_update(
instance: Recorder,
hass: HomeAssistant,
engine: Engine,
session_maker: Callable[[], Session],
new_version: int,
old_version: int,
) -> None:
"""Perform operations to bring schema up to date."""
migrator_cls = _SchemaVersionMigrator.get_migrator(new_version)
migrator_cls(instance, hass, engine, session_maker, old_version).apply_update()
class _SchemaVersionMigrator(ABC):
"""Perform operations to bring schema up to date."""
__migrators: dict[int, type[_SchemaVersionMigrator]] = {}
def __init_subclass__(cls, target_version: int, **kwargs: Any) -> None:
"""Post initialisation processing."""
super().__init_subclass__(**kwargs)
if target_version in _SchemaVersionMigrator.__migrators:
raise ValueError("Duplicated version")
_SchemaVersionMigrator.__migrators[target_version] = cls
def __init__(
self,
instance: Recorder,
hass: HomeAssistant,
engine: Engine,
session_maker: Callable[[], Session],
old_version: int,
) -> None:
"""Initialize."""
self.instance = instance
self.hass = hass
self.engine = engine
self.session_maker = session_maker
self.old_version = old_version
assert engine.dialect.name is not None, "Dialect name must be set"
dialect = try_parse_enum(SupportedDialect, engine.dialect.name)
self.column_types = _COLUMN_TYPES_FOR_DIALECT.get(dialect, _SQLITE_COLUMN_TYPES)
@classmethod
def get_migrator(cls, target_version: int) -> type[_SchemaVersionMigrator]:
"""Return a migrator for a specific schema version."""
try:
return cls.__migrators[target_version]
except KeyError as err:
raise ValueError(
f"No migrator for schema version {target_version}"
) from err
@final
def apply_update(self) -> None:
"""Perform operations to bring schema up to date."""
self._apply_update()
@abstractmethod
def _apply_update(self) -> None:
"""Version specific update method."""
class _SchemaVersion1Migrator(_SchemaVersionMigrator, target_version=1):
def _apply_update(self) -> None:
"""Version specific update method."""
# This used to create ix_events_time_fired, but it was removed in version 32
class _SchemaVersion2Migrator(_SchemaVersionMigrator, target_version=2):
def _apply_update(self) -> None:
"""Version specific update method."""
# Create compound start/end index for recorder_runs
_create_index(self.session_maker, "recorder_runs", "ix_recorder_runs_start_end")