SqlConnection Model

class smarter.apps.connection.models.SqlConnection(*args, **kwargs)[source]

Bases: ConnectionBase

Stores SQL connection configuration.

This model defines the connection details for a SQL database, including database engine, authentication method, host, port, credentials, SSL/TLS, and proxy settings. It provides methods for establishing connections using various authentication methods (TCP/IP, SSH, LDAP), executing queries, and validating the connection.

SqlConnection is a concrete subclass of ConnectionBase and is referenced by PluginDataSql to provide the database connection. It supports advanced features such as connection pooling, SSL configuration, SSH tunneling, and proxy authentication, enabling secure and flexible integration with a wide range of SQL databases.

This model is responsible for:
  • Managing connection credentials and secrets using the Secret model.

  • Constructing Django-compatible database connection settings and connection strings.

  • Providing methods for testing connectivity, executing SQL queries, and handling connection errors.

  • Supporting multiple authentication methods, including TCP/IP, SSH tunneling, and LDAP.

  • Integrating with Django’s database backend and connection pooling mechanisms.

  • Emitting signals for connection attempts, successes, failures, and query events for observability.

Typical use cases include plugins that need to query organizational databases, perform analytics, or retrieve structured data from remote SQL servers as part of the Smarter plugin ecosystem.

See also:

  • ConnectionBase

  • PluginDataSql

  • smarter.apps.account.models.Secret

Parameters:
  • id (Unknown) – Primary key: ID

  • created_at (Unknown) – Created at

  • updated_at (Unknown) – Updated at

  • name (Unknown) – Name. Name in camelCase, e.g., ‘apiKey’, no special characters.

  • description (Unknown) – Description. A brief description of this resource. Be verbose, but not too verbose.

  • version (Unknown) – Version. Semantic version in the format MAJOR.MINOR.PATCH, e.g., ‘1.0.0’.

  • kind (Unknown) – Kind. The kind of connection. Example: ‘SQL’, ‘API’.

  • db_engine (Unknown) –

    Db engine. The type of database management system. Example: ‘MariaDB’, ‘PostgreSQL’, ‘MS SQL Server’, ‘Oracle’.

    The type of database management system.

    Example: ‘MariaDB’, ‘PostgreSQL’, ‘MS SQL Server’, ‘Oracle’.

  • authentication_method (Unknown) –

    Authentication method. The authentication method to use for the connection. Example: ‘Standard TCP/IP’, ‘Standard TCP/IP over SSH’, ‘LDAP User/Password’.

    The authentication method to use for the connection.

    Example: ‘Standard TCP/IP’, ‘Standard TCP/IP over SSH’, ‘LDAP User/Password’.

  • timeout (Unknown) –

    Timeout. The timeout for the database connection in seconds. Default is 30 seconds.

    The timeout for the database connection in seconds.

    Default is 30 seconds.

  • use_ssl (Unknown) –

    Use ssl. Whether to use SSL/TLS for the connection.

    Whether to use SSL/TLS for the connection.

  • ssl_cert (Unknown) – Ssl cert. The SSL certificate for the connection, if required.

  • ssl_key (Unknown) – Ssl key. The SSL key for the connection, if required.

  • ssl_ca (Unknown) –

    Ssl ca. The Certificate Authority (CA) certificate for verifying the server.

    The SSL certificate for the connection, if required.

    The SSL key for the connection, if required. The Certificate Authority (CA) certificate for verifying the server.

  • hostname (Unknown) –

    Hostname. The remote host of the SQL connection. Should be a valid internet domain name.

    The remote host of the SQL connection.

    Should be a valid internet domain name.

  • port (Unknown) –

    Port. The port of the SQL connection. example: 3306 for MariaDB.

    The port of the SQL connection.

    example: 3306 for MariaDB. 5432 for PostgreSQL, 1521 for Oracle, 1433 for MS SQL Server. 5000 for Sybase. 1234 for SQLite (not commonly used). 3306 is a reasonable default as MariaDB is widely used. 5432 could also be a reasonable default as PostgreSQL is also widely used.

  • database (Unknown) –

    Database. The name of the database to connect to.

    The name of the database to connect to.

  • username (Unknown) –

    Username. The database username.

    The database username.

  • pool_size (Unknown) –

    Pool size. The size of the connection pool.

    The size of the connection pool.

  • max_overflow (Unknown) –

    Max overflow. The maximum number of connections to allow beyond the pool size.

    The maximum number of connections to allow beyond the pool size.

  • proxy_protocol (Unknown) –

    Proxy protocol. The protocol to use for the proxy connection.

    The protocol to use for the proxy connection.

  • proxy_host (Unknown) –

    Proxy host. The remote host of the SQL proxy connection. Should be a valid internet domain name.

    The remote host of the SQL proxy connection.

    Should be a valid internet domain name.

  • proxy_port (Unknown) –

    Proxy port. The port of the SQL proxy connection.

    The port of the SQL proxy connection.

    8080 is a common default for HTTP proxies. 3128 is another common default for HTTP proxies. 1080 is a common default for SOCKS proxies. 8080 is a reasonable default as it is widely used for HTTP proxies.

  • proxy_username (Unknown) –

    Proxy username. The username for the proxy connection.

    The username for the proxy connection.

  • ssh_known_hosts (Unknown) –

    Ssh known hosts. The known_hosts file content for verifying SSH connections. Usually comes from ~/.ssh/known_hosts.

    The known_hosts file content for verifying SSH connections.

    Usually comes from ~/.ssh/known_hosts.

Relationship fields:

Parameters:
  • user_profile (Unknown) – User profile (related name: connectionbase)

  • tags (Unknown) – Tags. Tags for categorizing and organizing this resource. (related name: connectionbase)

  • connectionbase_ptr (Unknown) – Primary key: Connectionbase ptr (related name: sqlconnection)

  • password (Unknown) –

    Password. The password for authentication, if required. (related name: sql_connections_password)

    The password for authentication, if required.

    See: smarter.apps.account.models.Secret

  • proxy_password (Unknown) –

    Proxy password. The API key for authentication, if required. (related name: sql_connections_proxy_password)

    The password for the proxy connection, if required.

    See: smarter.apps.account.models.Secret

  • tagged_items (Unknown) – Tagged items (related name: +)

