:orphan: :py:mod:`thanosql.resources._query` =================================== .. py:module:: thanosql.resources._query Module Contents --------------- Classes ~~~~~~~ .. autoapisummary:: thanosql.resources._query.QueryLog thanosql.resources._query.QueryService thanosql.resources._query.QueryLogService thanosql.resources._query.QueryTemplate thanosql.resources._query.QueryTemplateService .. py:class:: QueryLog(/, **data: Any) Bases: :py:obj:`thanosql.resources._model.BaseModel` Usage docs: https://docs.pydantic.dev/2.9/concepts/models/ A base class for creating Pydantic models. .. attribute:: __class_vars__ The names of the class variables defined on the model. .. attribute:: __private_attributes__ Metadata about the private attributes of the model. .. attribute:: __signature__ The synthesized `__init__` [`Signature`][inspect.Signature] of the model. .. attribute:: __pydantic_complete__ Whether model building is completed, or if there are still undefined fields. .. attribute:: __pydantic_core_schema__ The core schema of the model. .. attribute:: __pydantic_custom_init__ Whether the model has a custom `__init__` function. .. attribute:: __pydantic_decorators__ Metadata containing the decorators defined on the model. This replaces `Model.__validators__` and `Model.__root_validators__` from Pydantic V1. .. attribute:: __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. .. attribute:: __pydantic_parent_namespace__ Parent namespace of the model, used for automatic rebuilding of models. .. attribute:: __pydantic_post_init__ The name of the post-init method for the model, if defined. .. attribute:: __pydantic_root_model__ Whether the model is a [`RootModel`][pydantic.root_model.RootModel]. .. attribute:: __pydantic_serializer__ The `pydantic-core` `SchemaSerializer` used to dump instances of the model. .. attribute:: __pydantic_validator__ The `pydantic-core` `SchemaValidator` used to validate instances of the model. .. attribute:: __pydantic_extra__ A dictionary containing extra values, if [`extra`][pydantic.config.ConfigDict.extra] is set to `'allow'`. .. attribute:: __pydantic_fields_set__ The names of fields explicitly set during instantiation. .. attribute:: __pydantic_private__ Values of private attributes set on the model instance. .. py:attribute:: query_id :type: Optional[str] .. py:attribute:: statement_type :type: Optional[str] .. py:attribute:: start_time :type: Optional[datetime.datetime] .. py:attribute:: end_time :type: Optional[datetime.datetime] .. py:attribute:: query :type: str .. py:attribute:: referer :type: str .. py:attribute:: state :type: Optional[str] .. py:attribute:: destination_table_name :type: Optional[str] .. py:attribute:: destination_schema :type: Optional[str] .. py:attribute:: error_result :type: Optional[str] .. py:attribute:: created_at :type: Optional[datetime.datetime] .. py:attribute:: records :type: Optional[thanosql.resources._record.Records] .. py:attribute:: total_records :type: int .. py:attribute:: affected_records :type: Optional[int] .. py:class:: QueryService(client: thanosql._client.ThanoSQL) Bases: :py:obj:`thanosql._service.ThanoSQLService` Service layer for query methods. .. attribute:: client The ThanoSQL client used to make requests to the engine. :type: ThanoSQL .. attribute:: log The query log service layer to access methods involving query logs. :type: QueryLogService .. attribute:: template The query template service layer to access methods involving query templates. :type: QueryTemplateService .. py:method:: execute(query: Optional[str] = None, template_id: Optional[int] = None, template_name: Optional[str] = None, parameters: Optional[dict] = None, schema: Optional[str] = None, table_name: Optional[str] = None, overwrite: Optional[bool] = None, max_results: int = 100) -> QueryLog 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. :param query: The query string or template to be executed. :type query: str, optional :param template_id: 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. :type template_id: int, optional :param template_name: 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. :type template_name: str, optional :param parameters: 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. :type parameters: dict, optional :param schema: 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". :type schema: str, optional :param table_name: 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. :type table_name: str, optional :param overwrite: Whether to overwrite the table if a table with the same `table_name` and `schema` already exists. If not specified, the value is False. :type overwrite: bool, optional :param max_results: The maximum number of records to be returned by the response QueryLog. If not specified, it defaults to 100. :type max_results: int, optional :returns: A query log object containing details about the results of the executed query. :rtype: 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. .. py:method:: execute_values(query: str, values: Union[List[tuple], List[dict]], template: Optional[str] = None, page_size: int = 100, schema: Optional[str] = None, table_name: Optional[str] = None, overwrite: Optional[bool] = None, max_results: int = 100) -> QueryLog 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. :param query: The query string with a "{{ values }}" placeholder to be executed. :type query: str :param values: List of values to be inserted to the placeholder(s). :type values: list of tuples :param template: 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')) ``` :type template: str, optional :param page_size: The maximum number of rows (set of values) to be sent in one statement. If not specified, it defaults to 100. :type page_size: int, default 100 :param schema: 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". :type schema: str, optional :param table_name: 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. :type table_name: str, optional :param overwrite: Whether to overwrite the table if a table with the same `table_name` and `schema` already exists. If not specified, the value is False. :type overwrite: bool, optional :param max_results: The maximum number of records to be returned by the response QueryLog. If not specified, it defaults to 100. :type max_results: int, default 100 :returns: A query log object containing details about the results of the executed query. :rtype: 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. .. py:class:: QueryLogService(query: QueryService) Bases: :py:obj:`thanosql._service.ThanoSQLService` Service layer for query log methods. Cannot exist without a parent QueryService. .. attribute:: query The parent QueryService to connect to the ThanoSQL client. :type: QueryService .. py:method:: list(search: Optional[str] = None, offset: Optional[int] = None, limit: Optional[int] = None) -> dict Lists the details of stored query logs. :param search: Search keywords that the query strings in the results must contain. If not set, all query logs are returned by default. :type search: str, optional :param offset: 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. :type offset: int, optional :param limit: 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. :type limit: int, optional :returns: A dictionary of results in the format of:: { "query_logs": ["QueryLog"], "total": 0 } :rtype: dict :raises ThanoSQLValueError: If offset is less than 0 or if limit is not between 0 to 100 (inclusive). .. py:class:: QueryTemplate(/, **data: Any) Bases: :py:obj:`thanosql.resources._model.BaseModel` Usage docs: https://docs.pydantic.dev/2.9/concepts/models/ A base class for creating Pydantic models. .. attribute:: __class_vars__ The names of the class variables defined on the model. .. attribute:: __private_attributes__ Metadata about the private attributes of the model. .. attribute:: __signature__ The synthesized `__init__` [`Signature`][inspect.Signature] of the model. .. attribute:: __pydantic_complete__ Whether model building is completed, or if there are still undefined fields. .. attribute:: __pydantic_core_schema__ The core schema of the model. .. attribute:: __pydantic_custom_init__ Whether the model has a custom `__init__` function. .. attribute:: __pydantic_decorators__ Metadata containing the decorators defined on the model. This replaces `Model.__validators__` and `Model.__root_validators__` from Pydantic V1. .. attribute:: __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. .. attribute:: __pydantic_parent_namespace__ Parent namespace of the model, used for automatic rebuilding of models. .. attribute:: __pydantic_post_init__ The name of the post-init method for the model, if defined. .. attribute:: __pydantic_root_model__ Whether the model is a [`RootModel`][pydantic.root_model.RootModel]. .. attribute:: __pydantic_serializer__ The `pydantic-core` `SchemaSerializer` used to dump instances of the model. .. attribute:: __pydantic_validator__ The `pydantic-core` `SchemaValidator` used to validate instances of the model. .. attribute:: __pydantic_extra__ A dictionary containing extra values, if [`extra`][pydantic.config.ConfigDict.extra] is set to `'allow'`. .. attribute:: __pydantic_fields_set__ The names of fields explicitly set during instantiation. .. attribute:: __pydantic_private__ Values of private attributes set on the model instance. .. py:attribute:: id :type: Optional[int] .. py:attribute:: name :type: str .. py:attribute:: query :type: str .. py:attribute:: parameters :type: Optional[List[str]] :value: [] .. py:attribute:: created_at :type: Optional[datetime.datetime] .. py:attribute:: updated_at :type: Optional[datetime.datetime] .. py:class:: QueryTemplateService(query: QueryService) Bases: :py:obj:`thanosql._service.ThanoSQLService` Service layer for query template methods. Cannot exist without a parent QueryService. .. attribute:: query The parent QueryService to connect to the ThanoSQL client. :type: QueryService .. py:method:: list(search: Optional[str] = None, offset: Optional[int] = None, limit: Optional[int] = None, order_by: Optional[str] = None) -> List[QueryTemplate] Lists query templates stored in the workspace. :param search: Search keywords that the query strings in the results must contain. If not set, all query templates are returned by default. :type search: str, optional :param offset: 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. :type offset: int, optional :param limit: 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. :type limit: int, optional :param order_by: 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 :type order_by: str, optional :returns: A list of QueryTemplate objects. :rtype: 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". .. py:method:: create(name: Optional[str] = None, query: Optional[str] = None, dry_run: Optional[bool] = None) -> QueryTemplate Creates a new query template. :param name: The name of the query template to be created. If left empty, an automatic name will be given. :type name: str, optional :param query: The string contents of the template. :type query: str, optional :param dry_run: 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. :type dry_run: bool, optional :returns: QueryTemplate object of the created query template. :rtype: QueryTemplate :raises ThanoSQLValueError: - If the template name contains invalid characters or is too long. - If the query template contains invalid formatting. .. py:method:: get(name: str) -> QueryTemplate Shows the details of the specified query template. :param name: The name of the query template to be retrieved. :type name: str :returns: A QueryTemplate object. :rtype: QueryTemplate .. py:method:: update(current_name: str, new_name: Optional[str] = None, query: Optional[str] = None) -> QueryTemplate Updates the specified query template. :param current_name: The current name of the query template to be updated. :type current_name: str :param new_name: The new name of query template after update. If not set, the name will not be changed. :type new_name: str, optional :param query: The query contents of the query template after update. If not set, the query string will not be changed. :type query: str, optional :returns: QueryTemplate object of the new query template after update. :rtype: 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. .. py:method:: delete(name: str) -> dict Deletes the specified query template. :param name: The name of the query template to be deleted. :type name: str :returns: A dictionary containing a success message in the format of:: { "message": "string" } :rtype: dict