PluginDataSql Model
- class smarter.apps.plugin.models.PluginDataSql(*args, **kwargs)[source]
Bases:
PluginDataBaseStores SQL-based data configuration for a Smarter plugin.
This model is used for plugins that return data by executing SQL queries. It defines the SQL connection, query, parameters, test values, and result limits. The model provides methods for validating parameter and test value structures, preparing SQL queries with parameters, and executing queries.
PluginDataSqlis a concrete subclass ofPluginDataBaseand is referenced byPluginMetato provide the data payload for SQL-type plugins. It is tightly integrated withSqlConnectionfor managing database connectivity and query execution, and supports advanced features such as parameterized queries, dynamic placeholder validation, and result limiting.- This model is responsible for:
Storing the SQL query template and associated parameter schema.
Validating that all placeholders in the SQL query are defined in the parameters.
Ensuring that test values are provided and conform to the expected structure.
Preparing and executing SQL queries with runtime parameters, including safe substitution of placeholders.
Enforcing result limits to prevent excessive data retrieval.
Providing methods for returning sanitized query results for use in LLM responses.
Typical use cases include plugins that need to retrieve or analyze data from organizational databases, support dynamic user queries, or expose structured data to the Smarter LLM platform.
See also:
- Parameters:
id (BigAutoField) – Primary key: ID
created_at (DateTimeField) – Created at
updated_at (DateTimeField) – Updated at
description (TextField) – Description. A brief description of what this plugin returns. Be verbose, but not too verbose.
parameters (JSONField) –
Parameters. A JSON dict containing parameter names and data types. Example: {‘required’: [], ‘properties’: {‘max_cost’: {‘type’: ‘float’, ‘description’: ‘the maximum cost that a student is willing to pay for a course.’}, ‘description’: {‘enum’: [‘AI’, ‘mobile’, ‘web’, ‘database’, ‘network’, ‘neural networks’], ‘type’: ‘string’, ‘description’: ‘areas of specialization for courses in the catalogue.’}}}
A JSON dict containing parameter names and data types. Example: {‘required’: [], ‘properties’: {‘max_cost’: {‘type’: ‘float’, ‘description’: ‘the maximum cost that a student is willing to pay for a course.’}, ‘description’: {‘enum’: [‘AI’, ‘mobile’, ‘web’, ‘database’, ‘network’, ‘neural networks’], ‘type’: ‘string’, ‘description’: ‘areas of specialization for courses in the catalogue.’}}}
test_values (JSONField) –
Test values. A JSON dict containing test values for each parameter. Example: {‘city’: ‘San Francisco’}
A JSON dict containing test values for each parameter. Example: {‘city’: ‘San Francisco’}
sql_query (TextField) – Sql query. The SQL query that this plugin will execute when invoked by the user prompt.
limit (IntegerField) – Limit. The maximum number of rows to return from the query.
Relationship fields:
- Parameters:
plugin (
OneToOneFieldtoPluginMeta) – Plugin (related name:plugin_data_base_plugin)plugindatabase_ptr (
OneToOneFieldtoPluginDataBase) – Primary key: Plugindatabase ptr (related name:plugindatasql)connection (
ForeignKeytoSqlConnection) – Connection (related name:plugin_data_sql_connection)
- class DataTypes[source]
Bases:
object- ARRAY = 'array'
- BOOL = 'bool'
- INT = 'integer'
- NULL = 'null'
- NUMBER = 'number'
- OBJECT = 'object'
- STR = 'string'
- exception DoesNotExist
Bases:
DoesNotExist
- exception MultipleObjectsReturned
Bases:
MultipleObjectsReturned
- connection
-
Connection (related name:
plugin_data_sql_connection)- Type:
Type
- connection_id
Internal field, use
connectioninstead.
- classmethod get_cached_data_by_plugin(plugin, invalidate=False)[source]
Return a single instance of PluginDataSql by plugin.
This method caches the results to improve performance.
- Parameters:
plugin (PluginMeta) – The plugin whose data should be retrieved.
- Returns:
A PluginDataSql instance if found, otherwise None.
- Return type:
Union[PluginDataSql, None]
- classmethod get_cached_object(invalidate=False, pk=None, plugin=None)[source]
Retrieve a model instance by primary key, using caching to optimize performance. This method is selectively overridden in models that inherit from MetaDataModel to provide class-specific function parameters.
Example usage:
# Retrieve by primary key instance = MyModel.get_cached_object(pk=1)
- Parameters:
invalidate (bool) – If True, invalidate the cache for this query before retrieving the object.
pk (int) – The primary key of the model instance to retrieve.
plugin (PluginMeta) – The PluginMeta instance associated with the data to retrieve.
- Returns:
The model instance if found, otherwise None.
- Return type:
Optional[“PluginDataBase”]
- limit
-
Limit. The maximum number of rows to return from the query.
- Type:
Type
- plugindatabase_ptr
OneToOneFieldtoPluginDataBasePrimary key: Plugindatabase ptr (related name:
plugindatasql)- Type:
Type
- plugindatabase_ptr_id
Internal field, use
plugindatabase_ptrinstead.
- prepare_sql(params)[source]
Prepare the SQL query by replacing placeholders with values.
- Return type:
- sanitized_return_data(params=None)[source]
Return a dict by executing the query with the provided params.
- sql_query
-
Sql query. The SQL query that this plugin will execute when invoked by the user prompt.
- Type:
Type
- validate()[source]
Validate the model.
Attention
Intended to be overridden in subclasses to provide custom validation logic.
- Return type:
- validate_all_placeholders_in_parameters()[source]
Validates that every placeholder found in the SQL query string is defined as a parameter.
This method scans the
sql_queryattribute for placeholders in the format{parameter_name}. It then checks that each placeholder corresponds to a key in theparameters['properties']dictionary. If any placeholder is not defined in the parameters, aSmarterValueErroris raised.Example:
plugin = { 'plugin': <PluginMeta: sql_test>, 'description': 'test plugin', 'sql_query': "SELECT * FROM auth_user WHERE username = '{username}';", 'parameters': { 'type': 'object', 'properties': { 'username': { 'type': 'string', 'description': 'The username of the user.' } }, 'required': ['username'], 'additionalProperties': False }, 'test_values': 'admin', 'limit': 1, 'connection': <SqlConnection: test_sql_connection - django.db.backends.mysql://smarter:******@smarter-mysql:3306/smarter> }
- Raises:
SmarterValueError – If a placeholder in the SQL query is not defined in the parameters.
- Return type:
- validate_test_values()[source]
Validates the structure of the
test_valuesattribute to ensure it matches the expected JSON representation.Each item in
test_valuesmust be a dictionary with the keysnameandvalue. This method attempts to instantiate each item as a PydanticTestValuemodel to verify the structure.Example of a valid
test_valueslist:[ {"name": "username", "value": "admin"}, {"name": "unit", "value": "Celsius"} ]
- Raises:
SmarterValueError – If any item in
test_valuesdoes not conform to the required structure.- Return type: