The Database Layer

The nova.db.api Module

Defines interface for DB access.

Functions in this module are imported into the nova.db namespace. Call these functions from nova.db namespace, not the nova.db.api namespace.

All functions in this module return objects that implement a dictionary-like interface. Currently, many of these objects are sqlalchemy objects that implement a dictionary interface. However, a future goal is to have all of these objects be simple dictionaries.

class NovaDBAPI

Bases: object

Nova’s DB API wrapper class.

This wraps the oslo DB API with an option to be able to use eventlet’s thread pooling. Since the CONF variable may not be loaded at the time this class is instantiated, we must look at it on the first DB API call.

action_event_finish(context, values)

Finish an event on an instance action.

action_event_get_by_id(context, action_id, event_id)
action_event_start(context, values)

Start an event on an instance action.

action_events_get(context, action_id)

Get the events by action id.

action_finish(context, values)

Finish an action for an instance.

action_get_by_request_id(context, uuid, request_id)

Get the action by request_id and given instance.

action_start(context, values)

Start an action for an instance.

actions_get(context, uuid)

Get all instance actions for the provided instance.

agent_build_create(context, values)

Create a new agent build entry.

agent_build_destroy(context, agent_update_id)

Destroy agent build entry.

agent_build_get_all(context, hypervisor=None)

Get all agent builds.

agent_build_get_by_triple(context, hypervisor, os, architecture)

Get agent build by hypervisor/OS/architecture triple.

agent_build_update(context, agent_build_id, values)

Update agent build entry.

aggregate_create(context, values, metadata=None)

Create a new aggregate with metadata.

aggregate_delete(context, aggregate_id)

Delete an aggregate.

aggregate_get(context, aggregate_id)

Get a specific aggregate by id.

aggregate_get_all(context)

Get all aggregates.

aggregate_get_by_host(context, host, key=None)

Get a list of aggregates that host belongs to.

aggregate_get_by_metadata_key(context, key)
aggregate_host_add(context, aggregate_id, host)

Add host to the aggregate.

aggregate_host_delete(context, aggregate_id, host)

Delete the given host from the aggregate.

aggregate_host_get_all(context, aggregate_id)

Get hosts for the specified aggregate.

aggregate_host_get_by_metadata_key(context, key)

Get hosts with a specific metadata key metadata for all aggregates.

Returns a dictionary where each key is a hostname and each value is a set of the key values return value: {machine: set( az1, az2 )}

aggregate_metadata_add(context, aggregate_id, metadata, set_delete=False)

Add/update metadata. If set_delete=True, it adds only.

aggregate_metadata_delete(context, aggregate_id, key)

Delete the given metadata key.

aggregate_metadata_get(context, aggregate_id)

Get metadata for the specified aggregate.

aggregate_metadata_get_by_host(context, host, key=None)

Get metadata for all aggregates that host belongs to.

Returns a dictionary where each value is a set, this is to cover the case where there two aggregates have different values for the same key. Optional key filter

aggregate_metadata_get_by_metadata_key(context, aggregate_id, key)

Get metadata for an aggregate by metadata key.

aggregate_update(context, aggregate_id, values)

Update the attributes of an aggregates.

If values contains a metadata key, it updates the aggregate metadata too.

archive_deleted_rows(context, max_rows=None)

Move up to max_rows rows from production tables to corresponding shadow tables.

Returns:number of rows archived.
archive_deleted_rows_for_table(context, tablename, max_rows=None)

Move up to max_rows rows from tablename to corresponding shadow table.

Returns:number of rows archived.
block_device_mapping_create(context, values, legacy=True)

Create an entry of block device mapping.

block_device_mapping_destroy(context, bdm_id)

Destroy the block device mapping.

block_device_mapping_destroy_by_instance_and_device(context, instance_uuid, device_name)

Destroy the block device mapping.

block_device_mapping_destroy_by_instance_and_volume(context, instance_uuid, volume_id)

Destroy the block device mapping.

block_device_mapping_get_all_by_instance(context, instance_uuid, use_slave=False)

Get all block device mapping belonging to an instance.

block_device_mapping_get_by_volume_id(context, volume_id, columns_to_join=None)

Get block device mapping for a given volume.

block_device_mapping_update(context, bdm_id, values, legacy=True)

Update an entry of block device mapping.

block_device_mapping_update_or_create(context, values, legacy=True)

Update an entry of block device mapping.

If not existed, create a new entry

bw_usage_get(context, uuid, start_period, mac, use_slave=False)

Return bw usage for instance and mac in a given audit period.

bw_usage_get_by_uuids(context, uuids, start_period)

Return bw usages for instance(s) in a given audit period.

bw_usage_update(context, uuid, mac, start_period, bw_in, bw_out, last_ctr_in, last_ctr_out, last_refreshed=None, update_cells=True)

Update cached bandwidth usage for an instance’s network based on mac address. Creates new record if needed.

cell_create(context, values)

Create a new child Cell entry.

cell_delete(context, cell_name)

Delete a child Cell.

cell_get(context, cell_name)

Get a specific child Cell.

cell_get_all(context)

Get all child Cells.

cell_update(context, cell_name, values)

Update a child Cell entry.

certificate_create(context, values)

Create a certificate from the values dictionary.

certificate_get_all_by_project(context, project_id)

Get all certificates for a project.

certificate_get_all_by_user(context, user_id)

Get all certificates for a user.

certificate_get_all_by_user_and_project(context, user_id, project_id)

Get all certificates for a user and project.

compute_node_create(context, values)

Create a compute node from the values dictionary.

Parameters:
  • context – The security context
  • values – Dictionary containing compute node properties
Returns:

Dictionary-like object containing the properties of the created node, including its corresponding service and statistics

compute_node_delete(context, compute_id)

Delete a compute node from the database.

Parameters:
  • context – The security context
  • compute_id – ID of the compute node

Raises ComputeHostNotFound if compute node with the given ID doesn’t exist.

compute_node_get(context, compute_id)

Get a compute node by its id.

Parameters:
  • context – The security context
  • compute_id – ID of the compute node
Returns:

Dictionary-like object containing properties of the compute node, including its corresponding service

Raises ComputeHostNotFound if compute node with the given ID doesn’t exist.

compute_node_get_all(context, no_date_fields=False)

Get all computeNodes.

Parameters:
  • context – The security context
  • no_date_fields – If set to True, excludes ‘created_at’, ‘updated_at’, ‘deleted_at’ and ‘deleted’ fields from the output, thus significantly reducing its size. Set to False by default
Returns:

List of dictionaries each containing compute node properties, including corresponding service

compute_node_get_by_service_id(context, service_id)

Get a compute node by its associated service id.

Parameters:
  • context – The security context
  • service_id – ID of the associated service
Returns:

Dictionary-like object containing properties of the compute node, including its corresponding service and statistics

Raises ServiceNotFound if service with the given ID doesn’t exist.

compute_node_search_by_hypervisor(context, hypervisor_match)

Get compute nodes by hypervisor hostname.

Parameters:
  • context – The security context
  • hypervisor_match – The hypervisor hostname
Returns:

List of dictionary-like objects each containing compute node properties, including corresponding service

compute_node_statistics(context)

Get aggregate statistics over all compute nodes.

Parameters:context – The security context
Returns:Dictionary containing compute node characteristics summed up over all the compute nodes, e.g. ‘vcpus’, ‘free_ram_mb’ etc.
compute_node_update(context, compute_id, values)

Set the given properties on a compute node and update it.

Parameters:
  • context – The security context
  • compute_id – ID of the compute node
  • values – Dictionary containing compute node properties to be updated
Returns:

Dictionary-like object containing the properties of the updated compute node, including its corresponding service and statistics

Raises ComputeHostNotFound if compute node with the given ID doesn’t exist.

console_create(context, values)

Create a console.

console_delete(context, console_id)

Delete a console.

console_get(context, console_id, instance_uuid=None)

Get a specific console (possibly on a given instance).

console_get_all_by_instance(context, instance_uuid, columns_to_join=None)

Get consoles for a given instance.

console_get_by_pool_instance(context, pool_id, instance_uuid)

Get console entry for a given instance and pool.

console_pool_create(context, values)

Create console pool.

console_pool_get_all_by_host_type(context, host, console_type)

Fetch all pools for given proxy host and type.

console_pool_get_by_host_type(context, compute_host, proxy_host, console_type)

Fetch a console pool for a given proxy host, compute host, and type.

constraint(**conditions)

Return a constraint object suitable for use with some updates.

dnsdomain_get(context, fqdomain)

Get the db record for the specified domain.

dnsdomain_get_all(context)

Get a list of all dnsdomains in our database.

dnsdomain_list(context)

Get a list of all zones in our database, public and private.

dnsdomain_register_for_project(context, fqdomain, project)

Associated a DNS domain with a project id.

dnsdomain_register_for_zone(context, fqdomain, zone)

Associated a DNS domain with an availability zone.

dnsdomain_unregister(context, fqdomain)

Purge associations for the specified DNS zone.

ec2_instance_create(context, instance_uuid, id=None)

Create the ec2 id to instance uuid mapping on demand.

ec2_instance_get_by_id(context, instance_id)
ec2_instance_get_by_uuid(context, instance_uuid)
ec2_snapshot_create(context, snapshot_id, forced_id=None)
ec2_volume_create(context, volume_id, forced_id=None)
ec2_volume_get_by_id(context, volume_id)
ec2_volume_get_by_uuid(context, volume_uuid)
equal_any(*values)

Return an equality condition object suitable for use in a constraint.

Equal_any conditions require that a model object’s attribute equal any one of the given values.

fixed_ip_associate(context, address, instance_uuid, network_id=None, reserved=False)

Associate fixed ip to instance.

Raises if fixed ip is not available.

fixed_ip_associate_pool(context, network_id, instance_uuid=None, host=None)

Find free ip in network and associate it to instance or host.

Raises if one is not available.

fixed_ip_bulk_create(context, ips)

Create a lot of fixed ips from the values dictionary.

fixed_ip_create(context, values)

Create a fixed ip from the values dictionary.

fixed_ip_disassociate(context, address)

Disassociate a fixed ip from an instance by address.

fixed_ip_disassociate_all_by_timeout(context, host, time)

Disassociate old fixed ips from host.

fixed_ip_get(context, id, get_network=False)

Get fixed ip by id or raise if it does not exist.

If get_network is true, also return the associated network.

fixed_ip_get_all(context)

Get all defined fixed ips.

fixed_ip_get_by_address(context, address, columns_to_join=None)

Get a fixed ip by address or raise if it does not exist.

fixed_ip_get_by_address_detailed(context, address)

Get detailed fixed ip info by address or raise if it does not exist.

fixed_ip_get_by_floating_address(context, floating_address)

Get a fixed ip by a floating address.

fixed_ip_get_by_host(context, host)

Get fixed ips by compute host.

fixed_ip_get_by_instance(context, instance_uuid)

Get fixed ips by instance or raise if none exist.

fixed_ip_get_by_network_host(context, network_uuid, host)

Get fixed ip for a host in a network.

fixed_ip_update(context, address, values)

Create a fixed ip from the values dictionary.

fixed_ips_by_virtual_interface(context, vif_id)

Get fixed ips by virtual interface or raise if none exist.

flavor_access_add(context, flavor_id, project_id)

Add flavor access for project.

flavor_access_get_by_flavor_id(context, flavor_id)

Get flavor access by flavor id.

flavor_access_remove(context, flavor_id, project_id)

Remove flavor access for project.

flavor_create(context, values, projects=None)

Create a new instance type.

flavor_destroy(context, name)

Delete an instance type.

flavor_extra_specs_delete(context, flavor_id, key)

Delete the given extra specs item.

flavor_extra_specs_get(context, flavor_id)

Get all extra specs for an instance type.

flavor_extra_specs_get_item(context, flavor_id, key)

Get extra specs by key and flavor_id.

flavor_extra_specs_update_or_create(context, flavor_id, extra_specs)

Create or update instance type extra specs.

This adds or modifies the key/value pairs specified in the extra specs dict argument

flavor_get(context, id)

Get instance type by id.

flavor_get_all(context, inactive=False, filters=None, sort_key='flavorid', sort_dir='asc', limit=None, marker=None)

Get all instance flavors.

flavor_get_by_flavor_id(context, id, read_deleted=None)

Get instance type by flavor id.

flavor_get_by_name(context, name)

Get instance type by name.

floating_ip_allocate_address(context, project_id, pool, auto_assigned=False)

Allocate free floating ip from specified pool and return the address.

Raises if one is not available.

floating_ip_bulk_create(context, ips)

Create a lot of floating ips from the values dictionary.

floating_ip_bulk_destroy(context, ips)

Destroy a lot of floating ips from the values dictionary.

floating_ip_create(context, values)

Create a floating ip from the values dictionary.

floating_ip_deallocate(context, address)

Deallocate a floating ip by address.

floating_ip_destroy(context, address)

Destroy the floating_ip or raise if it does not exist.

floating_ip_disassociate(context, address)

Disassociate a floating ip from a fixed ip by address.

Returns:the fixed ip record joined to network record or None if the ip was not associated to an ip.
floating_ip_fixed_ip_associate(context, floating_address, fixed_address, host)

Associate a floating ip to a fixed_ip by address.

Returns:the fixed ip record joined to network record or None if the ip was already associated to the fixed ip.
floating_ip_get(context, id)
floating_ip_get_all(context)

Get all floating ips.

floating_ip_get_all_by_host(context, host)

Get all floating ips by host.

floating_ip_get_all_by_project(context, project_id)

Get all floating ips by project.

floating_ip_get_by_address(context, address)

Get a floating ip by address or raise if it doesn’t exist.

floating_ip_get_by_fixed_address(context, fixed_address)

Get a floating ips by fixed address.

floating_ip_get_by_fixed_ip_id(context, fixed_ip_id)

Get a floating ips by fixed address.

floating_ip_get_pools(context)

Returns a list of floating ip pools.

floating_ip_set_auto_assigned(context, address)

Set auto_assigned flag to floating ip.

floating_ip_update(context, address, values)

Update a floating ip by address or raise if it doesn’t exist.

get_ec2_instance_id_by_uuid(context, instance_id)

Get ec2 id through uuid from instance_id_mappings table.

get_ec2_snapshot_id_by_uuid(context, snapshot_id)
get_instance_uuid_by_ec2_id(context, ec2_id)

Get uuid through ec2 id from instance_id_mappings table.

get_snapshot_uuid_by_ec2_id(context, ec2_id)
instance_add_security_group(context, instance_id, security_group_id)

Associate the given security group with the given instance.

instance_create(context, values)

Create an instance from the values dictionary.

instance_destroy(context, instance_uuid, constraint=None, update_cells=True)

Destroy the instance or raise if it does not exist.

instance_fault_create(context, values)

Create a new Instance Fault.

instance_fault_get_by_instance_uuids(context, instance_uuids)

Get all instance faults for the provided instance_uuids.

instance_floating_address_get_all(context, instance_uuid)

Get all floating ip addresses of an instance.

instance_get(context, instance_id, columns_to_join=None)

Get an instance or raise if it does not exist.

instance_get_active_by_window_joined(context, begin, end=None, project_id=None, host=None)

Get instances and joins active during a certain time window.

Specifying a project_id will filter for a certain project. Specifying a host will filter for instances on a given compute host.

instance_get_all(context, columns_to_join=None)

Get all instances.

instance_get_all_by_filters(context, filters, sort_key='created_at', sort_dir='desc', limit=None, marker=None, columns_to_join=None, use_slave=False)

Get all instances that match all filters.

instance_get_all_by_host(context, host, columns_to_join=None, use_slave=False)

Get all instances belonging to a host.

instance_get_all_by_host_and_node(context, host, node)

Get all instances belonging to a node.

instance_get_all_by_host_and_not_type(context, host, type_id=None)

Get all instances belonging to a host with a different type_id.

instance_get_all_hung_in_rebooting(context, reboot_window)

Get all instances stuck in a rebooting state.

instance_get_by_uuid(context, uuid, columns_to_join=None, use_slave=False)

Get an instance or raise if it does not exist.

instance_get_floating_address(context, instance_id)

Get the first floating ip address of an instance.

instance_group_create(context, values, policies=None, metadata=None, members=None)

Create a new group with metadata.

Each group will receive a unique uuid. This will be used for access to the group.

instance_group_delete(context, group_uuid)

Delete an group.

instance_group_get(context, group_uuid)

Get a specific group by id.

instance_group_get_all(context)

Get all groups.

instance_group_get_all_by_project_id(context, project_id)

Get all groups for a specific project_id.

instance_group_member_delete(context, group_uuid, instance_id)

Delete a specific member from the group.

instance_group_members_add(context, group_uuid, members, set_delete=False)

