thanosql.resources._query

Module Contents

Classes

QueryLog

Usage docs: https://docs.pydantic.dev/2.9/concepts/models/

QueryService

Service layer for query methods.

QueryLogService

Service layer for query log methods.

QueryTemplate

Usage docs: https://docs.pydantic.dev/2.9/concepts/models/

QueryTemplateService

Service layer for query template methods.

class thanosql.resources._query.QueryLog(/, **data: Any)[source]

Bases: thanosql.resources._model.BaseModel

Usage docs: https://docs.pydantic.dev/2.9/concepts/models/

A base class for creating Pydantic models.

__class_vars__

The names of the class variables defined on the model.

__private_attributes__

Metadata about the private attributes of the model.

__signature__

The synthesized __init__ [Signature][inspect.Signature] of the model.

__pydantic_complete__

Whether model building is completed, or if there are still undefined fields.

__pydantic_core_schema__

The core schema of the model.

__pydantic_custom_init__

Whether the model has a custom __init__ function.

__pydantic_decorators__

Metadata containing the decorators defined on the model. This replaces Model.__validators__ and Model.__root_validators__ from Pydantic V1.

__pydantic_generic_metadata__

Metadata for generic models; contains data used for a similar purpose to __args__, __origin__, __parameters__ in typing-module generics. May eventually be replaced by these.

__pydantic_parent_namespace__

Parent namespace of the model, used for automatic rebuilding of models.

__pydantic_post_init__

The name of the post-init method for the model, if defined.

__pydantic_root_model__

Whether the model is a [RootModel][pydantic.root_model.RootModel].

__pydantic_serializer__

The pydantic-core SchemaSerializer used to dump instances of the model.

__pydantic_validator__

The pydantic-core SchemaValidator used to validate instances of the model.

__pydantic_extra__

A dictionary containing extra values, if [extra][pydantic.config.ConfigDict.extra] is set to ‘allow’.

__pydantic_fields_set__

The names of fields explicitly set during instantiation.

__pydantic_private__

Values of private attributes set on the model instance.

query_id: str | None
statement_type: str | None
start_time: datetime.datetime | None
end_time: datetime.datetime | None
query: str
referer: str
state: str | None
destination_table_name: str | None
destination_schema: str | None
error_result: str | None
created_at: datetime.datetime | None
records: thanosql.resources._record.Records | None
total_records: int
affected_records: int | None
class thanosql.resources._query.QueryService(client: thanosql._client.ThanoSQL)[source]

Bases: thanosql._service.ThanoSQLService

Service layer for query methods.

client

The ThanoSQL client used to make requests to the engine.

Type:

ThanoSQL

log

The query log service layer to access methods involving query logs.

Type:

QueryLogService

template

The query template service layer to access methods involving query templates.

Type:

QueryTemplateService

execute(query: str | None = None, template_id: int | None = None, template_name: str | None = None, parameters: dict | None = None, schema: str | None = None, table_name: str | None = None, overwrite: bool | None = None, keep_temp_table: bool | None = None, max_results: int = 100) QueryLog[source]

Executes a query string.

There are three ways of requesting a query:

  • Using a complete query directly in query, leaving template_id, template_name, and parameters empty.

  • Using a template query in query and completing it with parameters, leaving template_id and template_name empty.

  • Recalling a template query from the database using template_id or template_name (but not both) and completing it with parameters, leaving query empty.

One, and only one, of these ways must be chosen. That is, exactly one of query, template_id, or template_name must be specified. If none or more than one way is selected, an error will occur.

Parameters:
  • query (str, optional) – The query string or template to be executed.

  • template_id (int, optional) – The ID number of the query template to be used. Only relevant when a query template from the database is needed, and query and template_name are not used simultaneously.

  • template_name (str, optional) – The name of the query template to be used. Only relevant when a query template from the database is needed, and query and template_id are not used simultaneously.

  • parameters (dict, optional) – A dictionary of parameter names and values to fill in the template. Only relevant when a query template, either from query or the database, is used.

  • schema (str, optional) – The schema of the table to save the query results in. If not specified and table_name is also empty, it defaults to “qm”. If table_name is specified, it defaults to “public”.

  • table_name (str, optional) – The name of the table to save the query results in. If not specified while the query produces a result, an automatic table name will be given.

  • overwrite (bool, optional) – Whether to overwrite the table if a table with the same table_name and schema already exists. If not specified, the value is False.

  • keep_temp_table (bool, optional) – Whether to save temporary tables produced by query execution to the “qm” schema or not. If not specified, the value is True.

  • max_results (int, optional) – The maximum number of records to be returned by the response QueryLog. If not specified, it defaults to 100.

