Skip to content

query

query

Dataset query operations.

query_dataset_private async

query_dataset_private(
    auth: DomoAuth,
    dataset_id: str,
    sql: str,
    loop_until_end: bool = False,
    limit: int = 100,
    skip: int = 0,
    maximum: int = 100,
    filter_pdp_policy_id_ls: list[int] | None = None,
    timeout: int = 10,
    debug_loop: bool = False,
    *,
    context: RouteContext | None = None,
    return_raw: bool = False,
    **context_kwargs,
) -> ResponseGetData

Run a SQL query against a dataset; the rows are on the response's .response.

Posts to /api/query/v1/execute/{dataset_id} and pages with limit and offset appended to sql. Any LIMIT or OFFSET already in sql is stripped, because maximum (total rows) and limit (rows per request) control paging. Set loop_until_end=True to drain every row.

Domo behavior (proven in tests/integration/api_semantics/dataset_query_indexing_semantics_tests.py):

  • Right after rows are committed, the endpoint answers 404 "Not Found" until indexing finishes. A caller that waits on indexing should catch DatasetNotFoundError and retry.
  • That 404 is declared with expected_statuses(404), so it logs at DEBUG and does not produce ERROR records. Other failures still log at ERROR.
  • Row counts lag commits: poll SELECT COUNT(*) FROM table until it equals the count you expect.

Parameters:

Name Type Description Default
auth DomoAuth

Authenticated Domo session.

required
dataset_id str

Dataset to query.

required
sql str

SQL against the table name table.

required
loop_until_end bool

Page through all rows.

False
limit int

Rows per request.

100
skip int

Row offset to start from.

0
maximum int

Total rows to return.

100
filter_pdp_policy_id_ls list[int] | None

PDP policy ids to apply to the query.

None
timeout int

Seconds per request.

10
debug_loop bool

Log each page at DEBUG.

False
context RouteContext | None

Prebuilt RouteContext.

None
return_raw bool

Return the ResponseGetData without parsing.

False

Returns:

Type Description
ResponseGetData

ResponseGetData; the rows (list[dict]) are on .response.

Raises:

Type Description
DatasetNotFoundError

404 "Not Found": the dataset is missing or not yet indexed.

QueryRequestError

any other failed query, or unexpected column format.

Endpoint

  • POST /query/v1/execute/{}

Called by

Source code in src/crew_dcs/routes/dataset/query.py
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
@expected_statuses(404)
@gd.route_function
@log_call(
    level_name="route",
    config=LogDecoratorConfig(
        entity_extractor=DomoEntityExtractor(),
        result_processor=DomoEntityResultProcessor(),
    ),
)
async def query_dataset_private(
    auth: DomoAuth,
    dataset_id: str,
    sql: str,
    loop_until_end: bool = False,  # retrieve all available rows
    limit: int = 100,  # maximum rows to return per request.  refers to PAGINATION
    skip: int = 0,
    maximum: int = 100,  # equivalent to the LIMIT or TOP clause in SQL, the number of rows to return total
    filter_pdp_policy_id_ls: list[int] | None = None,
    timeout: int = 10,
    debug_loop: bool = False,
    *,
    context: RouteContext | None = None,
    return_raw: bool = False,
    **context_kwargs,
) -> rgd.ResponseGetData:
    """Run a SQL query against a dataset; the rows are on the response's ``.response``.

    Posts to ``/api/query/v1/execute/{dataset_id}`` and pages with ``limit`` and
    ``offset`` appended to ``sql``. Any LIMIT or OFFSET already in ``sql`` is
    stripped, because ``maximum`` (total rows) and ``limit`` (rows per request)
    control paging. Set ``loop_until_end=True`` to drain every row.

    Domo behavior (proven in
    ``tests/integration/api_semantics/dataset_query_indexing_semantics_tests.py``):

    - Right after rows are committed, the endpoint answers 404 "Not Found" until
      indexing finishes. A caller that waits on indexing should catch
      ``DatasetNotFoundError`` and retry.
    - That 404 is declared with ``expected_statuses(404)``, so it logs at DEBUG
      and does not produce ERROR records. Other failures still log at ERROR.
    - Row counts lag commits: poll ``SELECT COUNT(*) FROM table`` until it equals
      the count you expect.

    Args:
        auth: Authenticated Domo session.
        dataset_id: Dataset to query.
        sql: SQL against the table name ``table``.
        loop_until_end: Page through all rows.
        limit: Rows per request.
        skip: Row offset to start from.
        maximum: Total rows to return.
        filter_pdp_policy_id_ls: PDP policy ids to apply to the query.
        timeout: Seconds per request.
        debug_loop: Log each page at DEBUG.
        context: Prebuilt ``RouteContext``.
        return_raw: Return the ``ResponseGetData`` without parsing.

    Returns:
        ``ResponseGetData``; the rows (``list[dict]``) are on ``.response``.

    Raises:
        DatasetNotFoundError: 404 "Not Found": the dataset is missing or not yet
            indexed.
        QueryRequestError: any other failed query, or unexpected column format.
    """
    url = f"https://{auth.domo_instance}.domo.com/api/query/v1/execute/{dataset_id}"

    offset_params = {
        "offset": "offset",
        "limit": "limit",
    }

    def body_fn(skip, limit, body: dict[str, object]):
        # Strip any existing LIMIT/OFFSET clauses from the SQL to avoid duplication
        cleaned_sql = re.sub(r"\s+limit\s+\d+", "", sql, flags=re.IGNORECASE)
        cleaned_sql = re.sub(r"\s+offset\s+\d+", "", cleaned_sql, flags=re.IGNORECASE)

        body.update({"sql": f"{cleaned_sql} limit {limit} offset {skip}"})

        if filter_pdp_policy_id_ls:
            body.update(  # type: ignore
                {
                    "context": {
                        "dataControlContext": {
                            "filterGroupIds": filter_pdp_policy_id_ls,
                            "previewPdp": True,
                        }
                    }
                }
            )

        return body

    def arr_fn(res: rgd.ResponseGetData) -> list[dict]:
        rows_ls = res.response.get("rows", [])
        columns_ls: list[str] = res.response.get("columns", [])

        if not isinstance(columns_ls, list) or any(
            not isinstance(c, str) for c in columns_ls
        ):
            raise QueryRequestError(
                dataset_id=dataset_id,
                sql=sql,
                res=res,
                message=f"Unexpected 'columns' format: {columns_ls!r}",
            )

        output: list[dict] = []
        for row in rows_ls or []:
            # defensive: limit mapping to min shared length
            width = min(len(columns_ls), len(row))
            row_dict = {columns_ls[i]: row[i] for i in range(width)}
            # Optionally: if len(row) != len(columns_ls) you can log or raise
            output.append(row_dict)

        return output

    res = await gd.looper(
        auth=auth,
        method="POST",
        url=url,
        body={"sql": sql},
        arr_fn=arr_fn,
        offset_params=offset_params,
        limit=limit,
        skip=skip,
        maximum=maximum,
        body_fn=body_fn,
        return_raw=return_raw,
        loop_until_end=loop_until_end,
        timeout=timeout,
        debug_loop=debug_loop,
        context=context,
    )

    if return_raw:
        return res

    if res.status == 404 and res.response == "Not Found":
        raise DatasetNotFoundError(
            dataset_id=dataset_id,
            res=res,
        )

    if res.status == 400 and res.response == "Bad Request":
        raise QueryRequestError(dataset_id=dataset_id, sql=sql, res=res)

    if not res.is_success:
        raise QueryRequestError(dataset_id=dataset_id, sql=sql, res=res)

    return res

query_dataset_public async

query_dataset_public(
    dev_auth: DomoDeveloperAuth,
    dataset_id: str,
    sql: str,
    *,
    context: RouteContext | None = None,
    **context_kwargs,
) -> ResponseGetData

query for hitting public apis, requires client_id and secret authentication

Endpoint

  • POST /v1/datasets/query/execute/{}
Source code in src/crew_dcs/routes/dataset/query.py
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
@gd.route_function
@log_call(
    level_name="route",
    config=LogDecoratorConfig(
        entity_extractor=DomoEntityExtractor(),
        result_processor=DomoEntityResultProcessor(),
    ),
)
async def query_dataset_public(
    dev_auth: dmda.DomoDeveloperAuth,
    dataset_id: str,
    sql: str,
    *,
    context: RouteContext | None = None,
    **context_kwargs,
) -> rgd.ResponseGetData:
    """query for hitting public apis, requires client_id and secret authentication"""

    url = f"https://api.domo.com/v1/datasets/query/execute/{dataset_id}?IncludeHeaders=true"

    body = {"sql": sql}

    res = await gd.get_data(
        auth=dev_auth,
        url=url,
        method="POST",
        body=body,
        context=context,
    )

    if not res.is_success:
        raise Dataset_CRUD_Error(dataset_id=dataset_id, res=res)

    return res

See also

Official Domo docs

Domo Knowledge Base categories

  • Manage Data (DataSets, DataSet Views, PDP, tags)