Add members to the group.

instance_group_members_get(context, group_uuid)

Get the members from the group.

instance_group_metadata_add(context, group_uuid, metadata, set_delete=False)

Add metadata to the group.

instance_group_metadata_delete(context, group_uuid, key)

Delete metadata from the group.

instance_group_metadata_get(context, group_uuid)

Get the metadata from the group.

instance_group_policies_add(context, group_uuid, policies, set_delete=False)

Add policies to the group.

instance_group_policies_get(context, group_uuid)

Get the policies from the group.

instance_group_policy_delete(context, group_uuid, policy)

Delete a specific policy from the group.

instance_group_update(context, group_uuid, values)

Update the attributes of an group.

instance_info_cache_delete(context, instance_uuid)

Deletes an existing instance_info_cache record

Parameters:instance_uuid – = uuid of the instance tied to the cache record
instance_info_cache_get(context, instance_uuid)

Gets an instance info cache from the table.

Parameters:instance_uuid – = uuid of the info cache’s instance
instance_info_cache_update(context, instance_uuid, values)

Update an instance info cache record in the table.

Parameters:
  • instance_uuid – = uuid of info cache’s instance
  • values – = dict containing column values to update
instance_metadata_delete(context, instance_uuid, key)

Delete the given metadata item.

instance_metadata_get(context, instance_uuid)

Get all metadata for an instance.

instance_metadata_update(context, instance_uuid, metadata, delete)

Update metadata if it exists, otherwise create it.

instance_remove_security_group(context, instance_id, security_group_id)

Disassociate the given security group from the given instance.

instance_system_metadata_get(context, instance_uuid)

Get all system metadata for an instance.

instance_system_metadata_update(context, instance_uuid, metadata, delete)

Update metadata if it exists, otherwise create it.

instance_update(context, instance_uuid, values, update_cells=True)

Set the given properties on an instance and update it.

Raises NotFound if instance does not exist.

instance_update_and_get_original(context, instance_uuid, values, update_cells=True, columns_to_join=None)

Set the given properties on an instance and update it. Return a shallow copy of the original instance reference, as well as the updated one.

Parameters:
  • context – = request context object
  • instance_uuid – = instance id or uuid
  • values – = dict containing column values
Returns:

a tuple of the form (old_instance_ref, new_instance_ref)

Raises NotFound if instance does not exist.

key_pair_count_by_user(context, user_id)

Count number of key pairs for the given user ID.

key_pair_create(context, values)

Create a key_pair from the values dictionary.

key_pair_destroy(context, user_id, name)

Destroy the key_pair or raise if it does not exist.

key_pair_get(context, user_id, name)

Get a key_pair or raise if it does not exist.

key_pair_get_all_by_user(context, user_id)

Get all key_pairs by user.

migration_create(context, values)

Create a migration record.

migration_get(context, migration_id)

Finds a migration by the id.

migration_get_all_by_filters(context, filters)

Finds all migrations in progress.

migration_get_by_instance_and_status(context, instance_uuid, status)

Finds a migration by the instance uuid its migrating.

migration_get_in_progress_by_host_and_node(context, host, node)

Finds all migrations for the given host + node that are not yet confirmed or reverted.

migration_get_unconfirmed_by_dest_compute(context, confirm_window, dest_compute, use_slave=False)

Finds all unconfirmed migrations within the confirmation window for a specific destination compute host.

migration_update(context, id, values)

Update a migration instance.

network_associate(context, project_id, network_id=None, force=False)

Associate a free network to a project.

network_count_reserved_ips(context, network_id)

Return the number of reserved ips in the network.

network_create_safe(context, values)

Create a network from the values dict.

The network is only returned if the create succeeds. If the create violates constraints because the network already exists, no exception is raised.

network_delete_safe(context, network_id)

Delete network with key network_id.

This method assumes that the network is not associated with any project

network_disassociate(context, network_id, disassociate_host=True, disassociate_project=True)

Disassociate the network from project or host

Raises if it does not exist.

network_get(context, network_id, project_only='allow_none')

Get a network or raise if it does not exist.

network_get_all(context, project_only='allow_none')

Return all defined networks.

network_get_all_by_host(context, host)

All networks for which the given host is the network host.

network_get_all_by_uuids(context, network_uuids, project_only='allow_none')

Return networks by ids.

network_get_associated_fixed_ips(context, network_id, host=None)

Get all network’s ips that have been associated.

network_get_by_cidr(context, cidr)

Get a network by cidr or raise if it does not exist.

network_get_by_uuid(context, uuid)

Get a network by uuid or raise if it does not exist.

network_in_use_on_host(context, network_id, host=None)

Indicates if a network is currently in use on host.

network_set_host(context, network_id, host_id)

Safely set the host for network.

network_update(context, network_id, values)

Set the given properties on a network and update it.

Raises NotFound if network does not exist.

not_equal(*values)

Return an inequality condition object suitable for use in a constraint.

Not_equal conditions require that a model object’s attribute differs from all of the given values.

pci_device_destroy(context, node_id, address)

Delete a PCI device record.

pci_device_get_all_by_instance_uuid(context, instance_uuid)

Get PCI devices allocated to instance.

pci_device_get_all_by_node(context, node_id)

Get all PCI devices for one host.

pci_device_get_by_addr(context, node_id, dev_addr)

Get PCI device by address.

pci_device_get_by_id(context, id)

Get PCI device by id.

pci_device_update(context, node_id, address, value)

Update a pci device.

project_get_networks(context, project_id, associate=True)

Return the network associated with the project.

If associate is true, it will attempt to associate a new network if one is not found, otherwise it returns None.

provider_fw_rule_create(context, rule)

Add a firewall rule at the provider level (all hosts & instances).

provider_fw_rule_destroy(context, rule_id)

Delete a provider firewall rule from the database.

provider_fw_rule_get_all(context)

Get all provider-level firewall rules.

quota_class_create(context, class_name, resource, limit)

Create a quota class for the given name and resource.

quota_class_get(context, class_name, resource)

Retrieve a quota class or raise if it does not exist.

quota_class_get_all_by_name(context, class_name)

Retrieve all quotas associated with a given quota class.

quota_class_get_default(context)

Retrieve all default quotas.

quota_class_update(context, class_name, resource, limit)

Update a quota class or raise if it does not exist.

quota_create(context, project_id, resource, limit, user_id=None)

Create a quota for the given project and resource.

quota_destroy_all_by_project(context, project_id)

Destroy all quotas associated with a given project.

quota_destroy_all_by_project_and_user(context, project_id, user_id)

Destroy all quotas associated with a given project and user.

quota_get(context, project_id, resource, user_id=None)

Retrieve a quota or raise if it does not exist.

quota_get_all(context, project_id)

Retrieve all user quotas associated with a given project.

quota_get_all_by_project(context, project_id)

Retrieve all quotas associated with a given project.

quota_get_all_by_project_and_user(context, project_id, user_id)

Retrieve all quotas associated with a given project and user.

quota_reserve(context, resources, quotas, user_quotas, deltas, expire, until_refresh, max_age, project_id=None, user_id=None)

Check quotas and create appropriate reservations.

quota_update(context, project_id, resource, limit, user_id=None)

Update a quota or raise if it does not exist.

quota_usage_get(context, project_id, resource, user_id=None)

Retrieve a quota usage or raise if it does not exist.

quota_usage_get_all_by_project(context, project_id)

Retrieve all usage associated with a given resource.

quota_usage_get_all_by_project_and_user(context, project_id, user_id)

Retrieve all usage associated with a given resource.

quota_usage_update(context, project_id, user_id, resource, **kwargs)

Update a quota usage or raise if it does not exist.

reservation_commit(context, reservations, project_id=None, user_id=None)

Commit quota reservations.

reservation_expire(context)

Roll back any expired reservations.

reservation_rollback(context, reservations, project_id=None, user_id=None)

Roll back quota reservations.

s3_image_create(context, image_uuid)

Create local s3 image represented by provided uuid.

s3_image_get(context, image_id)

Find local s3 image represented by the provided id.

s3_image_get_by_uuid(context, image_uuid)

Find local s3 image represented by the provided uuid.

security_group_create(context, values)

Create a new security group.

security_group_default_rule_create(context, values)
security_group_default_rule_destroy(context, security_group_rule_default_id)
security_group_default_rule_get(context, security_group_rule_default_id)
security_group_default_rule_list(context)
security_group_destroy(context, security_group_id)

Deletes a security group.

