deb-heat/heat/db/sqlalchemy/migrate_repo/versions/065_root_resource.py
Steve Baker 1b2cd7495d Add resource.root_stack_id column
This change adds a root_stack_id column to the resource
record to allow a subsequent change enforce
max_resources_per_stack with a single query instead of the
many it currently requires.

This change includes the following:
- Data migration to add the resource.root_stack_id column
  and populate all existing resources with their calculated
  root stack
- Make new resources aquire and set their root_stack_id on
  store or update.
- StackResource._validate_nested_resources use the stored
  root_stack_id resulting in a ~15% performance improvement
  for the creation time of a test stack containing 40 nested
  stacks.

Change-Id: I2b00285514235834131222012408d2b5b2b37d30
Partial-Bug: 1489548
2015-09-22 15:43:15 +12:00

49 lines
1.9 KiB
Python

#
# 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 sqlalchemy
def upgrade(migrate_engine):
meta = sqlalchemy.MetaData(bind=migrate_engine)
res_table = sqlalchemy.Table('resource', meta, autoload=True)
stack_table = sqlalchemy.Table('stack', meta, autoload=True)
root_stack_id = sqlalchemy.Column('root_stack_id',
sqlalchemy.String(36))
root_stack_id.create(res_table)
root_stack_idx = sqlalchemy.Index('ix_resource_root_stack_id',
res_table.c.root_stack_id,
mysql_length=36)
root_stack_idx.create(migrate_engine)
# build stack->owner relationship for all stacks
stmt = sqlalchemy.select([stack_table.c.id, stack_table.c.owner_id])
stacks = migrate_engine.execute(stmt)
parent_stacks = dict([(s.id, s.owner_id) for s in stacks])
def root_for_stack(stack_id):
owner_id = parent_stacks.get(stack_id)
if owner_id:
return root_for_stack(owner_id)
return stack_id
# for each stack, update the resources with the root_stack_id
for stack_id, owner_id in parent_stacks.items():
root_id = root_for_stack(stack_id)
values = {'root_stack_id': root_id}
update = res_table.update().where(
res_table.c.stack_id == stack_id).values(values)
migrate_engine.execute(update)