{"record":{"id":"16a18fed4f289bb6","repo":"cube-js/cube","slug":"invalid-query-format-error-message-error-tos","errorCode":null,"errorMessage":"Invalid query format: ${error.message || error.toString()}","messagePattern":"Invalid query format: (.+?)","errorType":"validation","errorClass":"UserError","httpStatus":null,"severity":"error","filePath":"packages/cubejs-api-gateway/src/gateway.ts","lineNumber":557,"sourceCode":"    );\n\n    app.post(\n      `${this.basePath}/v1/cubesql`,\n      userMiddlewares,\n      userAsyncHandler(async (req, res) => {\n        const { query } = req.body;\n\n        const requestStarted = new Date();\n\n        res.setHeader('Content-Type', 'application/json');\n        res.setHeader('Transfer-Encoding', 'chunked');\n\n        try {\n          await this.assertApiScope('data', req.context?.securityContext);\n\n          const { error, value: body } = cubeSqlRequestSchema.validate(req.body);\n          if (error) {\n            throw new UserError(`Invalid query format: ${error.message || error.toString()}`);\n          }\n\n          await this.sqlServer.execSql(body.query, res, req.context?.securityContext, body.cache, body.timezone, body.throwContinueWait, req.context?.requestId);\n        } catch (e: any) {\n          // Quickfix for https://github.com/cube-js/cube/issues/10450,\n          // Right now, it's too complicated to fix the issue correctly, because\n          // native side control stream, without understanding that it's Express.response\n          res.removeHeader('Transfer-Encoding');\n\n          this.handleError({\n            e,\n            query: {\n              sql: query,\n            },\n            context: req.context,\n            res: this.resToResultFn(res),\n            requestStarted\n          });","sourceCodeStart":539,"sourceCodeEnd":575,"githubUrl":"https://github.com/cube-js/cube/blob/7d981676b36392fec34088b9afab6bdcad40207c/packages/cubejs-api-gateway/src/gateway.ts#L539-L575","documentation":"The /cubejs-system/v1/sql endpoint validates req.body against cubeSqlRequestSchema (which requires a valid 'query' SQL string among other fields). When Joi validation fails, ApiGateway wraps the Joi error message in this UserError. It means the HTTP request body does not conform to the expected SQL-API request shape.","triggerScenarios":"POSTing to the SQL API endpoint with a body missing the 'query' field, a non-string query value, or extra/invalid fields rejected by the schema, e.g. { q: 'SELECT 1' } or { query: 42 } instead of { query: 'SELECT 1' }.","commonSituations":"Client code built for the REST /load API being pointed at the SQL endpoint with the wrong payload shape; typos in the body key ('sql' vs 'query'); sending GraphQL-style payloads; SDK version mismatch where the request schema changed.","solutions":["Send a body matching the schema: { query: '<SQL string>' } (plus optional cache, timezone, throwContinueWait)","Read error.message in the response — it echoes the exact Joi validation failure (e.g. '\"query\" is required') and fix that field","If using an SDK or ORM integration, verify it targets the SQL API and is up to date","Log the outgoing req.body and diff it against cubeSqlRequestSchema in packages/cubejs-api-gateway/src"],"exampleFix":"// before\nawait fetch(`${apiUrl}/cubejs-system/v1/sql`, { method: 'POST', body: JSON.stringify({ sql: 'SELECT 1' }) });\n// after\nawait fetch(`${apiUrl}/cubejs-system/v1/sql`, { method: 'POST', body: JSON.stringify({ query: 'SELECT 1' }) });","handlingStrategy":"validation","validationCode":"function assertSqlApiBody(body) {\n  if (!body || typeof body !== 'object') throw new Error('Body must be an object');\n  if (typeof body.query !== 'string' || !body.query.trim()) throw new Error('\"query\" (string) is required for the SQL API');\n}","typeGuard":"const isSqlApiRequest = (b) => typeof b === 'object' && b !== null && typeof (b).query === 'string' && (b).query.length > 0;","tryCatchPattern":"try {\n  const res = await fetch(`${apiUrl}/cubejs-system/v1/sql`, { method: 'POST', headers: jsonHeaders, body: JSON.stringify({ query }) });\n  const data = await res.json();\n  if (data.error && data.error.startsWith('Invalid query format:')) throw new Error(`Fix request body: ${data.error}`);\n  return data;\n} catch (e) {\n  console.error('SQL API request rejected:', e.message);\n  throw e;\n}","preventionTips":["Use the official Cube client/SDK instead of hand-rolled fetch calls to this endpoint","Always send { query: '<sql>' } — the key is 'query', not 'sql' or 'q'","Set Content-Type: application/json","Read the echoed Joi message in the error to identify the offending field"],"tags":["request-validation","rest-api","schema-validation","http-400"],"backgroundTag":"request-body-validation-failed","analyzedSha":"7d981676b36392fec34088b9afab6bdcad40207c","analyzedAt":"2026-09-02T03:45:10.400Z","contentChangedAt":null,"schemaVersion":2},"datasetVersion":"2026-09-08T15:18:49.778Z"}