### Install SQLAlchemy-Utils official release Source: https://sqlalchemy-utils.readthedocs.io/en/latest/_sources/installation.rst This command installs the latest official release of SQLAlchemy-Utils from PyPI using the pip package manager. It's the recommended way for most users to get started with the library, ensuring a stable version. ```bash pip install sqlalchemy-utils ``` -------------------------------- ### Verify SQLAlchemy-Utils installation and check version Source: https://sqlalchemy-utils.readthedocs.io/en/latest/_sources/installation.rst These Python commands are executed within a Python interpreter to confirm that SQLAlchemy-Utils has been successfully installed. It imports the library and then prints its installed version, allowing users to verify the correct installation and version number. ```python import sqlalchemy_utils sqlalchemy_utils.__version__ ``` -------------------------------- ### Clone SQLAlchemy-Utils development repository Source: https://sqlalchemy-utils.readthedocs.io/en/latest/_sources/installation.rst This command clones the official SQLAlchemy-Utils Git repository, obtaining the source code for the development version. This is the initial step when installing the library directly from source for development or testing purposes. ```bash git clone git://github.com/kvesteri/sqlalchemy-utils.git ``` -------------------------------- ### Verify SQLAlchemy-Utils Installation and Version Source: https://sqlalchemy-utils.readthedocs.io/en/latest/installation These Python commands are executed within a Python interpreter to confirm that SQLAlchemy-Utils has been successfully installed. It imports the library and then prints its version number, providing a quick check of the installed package's presence and specific release. ```Python >>> import sqlalchemy_utils >>> sqlalchemy_utils.__version__ ``` -------------------------------- ### Install SQLAlchemy-Utils development version in editable mode Source: https://sqlalchemy-utils.readthedocs.io/en/latest/_sources/installation.rst After cloning the repository, these commands navigate into the project directory and install the SQLAlchemy-Utils library in 'editable' mode. This allows changes to the source code to be reflected without reinstallation, which is highly useful for active development and testing. ```bash cd sqlalchemy-utils pip install -e . ``` -------------------------------- ### Clone SQLAlchemy-Utils Development Repository Source: https://sqlalchemy-utils.readthedocs.io/en/latest/installation This command uses Git to clone the entire SQLAlchemy-Utils source code repository from GitHub. It's the first step required to obtain the development version of the library, allowing access to the latest features and contributions. ```Shell git clone git://github.com/kvesteri/sqlalchemy-utils.git ``` -------------------------------- ### Install SQLAlchemy-Utils Official Release via pip Source: https://sqlalchemy-utils.readthedocs.io/en/latest/installation This command installs the latest stable version of SQLAlchemy-Utils from PyPI using pip, the standard Python package installer. It ensures you have the most recent official release available for use in your projects. ```Shell pip install sqlalchemy-utils ``` -------------------------------- ### Install SQLAlchemy-Utils Development Version in Editable Mode Source: https://sqlalchemy-utils.readthedocs.io/en/latest/installation After cloning the repository, these commands navigate into the project directory and install the development version of SQLAlchemy-Utils in 'editable' mode. This allows you to make changes to the source code directly within the cloned directory, and those changes will be reflected in your Python environment without needing to reinstall the package. ```Shell cd sqlalchemy-utils pip install -e . ``` -------------------------------- ### Define SQLAlchemy-Utils TranslationHybrid Instance Source: https://sqlalchemy-utils.readthedocs.io/en/latest/_sources/internationalization.rst This snippet demonstrates how to initialize the TranslationHybrid from SQLAlchemy-Utils. It requires a callable for `current_locale` to determine the active language and an optional `default_locale` for fallback. The example uses a simple function returning 'fi' for testing purposes. ```Python from sqlalchemy_utils import TranslationHybrid def get_locale(): return 'fi' translation_hybrid = TranslationHybrid( current_locale=get_locale, default_locale='en' ) ``` -------------------------------- ### Implementing Basic Generic Relationships with SQLAlchemy-Utils Source: https://sqlalchemy-utils.readthedocs.io/en/latest/_sources/generic_relationship.rst This snippet demonstrates how to set up a generic one-to-many relationship using `sqlalchemy_utils.generic_relationship`. It shows defining a polymorphic `Event` model that can link to various target models like `User` or `Customer`, and provides examples of assigning and querying these relationships. ```Python from sqlalchemy_utils import generic_relationship class User(Base): __tablename__ = 'user' id = sa.Column(sa.Integer, primary_key=True) class Customer(Base): __tablename__ = 'customer' id = sa.Column(sa.Integer, primary_key=True) class Event(Base): __tablename__ = 'event' id = sa.Column(sa.Integer, primary_key=True) # This is used to discriminate between the linked tables. object_type = sa.Column(sa.Unicode(255)) # This is used to point to the primary key of the linked row. object_id = sa.Column(sa.Integer) object = generic_relationship(object_type, object_id) # Some general usage to attach an event to a user. user = User() customer = Customer() session.add_all([user, customer]) session.commit() ev = Event() ev.object = user session.add(ev) session.commit() # Find the event we just made. session.query(Event).filter_by(object=user).first() # Find any events that are bound to users. session.query(Event).filter(Event.object.is_type(User)).all() ``` -------------------------------- ### Define and Use Generic Relationships with SQLAlchemy-Utils Source: https://sqlalchemy-utils.readthedocs.io/en/latest/generic_relationship This snippet demonstrates how to set up a generic relationship using `sqlalchemy_utils.generic_relationship`. It defines models for `User`, `Customer`, and `Event`, where `Event` can link to any of the other models. The example includes creating instances, assigning generic objects, and querying events based on the linked object or its type. ```Python from sqlalchemy_utils import generic_relationship class User(Base): __tablename__ = 'user' id = sa.Column(sa.Integer, primary_key=True) class Customer(Base): __tablename__ = 'customer' id = sa.Column(sa.Integer, primary_key=True) class Event(Base): __tablename__ = 'event' id = sa.Column(sa.Integer, primary_key=True) # This is used to discriminate between the linked tables. object_type = sa.Column(sa.Unicode(255)) # This is used to point to the primary key of the linked row. object_id = sa.Column(sa.Integer) object = generic_relationship(object_type, object_id) # Some general usage to attach an event to a user. user = User() customer = Customer() session.add_all([user, customer]) session.commit() ev = Event() ev.object = user session.add(ev) session.commit() # Find the event we just made. session.query(Event).filter_by(object=user).first() # Find any events that are bound to users. session.query(Event).filter(Event.object.is_type(User)).all() ``` -------------------------------- ### Generic Relationships with Composite Primary Keys Source: https://sqlalchemy-utils.readthedocs.io/en/latest/_sources/generic_relationship.rst This example illustrates how to use `generic_relationship` with models that have composite primary keys. It demonstrates defining a `Customer` model with two primary key columns and an `Event` model that links to it using a tuple of columns for the `object_id` argument in `generic_relationship`. ```Python from sqlalchemy_utils import generic_relationship class Customer(Base): __tablename__ = 'customer' code1 = sa.Column(sa.Integer, primary_key=True) code2 = sa.Column(sa.Integer, primary_key=True) class Event(Base): __tablename__ = 'event' id = sa.Column(sa.Integer, primary_key=True) # This is used to discriminate between the linked tables. object_type = sa.Column(sa.Unicode(255)) object_code1 = sa.Column(sa.Integer) object_code2 = sa.Column(sa.Integer) object = generic_relationship( object_type, (object_code1, object_code2) ) ``` -------------------------------- ### Assign and Access Translations with TranslationHybrid Source: https://sqlalchemy-utils.readthedocs.io/en/latest/_sources/internationalization.rst This example illustrates how to interact with a translatable model. Assigning a value to the hybrid property (`article.name`) automatically stores it in the `name_translations` HSTORE column for the `current_locale`. Direct access to `name_translations` and the hybrid property are shown. ```Python article = Article(name='Joku artikkeli') article.name_translations['fi'] # Joku artikkeli article.name # Joku artikkeli ``` -------------------------------- ### Generic Relationships with SQLAlchemy Inheritance and Polymorphism Source: https://sqlalchemy-utils.readthedocs.io/en/latest/_sources/generic_relationship.rst This example illustrates how `generic_relationship` interacts with SQLAlchemy's inheritance mapping (polymorphic identity). It shows linking a generic `Activity` model to inherited classes like `Manager` (which inherits from `Employee`), and demonstrates querying based on specific types or supertypes. ```Python class Employee(Base): __tablename__ = 'employee' id = sa.Column(sa.Integer, primary_key=True) name = sa.Column(sa.String(50)) type = sa.Column(sa.String(20)) __mapper_args__ = { 'polymorphic_on': type, 'polymorphic_identity': 'employee' } class Manager(Employee): __mapper_args__ = { 'polymorphic_identity': 'manager' } class Engineer(Employee): __mapper_args__ = { 'polymorphic_identity': 'engineer' } class Activity(Base): __tablename__ = 'event' id = sa.Column(sa.Integer, primary_key=True) object_type = sa.Column(sa.Unicode(255)) object_id = sa.Column(sa.Integer, nullable=False) object = generic_relationship(object_type, object_id) # Now same as before we can add some objects:: manager = Manager() session.add(manager) session.commit() activity = Activity() activity.object = manager session.add(activity) session.commit() # Find the activity we just made. session.query(Event).filter_by(object=manager).first() # We can even test super types:: session.query(Activity).filter(Event.object.is_type(Employee)).all() ``` -------------------------------- ### Configure TranslationHybrid with Dynamic Locales Based on Available Translations Source: https://sqlalchemy-utils.readthedocs.io/en/latest/_sources/internationalization.rst This example shows an advanced dynamic locale configuration where the `default_locale` callable considers the available translations for a specific attribute. It sorts the keys (locales) present in the translation dictionary and picks the first one, ensuring a translation is always returned if available. ```Python translation_hybrid.default_locale = lambda obj, attr: sorted(getattr(obj, attr).keys())[0] article.name # Some article ``` -------------------------------- ### Using TranslationHybrid for Attribute Assignment and Access Source: https://sqlalchemy-utils.readthedocs.io/en/latest/internationalization This example shows how to assign values to and access values from translatable attributes managed by TranslationHybrid. It illustrates that assigning a value automatically stores it for the current locale, and accessing the attribute retrieves the translation for the current locale, falling back to the default locale if necessary. ```python article = Article(name='Joku artikkeli') article.name_translations['fi'] # Joku artikkeli article.name # Joku artikkeli ``` ```python article = Article(name_translations={'en': 'Some article'}) article.name # Some article article.name_translations['fi'] = 'Joku artikkeli' article.name # Joku artikkeli ``` -------------------------------- ### Customize TranslationHybrid Default Fallback Value Source: https://sqlalchemy-utils.readthedocs.io/en/latest/internationalization This example shows how to configure TranslationHybrid to return a custom default value (e.g., an empty string) instead of None when no translation is found for either the current or default locale. This is achieved by passing the 'default_value' parameter during hybrid initialization. ```python translation_hybrid = TranslationHybrid( current_locale=get_locale, default_locale='en', default_value='' ) ``` ```python class Article(Base): __tablename__ = 'article' id = Column(Integer, primary_key=True) name_translations = Column(HSTORE) name = translation_hybrid(name_translations, default) Article().name # '' ``` -------------------------------- ### Filter SQLAlchemy Queries Using TranslationHybrid Source: https://sqlalchemy-utils.readthedocs.io/en/latest/_sources/internationalization.rst This example shows that `TranslationHybrid` attributes can be used directly within SQLAlchemy query expressions. This allows filtering database records based on specific translations stored in the HSTORE column. ```Python session.query(Article).filter(Article.name_translations['en'] == 'Some article') ``` -------------------------------- ### SQLAlchemy-Utils Database View Management API Source: https://sqlalchemy-utils.readthedocs.io/en/latest/_sources/view.rst This section details the API for creating and managing both standard and materialized database views within SQLAlchemy-Utils. It includes functions for defining new views based on selectables and for refreshing existing materialized views. ```APIDOC sqlalchemy_utils.view.create_view(name: str, selectable, metadata, **kwargs) - Description: Creates a standard database view based on a SQLAlchemy selectable expression. - Parameters: - name (str): The name of the view to create. - selectable: A SQLAlchemy selectable object (e.g., a `select()` statement) that defines the view's content. - metadata: The SQLAlchemy `MetaData` object associated with the database. - **kwargs: Additional keyword arguments to pass to the underlying DDL operation. - Returns: None sqlalchemy_utils.view.create_materialized_view(name: str, selectable, metadata, **kwargs) - Description: Creates a materialized database view, which stores the query results physically. - Parameters: - name (str): The name of the materialized view to create. - selectable: A SQLAlchemy selectable object (e.g., a `select()` statement) that defines the view's content. - metadata: The SQLAlchemy `MetaData` object associated with the database. - **kwargs: Additional keyword arguments to pass to the underlying DDL operation. - Returns: None sqlalchemy_utils.view.refresh_materialized_view(name: str, connection) - Description: Refreshes the data in an existing materialized database view. - Parameters: - name (str): The name of the materialized view to refresh. - connection: An active SQLAlchemy `Connection` object to execute the refresh command. - Returns: None ``` -------------------------------- ### Initialize TranslationHybrid and Define Model with Dynamic Locales Source: https://sqlalchemy-utils.readthedocs.io/en/latest/internationalization This snippet demonstrates how to initialize `TranslationHybrid` with dynamic `current_locale` and `default_locale` callables. It then defines an `Article` model using this hybrid to manage `name_translations` stored in an HSTORE column, showcasing how to add and retrieve translated content based on the `locale` attribute. ```Python translation_hybrid = TranslationHybrid( current_locale=get_locale, default_locale=lambda obj: obj.locale, ) class Article(Base): __tablename__ = 'article' id = Column(Integer, primary_key=True) name_translations = Column(HSTORE) name = translation_hybrid(name_translations, default) locale = Column(String) article = Article(name_translations={'en': 'Some article'}) article.locale = 'en' session.add(article) session.commit() article.name # Some article (even if current locale is other than 'en') ``` -------------------------------- ### Implement Generic Relationships with SQLAlchemy Inheritance Source: https://sqlalchemy-utils.readthedocs.io/en/latest/generic_relationship This code illustrates how to combine generic relationships with SQLAlchemy's inheritance mapping. It defines a base `Employee` class with polymorphic subclasses (`Manager`, `Engineer`) and an `Activity` model that uses `generic_relationship` to link to any of these employee types. This allows for flexible tracking of activities related to different employee roles. ```Python class Employee(Base): __tablename__ = 'employee' id = sa.Column(sa.Integer, primary_key=True) name = sa.Column(sa.String(50)) type = sa.Column(sa.String(20)) __mapper_args__ = { 'polymorphic_on': type, 'polymorphic_identity': 'employee' } class Manager(Employee): __mapper_args__ = { 'polymorphic_identity': 'manager' } class Engineer(Employee): __mapper_args__ = { 'polymorphic_identity': 'engineer' } class Activity(Base): __tablename__ = 'event' id = sa.Column(sa.Integer, primary_key=True) object_type = sa.Column(sa.Unicode(255)) object_id = sa.Column(sa.Integer, nullable=False) object = generic_relationship(object_type, object_id) ``` ```Python manager = Manager() session.add(manager) session.commit() activity = Activity() activity.object = manager session.add(activity) session.commit() # Find the activity we just made. session.query(Event).filter_by(object=manager).first() ``` ```Python session.query(Activity).filter(Event.object.is_type(Employee)).all() ``` -------------------------------- ### SQLAlchemy-Utils CurrencyType and Currency API Source: https://sqlalchemy-utils.readthedocs.io/en/latest/_sources/data_types.rst Documents the CurrencyType, a custom data type for SQLAlchemy, and the Currency primitive, both provided by `sqlalchemy_utils` for handling currency-related data. ```APIDOC Module: sqlalchemy_utils.types.currency Class: CurrencyType Module: sqlalchemy_utils.primitives.currency Class: Currency ``` -------------------------------- ### Define TranslationHybrid Instance Source: https://sqlalchemy-utils.readthedocs.io/en/latest/internationalization This snippet demonstrates how to initialize a TranslationHybrid instance. It requires a callable function to determine the current user's locale and a default locale to use as a fallback when a translation for the current locale is not available. ```python from sqlalchemy_utils import TranslationHybrid # For testing purposes we define this as simple function which returns # locale 'fi'. Usually you would define this function as something that # returns the user's current locale. def get_locale(): return 'fi' translation_hybrid = TranslationHybrid( current_locale=get_locale, default_locale='en' ) ``` -------------------------------- ### SQLAlchemy-Utils URLType API Source: https://sqlalchemy-utils.readthedocs.io/en/latest/_sources/data_types.rst Documents the URLType, a custom data type for SQLAlchemy provided by the `sqlalchemy_utils.types.url` module, used for storing and validating URLs. ```APIDOC Module: sqlalchemy_utils.types.url Class: URLType ``` -------------------------------- ### Define SQLAlchemy Model with TranslationHybrid Attributes Source: https://sqlalchemy-utils.readthedocs.io/en/latest/_sources/internationalization.rst This code defines an `Article` SQLAlchemy model that incorporates translatable attributes using `TranslationHybrid`. It utilizes PostgreSQL's `HSTORE` type to store translations for `name` and `content`, and then maps these translation columns to hybrid properties via `translation_hybrid`. ```Python from sqlalchemy import * from sqlalchemy.dialects.postgresql import HSTORE class Article(Base): __tablename__ = 'article' id = Column(Integer, primary_key=True) name_translations = Column(HSTORE) content_translations = Column(HSTORE) name = translation_hybrid(name_translations) content = translation_hybrid(content_translations) ``` -------------------------------- ### SQLAlchemy-Utils LtreeType and Ltree API Source: https://sqlalchemy-utils.readthedocs.io/en/latest/_sources/data_types.rst Documents the LtreeType, a custom data type for SQLAlchemy, and the Ltree primitive, both provided by `sqlalchemy_utils` for handling hierarchical tree structures. ```APIDOC Module: sqlalchemy_utils.types.ltree Class: LtreeType Module: sqlalchemy_utils.primitives.ltree Class: Ltree ``` -------------------------------- ### Define SQLAlchemy Generic Relationship with Composite Keys Source: https://sqlalchemy-utils.readthedocs.io/en/latest/generic_relationship This Python snippet illustrates how to define a `generic_relationship` using SQLAlchemy-Utils for a model (`Event`) that links to another model (`Customer`) with a composite primary key. It sets up the `Customer` table with two primary key columns (`code1`, `code2`) and the `Event` table with discriminator (`object_type`) and corresponding composite key columns (`object_code1`, `object_code2`) to establish the generic relationship. ```Python from sqlalchemy_utils import generic_relationship class Customer(Base): __tablename__ = 'customer' code1 = sa.Column(sa.Integer, primary_key=True) code2 = sa.Column(sa.Integer, primary_key=True) class Event(Base): __tablename__ = 'event' id = sa.Column(sa.Integer, primary_key=True) # This is used to discriminate between the linked tables. object_type = sa.Column(sa.Unicode(255)) object_code1 = sa.Column(sa.Integer) object_code2 = sa.Column(sa.Integer) object = generic_relationship( object_type, (object_code1, object_code2) ) ``` -------------------------------- ### SQLAlchemy-Utils ChoiceType API Source: https://sqlalchemy-utils.readthedocs.io/en/latest/_sources/data_types.rst Documents the ChoiceType, a custom data type for SQLAlchemy provided by the `sqlalchemy_utils.types.choice` module, used for handling predefined choices or enumerations. ```APIDOC Module: sqlalchemy_utils.types.choice Class: ChoiceType ``` -------------------------------- ### SQLAlchemy-Utils ORM Helper Functions Source: https://sqlalchemy-utils.readthedocs.io/en/latest/_sources/orm_helpers.rst A collection of utility functions from the `sqlalchemy_utils.functions` module designed to assist with common Object-Relational Mapping (ORM) tasks in SQLAlchemy. These functions provide capabilities for type manipulation, metadata introspection, and object state management. ```APIDOC sqlalchemy_utils.functions.cast_if - Conditionally casts a column or expression to a specified type. sqlalchemy_utils.functions.escape_like - Escapes characters in a string for use in SQL LIKE clauses. sqlalchemy_utils.functions.get_bind - Retrieves the bind (engine or connection) associated with a SQLAlchemy object. sqlalchemy_utils.functions.get_class_by_table - Returns the declarative class mapped to a given SQLAlchemy Table object. sqlalchemy_utils.functions.get_column_key - Gets the key (attribute name) for a given column in a mapped class. sqlalchemy_utils.functions.get_columns - Returns all columns associated with a mapped class or mapper. sqlalchemy_utils.functions.get_declarative_base - Retrieves the declarative base class from a mapped instance or class. sqlalchemy_utils.functions.get_hybrid_properties - Returns all hybrid properties defined on a mapped class. sqlalchemy_utils.functions.get_mapper - Gets the SQLAlchemy mapper for a given class or instance. sqlalchemy_utils.functions.get_primary_keys - Returns the primary key columns for a mapped class or table. sqlalchemy_utils.functions.get_tables - Retrieves all tables associated with a mapped class or metadata. sqlalchemy_utils.functions.get_type - Determines the SQLAlchemy type of a given column or expression. sqlalchemy_utils.functions.has_changes - Checks if a SQLAlchemy object has pending changes. sqlalchemy_utils.functions.identity - Returns the identity (primary key values) of a SQLAlchemy object. sqlalchemy_utils.functions.is_loaded - Checks if a relationship or attribute on a SQLAlchemy object is loaded. sqlalchemy_utils.functions.make_order_by_deterministic - Ensures an ORDER BY clause is deterministic by adding primary keys if necessary. sqlalchemy_utils.functions.naturally_equivalent - Compares two SQLAlchemy objects for natural equivalence (based on natural keys). sqlalchemy_utils.functions.quote - Quotes an identifier for use in SQL, respecting the dialect's quoting rules. ``` -------------------------------- ### SQLAlchemy-Utils Foreign Key Helper Functions API Source: https://sqlalchemy-utils.readthedocs.io/en/latest/_sources/foreign_key_helpers.rst This API documentation describes a set of utility functions provided by `sqlalchemy_utils.functions` for advanced manipulation and inspection of foreign key relationships in SQLAlchemy. These functions assist in tasks such as identifying objects dependent on a foreign key, retrieving referencing foreign keys, grouping foreign keys, merging references, and detecting non-indexed foreign keys for performance optimization. ```APIDOC sqlalchemy_utils.functions.dependent_objects(obj) - Purpose: Returns a list of objects that depend on the given object via foreign key relationships. - Parameters: - obj: The SQLAlchemy mapped object to check for dependencies. - Returns: A list of dependent SQLAlchemy objects. sqlalchemy_utils.functions.get_referencing_foreign_keys(table, column=None) - Purpose: Retrieves a list of foreign key objects that reference the specified table or column. - Parameters: - table: The SQLAlchemy Table object being referenced. - column (optional): A specific Column object within the table. If None, all foreign keys referencing the table are returned. - Returns: A list of SQLAlchemy ForeignKeyConstraint objects. sqlalchemy_utils.functions.group_foreign_keys(foreign_keys) - Purpose: Groups a collection of foreign key objects by their referenced table. - Parameters: - foreign_keys: An iterable of SQLAlchemy ForeignKeyConstraint objects. - Returns: A dictionary where keys are referenced Table objects and values are lists of ForeignKeyConstraint objects referencing that table. sqlalchemy_utils.functions.merge_references(session, old_obj, new_obj) - Purpose: Merges all foreign key references from an old object to a new object. - Parameters: - session: The SQLAlchemy session. - old_obj: The SQLAlchemy mapped object whose references will be re-pointed. - new_obj: The SQLAlchemy mapped object to which references will be re-pointed. - Returns: None. Modifies the database directly. sqlalchemy_utils.functions.non_indexed_foreign_keys(table) - Purpose: Identifies foreign keys on a given table that do not have a corresponding index, which can be a performance bottleneck. - Parameters: - table: The SQLAlchemy Table object to inspect. - Returns: A list of SQLAlchemy ForeignKeyConstraint objects that are not indexed. ``` -------------------------------- ### Define SQLAlchemy Model with TranslationHybrid Source: https://sqlalchemy-utils.readthedocs.io/en/latest/internationalization This code defines an 'Article' SQLAlchemy model with translatable 'name' and 'content' attributes. It uses PostgreSQL's HSTORE type to store the translations and applies the TranslationHybrid to these columns, making them accessible as regular model attributes. ```python from sqlalchemy import * from sqlalchemy.dialects.postgresql import HSTORE class Article(Base): __tablename__ = 'article' id = Column(Integer, primary_key=True) name_translations = Column(HSTORE) content_translations = Column(HSTORE) name = translation_hybrid(name_translations) content = translation_hybrid(content_translations) ``` -------------------------------- ### Define Generic Relationships with Abstract Base Classes in SQLAlchemy Source: https://sqlalchemy-utils.readthedocs.io/en/latest/generic_relationship This code demonstrates how to implement generic relationships using abstract base classes in SQLAlchemy-Utils. It defines an `EventBase` as an abstract class that includes the generic relationship, using `declared_attr` and string arguments for the relationship definition. Concrete `Event` models can then inherit from this base, ensuring consistent generic relationship behavior across different event types. ```Python class Building(Base): __tablename__ = 'building' id = sa.Column(sa.Integer, primary_key=True) class User(Base): __tablename__ = 'user' id = sa.Column(sa.Integer, primary_key=True) class EventBase(Base): __abstract__ = True object_type = sa.Column(sa.Unicode(255)) object_id = sa.Column(sa.Integer, nullable=False) @declared_attr def object(cls): return generic_relationship('object_type', 'object_id') class Event(EventBase): __tablename__ = 'event' id = sa.Column(sa.Integer, primary_key=True) ``` -------------------------------- ### SQLAlchemy-Utils CompositeType API Source: https://sqlalchemy-utils.readthedocs.io/en/latest/_sources/data_types.rst Documents the CompositeType, a custom data type for SQLAlchemy provided by the `sqlalchemy_utils.types.pg_composite` module, used for handling PostgreSQL composite types. ```APIDOC Module: sqlalchemy_utils.types.pg_composite Class: CompositeType ``` -------------------------------- ### Using Generic Relationships with SQLAlchemy Abstract Base Classes Source: https://sqlalchemy-utils.readthedocs.io/en/latest/_sources/generic_relationship.rst This snippet demonstrates how to define a generic relationship within an abstract base class using the `declared_attr` decorator. This approach is necessary when the relationship needs to be defined once in a base class but instantiated differently in concrete subclasses, especially when using string arguments for `generic_relationship`. ```Python class Building(Base): __tablename__ = 'building' id = sa.Column(sa.Integer, primary_key=True) class User(Base): __tablename__ = 'user' id = sa.Column(sa.Integer, primary_key=True) class EventBase(Base): __abstract__ = True object_type = sa.Column(sa.Unicode(255)) object_id = sa.Column(sa.Integer, nullable=False) @declared_attr def object(cls): return generic_relationship('object_type', 'object_id') class Event(EventBase): __tablename__ = 'event' id = sa.Column(sa.Integer, primary_key=True) ``` -------------------------------- ### SQLAlchemy-Utils JSONType API Source: https://sqlalchemy-utils.readthedocs.io/en/latest/_sources/data_types.rst Documents the JSONType, a custom data type for SQLAlchemy provided by the `sqlalchemy_utils.types.json` module, used for storing and querying JSON data. ```APIDOC Module: sqlalchemy_utils.types.json Class: JSONType ``` -------------------------------- ### SQLAlchemy-Utils CountryType and Country API Source: https://sqlalchemy-utils.readthedocs.io/en/latest/_sources/data_types.rst Documents the CountryType, a custom data type for SQLAlchemy, and the Country primitive, both provided by `sqlalchemy_utils` for handling country-related data. ```APIDOC Module: sqlalchemy_utils.types.country Class: CountryType Module: sqlalchemy_utils.primitives.country Class: Country ``` -------------------------------- ### Configure TranslationHybrid with Dynamic Locales from Object Attribute Source: https://sqlalchemy-utils.readthedocs.io/en/latest/_sources/internationalization.rst This snippet illustrates how to set up `TranslationHybrid` with a dynamic `default_locale` that is determined by an attribute of the model instance itself. The `default_locale` is a callable that receives the object, allowing locale resolution based on the object's state. ```Python translation_hybrid = TranslationHybrid( current_locale=get_locale, default_locale=lambda obj: obj.locale, ) class Article(Base): __tablename__ = 'article' id = Column(Integer, primary_key=True) name_translations = Column(HSTORE) name = translation_hybrid(name_translations, default) locale = Column(String) article = Article(name_translations={'en': 'Some article'}) article.locale = 'en' session.add(article) session.commit() article.name # Some article (even if current locale is other than 'en') ``` -------------------------------- ### SQLAlchemy-Utils ArrowType API Source: https://sqlalchemy-utils.readthedocs.io/en/latest/_sources/data_types.rst Documents the ArrowType, a custom data type for SQLAlchemy provided by the `sqlalchemy_utils.types.arrow` module, used for handling Arrow objects. ```APIDOC Module: sqlalchemy_utils.types.arrow Class: ArrowType ``` -------------------------------- ### SQLAlchemy-Utils IPAddressType API Source: https://sqlalchemy-utils.readthedocs.io/en/latest/_sources/data_types.rst Documents the IPAddressType, a custom data type for SQLAlchemy provided by the `sqlalchemy_utils.types.ip_address` module, used for storing IP addresses. ```APIDOC Module: sqlalchemy_utils.types.ip_address Class: IPAddressType ``` -------------------------------- ### SQLAlchemy-Utils ColorType API Source: https://sqlalchemy-utils.readthedocs.io/en/latest/_sources/data_types.rst Documents the ColorType, a custom data type for SQLAlchemy provided by the `sqlalchemy_utils.types.color` module, used for storing color values. ```APIDOC Module: sqlalchemy_utils.types.color Class: ColorType ``` -------------------------------- ### Customize TranslationHybrid Default Return Value Source: https://sqlalchemy-utils.readthedocs.io/en/latest/_sources/internationalization.rst This code demonstrates how to configure `TranslationHybrid` to return a custom `default_value` (e.g., an empty string) instead of `None` when no translation is found for either the current or default locale. This can prevent `None` values in application logic. ```Python translation_hybrid = TranslationHybrid( current_locale=get_locale, default_locale='en', default_value='' ) class Article(Base): __tablename__ = 'article' id = Column(Integer, primary_key=True) name_translations = Column(HSTORE) name = translation_hybrid(name_translations, default) Article().name # '' ``` -------------------------------- ### SQLAlchemy-Utils WeekDaysType API Source: https://sqlalchemy-utils.readthedocs.io/en/latest/_sources/data_types.rst Documents the WeekDaysType, a custom data type for SQLAlchemy provided by the `sqlalchemy_utils.types.weekdays` module, used for storing information about days of the week. ```APIDOC Module: sqlalchemy_utils.types.weekdays Class: WeekDaysType ``` -------------------------------- ### SQLAlchemy-Utils PhoneNumber and PhoneNumberType API Source: https://sqlalchemy-utils.readthedocs.io/en/latest/_sources/data_types.rst Documents the PhoneNumber primitive and PhoneNumberType, a custom data type for SQLAlchemy, both provided by `sqlalchemy_utils.types.phone_number` for handling phone numbers. ```APIDOC Module: sqlalchemy_utils.types.phone_number Class: PhoneNumber Class: PhoneNumberType ``` -------------------------------- ### SQLAlchemy-Utils TSVectorType API Source: https://sqlalchemy-utils.readthedocs.io/en/latest/_sources/data_types.rst Documents the TSVectorType, a custom data type for SQLAlchemy provided by the `sqlalchemy_utils.types.ts_vector` module, used for PostgreSQL full-text search vectors. ```APIDOC Module: sqlalchemy_utils.types.ts_vector Class: TSVectorType ``` -------------------------------- ### SQLAlchemy-Utils PasswordType API Source: https://sqlalchemy-utils.readthedocs.io/en/latest/_sources/data_types.rst Documents the PasswordType, a custom data type for SQLAlchemy provided by the `sqlalchemy_utils.types.password` module, used for securely storing hashed passwords. ```APIDOC Module: sqlalchemy_utils.types.password Class: PasswordType ``` -------------------------------- ### SQLAlchemy-Utils UUIDType API Source: https://sqlalchemy-utils.readthedocs.io/en/latest/_sources/data_types.rst Documents the UUIDType, a custom data type for SQLAlchemy provided by the `sqlalchemy_utils.types.uuid` module, used for storing Universally Unique Identifiers. ```APIDOC Module: sqlalchemy_utils.types.uuid Class: UUIDType ``` -------------------------------- ### SQLAlchemy-Utils LocaleType API Source: https://sqlalchemy-utils.readthedocs.io/en/latest/_sources/data_types.rst Documents the LocaleType, a custom data type for SQLAlchemy provided by the `sqlalchemy_utils.types.locale` module, used for storing locale identifiers. ```APIDOC Module: sqlalchemy_utils.types.locale Class: LocaleType ``` -------------------------------- ### TranslationHybrid Default Locale Fallback Behavior Source: https://sqlalchemy-utils.readthedocs.io/en/latest/_sources/internationalization.rst This snippet demonstrates how `TranslationHybrid` handles missing translations for the `current_locale`. If a translation is not found for the current locale, it attempts to fetch the translation for the `default_locale` before returning a value. ```Python article = Article(name_translations={'en': 'Some article'}) article.name # Some article article.name_translations['fi'] = 'Joku artikkeli' article.name # Joku artikkeli ``` -------------------------------- ### Querying Translatable Attributes with TranslationHybrid Source: https://sqlalchemy-utils.readthedocs.io/en/latest/internationalization This snippet demonstrates how TranslationHybrid can be used directly within SQLAlchemy queries. It allows filtering records based on the translated value of an attribute for a specific locale, treating the hybrid as an expression. ```python session.query(Article).filter(Article.name_translations['en'] == 'Some article') ``` -------------------------------- ### SQLAlchemy-Utils EmailType API Source: https://sqlalchemy-utils.readthedocs.io/en/latest/_sources/data_types.rst Documents the EmailType, a custom data type for SQLAlchemy provided by the `sqlalchemy_utils.types.email` module, used for storing and validating email addresses. ```APIDOC Module: sqlalchemy_utils.types.email Class: EmailType ``` -------------------------------- ### SQLAlchemy-Utils TimezoneType API Source: https://sqlalchemy-utils.readthedocs.io/en/latest/_sources/data_types.rst Documents the TimezoneType, a custom data type for SQLAlchemy provided by the `sqlalchemy_utils.types.timezone` module, used for storing timezone information. ```APIDOC Module: sqlalchemy_utils.types.timezone Class: TimezoneType ``` -------------------------------- ### SQLAlchemy-Utils ScalarListType API Source: https://sqlalchemy-utils.readthedocs.io/en/latest/_sources/data_types.rst Documents the ScalarListType, a custom data type for SQLAlchemy provided by the `sqlalchemy_utils.types.scalar_list` module, used for storing lists of scalar values. ```APIDOC Module: sqlalchemy_utils.types.scalar_list Class: ScalarListType ``` -------------------------------- ### Configure Attribute-Dependent Default Locale for TranslationHybrid Source: https://sqlalchemy-utils.readthedocs.io/en/latest/internationalization This snippet shows how to reconfigure the `default_locale` of an existing `TranslationHybrid` instance to be dependent on an object's attribute. It sets the default locale to the first available key from the `name_translations` attribute, ensuring a translation is always returned. ```Python translation_hybrid.default_locale = lambda obj, attr: sorted(getattr(obj, attr).keys())[0] article.name # Some article ``` -------------------------------- ### SQLAlchemy-Utils StringEncryptedType API Source: https://sqlalchemy-utils.readthedocs.io/en/latest/_sources/data_types.rst Documents the StringEncryptedType, a custom data type for SQLAlchemy provided by the `sqlalchemy_utils.types.encrypted.encrypted_type` module, used for storing encrypted string data. ```APIDOC Module: sqlalchemy_utils.types.encrypted.encrypted_type Class: StringEncryptedType ``` -------------------------------- ### SQLAlchemy-Utils EncryptedType API (Deprecated) Source: https://sqlalchemy-utils.readthedocs.io/en/latest/_sources/data_types.rst Documents the EncryptedType, a custom data type for SQLAlchemy provided by `sqlalchemy_utils.types.encrypted.encrypted_type`. This type is deprecated; use StringEncryptedType instead. ```APIDOC Module: sqlalchemy_utils.types.encrypted.encrypted_type Class: EncryptedType Note: Deprecated since 0.36.6. Use StringEncryptedType instead. ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.