1 """Index and backfill block_type_name
2
3 Revision ID: 22ef3915ccd8
4 Revises: cef24af2ec34
5 Create Date: 2023-10-30 10:37:20.922002
6
7 """
8
9 import sqlalchemy as sa 1 ctx 1a
10 from alembic import op 1 ctx 1a
11
12 # revision identifiers, used by Alembic.
13 revision = "22ef3915ccd8" 1 ctx 1a
14 down_revision = "cef24af2ec34" 1 ctx 1a
15 branch_labels = None 1 ctx 1a
16 depends_on = None 1 ctx 1a
17
18
19 def upgrade ( ) : 1 ctx 1a
20 with op . batch_alter_table ( "block_document" , schema = None ) as batch_op : 1 ctx 1a
21 batch_op . create_index ( 1 ctx 1a
22 batch_op . f ( "ix_block_document__block_type_name_name" ) ,
23 [ "block_type_name" , "name" ] ,
24 unique = False ,
25 )
26
27 backfill_query = """ 1 ctx 1a
28 UPDATE block_document
29 SET block_type_name = (SELECT name from block_type where block_type.id = block_document.block_type_id)
30 WHERE block_document.id in (SELECT id from block_document where block_type_name is null limit 500);
31 """
32
33 with op . get_context ( ) . autocommit_block ( ) : 1 ctx 1a
34 conn = op . get_bind ( ) 1 ctx 1a
35 while True : 1 ctx 1a
36 # Execute until we've backfilled all block_type_names
37 result = conn . execute ( sa . text ( backfill_query ) ) 1 ctx 1a
38 if result . rowcount <= 0 : 38 ↛ 35 line 38 didn't jump to line 35 because the condition on line 38 was always true 1 ctx 1a
39 break 1 ctx 1a
40
41
42 def downgrade ( ) : 1 ctx 1a
43 with op . get_context ( ) . autocommit_block ( ) :
44 op . execute (
45 """
46 DROP INDEX
47 ix_block_document__block_type_name_name
48 """
49 )