Returns:

A query log object containing details about the results of the executed query.

Return type:

QueryLog

Raises:

ThanoSQLValueError

  • If invalid input combination is provided; that is:

    • query, template_id, and template_name are all empty, or

    • more than one of query, template_id, and template_name are non-empty

  • If max_results is not between 0 and 100 (inclusive).

  • If query and parameters are used but the template has invalid format.

  • If rendering query template by substituting in parameters fails, either by direct query template or templates from the database.

execute_values(query: str, values: List[tuple] | List[dict], template: str | None = None, page_size: int = 100, schema: str | None = None, table_name: str | None = None, overwrite: bool | None = None, keep_temp_table: bool | None = None, max_results: int = 100) QueryLog[source]

Executes a query string with a value placeholder.

Unlike execute, query templates cannot be used, as this might be confusing when combined with value placeholders. Following psycopg, only a single main placeholder is allowed. If multiple placeholders are required, users should use templates. Unlike psycopg, we will use jinja formatting for consistency with query template purposes.

Parameters:
  • query (str) – The query string with a “{{ values }}” placeholder to be executed.

  • values (list of tuples) – List of values to be inserted to the placeholder(s).

  • template (str, optional) –

    How values should be formatted inside {{ values }}. If it is left empty, values will just be listed inside brackets separated by commas. In this case, values should be a list of tuples. For example, we have the following values:

    [(1, "gangnam", "seoul"), (2, "haeundae", "busan")]
    

    and we leave template empty. The original query looks like:

    VALUES
        {{ values }}
    

    The rendered query will look like:

    VALUES
        (1, 'gangnam', 'seoul'),
        (2, 'haeundae', 'busan')
    

    Meanwhile, if we have the following named values:

    [
        {"id": 1, "name": "gangnam", "city": "seoul"},
        {"id": 2, "name": "haeundae", "city": "busan"},
    ]
    

    and we have the following template:

    ({{ id }}, CONCAT(INITCAP({{ name }}), '-gu'), INITCAP({{ city }}))
    

    the rendered query will be:

    VALUES
        (1, CONCAT(INITCAP('gangnam', '-gu')), INITCAP('seoul')),
        (2, CONCAT(INITCAP('haeundae', '-gu')), INITCAP('busan'))
    

  • page_size (int, default 100) – The maximum number of rows (set of values) to be sent in one statement. If not specified, it defaults to 100.

  • schema (str, optional) – The schema of the table to save the query results in. If not specified and table_name is also empty, it defaults to “qm”. If table_name is specified, it defaults to “public”.

  • table_name (str, optional) – The name of the table to save the query results in. If not specified while the query produces a result, an automatic table name will be given.

  • overwrite (bool, optional) – Whether to overwrite the table if a table with the same table_name and schema already exists. If not specified, the value is False.

  • keep_temp_table (bool, optional) – Whether to save temporary tables produced by query execution to the “qm” schema or not. If not specified, the value is True.

  • max_results (int, default 100) – The maximum number of records to be returned by the response QueryLog. If not specified, it defaults to 100.

Returns:

A query log object containing details about the results of the executed query.

Return type:

QueryLog

Raises:

ThanoSQLValueError

  • If values is empty.

  • If page_size is less than 1.

  • If max_results is not between 0 and 100 (inclusive).

  • If the formats of template and values don’t match.

class thanosql.resources._query.QueryLogService(query: QueryService)[source]

Bases: thanosql._service.ThanoSQLService

Service layer for query log methods.

Cannot exist without a parent QueryService.

query

The parent QueryService to connect to the ThanoSQL client.

Type:

QueryService

list(search: str | None = None, offset: int | None = None, limit: int | None = None) dict[source]

Lists the details of stored query logs.

Parameters:
  • search (str, optional) – Search keywords that the query strings in the results must contain. If not set, all query logs are returned by default.

  • offset (int, optional) – When set to n, skips the first n results and excludes them from the output list. Otherwise, starts the list from the first result stored. Must be greater than 0.

  • limit (int, optional) – When set to n, limits the number of results listed to n. Otherwise, lists up to 100 results per call. Must range between 0 to 100.

Returns:

A dictionary of results in the format of:

{
    "query_logs": ["QueryLog"],
    "total": 0
}

Return type:

dict

Raises:

ThanoSQLValueError – If offset is less than 0 or if limit is not between 0 to 100 (inclusive).

class thanosql.resources._query.QueryTemplate(/, **data: Any)[source]

Bases: thanosql.resources._model.BaseModel

Usage docs: https://docs.pydantic.dev/2.9/concepts/models/

A base class for creating Pydantic models.

__class_vars__

