# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.

from __future__ import annotations

from typing import Dict, Union, Iterable
from typing_extensions import Literal

import httpx

from .tables import (
    TablesResource,
    AsyncTablesResource,
    TablesResourceWithRawResponse,
    AsyncTablesResourceWithRawResponse,
    TablesResourceWithStreamingResponse,
    AsyncTablesResourceWithStreamingResponse,
)
from ...types import (
    db_cluster_params,
    db_recommend_params,
    db_find_similar_params,
    db_execute_batch_params,
    db_execute_query_params,
    db_hybrid_search_params,
    db_insert_record_params,
    db_delete_records_params,
    db_update_records_params,
    db_semantic_search_params,
    db_detect_anomalies_params,
    db_process_nl_query_params,
)
from ..._types import Body, Omit, Query, Headers, NotGiven, SequenceNotStr, omit, not_given
from ..._utils import maybe_transform, async_maybe_transform
from ..._compat import cached_property
from ..._resource import SyncAPIResource, AsyncAPIResource
from ..._response import (
    to_raw_response_wrapper,
    to_streamed_response_wrapper,
    async_to_raw_response_wrapper,
    async_to_streamed_response_wrapper,
)
from ..._base_client import make_request_options
from ...types.db_cluster_response import DBClusterResponse
from ...types.db_recommend_response import DBRecommendResponse
from ...types.db_find_similar_response import DBFindSimilarResponse
from ...types.db_execute_batch_response import DBExecuteBatchResponse
from ...types.db_execute_query_response import DBExecuteQueryResponse
from ...types.db_hybrid_search_response import DBHybridSearchResponse
from ...types.db_insert_record_response import DBInsertRecordResponse
from ...types.db_delete_records_response import DBDeleteRecordsResponse
from ...types.db_update_records_response import DBUpdateRecordsResponse
from ...types.db_semantic_search_response import DBSemanticSearchResponse
from ...types.db_detect_anomalies_response import DBDetectAnomaliesResponse
from ...types.db_process_nl_query_response import DBProcessNlQueryResponse

__all__ = ["DBResource", "AsyncDBResource"]