Reverse relationships:

Parameters:

plugin_data_sql_connection (Unknown) – All plugin data sql connection of this SQL Connection (related name of connection)

CONNECTION_KIND_CHOICES = [('SqlConnection', 'SqlConnection'), ('ApiConnection', 'ApiConnection')]
DBMS_AUTHENITCATION_METHODS = [('none', 'None'), ('tcpip', 'Standard TCP/IP'), ('tcpip_ssh', 'Standard TCP/IP over SSH'), ('ldap_user_pwd', 'LDAP User/Password')]

The supported authentication methods for SQL connections.

DBMS_CHOICES = [('django.db.backends.mysql', 'django.db.backends.mysql'), ('django.db.backends.postgresql', 'django.db.backends.postgresql'), ('django.db.backends.sqlite3', 'django.db.backends.sqlite3'), ('django.db.backends.oracle', 'django.db.backends.oracle'), ('django.db.backends.mssql', 'django.db.backends.mssql'), ('django.db.backends.sybase', 'django.db.backends.sybase')]

The supported database management systems (DBMS) for SQL connections.

DBMS_DEFAULT_TIMEOUT = 30

The default timeout for database connections in seconds.

30 seconds is a reasonable default that balances responsiveness with network latency.

exception DoesNotExist

Bases: DoesNotExist

__init__(*args, **kwargs)
add_note(note, /)

Add a note to the exception

args
silent_variable_failure = True
with_traceback(tb, /)

Set self.__traceback__ to tb and return self.

HASH_FLOOR = 1000000
HASH_PREFIX = 'r'
HASH_SUFFIX = 'x'
exception MultipleObjectsReturned

Bases: MultipleObjectsReturned

__init__(*args, **kwargs)
add_note(note, /)

Add a note to the exception

args
with_traceback(tb, /)

Set self.__traceback__ to tb and return self.

exception NotUpdated

Bases: NotUpdated

__init__(*args, **kwargs)
add_note(note, /)

Add a note to the exception

args
with_traceback(tb, /)

Set self.__traceback__ to tb and return self.

__init__(*args, **kwargs)
async adelete(using=None, keep_parents=False)
property amnesty_urls: list[str]

Returns a list of URLs that are exempt from certain checks.

Returns:

List of URL path strings that are exempt.

Return type:

list[str]

property annotations: dict[str, str]

a map of string keys to string values, as in Kubernetes.

Assigning to it validates the new annotations, and the next save() makes the stored annotations exactly these, adding, changing and removing rows of smarter.lib.annotation.models.Annotation. Assignment accepts a map, or the list of one-key maps of older manifests, and converts scalar values to strings.

Example:

llmclient.annotations = {**llmclient.annotations, "acme.com/crm-account-id": "A-10042"}
llmclient.save()
Returns:

A copy of the annotations. Changing it doesn’t change the resource.

Type:

The resource’s annotations

Setter accepts:

None | str | dict[str, Any] | list[dict[str, Any]]

apiconnection

Reverse OneToOneField from ApiConnection

The API Connection of this connection base (related name of connectionbase_ptr)

Type:

Type

async arefresh_from_db(using=None, fields=None, from_queryset=None)
async asave(*, force_insert=False, force_update=False, using=None, update_fields=None)
authentication_method

CharField

Authentication method. The authentication method to use for the connection. Example: ‘Standard TCP/IP’, ‘Standard TCP/IP over SSH’, ‘LDAP User/Password’.

Choices:

  • none

  • tcpip

  • tcpip_ssh

  • ldap_user_pwd

The authentication method to use for the connection.

Example: ‘Standard TCP/IP’, ‘Standard TCP/IP over SSH’, ‘LDAP User/Password’.

Type:

Type

authorize()

Check that no budget forbids charges to this resource.

Call it before spending on it.

It is not called when the resource is looked up, or checked for readiness, so that a resource whose budget is exceeded can still be viewed and managed.

Raises:

SmarterBudgetExceeded – if a budget’s resource lock forbids charges to it.

Return type:

None

bool_environment_variable(var_name, default=False)

Retrieves a boolean value from an environment variable.

This method checks the specified environment variable and returns its value as a boolean. It recognizes common truthy values such as “true”, “1”, “yes”, and “on”. If the variable is not set or cannot be interpreted as a boolean, it returns the provided default value.

Parameters:
  • var_name (str) – The name of the environment variable to check.

  • default (bool) – The default boolean value to return if the environment variable is not set or invalid.

Returns:

The boolean value of the environment variable or the default.

Return type:

bool

cache_expiration: ClassVar[int] = 60

Seconds that get_cached_object() caches a row, from smarter_settings.subsystem_cache_expiration.

classmethod check(**kwargs)
clean()

Hook for doing any extra model-wide validation after clean() has been called on every field by self.clean_fields. Any ValidationError raised by this method will not be associated with a particular field; it will have a special-case association with the field defined by NON_FIELD_ERRORS.

clean_fields(exclude=None)

Clean all fields and raise a ValidationError containing a dict of all validation errors if any occur.

clone(new_name=None, new_version=None, user_profile=None)

Create a clone of this instance with a new name, version, and/or user profile.

Parameters:
  • new_name (str | None) – The name for the cloned instance. If not provided, the original name will be suffixed with “ (clone)”.

  • new_version (str | None) – The version for the cloned instance. If not provided, the original version will be used.

  • user_profile (UserProfile | None) – The user profile for the cloned instance. If not provided, the original user profile will be used.

Returns:

A new instance of MetaDataWithOwnershipModel that is a clone of this instance with the specified changes.

Return type:

MetaDataWithOwnershipModel

close()[source]

Close the database connection.

This method closes the current database connection associated with this SQL connection instance, if it exists. If an error occurs while closing the connection, it is logged and the connection reference is cleared.