The names of the class variables defined on the model.

__private_attributes__

Metadata about the private attributes of the model.

__signature__

The synthesized __init__ [Signature][inspect.Signature] of the model.

__pydantic_complete__

Whether model building is completed, or if there are still undefined fields.

__pydantic_core_schema__

The core schema of the model.

__pydantic_custom_init__

Whether the model has a custom __init__ function.

__pydantic_decorators__

Metadata containing the decorators defined on the model. This replaces Model.__validators__ and Model.__root_validators__ from Pydantic V1.

__pydantic_generic_metadata__

Metadata for generic models; contains data used for a similar purpose to __args__, __origin__, __parameters__ in typing-module generics. May eventually be replaced by these.

__pydantic_parent_namespace__

Parent namespace of the model, used for automatic rebuilding of models.

__pydantic_post_init__

The name of the post-init method for the model, if defined.

__pydantic_root_model__

Whether the model is a [RootModel][pydantic.root_model.RootModel].

__pydantic_serializer__

The pydantic-core SchemaSerializer used to dump instances of the model.

__pydantic_validator__

The pydantic-core SchemaValidator used to validate instances of the model.

__pydantic_extra__

A dictionary containing extra values, if [extra][pydantic.config.ConfigDict.extra] is set to ‘allow’.

__pydantic_fields_set__

The names of fields explicitly set during instantiation.

__pydantic_private__

Values of private attributes set on the model instance.

id: int | None
name: str
query: str
parameters: List[str] | None = []
created_at: datetime.datetime | None
updated_at: datetime.datetime | None
class thanosql.resources._query.QueryTemplateService(query: QueryService)[source]

Bases: thanosql._service.ThanoSQLService

Service layer for query template methods.

Cannot exist without a parent QueryService.

query

The parent QueryService to connect to the ThanoSQL client.

Type:

QueryService

list(search: str | None = None, offset: int | None = None, limit: int | None = None, order_by: str | None = None) List[QueryTemplate][source]

Lists query templates stored in the workspace.

Parameters:
  • search (str, optional) – Search keywords that the query strings in the results must contain. If not set, all query templates are returned by default.

  • offset (int, optional) – When set to n, skips the first n results and excludes them from the output list. Otherwise, starts the list from the first result stored. Must be greater than 0.

  • limit (int, optional) – When set to n, limits the number of results listed to n. Otherwise, lists up to 100 results per call. Must range between 0 to 100.

  • order_by (str, optional) –

    How to order the results. There are only three possible values:

    • recent: based on the date of creation, from most recent to oldest

    • name_asc: based on the name of the template, from A to Z

    • name_desc: based on the name of the template, from Z to A

Returns:

A list of QueryTemplate objects.

Return type:

List[QueryTemplate]

Raises:

ThanoSQLValueError

  • If offset is less than 0 or if limit is not between 0 to 100 (inclusive).

  • If order_by is not one of “recent”, “name_asc”, or “name_desc”.

create(name: str | None = None, query: str | None = None, dry_run: bool | None = None) QueryTemplate[source]

Creates a new query template.

Parameters:
  • name (str, optional) – The name of the query template to be created. If left empty, an automatic name will be given.

  • query (str, optional) – The string contents of the template.

  • dry_run (bool, optional) – Whether to “dry run” the template creation or save it to database. When set to True, only shows whether the query template is valid or not without actually storing it. By default, created query templates will be saved to the workspace database.

Returns:

QueryTemplate object of the created query template.

Return type:

QueryTemplate

Raises:

ThanoSQLValueError

  • If the template name contains invalid characters or is too long.

  • If the query template contains invalid formatting.

get(name: str) QueryTemplate[source]

Shows the details of the specified query template.

Parameters:

name (str) – The name of the query template to be retrieved.

Returns:

A QueryTemplate object.

Return type:

QueryTemplate

update(current_name: str, new_name: str | None = None, query: str | None = None) QueryTemplate[source]

Updates the specified query template.

Parameters:
  • current_name (str) – The current name of the query template to be updated.

  • new_name (str, optional) – The new name of query template after update. If not set, the name will not be changed.

  • query (str, optional) – The query contents of the query template after update. If not set, the query string will not be changed.

Returns:

QueryTemplate object of the new query template after update.

Return type:

QueryTemplate

Raises:

ThanoSQLValueError

  • If the new template name is set but is empty or null, contains invalid characters, or is too long.

  • If the new query template is set but is null or contains invalid formatting.

delete(name: str) dict[source]

Deletes the specified query template.

Parameters:

name (str) – The name of the query template to be deleted.

Returns:

A dictionary containing a success message in the format of:

{
    "message": "string"
}

Return type:

dict