Agno Agents / Utils

Database

On this page

    #Overview

    The Database class acts as a connection factory for databases, providing a unified interface to connect to both a local SQLite database and a Postgres database hosted on Supabase. It abstracts configuration details and implementation choices, letting the developer select the type of database just by passing simple parameters, without having to deal with complex configuration.

    This design is useful when you have diverse environments, such as local development and cloud production, and want a consistent and elegant way to initialize connections to different databases, keeping the rest of the application decoupled from the persistence layer.

    #Execution Flow

    1. When you instantiate the Database class, you call its constructor (it actually uses the custom __new__ method).
    2. The local parameter decides whether the connection will be to local SQLite (local=True) or Supabase Postgres (local=False).
    3. If it is local, the _local_database method is called, which builds the SqliteDb connection using the .db file.
    4. Otherwise, _supabase is called, which creates the PostgresDb connection, building the database URL using environment variables or the parameter passed.
    5. Auxiliary static methods generate schema names, paths or URLs according to parameters and internal defaults.
    6. Finally, the object of the respective database class (SqliteDb or PostgresDb) is returned, ready to use.

    #Class Methods Table

    MethodDescription
    __new__Controls the creation of the object, decides which database to use
    _get_schema_nameReturns the schema name for Postgres
    _get_database_local_storageBuilds the SQLite file path
    _get_database_urlGenerates or returns the Postgres database URL
    _supabaseCreates and configures the Postgres connection object
    _local_databaseCreates and configures the SQLite object

    #Environment Variables

    • SUPABASE_PROJECT_HOST: Supabase project host used to build the connection URL.
    • SUPABASE_DATABASE_PASSWORD: Supabase Postgres database password.

    #Important Architecture Points and Insights

    • Uses the magic method __new__ to implement the Factory pattern, returning different types of objects according to parameters.
    • Encapsulation ensures that database-specific details (URLs, table names) stay centralized, making maintenance easier.
    • Static methods are used for string composition logic, separating responsibilities.
    • The class depends on the SqliteDb and PostgresDb classes, which represent the actual database connections.
    • Environment variables are used to keep sensitive data out of the code, following good practices.
    • Allows parameter injection for greater flexibility (e.g. database name, custom URL).

    #Class and Methods Description

    #Database Class

    #Description

    Factory class to make the connection to local SQLite or Supabase Postgres databases easier, abstracting the complexity of configuration and connection.

    #Constructor Arguments

    ArgumentTypeDescriptionDefault Value
    localboolDefines whether to connect locally (SQLite), otherwise Supabase PostgresFalse
    database_namestr | NoneName of the database or schema, optionalNone
    database_urlstr | NoneFull URL for remote connection, optionalNone

    #Methods

    #1. __new__

    #Description

    Special method that controls the creation of the class instance. According to the parameters, it decides whether a SqliteDb object will be created for a local database or a PostgresDb for Supabase.

    #Arguments

    • local (bool): indicates local or remote use.
    • database_name (str | None): database/schema name.
    • database_url (str | None): remote database URL.

    #Returns

    • SqliteDb or PostgresDb: object configured to interact with the corresponding database.

    #Raises

    None.

    #Examples

    # Conecta a banco SQLite local padrão
    db_local = Database(local=True)
    
    # Conecta a banco Supabase com nome específico
    db_supabase = Database(local=False, database_name="test_schema")

    #2. _get_schema_name

    #Description

    Returns the schema name for the Postgres connection, using the name passed or the default "agent_db".

    #Arguments

    • database_name (str | None): schema name.

    #Returns

    • str: schema name to be used.

    #Raises

    None.

    #Examples

    Database._get_schema_name("prod_schema")  # Retorna "prod_schema"
    Database._get_schema_name(None)           # Retorna "agent_db"

    #3. _get_database_local_storage

    #Description

    Builds the path of the .db file for the local SQLite database according to the name provided.

    #Arguments

    • database_name (str | None): file name without extension.

    #Returns

    • str: full path of the SQLite file.

    #Raises

    None.

    #Examples

    Database._get_database_local_storage("testdb")  # "src/agents/database/testdb.db"
    Database._get_database_local_storage(None)      # "src/agents/database/agno.db"

    #4. _get_database_url

    #Description

    Returns the connection URL for the Supabase Postgres database. Uses the URL passed, if provided, or builds it from the environment variables.

    #Arguments

    • database_url (str | None): optional full URL.

    #Returns

    • str: database connection URL.

    #Raises

    None.

    #Examples

    # Usando URL direta
    Database._get_database_url("postgresql://user:pass@host:5432/db")
    
    # Usando ENV-SUPABASE_PROJECT_HOST e SUPABASE_DATABASE_PASSWORD
    Database._get_database_url(None)  # Exemplo: "postgresql://postgres:password@db.projecthost:5432/postgres"

    #5. _supabase

    #Description

    Creates a PostgresDb instance configured for Supabase, with the schema name and URL defined.

    #Arguments

    • database_url (str | None): remote connection URL.
    • database_name (str | None): schema name.

    #Returns

    • PostgresDb: object configured for use with Supabase.

    #Raises

    None.

    #Examples

    db = Database._supabase(database_url=None, database_name="my_schema")
    # db é uma instância de PostgresDb pronta para manipular o banco remoto

    #6. _local_database

    #Description

    Creates a SqliteDb instance configured for local use, defining the path of the .db file and the tables.

    #Arguments

    • database_name (str | None): name of the local database file.

    #Returns

    • SqliteDb: object configured for the local SQLite database.

    #Raises

    None.

    #Examples

    db = Database._local_database(database_name="localdb")
    # db é uma instância de SqliteDb pronta para manipulação local

    This documentation provides a complete and didactic view of the Database class, making it easier to understand and use in practice.

    Source: src/agents/utils/database.py

    Esc
    ↑↓navigate Enteropen