class DBResource(SyncAPIResource):
    @cached_property
    def tables(self) -> TablesResource:
        return TablesResource(self._client)

    @cached_property
    def with_raw_response(self) -> DBResourceWithRawResponse:
        """
        This property can be used as a prefix for any HTTP method call to return
        the raw response object instead of the parsed content.

        For more information, see https://www.github.com/WorqHat/worqhat-python-sdk#accessing-raw-response-data-eg-headers
        """
        return DBResourceWithRawResponse(self)

    @cached_property
    def with_streaming_response(self) -> DBResourceWithStreamingResponse:
        """
        An alternative to `.with_raw_response` that doesn't eagerly read the response body.

        For more information, see https://www.github.com/WorqHat/worqhat-python-sdk#with_streaming_response
        """
        return DBResourceWithStreamingResponse(self)

    def cluster(
        self,
        *,
        table: str,
        environment: Literal["development", "staging", "production"] | Omit = omit,
        generate_labels: bool | Omit = omit,
        max_clusters: float | Omit = omit,
        min_clusters: float | Omit = omit,
        num_clusters: float | Omit = omit,
        # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs.
        # The extra values given here take precedence over values defined on the client or passed to this method.
        extra_headers: Headers | None = None,
        extra_query: Query | None = None,
        extra_body: Body | None = None,
        timeout: float | httpx.Timeout | None | NotGiven = not_given,
    ) -> DBClusterResponse:
        """
        Performs K-means clustering on vector embeddings to automatically group similar
        records. Supports auto-detection of optimal cluster count and AI-generated
        cluster labels. Returns cluster information including centroids, sample records,
        and quality metrics.

        Args:
          table: Table to cluster

          environment: Environment to cluster (development, staging, production)

          generate_labels: Whether to generate AI labels for clusters

          max_clusters: Maximum clusters for auto-detection

          min_clusters: Minimum clusters for auto-detection

          num_clusters: Number of clusters (auto-detected if not provided)

          extra_headers: Send extra headers

          extra_query: Add additional query parameters to the request

          extra_body: Add additional JSON properties to the request

          timeout: Override the client-level default timeout for this request, in seconds
        """
        return self._post(
            "/db/cluster",
            body=maybe_transform(
                {
                    "table": table,
                    "environment": environment,
                    "generate_labels": generate_labels,
                    "max_clusters": max_clusters,
                    "min_clusters": min_clusters,
                    "num_clusters": num_clusters,
                },
                db_cluster_params.DBClusterParams,
            ),
            options=make_request_options(
                extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout
            ),
            cast_to=DBClusterResponse,
        )

    def delete_records(
        self,
        *,
        table: str,
        where: Dict[str, object],
        environment: Literal["development", "staging", "production"] | Omit = omit,
        # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs.
        # The extra values given here take precedence over values defined on the client or passed to this method.
        extra_headers: Headers | None = None,
        extra_query: Query | None = None,
        extra_body: Body | None = None,
        timeout: float | httpx.Timeout | None | NotGiven = not_given,
    ) -> DBDeleteRecordsResponse:
        """
        Deletes records from the specified table that match the where conditions.
        Organization ID filtering is automatically applied for multi-tenant security.

        Args:
          table: Table name to delete from

          where: Where conditions

          environment: Environment to delete from (development, staging, production)

          extra_headers: Send extra headers

          extra_query: Add additional query parameters to the request

          extra_body: Add additional JSON properties to the request

          timeout: Override the client-level default timeout for this request, in seconds
        """
        return self._delete(
            "/db/delete",
            body=maybe_transform(
                {
                    "table": table,
                    "where": where,
                    "environment": environment,
                },
                db_delete_records_params.DBDeleteRecordsParams,
            ),
            options=make_request_options(
                extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout
            ),
            cast_to=DBDeleteRecordsResponse,
        )

    def detect_anomalies(
        self,
        *,
        table: str,
        environment: Literal["development", "staging", "production"] | Omit = omit,
        k: float | Omit = omit,
        limit: float | Omit = omit,
        threshold: float | Omit = omit,
        # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs.
        # The extra values given here take precedence over values defined on the client or passed to this method.
        extra_headers: Headers | None = None,
        extra_query: Query | None = None,
        extra_body: Body | None = None,
        timeout: float | httpx.Timeout | None | NotGiven = not_given,
    ) -> DBDetectAnomaliesResponse:
        """
        Identifies anomalous or outlier records using K-nearest neighbors analysis on
        vector embeddings. Useful for fraud detection, data quality checks, and
        identifying unusual patterns. Returns anomaly scores and nearest neighbors for
        each detected anomaly.

        Args:
          table: Table to analyze for anomalies

          environment: Environment to analyze (development, staging, production)

          k: Number of nearest neighbors to consider

          limit: Maximum number of anomalies to return

          threshold: Minimum anomaly score threshold

          extra_headers: Send extra headers

          extra_query: Add additional query parameters to the request

          extra_body: Add additional JSON properties to the request

          timeout: Override the client-level default timeout for this request, in seconds
        """
        return self._post(
            "/db/detect-anomalies",
            body=maybe_transform(
                {
                    "table": table,
                    "environment": environment,
                    "k": k,
                    "limit": limit,
                    "threshold": threshold,
                },
                db_detect_anomalies_params.DBDetectAnomaliesParams,
            ),
            options=make_request_options(
                extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout
            ),
            cast_to=DBDetectAnomaliesResponse,
        )

    def execute_batch(
        self,
        *,
        operations: Iterable[db_execute_batch_params.Operation],
        environment: Literal["development", "staging", "production"] | Omit = omit,
        transactional: bool | Omit = omit,
        # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs.
        # The extra values given here take precedence over values defined on the client or passed to this method.
        extra_headers: Headers | None = None,
        extra_query: Query | None = None,
        extra_body: Body | None = None,
        timeout: float | httpx.Timeout | None | NotGiven = not_given,
    ) -> DBExecuteBatchResponse:
        """
        Executes multiple database operations (queries, inserts, updates, deletes) in a
        single transaction. If transactional is true, all operations will be rolled back
        if any operation fails.

        Args:
          operations: Array of database operations to execute

          environment: Environment to execute operations in

          transactional: Whether to execute all operations in a single transaction

          extra_headers: Send extra headers

          extra_query: Add additional query parameters to the request

          extra_body: Add additional JSON properties to the request

          timeout: Override the client-level default timeout for this request, in seconds
        """
        return self._post(
            "/db/batch",
            body=maybe_transform(
                {
                    "operations": operations,
                    "environment": environment,
                    "transactional": transactional,
                },
                db_execute_batch_params.DBExecuteBatchParams,
            ),
            options=make_request_options(
                extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout
            ),
            cast_to=DBExecuteBatchResponse,
        )

    def execute_query(
        self,
        *,
        query: str,
        environment: Literal["development", "staging", "production"] | Omit = omit,
        params: Union[Dict[str, object], SequenceNotStr[Union[str, float, bool]]] | Omit = omit,
        # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs.
        # The extra values given here take precedence over values defined on the client or passed to this method.
        extra_headers: Headers | None = None,
        extra_query: Query | None = None,
        extra_body: Body | None = None,
        timeout: float | httpx.Timeout | None | NotGiven = not_given,
    ) -> DBExecuteQueryResponse:
        """Executes a raw SQL query directly against the database.

        Supports both named
        parameters ({param}) and positional parameters ($1, $2). Provides security
        guardrails to prevent destructive operations.

        Args:
          query: SQL query to execute. Supports both named parameters ({param}) and positional
              parameters ($1, $2)

          environment: Environment to query (development, staging, production)

          params: Named parameters for queries with {param} syntax

          extra_headers: Send extra headers

          extra_query: Add additional query parameters to the request

          extra_body: Add additional JSON properties to the request

          timeout: Override the client-level default timeout for this request, in seconds
        """
        return self._post(
            "/db/query",
            body=maybe_transform(
                {
                    "query": query,
                    "environment": environment,
                    "params": params,
                },
                db_execute_query_params.DBExecuteQueryParams,
            ),
            options=make_request_options(
                extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout
            ),
            cast_to=DBExecuteQueryResponse,
        )

    def find_similar(
        self,
        *,
        record_id: Union[str, float],
        table: str,
        environment: Literal["development", "staging", "production"] | Omit = omit,
        exclude_self: bool | Omit = omit,
        limit: float | Omit = omit,
        target_table: str | Omit = omit,
        threshold: float | Omit = omit,
        # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs.
        # The extra values given here take precedence over values defined on the client or passed to this method.
        extra_headers: Headers | None = None,
        extra_query: Query | None = None,
        extra_body: Body | None = None,
        timeout: float | httpx.Timeout | None | NotGiven = not_given,
    ) -> DBFindSimilarResponse:
        """
        Finds records similar to a specific existing record using vector embeddings.
        Useful for "More like this" functionality and cross-table similarity search.
        Returns similarity scores and supports excluding the source record.

        Args:
          record_id: ID of the source record

          table: Table containing the source record

          environment: Environment to search in (development, staging, production)

          exclude_self: Whether to exclude the source record from results

          limit: Maximum number of similar records to return

          target_table: Different table to search in (optional)

          threshold: Minimum similarity score threshold

          extra_headers: Send extra headers

          extra_query: Add additional query parameters to the request

          extra_body: Add additional JSON properties to the request

          timeout: Override the client-level default timeout for this request, in seconds
        """
        return self._post(
            "/db/find-similar",
            body=maybe_transform(
                {
                    "record_id": record_id,
                    "table": table,
                    "environment": environment,
                    "exclude_self": exclude_self,
                    "limit": limit,
                    "target_table": target_table,
                    "threshold": threshold,
                },
                db_find_similar_params.DBFindSimilarParams,
            ),
            options=make_request_options(
                extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout
            ),
            cast_to=DBFindSimilarResponse,
        )

    def hybrid_search(
        self,
        *,
        query: str,
        table: str,
        environment: Literal["development", "staging", "production"] | Omit = omit,
        keyword_weight: float | Omit = omit,
        limit: float | Omit = omit,
        semantic_weight: float | Omit = omit,
        text_columns: SequenceNotStr[str] | Omit = omit,
        # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs.
        # The extra values given here take precedence over values defined on the client or passed to this method.
        extra_headers: Headers | None = None,
        extra_query: Query | None = None,
        extra_body: Body | None = None,
        timeout: float | httpx.Timeout | None | NotGiven = not_given,
    ) -> DBHybridSearchResponse:
        """Combines semantic search using vector embeddings with traditional keyword
        search.

        Provides weighted scoring between semantic similarity and keyword
        matching. Ideal for queries that need both contextual understanding and exact
        term matching.

        Args:
          query: Search query combining natural language and keywords

          table: Table to search in

          environment: Environment to search in (development, staging, production)

          keyword_weight: Weight for keyword matching score

          limit: Maximum number of results to return

          semantic_weight: Weight for semantic similarity score

          text_columns: Columns to include in keyword search

          extra_headers: Send extra headers

          extra_query: Add additional query parameters to the request

          extra_body: Add additional JSON properties to the request

          timeout: Override the client-level default timeout for this request, in seconds
        """
        return self._post(
            "/db/hybrid-search",
            body=maybe_transform(
                {
                    "query": query,
                    "table": table,
                    "environment": environment,
                    "keyword_weight": keyword_weight,
                    "limit": limit,
                    "semantic_weight": semantic_weight,
                    "text_columns": text_columns,
                },
                db_hybrid_search_params.DBHybridSearchParams,
            ),
            options=make_request_options(
                extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout
            ),
            cast_to=DBHybridSearchResponse,
        )

    def insert_record(
        self,
        *,
        data: Dict[str, object],
        table: str,
        environment: Literal["development", "staging", "production"] | Omit = omit,
        # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs.
        # The extra values given here take precedence over values defined on the client or passed to this method.
        extra_headers: Headers | None = None,
        extra_query: Query | None = None,
        extra_body: Body | None = None,
        timeout: float | httpx.Timeout | None | NotGiven = not_given,
    ) -> DBInsertRecordResponse:
        """Inserts a new record into the specified table.

        Organization ID is automatically
        added for multi-tenant security.

        Args:
          data: Data to insert

          table: Table name to insert into

          environment: Environment to insert into (development, staging, production)

          extra_headers: Send extra headers

          extra_query: Add additional query parameters to the request

          extra_body: Add additional JSON properties to the request

          timeout: Override the client-level default timeout for this request, in seconds
        """
        return self._post(
            "/db/insert",
            body=maybe_transform(
                {
                    "data": data,
                    "table": table,
                    "environment": environment,
                },
                db_insert_record_params.DBInsertRecordParams,
            ),
            options=make_request_options(
                extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout
            ),
            cast_to=DBInsertRecordResponse,
        )

    def process_nl_query(
        self,
        *,
        question: str,
        context: Dict[str, object] | Omit = omit,
        environment: Literal["development", "staging", "production"] | Omit = omit,
        # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs.
        # The extra values given here take precedence over values defined on the client or passed to this method.
        extra_headers: Headers | None = None,
        extra_query: Query | None = None,
        extra_body: Body | None = None,
        timeout: float | httpx.Timeout | None | NotGiven = not_given,
    ) -> DBProcessNlQueryResponse:
        """
        Converts a natural language question into a SQL query and executes it.
        Organization ID filtering is automatically applied for multi-tenant security.

        Args:
          question: Natural language question

          context: Optional context for the query

          environment: Environment to query (development, staging, production)

          extra_headers: Send extra headers

          extra_query: Add additional query parameters to the request

          extra_body: Add additional JSON properties to the request

          timeout: Override the client-level default timeout for this request, in seconds
        """
        return self._post(
            "/db/nl-query",
            body=maybe_transform(
                {
                    "question": question,
                    "context": context,
                    "environment": environment,
                },
                db_process_nl_query_params.DBProcessNlQueryParams,
            ),
            options=make_request_options(
                extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout
            ),
            cast_to=DBProcessNlQueryResponse,
        )

    def recommend(
        self,
        *,
        table: str,
        environment: Literal["development", "staging", "production"] | Omit = omit,
        exclude_ids: SequenceNotStr[str] | Omit = omit,
        limit: float | Omit = omit,
        record_id: Union[str, float] | Omit = omit,
        strategy: Literal["similar", "diverse", "popular"] | Omit = omit,
        user_history: SequenceNotStr[str] | Omit = omit,
        # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs.
        # The extra values given here take precedence over values defined on the client or passed to this method.
        extra_headers: Headers | None = None,
        extra_query: Query | None = None,
        extra_body: Body | None = None,
        timeout: float | httpx.Timeout | None | NotGiven = not_given,
    ) -> DBRecommendResponse:
        """
        Generates item recommendations using vector embeddings and collaborative
        filtering. Supports multiple recommendation strategies including similar items,
        diverse recommendations, and user history-based recommendations.

        Args:
          table: Table to generate recommendations from

          environment: Environment to search in (development, staging, production)

          exclude_ids: Record IDs to exclude from recommendations

          limit: Maximum number of recommendations to return

          record_id: Source item ID for item-to-item recommendations

          strategy: Recommendation strategy to use

          user_history: Array of record IDs the user has interacted with

          extra_headers: Send extra headers

          extra_query: Add additional query parameters to the request

          extra_body: Add additional JSON properties to the request

          timeout: Override the client-level default timeout for this request, in seconds
        """
        return self._post(
            "/db/recommend",
            body=maybe_transform(
                {
                    "table": table,
                    "environment": environment,
                    "exclude_ids": exclude_ids,
                    "limit": limit,
                    "record_id": record_id,
                    "strategy": strategy,
                    "user_history": user_history,
                },
                db_recommend_params.DBRecommendParams,
            ),
            options=make_request_options(
                extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout
            ),
            cast_to=DBRecommendResponse,
        )

    def semantic_search(
        self,
        *,
        query: str,
        environment: Literal["development", "staging", "production"] | Omit = omit,
        filters: Dict[str, object] | Omit = omit,
        limit: float | Omit = omit,
        table: str | Omit = omit,
        tables: SequenceNotStr[str] | Omit = omit,
        threshold: float | Omit = omit,
        # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs.
        # The extra values given here take precedence over values defined on the client or passed to this method.
        extra_headers: Headers | None = None,
        extra_query: Query | None = None,
        extra_body: Body | None = None,
        timeout: float | httpx.Timeout | None | NotGiven = not_given,
    ) -> DBSemanticSearchResponse:
        """
        Performs semantic search across database tables using vector embeddings.
        Supports both single table and cross-table searches with configurable similarity
        thresholds. Returns records with similarity scores and metadata about matched
        fields.

        Args:
          query: Natural language search query

          environment: Environment to search in (development, staging, production)

          filters: Additional WHERE conditions to apply

          limit: Maximum number of results to return

          table: Single table to search in (optional if tables is provided)

          tables: Multiple tables to search across (optional if table is provided)

          threshold: Minimum similarity score threshold

          extra_headers: Send extra headers

          extra_query: Add additional query parameters to the request

          extra_body: Add additional JSON properties to the request

          timeout: Override the client-level default timeout for this request, in seconds
        """
        return self._post(
            "/db/semantic-search",
            body=maybe_transform(
                {
                    "query": query,
                    "environment": environment,
                    "filters": filters,
                    "limit": limit,
                    "table": table,
                    "tables": tables,
                    "threshold": threshold,
                },
                db_semantic_search_params.DBSemanticSearchParams,
            ),
            options=make_request_options(
                extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout
            ),
            cast_to=DBSemanticSearchResponse,
        )

    def update_records(
        self,
        *,
        data: Dict[str, object],
        table: str,
        where: Dict[str, object],
        environment: Literal["development", "staging", "production"] | Omit = omit,
        # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs.
        # The extra values given here take precedence over values defined on the client or passed to this method.
        extra_headers: Headers | None = None,
        extra_query: Query | None = None,
        extra_body: Body | None = None,
        timeout: float | httpx.Timeout | None | NotGiven = not_given,
    ) -> DBUpdateRecordsResponse:
        """
        Updates records in the specified table that match the where conditions.
        Organization ID filtering is automatically applied for multi-tenant security.

        Args:
          data: Data to update

          table: Table name to update

          where: Where conditions

          environment: Environment to update in (development, staging, production)

          extra_headers: Send extra headers

          extra_query: Add additional query parameters to the request

          extra_body: Add additional JSON properties to the request

          timeout: Override the client-level default timeout for this request, in seconds
        """
        return self._put(
            "/db/update",
            body=maybe_transform(
                {
                    "data": data,
                    "table": table,
                    "where": where,
                    "environment": environment,
                },
                db_update_records_params.DBUpdateRecordsParams,
            ),
            options=make_request_options(
                extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout
            ),
            cast_to=DBUpdateRecordsResponse,
        )


class AsyncDBResource(AsyncAPIResource):
    @cached_property
    def tables(self) -> AsyncTablesResource:
        return AsyncTablesResource(self._client)

    @cached_property
    def with_raw_response(self) -> AsyncDBResourceWithRawResponse:
        """
        This property can be used as a prefix for any HTTP method call to return
        the raw response object instead of the parsed content.

        For more information, see https://www.github.com/WorqHat/worqhat-python-sdk#accessing-raw-response-data-eg-headers
        """
        return AsyncDBResourceWithRawResponse(self)

    @cached_property
    def with_streaming_response(self) -> AsyncDBResourceWithStreamingResponse:
        """
        An alternative to `.with_raw_response` that doesn't eagerly read the response body.

        For more information, see https://www.github.com/WorqHat/worqhat-python-sdk#with_streaming_response
        """
        return AsyncDBResourceWithStreamingResponse(self)

    async def cluster(
        self,
        *,
        table: str,
        environment: Literal["development", "staging", "production"] | Omit = omit,
        generate_labels: bool | Omit = omit,
        max_clusters: float | Omit = omit,
        min_clusters: float | Omit = omit,
        num_clusters: float | Omit = omit,
        # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs.
        # The extra values given here take precedence over values defined on the client or passed to this method.
        extra_headers: Headers | None = None,
        extra_query: Query | None = None,
        extra_body: Body | None = None,
        timeout: float | httpx.Timeout | None | NotGiven = not_given,
    ) -> DBClusterResponse:
        """
        Performs K-means clustering on vector embeddings to automatically group similar
        records. Supports auto-detection of optimal cluster count and AI-generated
        cluster labels. Returns cluster information including centroids, sample records,
        and quality metrics.

        Args:
          table: Table to cluster

          environment: Environment to cluster (development, staging, production)

          generate_labels: Whether to generate AI labels for clusters

          max_clusters: Maximum clusters for auto-detection

          min_clusters: Minimum clusters for auto-detection

          num_clusters: Number of clusters (auto-detected if not provided)

          extra_headers: Send extra headers

          extra_query: Add additional query parameters to the request

          extra_body: Add additional JSON properties to the request

          timeout: Override the client-level default timeout for this request, in seconds
        """
        return await self._post(
            "/db/cluster",
            body=await async_maybe_transform(
                {
                    "table": table,
                    "environment": environment,
                    "generate_labels": generate_labels,
                    "max_clusters": max_clusters,
                    "min_clusters": min_clusters,
                    "num_clusters": num_clusters,
                },
                db_cluster_params.DBClusterParams,
            ),
            options=make_request_options(
                extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout
            ),
            cast_to=DBClusterResponse,
        )

    async def delete_records(
        self,
        *,
        table: str,
        where: Dict[str, object],
        environment: Literal["development", "staging", "production"] | Omit = omit,
        # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs.
        # The extra values given here take precedence over values defined on the client or passed to this method.
        extra_headers: Headers | None = None,
        extra_query: Query | None = None,
        extra_body: Body | None = None,
        timeout: float | httpx.Timeout | None | NotGiven = not_given,
    ) -> DBDeleteRecordsResponse:
        """
        Deletes records from the specified table that match the where conditions.
        Organization ID filtering is automatically applied for multi-tenant security.

        Args:
          table: Table name to delete from

          where: Where conditions

          environment: Environment to delete from (development, staging, production)

          extra_headers: Send extra headers

          extra_query: Add additional query parameters to the request

          extra_body: Add additional JSON properties to the request

          timeout: Override the client-level default timeout for this request, in seconds
        """
        return await self._delete(
            "/db/delete",
            body=await async_maybe_transform(
                {
                    "table": table,
                    "where": where,
                    "environment": environment,
                },
                db_delete_records_params.DBDeleteRecordsParams,
            ),
            options=make_request_options(
                extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout
            ),
            cast_to=DBDeleteRecordsResponse,
        )

    async def detect_anomalies(
        self,
        *,
        table: str,
        environment: Literal["development", "staging", "production"] | Omit = omit,
        k: float | Omit = omit,
        limit: float | Omit = omit,
        threshold: float | Omit = omit,
        # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs.
        # The extra values given here take precedence over values defined on the client or passed to this method.
        extra_headers: Headers | None = None,
        extra_query: Query | None = None,
        extra_body: Body | None = None,
        timeout: float | httpx.Timeout | None | NotGiven = not_given,
    ) -> DBDetectAnomaliesResponse:
        """
        Identifies anomalous or outlier records using K-nearest neighbors analysis on
        vector embeddings. Useful for fraud detection, data quality checks, and
        identifying unusual patterns. Returns anomaly scores and nearest neighbors for
        each detected anomaly.

        Args:
          table: Table to analyze for anomalies

          environment: Environment to analyze (development, staging, production)

          k: Number of nearest neighbors to consider

          limit: Maximum number of anomalies to return

          threshold: Minimum anomaly score threshold

          extra_headers: Send extra headers

          extra_query: Add additional query parameters to the request

          extra_body: Add additional JSON properties to the request

          timeout: Override the client-level default timeout for this request, in seconds
        """
        return await self._post(
            "/db/detect-anomalies",
            body=await async_maybe_transform(
                {
                    "table": table,
                    "environment": environment,
                    "k": k,
                    "limit": limit,
                    "threshold": threshold,
                },
                db_detect_anomalies_params.DBDetectAnomaliesParams,
            ),
            options=make_request_options(
                extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout
            ),
            cast_to=DBDetectAnomaliesResponse,
        )

    async def execute_batch(
        self,
        *,
        operations: Iterable[db_execute_batch_params.Operation],
        environment: Literal["development", "staging", "production"] | Omit = omit,
        transactional: bool | Omit = omit,
        # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs.
        # The extra values given here take precedence over values defined on the client or passed to this method.
        extra_headers: Headers | None = None,
        extra_query: Query | None = None,
        extra_body: Body | None = None,
        timeout: float | httpx.Timeout | None | NotGiven = not_given,
    ) -> DBExecuteBatchResponse:
        """
        Executes multiple database operations (queries, inserts, updates, deletes) in a
        single transaction. If transactional is true, all operations will be rolled back
        if any operation fails.

        Args:
          operations: Array of database operations to execute

          environment: Environment to execute operations in

          transactional: Whether to execute all operations in a single transaction

          extra_headers: Send extra headers

          extra_query: Add additional query parameters to the request

          extra_body: Add additional JSON properties to the request

          timeout: Override the client-level default timeout for this request, in seconds
        """
        return await self._post(
            "/db/batch",
            body=await async_maybe_transform(
                {
                    "operations": operations,
                    "environment": environment,
                    "transactional": transactional,
                },
                db_execute_batch_params.DBExecuteBatchParams,
            ),
            options=make_request_options(
                extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout
            ),
            cast_to=DBExecuteBatchResponse,
        )

    async def execute_query(
        self,
        *,
        query: str,
        environment: Literal["development", "staging", "production"] | Omit = omit,
        params: Union[Dict[str, object], SequenceNotStr[Union[str, float, bool]]] | Omit = omit,
        # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs.
        # The extra values given here take precedence over values defined on the client or passed to this method.
        extra_headers: Headers | None = None,
        extra_query: Query | None = None,
        extra_body: Body | None = None,
        timeout: float | httpx.Timeout | None | NotGiven = not_given,
    ) -> DBExecuteQueryResponse:
        """Executes a raw SQL query directly against the database.

        Supports both named
        parameters ({param}) and positional parameters ($1, $2). Provides security
        guardrails to prevent destructive operations.

        Args:
          query: SQL query to execute. Supports both named parameters ({param}) and positional
              parameters ($1, $2)

          environment: Environment to query (development, staging, production)

          params: Named parameters for queries with {param} syntax

          extra_headers: Send extra headers

          extra_query: Add additional query parameters to the request

          extra_body: Add additional JSON properties to the request

          timeout: Override the client-level default timeout for this request, in seconds
        """
        return await self._post(
            "/db/query",
            body=await async_maybe_transform(
                {
                    "query": query,
                    "environment": environment,
                    "params": params,
                },
                db_execute_query_params.DBExecuteQueryParams,
            ),
            options=make_request_options(
                extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout
            ),
            cast_to=DBExecuteQueryResponse,
        )

    async def find_similar(
        self,
        *,
        record_id: Union[str, float],
        table: str,
        environment: Literal["development", "staging", "production"] | Omit = omit,
        exclude_self: bool | Omit = omit,
        limit: float | Omit = omit,
        target_table: str | Omit = omit,
        threshold: float | Omit = omit,
        # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs.
        # The extra values given here take precedence over values defined on the client or passed to this method.
        extra_headers: Headers | None = None,
        extra_query: Query | None = None,
        extra_body: Body | None = None,
        timeout: float | httpx.Timeout | None | NotGiven = not_given,
    ) -> DBFindSimilarResponse:
        """
        Finds records similar to a specific existing record using vector embeddings.
        Useful for "More like this" functionality and cross-table similarity search.
        Returns similarity scores and supports excluding the source record.

        Args:
          record_id: ID of the source record

          table: Table containing the source record

          environment: Environment to search in (development, staging, production)

          exclude_self: Whether to exclude the source record from results

          limit: Maximum number of similar records to return

          target_table: Different table to search in (optional)

          threshold: Minimum similarity score threshold

          extra_headers: Send extra headers

          extra_query: Add additional query parameters to the request

          extra_body: Add additional JSON properties to the request

          timeout: Override the client-level default timeout for this request, in seconds
        """
        return await self._post(
            "/db/find-similar",
            body=await async_maybe_transform(
                {
                    "record_id": record_id,
                    "table": table,
                    "environment": environment,
                    "exclude_self": exclude_self,
                    "limit": limit,
                    "target_table": target_table,
                    "threshold": threshold,
                },
                db_find_similar_params.DBFindSimilarParams,
            ),
            options=make_request_options(
                extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout
            ),
            cast_to=DBFindSimilarResponse,
        )

    async def hybrid_search(
        self,
        *,
        query: str,
        table: str,
        environment: Literal["development", "staging", "production"] | Omit = omit,
        keyword_weight: float | Omit = omit,
        limit: float | Omit = omit,
        semantic_weight: float | Omit = omit,
        text_columns: SequenceNotStr[str] | Omit = omit,
        # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs.
        # The extra values given here take precedence over values defined on the client or passed to this method.
        extra_headers: Headers | None = None,
        extra_query: Query | None = None,
        extra_body: Body | None = None,
        timeout: float | httpx.Timeout | None | NotGiven = not_given,
    ) -> DBHybridSearchResponse:
        """Combines semantic search using vector embeddings with traditional keyword
        search.

        Provides weighted scoring between semantic similarity and keyword
        matching. Ideal for queries that need both contextual understanding and exact
        term matching.

        Args:
          query: Search query combining natural language and keywords

          table: Table to search in

          environment: Environment to search in (development, staging, production)

          keyword_weight: Weight for keyword matching score

          limit: Maximum number of results to return

          semantic_weight: Weight for semantic similarity score

          text_columns: Columns to include in keyword search

          extra_headers: Send extra headers

          extra_query: Add additional query parameters to the request

          extra_body: Add additional JSON properties to the request

          timeout: Override the client-level default timeout for this request, in seconds
        """
        return await self._post(
            "/db/hybrid-search",
            body=await async_maybe_transform(
                {
                    "query": query,
                    "table": table,
                    "environment": environment,
                    "keyword_weight": keyword_weight,
                    "limit": limit,
                    "semantic_weight": semantic_weight,
                    "text_columns": text_columns,
                },
                db_hybrid_search_params.DBHybridSearchParams,
            ),
            options=make_request_options(
                extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout
            ),
            cast_to=DBHybridSearchResponse,
        )

    async def insert_record(
        self,
        *,
        data: Dict[str, object],
        table: str,
        environment: Literal["development", "staging", "production"] | Omit = omit,
        # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs.
        # The extra values given here take precedence over values defined on the client or passed to this method.
        extra_headers: Headers | None = None,
        extra_query: Query | None = None,
        extra_body: Body | None = None,
        timeout: float | httpx.Timeout | None | NotGiven = not_given,
    ) -> DBInsertRecordResponse:
        """Inserts a new record into the specified table.

        Organization ID is automatically
        added for multi-tenant security.

        Args:
          data: Data to insert

          table: Table name to insert into

          environment: Environment to insert into (development, staging, production)

          extra_headers: Send extra headers

          extra_query: Add additional query parameters to the request

          extra_body: Add additional JSON properties to the request

          timeout: Override the client-level default timeout for this request, in seconds
        """
        return await self._post(
            "/db/insert",
            body=await async_maybe_transform(
                {
                    "data": data,
                    "table": table,
                    "environment": environment,
                },
                db_insert_record_params.DBInsertRecordParams,
            ),
            options=make_request_options(
                extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout
            ),
            cast_to=DBInsertRecordResponse,
        )

    async def process_nl_query(
        self,
        *,
        question: str,
        context: Dict[str, object] | Omit = omit,
        environment: Literal["development", "staging", "production"] | Omit = omit,
        # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs.
        # The extra values given here take precedence over values defined on the client or passed to this method.
        extra_headers: Headers | None = None,
        extra_query: Query | None = None,
        extra_body: Body | None = None,
        timeout: float | httpx.Timeout | None | NotGiven = not_given,
    ) -> DBProcessNlQueryResponse:
        """
        Converts a natural language question into a SQL query and executes it.
        Organization ID filtering is automatically applied for multi-tenant security.

        Args:
          question: Natural language question

          context: Optional context for the query

          environment: Environment to query (development, staging, production)

          extra_headers: Send extra headers

          extra_query: Add additional query parameters to the request

          extra_body: Add additional JSON properties to the request

          timeout: Override the client-level default timeout for this request, in seconds
        """
        return await self._post(
            "/db/nl-query",
            body=await async_maybe_transform(
                {
                    "question": question,
                    "context": context,
                    "environment": environment,
                },
                db_process_nl_query_params.DBProcessNlQueryParams,
            ),
            options=make_request_options(
                extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout
            ),
            cast_to=DBProcessNlQueryResponse,
        )

    async def recommend(
        self,
        *,
        table: str,
        environment: Literal["development", "staging", "production"] | Omit = omit,
        exclude_ids: SequenceNotStr[str] | Omit = omit,
        limit: float | Omit = omit,
        record_id: Union[str, float] | Omit = omit,
        strategy: Literal["similar", "diverse", "popular"] | Omit = omit,
        user_history: SequenceNotStr[str] | Omit = omit,
        # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs.
        # The extra values given here take precedence over values defined on the client or passed to this method.
        extra_headers: Headers | None = None,
        extra_query: Query | None = None,
        extra_body: Body | None = None,
        timeout: float | httpx.Timeout | None | NotGiven = not_given,
    ) -> DBRecommendResponse:
        """
        Generates item recommendations using vector embeddings and collaborative
        filtering. Supports multiple recommendation strategies including similar items,
        diverse recommendations, and user history-based recommendations.

        Args:
          table: Table to generate recommendations from

          environment: Environment to search in (development, staging, production)

          exclude_ids: Record IDs to exclude from recommendations

          limit: Maximum number of recommendations to return

          record_id: Source item ID for item-to-item recommendations

          strategy: Recommendation strategy to use

          user_history: Array of record IDs the user has interacted with

          extra_headers: Send extra headers

          extra_query: Add additional query parameters to the request

          extra_body: Add additional JSON properties to the request

          timeout: Override the client-level default timeout for this request, in seconds
        """
        return await self._post(
            "/db/recommend",
            body=await async_maybe_transform(
                {
                    "table": table,
                    "environment": environment,
                    "exclude_ids": exclude_ids,
                    "limit": limit,
                    "record_id": record_id,
                    "strategy": strategy,
                    "user_history": user_history,
                },
                db_recommend_params.DBRecommendParams,
            ),
            options=make_request_options(
                extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout
            ),
            cast_to=DBRecommendResponse,
        )

    async def semantic_search(
        self,
        *,
        query: str,
        environment: Literal["development", "staging", "production"] | Omit = omit,
        filters: Dict[str, object] | Omit = omit,
        limit: float | Omit = omit,
        table: str | Omit = omit,
        tables: SequenceNotStr[str] | Omit = omit,
        threshold: float | Omit = omit,
        # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs.
        # The extra values given here take precedence over values defined on the client or passed to this method.
        extra_headers: Headers | None = None,
        extra_query: Query | None = None,
        extra_body: Body | None = None,
        timeout: float | httpx.Timeout | None | NotGiven = not_given,
    ) -> DBSemanticSearchResponse:
        """
        Performs semantic search across database tables using vector embeddings.
        Supports both single table and cross-table searches with configurable similarity
        thresholds. Returns records with similarity scores and metadata about matched
        fields.

        Args:
          query: Natural language search query

          environment: Environment to search in (development, staging, production)

          filters: Additional WHERE conditions to apply

          limit: Maximum number of results to return

          table: Single table to search in (optional if tables is provided)

          tables: Multiple tables to search across (optional if table is provided)

          threshold: Minimum similarity score threshold

          extra_headers: Send extra headers

          extra_query: Add additional query parameters to the request

          extra_body: Add additional JSON properties to the request

          timeout: Override the client-level default timeout for this request, in seconds
        """
        return await self._post(
            "/db/semantic-search",
            body=await async_maybe_transform(
                {
                    "query": query,
                    "environment": environment,
                    "filters": filters,
                    "limit": limit,
                    "table": table,
                    "tables": tables,
                    "threshold": threshold,
                },
                db_semantic_search_params.DBSemanticSearchParams,
            ),
            options=make_request_options(
                extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout
            ),
            cast_to=DBSemanticSearchResponse,
        )

    async def update_records(
        self,
        *,
        data: Dict[str, object],
        table: str,
        where: Dict[str, object],
        environment: Literal["development", "staging", "production"] | Omit = omit,
        # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs.
        # The extra values given here take precedence over values defined on the client or passed to this method.
        extra_headers: Headers | None = None,
        extra_query: Query | None = None,
        extra_body: Body | None = None,
        timeout: float | httpx.Timeout | None | NotGiven = not_given,
    ) -> DBUpdateRecordsResponse:
        """
        Updates records in the specified table that match the where conditions.
        Organization ID filtering is automatically applied for multi-tenant security.

        Args:
          data: Data to update

          table: Table name to update

          where: Where conditions

          environment: Environment to update in (development, staging, production)

          extra_headers: Send extra headers

          extra_query: Add additional query parameters to the request

          extra_body: Add additional JSON properties to the request

          timeout: Override the client-level default timeout for this request, in seconds
        """
        return await self._put(
            "/db/update",
            body=await async_maybe_transform(
                {
                    "data": data,
                    "table": table,
                    "where": where,
                    "environment": environment,
                },
                db_update_records_params.DBUpdateRecordsParams,
            ),
            options=make_request_options(
                extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout
            ),
            cast_to=DBUpdateRecordsResponse,
        )


class DBResourceWithRawResponse:
    def __init__(self, db: DBResource) -> None:
        self._db = db

        self.cluster = to_raw_response_wrapper(
            db.cluster,
        )
        self.delete_records = to_raw_response_wrapper(
            db.delete_records,
        )
        self.detect_anomalies = to_raw_response_wrapper(
            db.detect_anomalies,
        )
        self.execute_batch = to_raw_response_wrapper(
            db.execute_batch,
        )
        self.execute_query = to_raw_response_wrapper(
            db.execute_query,
        )
        self.find_similar = to_raw_response_wrapper(
            db.find_similar,
        )
        self.hybrid_search = to_raw_response_wrapper(
            db.hybrid_search,
        )
        self.insert_record = to_raw_response_wrapper(
            db.insert_record,
        )
        self.process_nl_query = to_raw_response_wrapper(
            db.process_nl_query,
        )
        self.recommend = to_raw_response_wrapper(
            db.recommend,
        )
        self.semantic_search = to_raw_response_wrapper(
            db.semantic_search,
        )
        self.update_records = to_raw_response_wrapper(
            db.update_records,
        )

    @cached_property
    def tables(self) -> TablesResourceWithRawResponse:
        return TablesResourceWithRawResponse(self._db.tables)


class AsyncDBResourceWithRawResponse:
    def __init__(self, db: AsyncDBResource) -> None:
        self._db = db

        self.cluster = async_to_raw_response_wrapper(
            db.cluster,
        )
        self.delete_records = async_to_raw_response_wrapper(
            db.delete_records,
        )
        self.detect_anomalies = async_to_raw_response_wrapper(
            db.detect_anomalies,
        )
        self.execute_batch = async_to_raw_response_wrapper(
            db.execute_batch,
        )
        self.execute_query = async_to_raw_response_wrapper(
            db.execute_query,
        )
        self.find_similar = async_to_raw_response_wrapper(
            db.find_similar,
        )
        self.hybrid_search = async_to_raw_response_wrapper(
            db.hybrid_search,
        )
        self.insert_record = async_to_raw_response_wrapper(
            db.insert_record,
        )
        self.process_nl_query = async_to_raw_response_wrapper(
            db.process_nl_query,
        )
        self.recommend = async_to_raw_response_wrapper(
            db.recommend,
        )
        self.semantic_search = async_to_raw_response_wrapper(
            db.semantic_search,
        )
        self.update_records = async_to_raw_response_wrapper(
            db.update_records,
        )

    @cached_property
    def tables(self) -> AsyncTablesResourceWithRawResponse:
        return AsyncTablesResourceWithRawResponse(self._db.tables)


class DBResourceWithStreamingResponse:
    def __init__(self, db: DBResource) -> None:
        self._db = db

        self.cluster = to_streamed_response_wrapper(
            db.cluster,
        )
        self.delete_records = to_streamed_response_wrapper(
            db.delete_records,
        )
        self.detect_anomalies = to_streamed_response_wrapper(
            db.detect_anomalies,
        )
        self.execute_batch = to_streamed_response_wrapper(
            db.execute_batch,
        )
        self.execute_query = to_streamed_response_wrapper(
            db.execute_query,
        )
        self.find_similar = to_streamed_response_wrapper(
            db.find_similar,
        )
        self.hybrid_search = to_streamed_response_wrapper(
            db.hybrid_search,
        )
        self.insert_record = to_streamed_response_wrapper(
            db.insert_record,
        )
        self.process_nl_query = to_streamed_response_wrapper(
            db.process_nl_query,
        )
        self.recommend = to_streamed_response_wrapper(
            db.recommend,
        )
        self.semantic_search = to_streamed_response_wrapper(
            db.semantic_search,
        )
        self.update_records = to_streamed_response_wrapper(
            db.update_records,
        )

    @cached_property
    def tables(self) -> TablesResourceWithStreamingResponse:
        return TablesResourceWithStreamingResponse(self._db.tables)


class AsyncDBResourceWithStreamingResponse:
    def __init__(self, db: AsyncDBResource) -> None:
        self._db = db

        self.cluster = async_to_streamed_response_wrapper(
            db.cluster,
        )
        self.delete_records = async_to_streamed_response_wrapper(
            db.delete_records,
        )
        self.detect_anomalies = async_to_streamed_response_wrapper(
            db.detect_anomalies,
        )
        self.execute_batch = async_to_streamed_response_wrapper(
            db.execute_batch,
        )
        self.execute_query = async_to_streamed_response_wrapper(
            db.execute_query,
        )
        self.find_similar = async_to_streamed_response_wrapper(
            db.find_similar,
        )
        self.hybrid_search = async_to_streamed_response_wrapper(
            db.hybrid_search,
        )
        self.insert_record = async_to_streamed_response_wrapper(
            db.insert_record,
        )
        self.process_nl_query = async_to_streamed_response_wrapper(
            db.process_nl_query,
        )
        self.recommend = async_to_streamed_response_wrapper(
            db.recommend,
        )
        self.semantic_search = async_to_streamed_response_wrapper(
            db.semantic_search,
        )
        self.update_records = async_to_streamed_response_wrapper(
            db.update_records,
        )

    @cached_property
    def tables(self) -> AsyncTablesResourceWithStreamingResponse:
        return AsyncTablesResourceWithStreamingResponse(self._db.tables)