security_group_ensure_default(context)

Ensure default security group exists for a project_id.

Returns a tuple with the first element being a bool indicating if the default security group previously existed. Second element is the dict used to create the default security group.

security_group_get(context, security_group_id, columns_to_join=None)

Get security group by its id.

security_group_get_all(context)

Get all security groups.

security_group_get_by_instance(context, instance_uuid)

Get security groups to which the instance is assigned.

security_group_get_by_name(context, project_id, group_name, columns_to_join=None)

Returns a security group with the specified name from a project.

security_group_get_by_project(context, project_id)

Get all security groups belonging to a project.

security_group_in_use(context, group_id)

Indicates if a security group is currently in use.

security_group_rule_count_by_group(context, security_group_id)

Count rules in a given security group.

security_group_rule_create(context, values)

Create a new security group.

security_group_rule_destroy(context, security_group_rule_id)

Deletes a security group rule.

security_group_rule_get(context, security_group_rule_id)

Gets a security group rule.

security_group_rule_get_by_security_group(context, security_group_id, columns_to_join=None)

Get all rules for a given security group.

security_group_rule_get_by_security_group_grantee(context, security_group_id)

Get all rules that grant access to the given security group.

security_group_update(context, security_group_id, values, columns_to_join=None)

Update a security group.

service_create(context, values)

Create a service from the values dictionary.

service_destroy(context, service_id)

Destroy the service or raise if it does not exist.

service_get(context, service_id, with_compute_node=False)

Get a service or raise if it does not exist.

service_get_all(context, disabled=None)

Get all services.

service_get_all_by_host(context, host)

Get all services for a given host.

service_get_all_by_topic(context, topic)

Get all services for a given topic.

service_get_by_args(context, host, binary)

Get the state of a service by node name and binary.

service_get_by_compute_host(context, host)

Get the service entry for a given compute host.

Returns the service entry joined with the compute_node entry.

service_get_by_host_and_topic(context, host, topic)

Get a service by host it’s on and topic it listens to.

service_update(context, service_id, values)

Set the given properties on a service and update it.

Raises NotFound if service does not exist.

task_log_begin_task(context, task_name, period_beginning, period_ending, host, task_items=None, message=None)

Mark a task as started for a given host/time period.

task_log_end_task(context, task_name, period_beginning, period_ending, host, errors, message=None)

Mark a task as complete for a given host/time period.

task_log_get(context, task_name, period_beginning, period_ending, host, state=None)
task_log_get_all(context, task_name, period_beginning, period_ending, host=None, state=None)
virtual_interface_create(context, values)

Create a virtual interface record in the database.

virtual_interface_delete_by_instance(context, instance_id)

Delete virtual interface records associated with instance.

virtual_interface_get(context, vif_id)

Gets a virtual interface from the table.

virtual_interface_get_all(context)

Gets all virtual interfaces from the table.

virtual_interface_get_by_address(context, address)

Gets a virtual interface from the table filtering on address.

virtual_interface_get_by_instance(context, instance_id, use_slave=False)

Gets all virtual_interfaces for instance.

virtual_interface_get_by_instance_and_network(context, instance_id, network_id)

Gets all virtual interfaces for instance.

virtual_interface_get_by_uuid(context, vif_uuid)

Gets a virtual interface from the table filtering on vif uuid.

vol_get_usage_by_time(context, begin)

Return volumes usage that have been updated after a specified time.

vol_usage_update(context, id, rd_req, rd_bytes, wr_req, wr_bytes, instance_id, project_id, user_id, availability_zone, update_totals=False)

Update cached volume usage for a volume

Creates new record if needed.

The Sqlalchemy Driver

The nova.db.sqlalchemy.api Module

Implementation of SQLAlchemy backend.

The nova.db.sqlalchemy.models Module

SQLAlchemy models for nova data.

class AgentBuild(**kwargs)

Bases: sqlalchemy.ext.declarative.api.Base, nova.db.sqlalchemy.models.NovaBase

Represents an agent build.

architecture
created_at
deleted
deleted_at
hypervisor
id
md5hash
os
updated_at
url
version
class Aggregate(**kwargs)

Bases: sqlalchemy.ext.declarative.api.Base, nova.db.sqlalchemy.models.NovaBase

Represents a cluster of hosts that exists in this zone.

availability_zone
created_at
deleted
deleted_at
hosts
id
metadetails
name
updated_at
class AggregateHost(**kwargs)

Bases: sqlalchemy.ext.declarative.api.Base, nova.db.sqlalchemy.models.NovaBase

Represents a host that is member of an aggregate.

aggregate_id
created_at
deleted
deleted_at
host
id
updated_at
class AggregateMetadata(**kwargs)

Bases: sqlalchemy.ext.declarative.api.Base, nova.db.sqlalchemy.models.NovaBase

Represents a metadata key/value pair for an aggregate.

aggregate_id
created_at
deleted
deleted_at
id
key
updated_at
value
class BandwidthUsage(**kwargs)

Bases: sqlalchemy.ext.declarative.api.Base, nova.db.sqlalchemy.models.NovaBase

Cache for instance bandwidth usage data pulled from the hypervisor.

bw_in
bw_out
created_at
deleted
deleted_at
id
last_ctr_in
last_ctr_out
last_refreshed
mac
start_period
updated_at
uuid
class BlockDeviceMapping(**kwargs)

Bases: sqlalchemy.ext.declarative.api.Base, nova.db.sqlalchemy.models.NovaBase

Represents block device mapping that is defined by EC2.

boot_index
connection_info
created_at
delete_on_termination
deleted
deleted_at
destination_type
device_name
device_type
disk_bus
guest_format
id
image_id
instance
instance_uuid
no_device
snapshot_id
source_type
updated_at
volume_id
volume_size
class Cell(**kwargs)

Bases: sqlalchemy.ext.declarative.api.Base, nova.db.sqlalchemy.models.NovaBase

Represents parent and child cells of this cell. Cells can have multiple parents and children, so there could be any number of entries with is_parent=True or False

api_url
created_at
deleted
deleted_at
id
is_parent
name
transport_url
updated_at
weight_offset
weight_scale
class Certificate(**kwargs)

Bases: sqlalchemy.ext.declarative.api.Base, nova.db.sqlalchemy.models.NovaBase

Represents a x509 certificate.

created_at
deleted
deleted_at
file_name
id
project_id
updated_at
user_id
class ComputeNode(**kwargs)

Bases: sqlalchemy.ext.declarative.api.Base, nova.db.sqlalchemy.models.NovaBase

Represents a running compute service on a host.

cpu_info
created_at
current_workload
deleted
deleted_at
disk_available_least
extra_resources
free_disk_gb
free_ram_mb
host_ip
hypervisor_hostname
hypervisor_type
hypervisor_version
id
local_gb
local_gb_used
memory_mb
memory_mb_used
metrics
pci_stats
running_vms
service
service_id
stats
supported_instances
updated_at
vcpus
vcpus_used
class Console(**kwargs)

Bases: sqlalchemy.ext.declarative.api.Base, nova.db.sqlalchemy.models.NovaBase

Represents a console session for an instance.

created_at
deleted
deleted_at
id
instance_name
instance_uuid
password
pool
pool_id
port
updated_at
class ConsolePool(**kwargs)

Bases: sqlalchemy.ext.declarative.api.Base, nova.db.sqlalchemy.models.NovaBase

Represents pool of consoles on the same physical node.

address
compute_host
console_type
created_at
deleted
deleted_at
host
id
password
public_hostname
updated_at
username
class DNSDomain(**kwargs)

Bases: sqlalchemy.ext.declarative.api.Base, nova.db.sqlalchemy.models.NovaBase

Represents a DNS domain with availability zone or project info.

availability_zone
created_at
deleted
deleted_at
domain
project_id
scope
updated_at
class FixedIp(**kwargs)

Bases: sqlalchemy.ext.declarative.api.Base, nova.db.sqlalchemy.models.NovaBase

Represents a fixed ip for an instance.

address
allocated
created_at
deleted
deleted_at
host
id
instance
instance_uuid
leased
network
network_id
reserved
updated_at
virtual_interface_id
class FloatingIp(**kwargs)

Bases: sqlalchemy.ext.declarative.api.Base, nova.db.sqlalchemy.models.NovaBase

Represents a floating ip that dynamically forwards to a fixed ip.

address
auto_assigned
created_at
deleted
deleted_at
fixed_ip
fixed_ip_id
host
id
interface
pool
project_id
updated_at
class Instance(**kwargs)

Bases: sqlalchemy.ext.declarative.api.Base, nova.db.sqlalchemy.models.NovaBase

Represents a guest VM.

access_ip_v4
access_ip_v6
architecture
auto_disk_config
availability_zone
cell_name
cleaned
config_drive
created_at
default_ephemeral_device
default_swap_device
deleted
deleted_at
disable_terminate
display_description
display_name
ephemeral_gb
ephemeral_key_uuid
host
hostname
id
image_ref
injected_files = []
instance_type_id
internal_id
kernel_id
key_data
key_name
launch_index
launched_at
launched_on
locked
locked_by
memory_mb
name
node
os_type
power_state
progress
project_id
ramdisk_id
reservation_id
root_device_name
root_gb
scheduled_at
shutdown_terminate
task_state
terminated_at
updated_at
user_data
user_id
uuid
vcpus
vm_mode
vm_state
class InstanceAction(**kwargs)

Bases: sqlalchemy.ext.declarative.api.Base, nova.db.sqlalchemy.models.NovaBase

Track client actions on an instance.

The intention is that there will only be one of these per user request. A lookup by (instance_uuid, request_id) should always return a single result.

action
created_at
deleted
deleted_at
finish_time
id
instance_uuid
message
project_id
request_id
start_time
updated_at
user_id
class InstanceActionEvent(**kwargs)

Bases: sqlalchemy.ext.declarative.api.Base, nova.db.sqlalchemy.models.NovaBase

Track events that occur during an InstanceAction.

action_id
created_at
deleted
deleted_at
details
event
finish_time
host
id
result
start_time
traceback
updated_at
class InstanceFault(**kwargs)

Bases: sqlalchemy.ext.declarative.api.Base, nova.db.sqlalchemy.models.NovaBase

code
created_at
deleted
deleted_at
details
host
id
instance_uuid
message
updated_at
class InstanceGroup(**kwargs)

Bases: sqlalchemy.ext.declarative.api.Base, nova.db.sqlalchemy.models.NovaBase

Represents an instance group.

A group will maintain a collection of instances and the relationship between them.

created_at
deleted
deleted_at
id
members
metadetails
name
policies
project_id
updated_at
user_id
uuid
class InstanceGroupMember(**kwargs)

Bases: sqlalchemy.ext.declarative.api.Base, nova.db.sqlalchemy.models.NovaBase

Represents the members for an instance group.

created_at
deleted
deleted_at
group_id
id
instance_id
updated_at
class InstanceGroupMetadata(**kwargs)

Bases: sqlalchemy.ext.declarative.api.Base, nova.db.sqlalchemy.models.NovaBase

Represents a key/value pair for an instance group.

created_at
deleted
deleted_at
group_id
id
key
updated_at
value
class InstanceGroupPolicy(**kwargs)

Bases: sqlalchemy.ext.declarative.api.Base, nova.db.sqlalchemy.models.NovaBase

Represents the policy type for an instance group.

created_at
deleted
deleted_at
group_id
id
policy
updated_at
class InstanceIdMapping(**kwargs)

Bases: sqlalchemy.ext.declarative.api.Base, nova.db.sqlalchemy.models.NovaBase

Compatibility layer for the EC2 instance service.

created_at
deleted
deleted_at
id
updated_at
uuid
class InstanceInfoCache(**kwargs)

Bases: sqlalchemy.ext.declarative.api.Base, nova.db.sqlalchemy.models.NovaBase

Represents a cache of information about an instance

created_at
deleted
deleted_at
id
instance
instance_uuid
network_info
updated_at
class InstanceMetadata(**kwargs)

Bases: sqlalchemy.ext.declarative.api.Base, nova.db.sqlalchemy.models.NovaBase

Represents a user-provided metadata key/value pair for an instance.

created_at
deleted
deleted_at
id
instance
instance_uuid
key
updated_at
value
class InstanceSystemMetadata(**kwargs)

Bases: sqlalchemy.ext.declarative.api.Base, nova.db.sqlalchemy.models.NovaBase

Represents a system-owned metadata key/value pair for an instance.

created_at
deleted
deleted_at
id
instance
instance_uuid
key
primary_join = 'and_(InstanceSystemMetadata.instance_uuid == Instance.uuid, InstanceSystemMetadata.deleted == 0)'
updated_at
value
class InstanceTypeExtraSpecs(**kwargs)

Bases: sqlalchemy.ext.declarative.api.Base, nova.db.sqlalchemy.models.NovaBase

Represents additional specs as key/value pairs for an instance_type.

created_at
deleted
deleted_at
id
instance_type
instance_type_id
key
updated_at
value
class InstanceTypeProjects(**kwargs)

Bases: sqlalchemy.ext.declarative.api.Base, nova.db.sqlalchemy.models.NovaBase

Represent projects associated instance_types.

created_at
deleted
deleted_at
id
instance_type
instance_type_id
project_id
updated_at
class InstanceTypes(**kwargs)

Bases: sqlalchemy.ext.declarative.api.Base, nova.db.sqlalchemy.models.NovaBase

Represents possible flavors for instances.

Note: instance_type and flavor are synonyms and the term instance_type is deprecated and in the process of being removed.

created_at
deleted
deleted_at
disabled
ephemeral_gb
flavorid
id
is_public
memory_mb
name
root_gb
rxtx_factor
swap
updated_at
vcpu_weight
vcpus
class IscsiTarget(**kwargs)

Bases: sqlalchemy.ext.declarative.api.Base, nova.db.sqlalchemy.models.NovaBase

Represents an iscsi target for a given host.

created_at
deleted
deleted_at
host
id
target_num
updated_at
volume
volume_id
class KeyPair(**kwargs)

Bases: sqlalchemy.ext.declarative.api.Base, nova.db.sqlalchemy.models.NovaBase

Represents a public key pair for ssh.

created_at
deleted
deleted_at
fingerprint
id
name
public_key
updated_at
user_id
MediumText()
class Migration(**kwargs)

Bases: sqlalchemy.ext.declarative.api.Base, nova.db.sqlalchemy.models.NovaBase

Represents a running host-to-host migration.

created_at
deleted
deleted_at
dest_compute
dest_host
dest_node
id
instance
instance_uuid
new_instance_type_id
old_instance_type_id
source_compute
source_node
status
updated_at
class Network(**kwargs)

Bases: sqlalchemy.ext.declarative.api.Base, nova.db.sqlalchemy.models.NovaBase

Represents a network.

bridge
bridge_interface
broadcast
cidr
cidr_v6
created_at
deleted
deleted_at
dhcp_server
dhcp_start
dns1
dns2
enable_dhcp
gateway
gateway_v6
host
id
injected
label
mtu
multi_host
netmask
netmask_v6
priority
project_id
rxtx_base
share_address
updated_at
uuid
vlan
vpn_private_address
vpn_public_address
vpn_public_port
class NovaBase

Bases: nova.openstack.common.db.sqlalchemy.models.SoftDeleteMixin, nova.openstack.common.db.sqlalchemy.models.TimestampMixin, nova.openstack.common.db.sqlalchemy.models.ModelBase

metadata = None
save(session=None)
class PciDevice(**kwargs)

Bases: sqlalchemy.ext.declarative.api.Base, nova.db.sqlalchemy.models.NovaBase

Represents a PCI host device that can be passed through to instances.

address
compute_node_id
created_at
deleted
deleted_at
dev_id
dev_type
extra_info
id
instance
instance_uuid
label
product_id
status
updated_at
vendor_id
class ProjectUserQuota(**kwargs)

Bases: sqlalchemy.ext.declarative.api.Base, nova.db.sqlalchemy.models.NovaBase

Represents a single quota override for a user with in a project.

created_at
deleted
deleted_at
hard_limit
id
project_id
resource
uniq_name = 'uniq_project_user_quotas0user_id0project_id0resource0deleted'
updated_at
user_id
class ProviderFirewallRule(**kwargs)

Bases: sqlalchemy.ext.declarative.api.Base, nova.db.sqlalchemy.models.NovaBase

Represents a rule in a security group.

cidr
created_at
deleted
deleted_at
from_port
id
protocol
to_port
updated_at
class Quota(**kwargs)

Bases: sqlalchemy.ext.declarative.api.Base, nova.db.sqlalchemy.models.NovaBase

Represents a single quota override for a project.

If there is no row for a given project id and resource, then the default for the quota class is used. If there is no row for a given quota class and resource, then the default for the deployment is used. If the row is present but the hard limit is Null, then the resource is unlimited.