Returns:

None

connect_ldap_user_pwd()[source]

Establish a database connection using LDAP User/Password authentication.

This method attempts to create and validate a database connection using LDAP User/Password authentication, based on the current SQL connection instance’s configuration. It emits signals for connection attempts, successes, and failures for observability.

Returns:

The database connection object if successful, otherwise None.

Return type:

BaseDatabaseWrapper | None

connect_tcpip()[source]

Establish a test database connection using Standard TCP/IP.

This method attempts to create and validate a database connection using the standard TCP/IP authentication method, based on the current SQL connection instance’s configuration. It emits signals for connection attempts, successes, and failures for observability.

Returns:

The database connection object if successful, otherwise None.

Return type:

BaseDatabaseWrapper | None

Example:

db_wrapper = sql_connection.connect_tcpip()
if db_wrapper:
    # Connection established, use db_wrapper...
    pass

See also:

connect_tcpip_ssh()[source]

Establish a database connection through an SSH tunnel.

It opens an SshTunnel to the SSH server, which forwards a loopback port to the database, and connects the database driver to that port. The tunnel stays open while the connection is used, and close() closes both. The SSH server’s host key must be in ssh_known_hosts: an unknown one is refused, never learned. It emits signals for connection attempts, successes, and failures for observability.

Returns:

The database connection object if successful, otherwise None.

Return type:

BaseDatabaseWrapper | None

connected: bool | None = None

Whether the most recent execute_query() established a database connection, which.

includes authenticating to the database. None until a query is executed.

property connection: BaseDatabaseWrapper | None

Return the database connection if it exists, otherwise create a new one.

This property returns the current database connection for this SQL connection instance. If a connection has already been established, it is returned; otherwise, a new connection is created using the configured authentication method and connection parameters.

Returns:

The database connection object, or None if the connection could not be established.

Return type:

Optional[BaseDatabaseWrapper]

Example:

conn = sql_connection.connection
if conn:
    # Use the database connection
    ...

See also:

property connection_string: str

Return the database connection string.

This property constructs and returns a database connection string based on the current SQL connection instance’s configuration.

Returns:

A database connection string.

Return type:

str

connectionbase_ptr

OneToOneField to ConnectionBase

Primary key: Connectionbase ptr (related name: sqlconnection)

Type:

Type

connectionbase_ptr_id

Internal field, use connectionbase_ptr instead.

created_at

DateTimeField

Created at

Timestamp indicating when the model instance was created.

This field is automatically set to the current date and time when the instance is first created. It is indexed in the database for efficient querying.

Type:

Type

data_to_dict(data)

Converts data to a dictionary, handling different types of input.

This method accepts either a dictionary or a string. If a string is provided, it will attempt to parse it as JSON first, and if that fails, as YAML. If parsing fails or the data type is unsupported, a SmarterValueError is raised.

Parameters:

data (dict[str, Any] | str) – The data to convert, either a dict or a JSON/YAML string.

Returns:

The data as a dictionary.

Return type:

dict[str, Any]

Raises:

SmarterValueError – If the data cannot be converted to a dictionary.

database

CharField

Database. The name of the database to connect to.

The name of the database to connect to.

Type:

Type

date_error_message(lookup_type, field_name, unique_for)
db_engine

CharField

Db engine. The type of database management system. Example: ‘MariaDB’, ‘PostgreSQL’, ‘MS SQL Server’, ‘Oracle’.

Choices:

  • django.db.backends.mysql

  • django.db.backends.postgresql

  • django.db.backends.sqlite3

  • django.db.backends.oracle

  • django.db.backends.mssql

  • django.db.backends.sybase

The type of database management system.

Example: ‘MariaDB’, ‘PostgreSQL’, ‘MS SQL Server’, ‘Oracle’.

Type:

Type

property db_options: dict[str, Any]

Return the database connection options.

This property constructs and returns a dictionary of options for the database connection, including SSL/TLS settings and authentication method if applicable.

  • timeout, in the driver’s own options: for MySQL, connect_timeout, read_timeout and write_timeout, and for PostgreSQL, connect_timeout and a statement_timeout. Without them, PyMySQL waits forever for a query’s reply, and a slow query holds the request’s thread for as long as it runs. Other engines get none.

  • If SSL is enabled (use_ssl is True), the returned dictionary includes the keys ca, cert, and key for SSL configuration.

  • If the authentication method is LDAP user/password, the dictionary includes an authentication key set to LDAP.

Returns:

A dictionary of database connection options.

Return type:

dict

Example:

options = sql_connection.db_options
# returns: {'connect_timeout': 30, 'read_timeout': 30, 'write_timeout': 30,
#           'ssl': {'ca': '...', 'cert': '...', 'key': '...'}, 'authentication': 'LDAP'}
delete(using=None, keep_parents=False)
description

TextField

Description. A brief description of this resource. Be verbose, but not too verbose.

Type:

Type

deserves_amnesty(slug)

Determines if a given URL deserves amnesty based on the amnesty URLs list.

This excuses certain endpoints (like health checks) from select middleware checks.

Parameters:

slug (str) – The URL path to check.

Returns:

True if the URL deserves amnesty, False otherwise.

Return type:

bool

dict_is_contained_in(dict1, dict2)

Checks if one dictionary is contained within another.

This method determines if all key-value pairs in dict1 are present in dict2.

Parameters:
  • dict1 (dict[str, Any]) – The dictionary to check for containment.

  • dict2 (dict[str, Any]) – The dictionary to check against for containment.

Returns:

True if dict1 is contained in dict2, False otherwise.

Return type:

bool

dict_is_subset(small, big)

Checks if one dictionary is a subset of another.

This method determines if all key-value pairs in the small dictionary are present in the big dictionary. It returns True if the small dictionary is a subset of the big dictionary, and False otherwise.

Parameters:
  • small (dict[str, Any]) – The dictionary to check as a subset.

  • big (dict[str, Any]) – The dictionary to check against as a superset.

Returns:

True if the small dictionary is a subset of the big dictionary, False otherwise.

Return type:

bool

property django_db_connection: dict[str, Any]

Return the database connection settings for Django.

This property constructs and returns a dictionary of settings compatible with Django’s database connection handler, using the current SQL connection instance’s configuration.

The returned dictionary includes the following keys:

  • ENGINE: The database backend engine (e.g., django.db.backends.mysql).

  • NAME: The name of the database.

  • USER: The database username.

  • PASSWORD: The password for authentication, if set.

  • HOST: The database host.

  • PORT: The database port as a string.

  • OPTIONS: Additional database connection options (such as SSL or authentication settings).

Returns:

A dictionary of Django database connection settings.

Return type:

dict

Example:

settings = sql_connection.django_db_connection
# returns:
# {
#     "ENGINE": "django.db.backends.mysql",
#     "NAME": "mydb",
#     "USER": "myuser",
#     "PASSWORD": "mypassword",
#     "HOST": "localhost",
#     "PORT": "3306",
#     "OPTIONS": {...}
# }
property elapsed_updated: int | None

The number of whole seconds since the model’s updated_at timestamp.

It is a property, so it always compares updated_at with the current time: the dt parameter can’t be passed, and is always None. A naive updated_at is compared with the naive current time, and an aware one with the current UTC time.

Example

obj = MyModel.objects.get(pk=1)
seconds = obj.elapsed_updated
print(f"Seconds since last update: {seconds}")
Returns:

The absolute difference in seconds between updated_at and now, or None if updated_at is not set, e.g. because the object has not been saved.

execute_query(sql, limit=None)[source]

Execute a SQL query and return the results as a JSON string.

The query is resolved here, in the app, into a SqlToolCall, with the passwords read from their Smarter Secrets, and executed by the tool runner (smarter.apps.llmtool.runner), with execute_sql_call(), through the SSH tunnel if the connection uses one. The signals are sent here, from its result.

Sets connected, so that a caller can tell a failed connection, such as rejected credentials, from a failed query.

Parameters:
  • sql (str) – The SQL query to execute.

  • limit (int | None) – Optional limit on the number of rows to return.

Return type:

str | bool

Returns:

JSON string of query results if successful, otherwise False.

Warning

This method does not perform any SQL injection protection or parameterization. It is the caller’s responsibility to ensure that the SQL query is safe and properly formatted.

Warning

This method does not limit the number of rows returned by the query, unless the limit parameter is provided. The connection’s timeout limits how long the query runs, on MySQL and PostgreSQL. It is the caller’s responsibility to ensure that the query is efficient and does not return excessive data.

classmethod find_hash(value)

Finds and returns the first url path segment in the given value that is a hashed ID.

A segment counts only if it matches hash_regex() and also decodes to an id, so a path segment that merely looks like one, e.g. rex, is skipped. Pass a url’s path, not the whole url: a host name is never a hashed ID.

Example:

MyModel.find_hash("/workbench/llm-clients/rMTAwMDAyNwx/prompt/")  # "rMTAwMDAyNwx"
MyModel.find_hash("/api/v1/llm-clients/repo-ex/prompt/")  # None
Parameters:

value (str) – The string to search for a hashed ID, usually a url path.

Return type:

str | None

Returns:

The first hashed ID found, otherwise None.

property formatted_class_name: str

Returns the class name formatted for logging.

Returns:

The formatted class name as a string.

Return type:

str

formatted_json(json_obj)

Formats a JSON object as a pretty-printed string with ANSI color codes for logging.

Parameters:

json_obj (dict[str, Any] | list) – The JSON object (dict or list) to format.

Returns:

A string representation of the JSON object with ANSI color codes.

Return type:

str

property formatted_state_not_ready: str

Returns the not-ready state formatted for logging.

Returns:

The formatted not-ready state as a string.

Return type:

str

property formatted_state_ready: str

Returns the readiness state formatted for logging.

Returns:

The formatted readiness state as a string.

Return type:

str

formatted_text(text, color_code='\x1b[1;31m')

Formats text with ANSI color codes for logging.

Parameters:
  • text (str) – The text to format.

  • color_code (str) – The ANSI color code to apply.

Returns:

The formatted text with ANSI color codes.

Return type:

str

formatted_text_blue(text)

Formats text in bold dark blue for logging.

Parameters:

text (str) – The text to format.

Returns:

The formatted text in bold dark blue.

Return type:

str

formatted_text_green(text)

Formats text in bright green for logging.

Parameters:

text (str) – The text to format.

Returns:

The formatted text in bright green.

Return type:

str

formatted_text_red(text)

Formats text in dark red for logging.

Parameters:

text (str) – The text to format.

Returns:

The formatted text in dark red.

Return type:

str

classmethod from_db(db, field_names, values, **kwargs)

Load a row, and remember its name, so that save() can tell a rename.

Parameters:
  • db (str | None) – The database alias.

  • field_names (Collection[str]) – The loaded fields’ names.

  • values (Collection[Any]) – The loaded fields’ values.

  • kwargs (Any) – Passed on to Django’s, e.g. the fetch_mode that Django’s type stubs already declare.

Return type:

Self

Returns:

The instance.

full_clean(exclude=None, validate_unique=True, validate_constraints=True)

Call clean_fields(), clean(), validate_unique(), and validate_constraints() on the model. Raise a ValidationError for any errors that occur.

generate_fernet_encryption_key()

Generates a Fernet encryption key.

This method creates a new Fernet encryption key, which can be used for secure encryption and decryption of data. The generated key is returned as a URL-safe base64-encoded string.

Returns:

A new Fernet encryption key.

Return type:

str

get_authentication_method_display(*, field=<django.db.models.CharField: authentication_method>)

Shows the label of the authentication_method. See get_FOO_display() for more information.

classmethod get_cached_connections_for_user(user, invalidate=False)

Return a list of all instances of all concrete subclasses of ConnectionBase.

This method retrieves all connection objects (such as SqlConnection and ApiConnection) associated with the user’s account, across all concrete subclasses of ConnectionBase. It is useful for enumerating all available connections for a given user, regardless of connection type.

Parameters:

user (User) – The user whose connections should be retrieved.

Returns:

A list of all connection instances for the user’s account.

Return type:

list[ConnectionBase]

Example:

connections = ConnectionBase.get_cached_connections_for_user(user)
# returns [<SqlConnection ...>, <ApiConnection ...>, ...]

See also:

classmethod get_cached_object(*args, invalidate=False, pk=None, name=None, user=None, user_profile=None, username=None, account=None, session_key=None, taggit=True, **kwargs)

Retrieve a model instance using caching to optimize performance.

Examples of retrieval patterns:

# By primary key
instance = MyModel.get_cached_object(pk=123)

# By name and user profile
instance = MyModel.get_cached_object(name="Resource Name", user_profile=user_profile)

# By name and account
instance = MyModel.get_cached_object(name="Resource Name", account=account)
Parameters:
  • pk (int | None) – The primary key of the model instance to retrieve.

  • name (str | None) – The name of the model instance to retrieve.

  • user (User | None) – The user associated with the model instance.

  • user_profile (UserProfile | None) – The user profile associated with the model instance.

  • account (Account | None) – The account associated with the model instance.

  • invalidate (bool | None) – Whether to invalidate the cache for this retrieval.

Returns:

The model instance if found, otherwise raises DoesNotExist.

Return type:

MetaDataWithOwnershipModel

classmethod get_cached_objects(invalidate=False, user_profile=None, taggit=True, **kwargs)

Retrieve a list of MetaDataWithOwnershipModel instances associated with a user profile using caching.

Example usage:

# Retrieve MetaDataWithOwnershipModel instances for a user profile with caching
models = MetaDataWithOwnershipModel.get_cached_objects(my_user_profile, invalidate=invalidate)
Parameters:
  • invalidate (bool | None) – Whether to invalidate the cache for this retrieval.

  • user_profile (UserProfile | None) – The user profile for which to retrieve MetaDataWithOwnershipModel instances.

Returns:

A queryset of MetaDataWithOwnershipModel instances associated with the user profile.

Return type:

QuerySet[MetaDataWithOwnershipModel]

get_connection()[source]

Establish a database connection based on the authentication method.

This method attempts to establish a database connection using the configured authentication method for this SQL connection instance. The authentication method can be standard TCP/IP, TCP/IP over SSH, LDAP user/password, or none. Returns the database connection object if successful, otherwise None.

Returns:

The database connection object if successful, otherwise None.

Return type:

BaseDatabaseWrapper | None

get_connection_string(masked=True)[source]

Return the connection string.

This method constructs and returns a database connection string based on the current connection instance’s configuration. If masked is True, sensitive information such as the password or API key will be masked in the returned string.

Parameters:

masked (bool) – Whether to mask sensitive information in the connection string.

Returns:

The constructed connection string.

Return type:

str

Example:

conn_str = sql_connection.get_connection_string(masked=True)
# returns: 'mysql://user:******@host:3306/dbname'

Important

Unlike most of the Smarter codebase, this method does not use Pydantic SecretStr for masking to avoid adding Pydantic as a dependency for the entire smarter package.

get_constraints()
get_db_engine_display(*, field=<django.db.models.CharField: db_engine>)

Shows the label of the db_engine. See get_FOO_display() for more information.

get_deferred_fields()

Return a set containing names of deferred fields for this instance.

get_kind_display(*, field=<django.db.models.CharField: kind>)

Shows the label of the kind. See get_FOO_display() for more information.

classmethod get_object_by_locator(locator)

Retrieves an object based on its record locator.

Example:

obj = MyModel.objects.create()
print(obj.id)  # e.g., 123
locator = obj.record_locator # e.g., "mymodel-rc2x"

retrieved_obj = MyModel.get_object_by_locator(locator)
print(type(retrieved_obj))  # Should be <class 'MyModel'>
print(retrieved_obj)  # Should be the same as obj
Parameters:

locator (str) – The record locator string to decode and search for.

Return type:

TimestampedModel | None

Returns:

The model instance if found, otherwise None. A failure to decode or find the object is logged, and returns None. A locator comes from the client, so a locator that doesn’t decode, or whose row doesn’t exist, is a WARNING, not an ERROR.

get_proxy_protocol_display(*, field=<django.db.models.CharField: proxy_protocol>)

Shows the label of the proxy_protocol. See get_FOO_display() for more information.

get_readonly_csv_file(file_path)

Reads a CSV file and returns its contents as a list of dictionaries, one per row.

The file is opened read-only, so reading it never modifies it.

Parameters:

file_path (str) – The path to the CSV file to read.

Returns:

The rows of the CSV file, one dictionary per row, keyed by the column headers.

Return type:

list[dict]

get_readonly_yaml_file(file_path)

Reads a YAML file and returns its contents as a dictionary.

The file is opened read-only, so reading it never modifies it.

Parameters:

file_path (str) – The path to the YAML file to read.

Returns:

The contents of the YAML file, parsed into a dictionary.

Return type:

dict

classmethod hash_regex()

Returns a regex pattern that matches a hashed ID that is a whole url path segment.

The hashed ID format is defined by the HASH_PREFIX and HASH_SUFFIX class attributes, with a base64-encoded string in between. A match must start at the beginning of the string or after a /, and end at the end of the string or before a /. Without these boundaries, the pattern would match inside ordinary words, e.g. repo-ex in the host name repo-explorer.

Example:

pattern = MyModel.hash_regex()
pattern.search("/workbench/llm-clients/rMTAwMDAyNwx/prompt/")  # matches rMTAwMDAyNwx
pattern.search("http://repo-explorer.example.com/")  # None
Return type:

Pattern

Returns:

A regex pattern for matching hashed IDs.

property hashed_id: str

Returns a URL-friendly hashed version of the object’s ID for use in URLs and other contexts where an obscured, non-identifying, non-sequential identifier is preferred.