created_at
deleted
deleted_at
hard_limit
id
project_id
resource
updated_at
class QuotaClass(**kwargs)

Bases: sqlalchemy.ext.declarative.api.Base, nova.db.sqlalchemy.models.NovaBase

Represents a single quota override for a quota class.

If there is no row for a given quota class and resource, then the default for the deployment is used. If the row is present but the hard limit is Null, then the resource is unlimited.

class_name
created_at
deleted
deleted_at
hard_limit
id
resource
updated_at
class QuotaUsage(**kwargs)

Bases: sqlalchemy.ext.declarative.api.Base, nova.db.sqlalchemy.models.NovaBase

Represents the current usage for a given resource.

created_at
deleted
deleted_at
id
in_use
project_id
reserved
resource
total
until_refresh
updated_at
user_id
class Reservation(**kwargs)

Bases: sqlalchemy.ext.declarative.api.Base, nova.db.sqlalchemy.models.NovaBase

Represents a resource reservation for quotas.

created_at
deleted
deleted_at
delta
expire
id
project_id
resource
updated_at
usage
usage_id
user_id
uuid
class S3Image(**kwargs)

Bases: sqlalchemy.ext.declarative.api.Base, nova.db.sqlalchemy.models.NovaBase

Compatibility layer for the S3 image service talking to Glance.

created_at
deleted
deleted_at
id
updated_at
uuid
class SecurityGroup(**kwargs)

Bases: sqlalchemy.ext.declarative.api.Base, nova.db.sqlalchemy.models.NovaBase

Represents a security group.

created_at
deleted
deleted_at
description
id
instances
name
project_id
updated_at
user_id
class SecurityGroupIngressDefaultRule(**kwargs)

Bases: sqlalchemy.ext.declarative.api.Base, nova.db.sqlalchemy.models.NovaBase

cidr
created_at
deleted
deleted_at
from_port
id
protocol
to_port
updated_at
class SecurityGroupIngressRule(**kwargs)

Bases: sqlalchemy.ext.declarative.api.Base, nova.db.sqlalchemy.models.NovaBase

Represents a rule in a security group.

cidr
created_at
deleted
deleted_at
from_port
grantee_group
group_id
id
parent_group
parent_group_id
protocol
to_port
updated_at
class SecurityGroupInstanceAssociation(**kwargs)

Bases: sqlalchemy.ext.declarative.api.Base, nova.db.sqlalchemy.models.NovaBase

created_at
deleted
deleted_at
id
instance_uuid
security_group_id
updated_at
class Service(**kwargs)

Bases: sqlalchemy.ext.declarative.api.Base, nova.db.sqlalchemy.models.NovaBase

Represents a running service on a host.

binary
created_at
deleted
deleted_at
disabled
disabled_reason
host
id
report_count
topic
updated_at
class Snapshot(**kwargs)

Bases: sqlalchemy.ext.declarative.api.Base, nova.db.sqlalchemy.models.NovaBase

Represents a block storage device that can be attached to a VM.

created_at
deleted
deleted_at
display_description
display_name
id
name
progress
project_id
scheduled_at
status
updated_at
user_id
volume_id
volume_name
volume_size
class SnapshotIdMapping(**kwargs)

Bases: sqlalchemy.ext.declarative.api.Base, nova.db.sqlalchemy.models.NovaBase

Compatibility layer for the EC2 snapshot service.

created_at
deleted
deleted_at
id
updated_at
uuid
class TaskLog(**kwargs)

Bases: sqlalchemy.ext.declarative.api.Base, nova.db.sqlalchemy.models.NovaBase

Audit log for background periodic tasks.

created_at
deleted
deleted_at
errors
host
id
message
period_beginning
period_ending
state
task_items
task_name
updated_at
class VirtualInterface(**kwargs)

Bases: sqlalchemy.ext.declarative.api.Base, nova.db.sqlalchemy.models.NovaBase

Represents a virtual interface on an instance.

address
created_at
deleted
deleted_at
id
instance_uuid
network_id
updated_at
uuid
class Volume(**kwargs)

Bases: sqlalchemy.ext.declarative.api.Base, nova.db.sqlalchemy.models.NovaBase

Represents a block storage device that can be attached to a VM.

attach_status
attach_time
availability_zone
created_at
deleted
deleted_at
display_description
display_name
ec2_id
host
id
instance_uuid
launched_at
mountpoint
name
project_id
provider_auth
provider_location
scheduled_at
size
snapshot_id
status
terminated_at
updated_at
user_id
volume_type_id
class VolumeIdMapping(**kwargs)

Bases: sqlalchemy.ext.declarative.api.Base, nova.db.sqlalchemy.models.NovaBase

Compatibility layer for the EC2 volume service.

created_at
deleted
deleted_at
id
updated_at
uuid
class VolumeUsage(**kwargs)

Bases: sqlalchemy.ext.declarative.api.Base, nova.db.sqlalchemy.models.NovaBase

Cache for volume usage data pulled from the hypervisor.

availability_zone
created_at
curr_last_refreshed
curr_read_bytes
curr_reads
curr_write_bytes
curr_writes
deleted
deleted_at
id
instance_uuid
project_id
tot_last_refreshed
tot_read_bytes
tot_reads
tot_write_bytes
tot_writes
updated_at
user_id
volume_id
relationship(argument, secondary=None, primaryjoin=None, secondaryjoin=None, foreign_keys=None, uselist=None, order_by=False, backref=None, back_populates=None, post_update=False, cascade=False, extension=None, viewonly=False, lazy=True, collection_class=None, passive_deletes=False, passive_updates=True, remote_side=None, enable_typechecks=True, join_depth=None, comparator_factory=None, single_parent=False, innerjoin=False, distinct_target_key=None, doc=None, active_history=False, cascade_backrefs=True, load_on_pending=False, strategy_class=None, _local_remote_pairs=None, query_class=None, info=None)

Provide a relationship between two mapped classes.

This corresponds to a parent-child or associative table relationship. The constructed class is an instance of RelationshipProperty.

A typical relationship(), used in a classical mapping:

mapper(Parent, properties={
  'children': relationship(Child)
})

Some arguments accepted by relationship() optionally accept a callable function, which when called produces the desired value. The callable is invoked by the parent Mapper at “mapper initialization” time, which happens only when mappers are first used, and is assumed to be after all mappings have been constructed. This can be used to resolve order-of-declaration and other dependency issues, such as if Child is declared below Parent in the same file:

mapper(Parent, properties={
    "children":relationship(lambda: Child,
                        order_by=lambda: Child.id)
})

When using the declarative_toplevel extension, the Declarative initializer allows string arguments to be passed to relationship(). These string arguments are converted into callables that evaluate the string as Python code, using the Declarative class-registry as a namespace. This allows the lookup of related classes to be automatic via their string name, and removes the need to import related classes at all into the local module space:

from sqlalchemy.ext.declarative import declarative_base

Base = declarative_base()

class Parent(Base):
    __tablename__ = 'parent'
    id = Column(Integer, primary_key=True)
    children = relationship("Child", order_by="Child.id")

See also

relationship_config_toplevel - Full introductory and reference documentation for relationship().

orm_tutorial_relationship - ORM tutorial introduction.