Encoding scheme:

  1. Take the object’s ID and add a large constant (HASH_FLOOR) to ensure it’s not easily guessable.

  2. Convert the resulting number to a string and encode it using URL-safe base64 encoding.

  3. Remove any padding characters from the encoded string.

  4. Add a prefix and suffix to the encoded string to create a recognizable format.

Example:

obj = MyModel.objects.create()
print(obj.id)  # e.g., 123
print(obj.hashed_id)  # e.g., "rc2x"
Returns:

Hashed ID string (URL-safe, no padding).

property health_check_urls: list[str]

Returns a list of URL paths that are considered health check endpoints.

Returns:

List of health check URL path strings.

Return type:

list[str]

hostname

CharField

Hostname. The remote host of the SQL connection. Should be a valid internet domain name.

The remote host of the SQL connection.

Should be a valid internet domain name.

Type:

Type

id: int

BigAutoField

Primary key: ID

The row’s primary key, which Django adds to every concrete model. Declared, without a value, only so that type checkers know it: Django ignores a bare annotation.

Type:

Type

classmethod id_from_hashed_id(hashed_id)

Decodes a hashed ID back to the original object ID.

Decoding scheme:

  1. Validate that the hashed ID starts with the expected prefix and ends with the expected suffix.

  2. Remove the prefix and suffix to isolate the base64-encoded string.

  3. Add padding if necessary to make the length of the encoded string a multiple of 4.

  4. Decode the base64 string to get the original number as a string.

  5. Convert the decoded string to an integer and subtract the HASH_FLOOR to get the original ID.

Example:

my_record = MyModel.objects.create()
print(my_record.id)  # e.g., 123
hashed_id = my_record.hashed_id  # e.g., "rc2x"

original_id = MyModel.id_from_hashed_id(hashed_id)
print(original_id)  # Should print the original ID (e.g., 123)
Parameters:

hashed_id (str) – The hashed ID string to decode (URL-safe, no padding).

Return type:

int | None

Returns:

The original object ID if decoding is successful, otherwise None.

classmethod invalidate_cached_name(name)

Drop the cached copy of the row that had name.

get_cached_object() with invalidate=True drops it, then looks the name up again. That lookup fails when no row has the name any more, e.g. after a rename, or when several rows share it, e.g. the profiles of one user in several accounts. Either way the cached copy is already gone, so the failure is ignored.

Parameters:

name (str) – The name the row was cached by.

Return type:

None

property is_billable_resource: bool

Indicates whether the model instance is considered a billable resource.

This property can be overridden in subclasses to specify which models are billable. By default, it returns False, indicating that the base TimestampedModel is not billable.

Returns:

True if the instance is billable, False otherwise.

Return type:

bool

kind

CharField

Kind. The kind of connection. Example: ‘SQL’, ‘API’.

Choices:

  • SqlConnection

  • ApiConnection

Type:

Type

property manifest_url: str

Returns the URL to the plugin’s manifest.

This property constructs the URL to the plugin’s manifest based on its kind and RFC 1034-compliant name. The URL follows the pattern: /plugins/{kind}/{name}/manifest/, where {kind} is the RFC 1034-compliant kind of the plugin, and {name} is the RFC 1034-compliant name of the plugin.

Warning

ToDo: This should be implemented by the subclass. This base SHOULD return a NotImplementedError.

Example:

self.rfc1034_compliant_kind  # 'static'
self.rfc1034_compliant_name  # 'example-plugin
self.manifest_url  # '/plugins/static/example-plugin/manifest/'
mask_string(string='', mask_char='*', mask_length=4, string_length=8)

Masks a string for secure logging.

This utility function masks all but the last unmasked_chars characters of the input string, replacing them with asterisks. It is useful for logging sensitive information like API keys or passwords.

Parameters:
  • string (str | None) – The string to be masked.

  • mask_char (str) – The character used for masking.

  • mask_length (int) – The number of characters to mask.

  • string_length (int) – The length of the string to consider for masking.

Returns:

The masked string.

Return type:

str

max_overflow

IntegerField

Max overflow. The maximum number of connections to allow beyond the pool size.

The maximum number of connections to allow beyond the pool size.

Type:

Type

name

CharField

Name. Name in camelCase, e.g., ‘apiKey’, no special characters.

Type:

Type

objects: MetaDataWithOwnershipModelManager = <smarter.apps.account.models.metadata_with_ownership.MetaDataWithOwnershipModelManager object>
password

ForeignKey to Secret

Password. The password for authentication, if required. (related name: sql_connections_password)

The password for authentication, if required.

See: smarter.apps.account.models.Secret

Type:

Type

password_id

Internal field, use password instead.

property pk
plugin_data_sql_connection

Reverse ForeignKey from PluginDataSql

All plugin data sql connection of this SQL Connection (related name of connection)

Type:

Type

pool_size

IntegerField

Pool size. The size of the connection pool.

The size of the connection pool.

Type:

Type

port

IntegerField

Port. The port of the SQL connection. example: 3306 for MariaDB.

The port of the SQL connection.

example: 3306 for MariaDB. 5432 for PostgreSQL, 1521 for Oracle, 1433 for MS SQL Server. 5000 for Sybase. 1234 for SQLite (not commonly used). 3306 is a reasonable default as MariaDB is widely used. 5432 could also be a reasonable default as PostgreSQL is also widely used.

Type:

Type

prepare_database_save(field)
proxy_host

CharField

Proxy host. The remote host of the SQL proxy connection. Should be a valid internet domain name.

The remote host of the SQL proxy connection.

Should be a valid internet domain name.

Type:

Type

proxy_password

ForeignKey to Secret

Proxy password. The API key for authentication, if required. (related name: sql_connections_proxy_password)

The password for the proxy connection, if required.

See: smarter.apps.account.models.Secret

Type:

Type

proxy_password_id

Internal field, use proxy_password instead.

proxy_port

IntegerField

Proxy port. The port of the SQL proxy connection.

The port of the SQL proxy connection.

8080 is a common default for HTTP proxies. 3128 is another common default for HTTP proxies. 1080 is a common default for SOCKS proxies. 8080 is a reasonable default as it is widely used for HTTP proxies.

Type:

Type

proxy_protocol

CharField

Proxy protocol. The protocol to use for the proxy connection.

Choices:

  • http

  • https

  • socks

The protocol to use for the proxy connection.

Type:

Type

proxy_username

CharField

Proxy username. The username for the proxy connection.

The username for the proxy connection.

Type:

Type

property ready: bool

Returns True if the resource is ready for use, False otherwise.

A resource is considered ready if it has been fully initialized and is in a usable state. This property can be overridden in subclasses to implement custom readiness checks.

Returns:

True if the resource is ready, False otherwise.

Return type:

bool

property record_locator: str

Returns a short, URL-friendly record locator derived from the object’s ID.

Example:

obj = MyModel.objects.create(name="Example")
print(obj.id)  # e.g., 123
print(obj.record_locator)  # e.g., "llmclient-rc2x"
Returns:

Record locator string (URL-safe, no padding).

recursive_sort_dict(data)

Recursively sorts a dictionary by its keys.

This method takes a dictionary and returns a new dictionary with all keys sorted in ascending order. If any values are also dictionaries, they will be sorted recursively as well.

Parameters:

data (dict[str, Any]) – The dictionary to sort.

Returns:

A new dictionary with all keys sorted.

Return type:

dict[str, Any]

refresh_from_db(using=None, fields=None, from_queryset=None)

Reload field values from the database.

By default, the reloading happens from the database this instance was loaded from, or by the read router if this instance wasn’t loaded from any database. The using parameter will override the default.

Fields can be used to specify which fields to reload. The fields should be an iterable of field attnames. If fields is None, then all non-deferred fields are reloaded.

When accessing deferred fields of an instance, the deferred loading of the field will call this method.

remove_annotation(key)

Remove one annotation of a saved resource, immediately.

Does nothing if it doesn’t exist.

Parameters:

key (str) – The annotation key.

Return type:

None

rename(new_name)

Rename the model instance with a new name.

The instance is validated and saved.

Parameters:

new_name (str) – The new name for the instance.

Return type:

MetaDataModel

Returns:

The updated instance of MetaDataModel with the new name.

classmethod restrict_readable(queryset, user)

Hide rows that a user may not read, although their owner would let them.

SmarterQuerySetWithPermissions.with_read_permission_for() calls it last, after it has found the rows of the user’s own account and of the Smarter account. Most kinds hide nothing, and return the queryset as it is. A kind with rows for some users only overrides it, e.g. smarter.apps.llmclient.models.LLMClient.restrict_readable(), which hides an LLMClient that only the platform’s staff may use.

Parameters:
Return type:

SmarterQuerySetWithPermissions[Any]

Returns:

The rows that the user may read.

property rfc1034_compliant_name: str | None

Returns a URL-friendly name for the llmclient.

This property returns an RFC 1034-compliant name for the llmclient, suitable for use in URLs and DNS labels.

Example:

self.name = 'Example LLMClient 1'
self.rfc1034_compliant_name  # 'example-llmclient-1'
Returns:

The RFC 1034-compliant name, or None if self.name is not set.

rfc1034_compliant_str(name)

Converts a string to an RFC 1034 compliant format.

This method takes a string and converts it to a format that complies with RFC 1034, which is commonly used for domain names. It replaces invalid characters with hyphens and ensures the resulting string is lowercase.

Parameters:

name (str) – The string to convert to RFC 1034 compliant format.

Returns:

The converted string in RFC 1034 compliant format.

Return type:

str

rfc1034_compliant_to_snake(name)

Converts an RFC 1034 compliant string to snake_case.

This method takes a string in RFC 1034 compliant format and converts it to snake_case. It replaces hyphens with underscores and ensures the resulting string is lowercase.

Parameters:

name (str) – The RFC 1034 compliant string to convert.

Returns:

The converted string in snake_case.

Return type:

str

save(*args, **kwargs)[source]

Override the save method to validate the field dicts.

This method ensures that all relevant fields are validated before saving the model instance. For example, it checks that the name is in snake_case and converts it if necessary, logs a warning if conversion occurs, and calls the model’s validate() method to enforce any additional validation logic defined on the model. After validation, it proceeds with the standard Django save operation.

Parameters:
  • args – Positional arguments passed to the parent save method.

  • kwargs – Keyword arguments passed to the parent save method.

Returns:

None

save_annotations()

Write annotations assigned since the last save() to the database, without saving the resource’s other fields.

Return type:

None

save_base(raw=False, force_insert=False, force_update=False, using=None, update_fields=None)

Handle the parts of saving which should be done only once per save, yet need to be done in raw saves, too. This includes some sanity checks and signal sending.

The ‘raw’ argument is telling save_base not to save any parent models and not to do any changes to the values before save. This is used by fixture loading.

serializable_value(field_name)

Return the value of the field name for this instance. If the field is a foreign key, return the id value instead of the object. If there’s no Field object with this name on the model, return the model attribute’s value.

Used to serialize a field’s value (in the serializer, or form output, for example). Normally, you would just access the attribute directly and not use this method.

set_annotation(key, value)

Add or change one annotation of a saved resource, immediately.

Parameters:
  • key (str) – The annotation key, e.g. acme.com/crm-account-id.

  • value (object) – The value. Scalars are converted to strings.

Raises:

SmarterAnnotationError – If the key or value is invalid.

Return type:

None

smarter_build_absolute_uri(request)

Attempts to get the absolute URI from a request object.

This utility function tries to retrieve the request URL from any valid child class of django.http.HttpRequest. It is especially useful in unit tests or scenarios where the request object may not implement build_absolute_uri().

Parameters:

request (HttpRequest) – The request object.

Returns:

The absolute request URL.

Return type:

str | None

Raises:

SmarterValueError – If the URI cannot be built from the request.

sorted_dict(data)

Returns a new dictionary with keys sorted.

Parameters:

data (dict[str, Any]) – The dictionary to sort.

Returns:

A new dictionary with sorted keys.

Return type:

dict[str, Any]

sqlconnection

Reverse OneToOneField from SqlConnection

The SQL Connection of this connection base (related name of connectionbase_ptr)

Type:

Type

ssh_known_hosts

TextField

Ssh known hosts. The known_hosts file content for verifying SSH connections. Usually comes from ~/.ssh/known_hosts.

The known_hosts file content for verifying SSH connections.

Usually comes from ~/.ssh/known_hosts.

Type:

Type

ssh_tunnel_settings()[source]

Return the SSH tunnel’s settings, with its password decrypted, or None if the connection doesn’t use one.

For tcpip_ssh, proxy_host and proxy_port (22 when unset) are the SSH server, proxy_username and proxy_password its login, and ssh_known_hosts its host keys. hostname and port are the database, as the SSH server reaches it. See smarter.apps.connection.ssh.

Return type:

SshTunnelSettings | None

Returns:

The settings, or None.

Raises:

SmarterValueError – If the connection uses SSH, but has no proxy_host.

ssl_ca

TextField

Ssl ca. The Certificate Authority (CA) certificate for verifying the server.

The SSL certificate for the connection, if required.

The SSL key for the connection, if required. The Certificate Authority (CA) certificate for verifying the server.

Type:

Type

ssl_cert

TextField

Ssl cert. The SSL certificate for the connection, if required.

Type:

Type

ssl_key

TextField

Ssl key. The SSL key for the connection, if required.

Type:

Type

tagged_items

Reverse GenericRelation from SqlConnection

All + of this tagged item (related name of tagged_items)

Type:

Type

tags = <taggit.managers._TaggableManager object>
property tags_list: list[str]

Return the tags as a list of strings.

It is cached twice: cached_property keeps it on the instance, which is the fastest lookup, and cache_results keeps it in the Django cache, which outlives the instance.

Returns:

List of tag names.

test_connection()[source]

Establish a database connection based on the authentication method.

This method attempts to establish a database connection using the configured authentication method for this SQL connection instance. The authentication method can be standard TCP/IP, TCP/IP over SSH, LDAP user/password, or none. Returns True if the connection is successfully established, otherwise False.

Returns:

True if the connection is established, False otherwise.

Return type:

bool

Important

This method is called during the validation process to ensure that the connection parameters are correct and that a connection can be successfully made to the database. For example, it is invoked when saving a SqlConnection instance to verify the connection details.

See also:

test_proxy()[source]

Test the proxy connection by making a request to a known URL through the proxy.

Returns:

True if the proxy connection is successful, otherwise False.

Return type:

bool

timeout

IntegerField

Timeout. The timeout for the database connection in seconds. Default is 30 seconds.

The timeout for the database connection in seconds.

Default is 30 seconds.

Type:

Type

to_camel_case(data, convert_values=False)

Converts a snake_case string to camelCase.

This method takes a string in snake_case format and converts it to camelCase. It is useful for standardizing naming conventions across different formats.

Parameters:
  • data (ConvertibleCaseT) – The snake_case string to convert.

  • convert_values (bool) – Whether to convert the values of dictionaries and lists recursively.

Returns:

The converted string in camelCase.

Return type:

ConvertibleCaseT

to_json()

Serialize the model instance to a JSON-compatible dictionary.

This method uses the custom SmarterJSONEncoder to ensure that all fields, including timestamps and any complex data types, are properly serialized.

Return type:

dict[str, Any]

Returns:

A dictionary representation of the model instance suitable for JSON serialization.

Raises:

SmarterValueError – if the instance can’t be serialized.

to_snake_case(data, convert_values=False)

Converts a camelCase or PascalCase string to snake_case.

This method takes a string in camelCase or PascalCase format and converts it to snake_case. It is useful for standardizing naming conventions across different formats.

Parameters:
  • data (ConvertibleCaseT) – The camelCase or PascalCase string to convert.

  • convert_values (bool) – Whether to convert the values of dictionaries and lists recursively.

Returns:

The converted string in snake_case.

Return type:

ConvertibleCaseT

tool_call(sql)[source]

Resolve a query into a SqlToolCall, for the tool runner.

Parameters:

sql (str) – The final SQL.

Return type:

SqlToolCall

Returns:

The call, with the database’s password, and the SSH tunnel’s, decrypted.

Raises:

SmarterValueError – If the connection uses SSH, but has no SSH server.

property unformatted_class_name: str

Returns the raw class name without formatting.

Returns:

The unformatted class name as a string.

Return type:

str

This is useful for logging or serialization where the plain class name is needed.

unique_error_message(model_class, unique_check)
updated_at

DateTimeField

Updated at

Timestamp indicating when the model instance was last updated.

This field is automatically updated to the current date and time whenever the instance is saved. It is indexed in the database for efficient querying.

Type:

Type

use_ssl

BooleanField

Use ssl. Whether to use SSL/TLS for the connection.

Whether to use SSL/TLS for the connection.

Type:

Type

user_profile

ForeignKey to UserProfile

User profile (related name: connectionbase)

Type:

Type

user_profile_id

Internal field, use user_profile instead.

username

CharField

Username. The database username.

The database username.

Type:

Type

validate()[source]

Override the validate method to test the SQL connection.

Returns:

True if the connection test is successful, otherwise False.

Return type:

bool

validate_constraints(exclude=None)
validate_unique(exclude=None)

Check unique constraints on the model and raise ValidationError if any failed.

version

CharField

Version. Semantic version in the format MAJOR.MINOR.PATCH, e.g., ‘1.0.0’.

Type:

Type

classmethod with_annotation(key, value=None)

Return the resources of this model that have the annotation key, with value if given.

Example:

LLMClient.with_annotation("acme.com/crm-account-id", "A-10042")
Parameters:
  • key (str) – The annotation key.

  • value (str | None) – The value to match, or None for any value.

Return type:

QuerySet

Returns:

The resources, not filtered by any user’s permissions.