Parameters:
  • argument

    a mapped class, or actual Mapper instance, representing the target of the relationship.

    :paramref:`~.relationship.argument` may also be passed as a callable function which is evaluated at mapper initialization time, and may be passed as a Python-evaluable string when using Declarative.

    See also

    declarative_configuring_relationships - further detail on relationship configuration when using Declarative.

  • secondary

    for a many-to-many relationship, specifies the intermediary table, and is typically an instance of Table. In less common circumstances, the argument may also be specified as an Alias construct, or even a Join construct.

    :paramref:`~.relationship.secondary` may also be passed as a callable function which is evaluated at mapper initialization time. When using Declarative, it may also be a string argument noting the name of a Table that is present in the MetaData collection associated with the parent-mapped Table.

    The :paramref:`~.relationship.secondary` keyword argument is typically applied in the case where the intermediary Table is not otherwise exprssed in any direct class mapping. If the “secondary” table is also explicitly mapped elsewhere (e.g. as in association_pattern), one should consider applying the :paramref:`~.relationship.viewonly` flag so that this relationship() is not used for persistence operations which may conflict with those of the association object pattern.

    See also

    relationships_many_to_many - Reference example of “many to many”.

    orm_tutorial_many_to_many - ORM tutorial introduction to many-to-many relationships.

    self_referential_many_to_many - Specifics on using many-to-many in a self-referential case.

    declarative_many_to_many - Additional options when using Declarative.

    association_pattern - an alternative to :paramref:`~.relationship.secondary` when composing association table relationships, allowing additional attributes to be specified on the association table.

    composite_secondary_join - a lesser-used pattern which in some cases can enable complex relationship() SQL conditions to be used.

    New in version 0.9.2: :paramref:`~.relationship.secondary` works more effectively when referring to a Join instance.

  • active_history=False – When True, indicates that the “previous” value for a many-to-one reference should be loaded when replaced, if not already loaded. Normally, history tracking logic for simple many-to-ones only needs to be aware of the “new” value in order to perform a flush. This flag is available for applications that make use of attributes.get_history() which also need to know the “previous” value of the attribute.
  • backref

    indicates the string name of a property to be placed on the related mapper’s class that will handle this relationship in the other direction. The other property will be created automatically when the mappers are configured. Can also be passed as a backref() object to control the configuration of the new relationship.

    See also

    relationships_backref - Introductory documentation and examples.

    :paramref:`~.relationship.back_populates` - alternative form of backref specification.

    backref() - allows control over relationship() configuration when using :paramref:`~.relationship.backref`.

  • back_populates

    Takes a string name and has the same meaning as :paramref:`~.relationship.backref`, except the complementing property is not created automatically, and instead must be configured explicitly on the other mapper. The complementing property should also indicate :paramref:`~.relationship.back_populates` to this relationship to ensure proper functioning.

    See also

    relationships_backref - Introductory documentation and examples.

    :paramref:`~.relationship.backref` - alternative form of backref specification.

  • cascade

    a comma-separated list of cascade rules which determines how Session operations should be “cascaded” from parent to child. This defaults to False, which means the default cascade should be used - this default cascade is "save-update, merge".

    The available cascades are save-update, merge, expunge, delete, delete-orphan, and refresh-expire. An additional option, all indicates shorthand for "save-update, merge, refresh-expire, expunge, delete", and is often used as in "all, delete-orphan" to indicate that related objects should follow along with the parent object in all cases, and be deleted when de-associated.

    See also

    unitofwork_cascades - Full detail on each of the available cascade options.

    tutorial_delete_cascade - Tutorial example describing a delete cascade.

  • cascade_backrefs=True

    a boolean value indicating if the save-update cascade should operate along an assignment event intercepted by a backref. When set to False, the attribute managed by this relationship will not cascade an incoming transient object into the session of a persistent parent, if the event is received via backref.

    See also

    backref_cascade - Full discussion and examples on how the :paramref:`~.relationship.cascade_backrefs` option is used.

  • collection_class

    a class or callable that returns a new list-holding object. will be used in place of a plain list for storing elements.

    See also

    custom_collections - Introductory documentation and examples.

  • comparator_factory

    a class which extends RelationshipProperty.Comparator which provides custom SQL clause generation for comparison operations.

    See also

    PropComparator - some detail on redefining comparators at this level.

    custom_comparators - Brief intro to this feature.

  • distinct_target_key=None

    Indicate if a “subquery” eager load should apply the DISTINCT keyword to the innermost SELECT statement. When left as None, the DISTINCT keyword will be applied in those cases when the target columns do not comprise the full primary key of the target table. When set to True, the DISTINCT keyword is applied to the innermost SELECT unconditionally.

    It may be desirable to set this flag to False when the DISTINCT is reducing performance of the innermost subquery beyond that of what duplicate innermost rows may be causing.

    New in version 0.8.3: - :paramref:`~.relationship.distinct_target_key` allows the subquery eager loader to apply a DISTINCT modifier to the innermost SELECT.

    Changed in version 0.9.0: - :paramref:`~.relationship.distinct_target_key` now defaults to None, so that the feature enables itself automatically for those cases where the innermost query targets a non-unique key.

    See also

    loading_toplevel - includes an introduction to subquery eager loading.

  • doc – docstring which will be applied to the resulting descriptor.
  • extension

    an AttributeExtension instance, or list of extensions, which will be prepended to the list of attribute listeners for the resulting descriptor placed on the class.

    Deprecated since version 0.7: Please see AttributeEvents.

  • foreign_keys

    a list of columns which are to be used as “foreign key” columns, or columns which refer to the value in a remote column, within the context of this relationship() object’s :paramref:`~.relationship.primaryjoin` condition. That is, if the :paramref:`~.relationship.primaryjoin` condition of this relationship() is a.id == b.a_id, and the values in b.a_id are required to be present in a.id, then the “foreign key” column of this relationship() is b.a_id.

    In normal cases, the :paramref:`~.relationship.foreign_keys` parameter is not required. relationship() will automatically determine which columns in the :paramref:`~.relationship.primaryjoin` conditition are to be considered “foreign key” columns based on those Column objects that specify ForeignKey, or are otherwise listed as referencing columns in a ForeignKeyConstraint construct. :paramref:`~.relationship.foreign_keys` is only needed when:

    1. There is more than one way to construct a join from the local table to the remote table, as there are multiple foreign key references present. Setting foreign_keys will limit the relationship() to consider just those columns specified here as “foreign”.

      Changed in version 0.8: A multiple-foreign key join ambiguity can be resolved by setting the :paramref:`~.relationship.foreign_keys` parameter alone, without the need to explicitly set :paramref:`~.relationship.primaryjoin` as well.

    2. The Table being mapped does not actually have ForeignKey or ForeignKeyConstraint constructs present, often because the table was reflected from a database that does not support foreign key reflection (MySQL MyISAM).
    3. The :paramref:`~.relationship.primaryjoin` argument is used to construct a non-standard join condition, which makes use of columns or expressions that do not normally refer to their “parent” column, such as a join condition expressed by a complex comparison using a SQL function.

    The relationship() construct will raise informative error messages that suggest the use of the :paramref:`~.relationship.foreign_keys` parameter when presented with an ambiguous condition. In typical cases, if relationship() doesn’t raise any exceptions, the :paramref:`~.relationship.foreign_keys` parameter is usually not needed.

    :paramref:`~.relationship.foreign_keys` may also be passed as a callable function which is evaluated at mapper initialization time, and may be passed as a Python-evaluable string when using Declarative.

    See also

    relationship_foreign_keys

    relationship_custom_foreign

    foreign() - allows direct annotation of the “foreign” columns within a :paramref:`~.relationship.primaryjoin` condition.

    New in version 0.8: The foreign() annotation can also be applied directly to the :paramref:`~.relationship.primaryjoin` expression, which is an alternate, more specific system of describing which columns in a particular :paramref:`~.relationship.primaryjoin` should be considered “foreign”.

  • info

    Optional data dictionary which will be populated into the MapperProperty.info attribute of this object.

    New in version 0.8.

  • innerjoin=False

    when True, joined eager loads will use an inner join to join against related tables instead of an outer join. The purpose of this option is generally one of performance, as inner joins generally perform better than outer joins.

    This flag can be set to True when the relationship references an object via many-to-one using local foreign keys that are not nullable, or when the reference is one-to-one or a collection that is guaranteed to have one or at least one entry.

    If the joined-eager load is chained onto an existing LEFT OUTER JOIN, innerjoin=True will be bypassed and the join will continue to chain as LEFT OUTER JOIN so that the results don’t change. As an alternative, specify the value "nested". This will instead nest the join on the right side, e.g. using the form “a LEFT OUTER JOIN (b JOIN c)”.

    New in version 0.9.4: Added innerjoin="nested" option to support nesting of eager “inner” joins.

    See also

    what_kind_of_loading - Discussion of some details of various loader options.

    :paramref:`.joinedload.innerjoin` - loader option version

  • join_depth

    when non-None, an integer value indicating how many levels deep “eager” loaders should join on a self-referring or cyclical relationship. The number counts how many times the same Mapper shall be present in the loading condition along a particular join branch. When left at its default of None, eager loaders will stop chaining when they encounter a the same target mapper which is already higher up in the chain. This option applies both to joined- and subquery- eager loaders.

    See also

    self_referential_eager_loading - Introductory documentation and examples.

  • lazy=’select’

    specifies how the related items should be loaded. Default value is select. Values include:

    • select - items should be loaded lazily when the property is first accessed, using a separate SELECT statement, or identity map fetch for simple many-to-one references.
    • immediate - items should be loaded as the parents are loaded, using a separate SELECT statement, or identity map fetch for simple many-to-one references.
    • joined - items should be loaded “eagerly” in the same query as that of the parent, using a JOIN or LEFT OUTER JOIN. Whether the join is “outer” or not is determined by the :paramref:`~.relationship.innerjoin` parameter.
    • subquery - items should be loaded “eagerly” as the parents are loaded, using one additional SQL statement, which issues a JOIN to a subquery of the original statement, for each collection requested.
    • noload - no loading should occur at any time. This is to support “write-only” attributes, or attributes which are populated in some manner specific to the application.
    • dynamic - the attribute will return a pre-configured Query object for all read operations, onto which further filtering operations can be applied before iterating the results. See the section dynamic_relationship for more details.
    • True - a synonym for ‘select’
    • False - a synonym for ‘joined’
    • None - a synonym for ‘noload’

    See also

    /orm/loading - Full documentation on relationship loader configuration.

    dynamic_relationship - detail on the dynamic option.

  • load_on_pending=False

    Indicates loading behavior for transient or pending parent objects.

    When set to True, causes the lazy-loader to issue a query for a parent object that is not persistent, meaning it has never been flushed. This may take effect for a pending object when autoflush is disabled, or for a transient object that has been “attached” to a Session but is not part of its pending collection.

    The :paramref:`~.relationship.load_on_pending` flag does not improve behavior when the ORM is used normally - object references should be constructed at the object level, not at the foreign key level, so that they are present in an ordinary way before a flush proceeds. This flag is not not intended for general use.

    See also

    Session.enable_relationship_loading() - this method establishes “load on pending” behavior for the whole object, and also allows loading on objects that remain transient or detached.

  • order_by

    indicates the ordering that should be applied when loading these items. :paramref:`~.relationship.order_by` is expected to refer to one of the Column objects to which the target class is mapped, or the attribute itself bound to the target class which refers to the column.

    :paramref:`~.relationship.order_by` may also be passed as a callable function which is evaluated at mapper initialization time, and may be passed as a Python-evaluable string when using Declarative.

  • passive_deletes=False

    Indicates loading behavior during delete operations.

    A value of True indicates that unloaded child items should not be loaded during a delete operation on the parent. Normally, when a parent item is deleted, all child items are loaded so that they can either be marked as deleted, or have their foreign key to the parent set to NULL. Marking this flag as True usually implies an ON DELETE <CASCADE|SET NULL> rule is in place which will handle updating/deleting child rows on the database side.

    Additionally, setting the flag to the string value ‘all’ will disable the “nulling out” of the child foreign keys, when there is no delete or delete-orphan cascade enabled. This is typically used when a triggering or error raise scenario is in place on the database side. Note that the foreign key attributes on in-session child objects will not be changed after a flush occurs so this is a very special use-case setting.

    See also

    passive_deletes - Introductory documentation and examples.

  • passive_updates=True

    Indicates loading and INSERT/UPDATE/DELETE behavior when the source of a foreign key value changes (i.e. an “on update” cascade), which are typically the primary key columns of the source row.

    When True, it is assumed that ON UPDATE CASCADE is configured on the foreign key in the database, and that the database will handle propagation of an UPDATE from a source column to dependent rows. Note that with databases which enforce referential integrity (i.e. PostgreSQL, MySQL with InnoDB tables), ON UPDATE CASCADE is required for this operation. The relationship() will update the value of the attribute on related items which are locally present in the session during a flush.

    When False, it is assumed that the database does not enforce referential integrity and will not be issuing its own CASCADE operation for an update. The relationship() will issue the appropriate UPDATE statements to the database in response to the change of a referenced key, and items locally present in the session during a flush will also be refreshed.

    This flag should probably be set to False if primary key changes are expected and the database in use doesn’t support CASCADE (i.e. SQLite, MySQL MyISAM tables).

    See also

    passive_updates - Introductory documentation and examples.

    :paramref:`.mapper.passive_updates` - a similar flag which takes effect for joined-table inheritance mappings.

  • post_update

    this indicates that the relationship should be handled by a second UPDATE statement after an INSERT or before a DELETE. Currently, it also will issue an UPDATE after the instance was UPDATEd as well, although this technically should be improved. This flag is used to handle saving bi-directional dependencies between two individual rows (i.e. each row references the other), where it would otherwise be impossible to INSERT or DELETE both rows fully since one row exists before the other. Use this flag when a particular mapping arrangement will incur two rows that are dependent on each other, such as a table that has a one-to-many relationship to a set of child rows, and also has a column that references a single child row within that list (i.e. both tables contain a foreign key to each other). If a flush operation returns an error that a “cyclical dependency” was detected, this is a cue that you might want to use :paramref:`~.relationship.post_update` to “break” the cycle.

    See also

    post_update - Introductory documentation and examples.

  • primaryjoin

    a SQL expression that will be used as the primary join of this child object against the parent object, or in a many-to-many relationship the join of the primary object to the association table. By default, this value is computed based on the foreign key relationships of the parent and child tables (or association table).

    :paramref:`~.relationship.primaryjoin` may also be passed as a callable function which is evaluated at mapper initialization time, and may be passed as a Python-evaluable string when using Declarative.

    See also

    relationship_primaryjoin

  • remote_side

    used for self-referential relationships, indicates the column or list of columns that form the “remote side” of the relationship.

    :paramref:`.relationship.remote_side` may also be passed as a callable function which is evaluated at mapper initialization time, and may be passed as a Python-evaluable string when using Declarative.

    Changed in version 0.8: The remote() annotation can also be applied directly to the primaryjoin expression, which is an alternate, more specific system of describing which columns in a particular primaryjoin should be considered “remote”.

    See also

    self_referential - in-depth explanation of how :paramref:`~.relationship.remote_side` is used to configure self-referential relationships.

    remote() - an annotation function that accomplishes the same purpose as :paramref:`~.relationship.remote_side`, typically when a custom :paramref:`~.relationship.primaryjoin` condition is used.

  • query_class

    a Query subclass that will be used as the base of the “appender query” returned by a “dynamic” relationship, that is, a relationship that specifies lazy="dynamic" or was otherwise constructed using the orm.dynamic_loader() function.

    See also

    dynamic_relationship - Introduction to “dynamic” relationship loaders.

  • secondaryjoin

    a SQL expression that will be used as the join of an association table to the child object. By default, this value is computed based on the foreign key relationships of the association and child tables.

    :paramref:`~.relationship.secondaryjoin` may also be passed as a callable function which is evaluated at mapper initialization time, and may be passed as a Python-evaluable string when using Declarative.

    See also

    relationship_primaryjoin

  • single_parent

    when True, installs a validator which will prevent objects from being associated with more than one parent at a time. This is used for many-to-one or many-to-many relationships that should be treated either as one-to-one or one-to-many. Its usage is optional, except for relationship() constructs which are many-to-one or many-to-many and also specify the delete-orphan cascade option. The relationship() construct itself will raise an error instructing when this option is required.

    See also

    unitofwork_cascades - includes detail on when the :paramref:`~.relationship.single_parent` flag may be appropriate.

  • uselist

    a boolean that indicates if this property should be loaded as a list or a scalar. In most cases, this value is determined automatically by relationship() at mapper configuration time, based on the type and direction of the relationship - one to many forms a list, many to one forms a scalar, many to many is a list. If a scalar is desired where normally a list would be present, such as a bi-directional one-to-one relationship, set :paramref:`~.relationship.uselist` to False.

    The :paramref:`~.relationship.uselist` flag is also available on an existing relationship() construct as a read-only attribute, which can be used to determine if this relationship() deals with collections or scalar attributes:

    >>> User.addresses.property.uselist
    True
    

    See also

    relationships_one_to_one - Introduction to the “one to one” relationship pattern, which is typically when the :paramref:`~.relationship.uselist` flag is needed.

  • viewonly=False – when set to True, the relationship is used only for loading objects, and not for any persistence operation. A relationship() which specifies :paramref:`~.relationship.viewonly` can work with a wider range of SQL operations within the :paramref:`~.relationship.primaryjoin` condition, including operations that feature the use of a variety of comparison operators as well as SQL functions such as cast(). The :paramref:`~.relationship.viewonly` flag is also of general use when defining any kind of relationship() that doesn’t represent the full set of related objects, to prevent modifications of the collection from resulting in persistence operations.

The nova.db.sqlalchemy.session Module

Tests

Tests are lacking for the db api layer and for the sqlalchemy driver. Failures in the drivers would be detected in other test cases, though.