@querypanel/node-sdk 1.2.10 → 1.3.0-beta.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.cts CHANGED
@@ -220,11 +220,8 @@ declare class PostgresAdapter implements DatabaseAdapter {
220
220
  execute(sql: string, params?: Record<string, string | number | boolean | string[] | number[]>): Promise<DatabaseExecutionResult>;
221
221
  private validateQueryTables;
222
222
  /**
223
- * Convert params to positional array for PostgreSQL.
224
- * PostgreSQL expects $1, $2, $3 in SQL and an array of values [val1, val2, val3].
225
- * When the record has numeric keys ("1", "2", "3") — e.g. from mapGeneratedParams —
226
- * use only those in order so placeholder order matches SQL. Otherwise fall back to
227
- * named keys in alphabetical order for backward compatibility.
223
+ * Convert params to positional array for PostgreSQL ($1, $2, …).
224
+ * Values must align with v2 generation order via numeric keys from mapGeneratedParams.
228
225
  */
229
226
  private convertNamedToPositionalParams;
230
227
  validate(sql: string, params?: Record<string, string | number | boolean | string[] | number[]>): Promise<void>;
@@ -727,13 +724,14 @@ interface AskOptions {
727
724
  */
728
725
  querypanelSessionId?: string;
729
726
  /**
730
- * Pipeline version to use for query generation.
731
- * - "v1" (default): Original query pipeline
732
- * - "v2": Improved pipeline with intent planning, hybrid retrieval, schema linking, and SQL reflection
727
+ * Pipeline version for query generation.
728
+ * Defaults to `"v2"` (`POST /v2/query`).
729
+ * - `"v2"` (default): intent planning, hybrid retrieval, schema linking, SQL reflection
730
+ * - `"v1"` (**deprecated**): legacy `POST /query` pipeline — prefer omitting or `"v2"`
733
731
  */
734
732
  pipeline?: "v1" | "v2";
735
733
  /**
736
- * Optional OpenAI model id for v2 SQL generation. Omit to use server default.
734
+ * Optional model id for SQL generation (e.g. OpenAI or `gemini-*` when the API uses Gemini). Omit for server default.
737
735
  */
738
736
  model?: string;
739
737
  /**
@@ -745,7 +743,7 @@ interface AskOptions {
745
743
  * Use this for tenant-specific policies (e.g. retention windows) that must
746
744
  * be enforced on every query.
747
745
  *
748
- * Only sent when `pipeline: "v2"`.
746
+ * Sent when the resolved pipeline is `"v2"` (the default).
749
747
  */
750
748
  systemPrompt?: string;
751
749
  /**
@@ -822,6 +820,10 @@ interface AskResponse {
822
820
  /** Pipeline execution trace from v2 pipeline. */
823
821
  trace?: PipelineTrace;
824
822
  }
823
+ /**
824
+ * Resolve ask/modify pipeline. Defaults to v2; `"v1"` remains available but deprecated.
825
+ */
826
+ declare function resolveQueryPipeline(pipeline?: "v1" | "v2"): "v1" | "v2";
825
827
  declare function anonymizeResults(rows: Array<Record<string, unknown>>): Array<Record<string, string>>;
826
828
 
827
829
  /**
@@ -965,9 +967,10 @@ interface ChartModifyOptions {
965
967
  /** Chart generation method: 'vega-lite' or 'vizspec' */
966
968
  chartType?: "vega-lite" | "vizspec";
967
969
  /**
968
- * Pipeline version to use for SQL regeneration.
969
- * - "v1" (default): Original query pipeline
970
- * - "v2": Improved pipeline with intent planning, hybrid retrieval, schema linking, and SQL reflection
970
+ * Pipeline version for SQL regeneration.
971
+ * Defaults to `"v2"` (`POST /v2/query`).
972
+ * - `"v2"` (default): intent planning, hybrid retrieval, schema linking, SQL reflection
973
+ * - `"v1"` (**deprecated**): legacy `POST /query` pipeline — prefer omitting or `"v2"`
971
974
  */
972
975
  pipeline?: "v1" | "v2";
973
976
  /**
@@ -1138,6 +1141,16 @@ declare class CallbackApiClient implements IQueryPanelApi {
1138
1141
  delete<T = void>(path: string, tenantId: string, userId?: string, scopes?: string[], signal?: AbortSignal, sessionId?: string): Promise<T>;
1139
1142
  }
1140
1143
 
1144
+ /**
1145
+ * Maps v2-style param metadata (array order = $1, $2, $3 in SQL) to a ParamRecord.
1146
+ * Numeric keys preserve placeholder order for PostgreSQL; named keys support tenant lookups.
1147
+ */
1148
+ declare function mapGeneratedParams(params: Array<Record<string, unknown>>): ParamRecord;
1149
+ /**
1150
+ * Normalizes run-sql / dashboard request params into a ParamRecord.
1151
+ */
1152
+ declare function normalizeSqlParamsInput(params: unknown[] | Record<string, unknown> | null | undefined): ParamRecord;
1153
+
1141
1154
  /** Options when constructing the SDK with HTTP (default) or with a custom API implementation. */
1142
1155
  interface QueryPanelSdkAPIOptions {
1143
1156
  defaultTenantId?: string;
@@ -1950,4 +1963,4 @@ declare class QueryPanelSdkAPI {
1950
1963
  }, signal?: AbortSignal): Promise<SdkDashboard[]>;
1951
1964
  }
1952
1965
 
1953
- export { ALL_VIZ_CHART_TYPES, type ActiveChartBulkGetResponse, type ActiveChartCreateInput, type ActiveChartListOptions, type ActiveChartUpdateInput, type AggregateOp, type AskOptions, type AskResponse, type AxisField, type AxisFieldInput, BigQueryAdapter, type BigQueryAdapterOptions, type BigQueryClientFn, type BigQueryQueryRequest, type BigQueryQueryResult, CallbackApiClient, type ChartBulkGetResponse, type ChartCreateInput, type ChartEncoding, type ChartEnvelope, type ChartListAllOptions, type ChartListOptions, type ChartModifyInput, type ChartModifyOptions, type ChartModifyResponse, type ChartSpec, type ChartType, type ChartUpdateInput, ClickHouseAdapter, type ClickHouseAdapterOptions, type ClickHouseClientFn, type ContextDocument, type DashboardCreateInput, type DashboardForkInput, type DashboardForkUpdateInput, type DashboardListOptions, type DashboardUpdateInput, type DatabaseAdapter, type DatabaseDialect, type DateRangeInput, type EncodingHints, type FieldRef, type FieldRefInput, type FieldType, type IQueryPanelApi, type IngestResponse, type IntentResult, type MetricEncoding, type MetricField, type MetricSpec, type PaginatedResponse$1 as PaginatedResponse, type PaginationInfo$1 as PaginationInfo, type PaginationQuery$1 as PaginationQuery, type ParamRecord, type ParamValue, type PipelineTrace, PostgresAdapter, type PostgresAdapterOptions, type PostgresClientFn, QueryErrorCode, QueryErrorCode as QueryErrorCodeType, QueryPanelSdkAPI, type QueryPanelSdkAPIOptions, QueryPipelineError, type RequestHandler, type RequestHandlerOptions, type RequestHandlerResult, type SchemaIntrospection, type SchemaSyncOptions, type SdkActiveChart, type SdkChart, type SdkDashboard, type SdkSession, type SdkSessionTurn, type SessionGetOptions, type SessionListOptions, type SessionUpdateInput, type SqlModifications, type StackingMode, type TableColumn, type TableEncoding, type TableSpec, type TimeUnit, type ValueFormat, type VizModifications, type VizSpec, type VizSpecGenerateInput, type VizSpecGenerateOptions, type VizSpecGeneratorInput, type VizSpecKind, type VizSpecResponse, type VizSpecResult, anonymizeResults };
1966
+ export { ALL_VIZ_CHART_TYPES, type ActiveChartBulkGetResponse, type ActiveChartCreateInput, type ActiveChartListOptions, type ActiveChartUpdateInput, type AggregateOp, type AskOptions, type AskResponse, type AxisField, type AxisFieldInput, BigQueryAdapter, type BigQueryAdapterOptions, type BigQueryClientFn, type BigQueryQueryRequest, type BigQueryQueryResult, CallbackApiClient, type ChartBulkGetResponse, type ChartCreateInput, type ChartEncoding, type ChartEnvelope, type ChartListAllOptions, type ChartListOptions, type ChartModifyInput, type ChartModifyOptions, type ChartModifyResponse, type ChartSpec, type ChartType, type ChartUpdateInput, ClickHouseAdapter, type ClickHouseAdapterOptions, type ClickHouseClientFn, type ContextDocument, type DashboardCreateInput, type DashboardForkInput, type DashboardForkUpdateInput, type DashboardListOptions, type DashboardUpdateInput, type DatabaseAdapter, type DatabaseDialect, type DateRangeInput, type EncodingHints, type FieldRef, type FieldRefInput, type FieldType, type IQueryPanelApi, type IngestResponse, type IntentResult, type MetricEncoding, type MetricField, type MetricSpec, type PaginatedResponse$1 as PaginatedResponse, type PaginationInfo$1 as PaginationInfo, type PaginationQuery$1 as PaginationQuery, type ParamRecord, type ParamValue, type PipelineTrace, PostgresAdapter, type PostgresAdapterOptions, type PostgresClientFn, QueryErrorCode, QueryErrorCode as QueryErrorCodeType, QueryPanelSdkAPI, type QueryPanelSdkAPIOptions, QueryPipelineError, type RequestHandler, type RequestHandlerOptions, type RequestHandlerResult, type SchemaIntrospection, type SchemaSyncOptions, type SdkActiveChart, type SdkChart, type SdkDashboard, type SdkSession, type SdkSessionTurn, type SessionGetOptions, type SessionListOptions, type SessionUpdateInput, type SqlModifications, type StackingMode, type TableColumn, type TableEncoding, type TableSpec, type TimeUnit, type ValueFormat, type VizModifications, type VizSpec, type VizSpecGenerateInput, type VizSpecGenerateOptions, type VizSpecGeneratorInput, type VizSpecKind, type VizSpecResponse, type VizSpecResult, anonymizeResults, mapGeneratedParams, normalizeSqlParamsInput, resolveQueryPipeline };
package/dist/index.d.ts CHANGED
@@ -220,11 +220,8 @@ declare class PostgresAdapter implements DatabaseAdapter {
220
220
  execute(sql: string, params?: Record<string, string | number | boolean | string[] | number[]>): Promise<DatabaseExecutionResult>;
221
221
  private validateQueryTables;
222
222
  /**
223
- * Convert params to positional array for PostgreSQL.
224
- * PostgreSQL expects $1, $2, $3 in SQL and an array of values [val1, val2, val3].
225
- * When the record has numeric keys ("1", "2", "3") — e.g. from mapGeneratedParams —
226
- * use only those in order so placeholder order matches SQL. Otherwise fall back to
227
- * named keys in alphabetical order for backward compatibility.
223
+ * Convert params to positional array for PostgreSQL ($1, $2, …).
224
+ * Values must align with v2 generation order via numeric keys from mapGeneratedParams.
228
225
  */
229
226
  private convertNamedToPositionalParams;
230
227
  validate(sql: string, params?: Record<string, string | number | boolean | string[] | number[]>): Promise<void>;
@@ -727,13 +724,14 @@ interface AskOptions {
727
724
  */
728
725
  querypanelSessionId?: string;
729
726
  /**
730
- * Pipeline version to use for query generation.
731
- * - "v1" (default): Original query pipeline
732
- * - "v2": Improved pipeline with intent planning, hybrid retrieval, schema linking, and SQL reflection
727
+ * Pipeline version for query generation.
728
+ * Defaults to `"v2"` (`POST /v2/query`).
729
+ * - `"v2"` (default): intent planning, hybrid retrieval, schema linking, SQL reflection
730
+ * - `"v1"` (**deprecated**): legacy `POST /query` pipeline — prefer omitting or `"v2"`
733
731
  */
734
732
  pipeline?: "v1" | "v2";
735
733
  /**
736
- * Optional OpenAI model id for v2 SQL generation. Omit to use server default.
734
+ * Optional model id for SQL generation (e.g. OpenAI or `gemini-*` when the API uses Gemini). Omit for server default.
737
735
  */
738
736
  model?: string;
739
737
  /**
@@ -745,7 +743,7 @@ interface AskOptions {
745
743
  * Use this for tenant-specific policies (e.g. retention windows) that must
746
744
  * be enforced on every query.
747
745
  *
748
- * Only sent when `pipeline: "v2"`.
746
+ * Sent when the resolved pipeline is `"v2"` (the default).
749
747
  */
750
748
  systemPrompt?: string;
751
749
  /**
@@ -822,6 +820,10 @@ interface AskResponse {
822
820
  /** Pipeline execution trace from v2 pipeline. */
823
821
  trace?: PipelineTrace;
824
822
  }
823
+ /**
824
+ * Resolve ask/modify pipeline. Defaults to v2; `"v1"` remains available but deprecated.
825
+ */
826
+ declare function resolveQueryPipeline(pipeline?: "v1" | "v2"): "v1" | "v2";
825
827
  declare function anonymizeResults(rows: Array<Record<string, unknown>>): Array<Record<string, string>>;
826
828
 
827
829
  /**
@@ -965,9 +967,10 @@ interface ChartModifyOptions {
965
967
  /** Chart generation method: 'vega-lite' or 'vizspec' */
966
968
  chartType?: "vega-lite" | "vizspec";
967
969
  /**
968
- * Pipeline version to use for SQL regeneration.
969
- * - "v1" (default): Original query pipeline
970
- * - "v2": Improved pipeline with intent planning, hybrid retrieval, schema linking, and SQL reflection
970
+ * Pipeline version for SQL regeneration.
971
+ * Defaults to `"v2"` (`POST /v2/query`).
972
+ * - `"v2"` (default): intent planning, hybrid retrieval, schema linking, SQL reflection
973
+ * - `"v1"` (**deprecated**): legacy `POST /query` pipeline — prefer omitting or `"v2"`
971
974
  */
972
975
  pipeline?: "v1" | "v2";
973
976
  /**
@@ -1138,6 +1141,16 @@ declare class CallbackApiClient implements IQueryPanelApi {
1138
1141
  delete<T = void>(path: string, tenantId: string, userId?: string, scopes?: string[], signal?: AbortSignal, sessionId?: string): Promise<T>;
1139
1142
  }
1140
1143
 
1144
+ /**
1145
+ * Maps v2-style param metadata (array order = $1, $2, $3 in SQL) to a ParamRecord.
1146
+ * Numeric keys preserve placeholder order for PostgreSQL; named keys support tenant lookups.
1147
+ */
1148
+ declare function mapGeneratedParams(params: Array<Record<string, unknown>>): ParamRecord;
1149
+ /**
1150
+ * Normalizes run-sql / dashboard request params into a ParamRecord.
1151
+ */
1152
+ declare function normalizeSqlParamsInput(params: unknown[] | Record<string, unknown> | null | undefined): ParamRecord;
1153
+
1141
1154
  /** Options when constructing the SDK with HTTP (default) or with a custom API implementation. */
1142
1155
  interface QueryPanelSdkAPIOptions {
1143
1156
  defaultTenantId?: string;
@@ -1950,4 +1963,4 @@ declare class QueryPanelSdkAPI {
1950
1963
  }, signal?: AbortSignal): Promise<SdkDashboard[]>;
1951
1964
  }
1952
1965
 
1953
- export { ALL_VIZ_CHART_TYPES, type ActiveChartBulkGetResponse, type ActiveChartCreateInput, type ActiveChartListOptions, type ActiveChartUpdateInput, type AggregateOp, type AskOptions, type AskResponse, type AxisField, type AxisFieldInput, BigQueryAdapter, type BigQueryAdapterOptions, type BigQueryClientFn, type BigQueryQueryRequest, type BigQueryQueryResult, CallbackApiClient, type ChartBulkGetResponse, type ChartCreateInput, type ChartEncoding, type ChartEnvelope, type ChartListAllOptions, type ChartListOptions, type ChartModifyInput, type ChartModifyOptions, type ChartModifyResponse, type ChartSpec, type ChartType, type ChartUpdateInput, ClickHouseAdapter, type ClickHouseAdapterOptions, type ClickHouseClientFn, type ContextDocument, type DashboardCreateInput, type DashboardForkInput, type DashboardForkUpdateInput, type DashboardListOptions, type DashboardUpdateInput, type DatabaseAdapter, type DatabaseDialect, type DateRangeInput, type EncodingHints, type FieldRef, type FieldRefInput, type FieldType, type IQueryPanelApi, type IngestResponse, type IntentResult, type MetricEncoding, type MetricField, type MetricSpec, type PaginatedResponse$1 as PaginatedResponse, type PaginationInfo$1 as PaginationInfo, type PaginationQuery$1 as PaginationQuery, type ParamRecord, type ParamValue, type PipelineTrace, PostgresAdapter, type PostgresAdapterOptions, type PostgresClientFn, QueryErrorCode, QueryErrorCode as QueryErrorCodeType, QueryPanelSdkAPI, type QueryPanelSdkAPIOptions, QueryPipelineError, type RequestHandler, type RequestHandlerOptions, type RequestHandlerResult, type SchemaIntrospection, type SchemaSyncOptions, type SdkActiveChart, type SdkChart, type SdkDashboard, type SdkSession, type SdkSessionTurn, type SessionGetOptions, type SessionListOptions, type SessionUpdateInput, type SqlModifications, type StackingMode, type TableColumn, type TableEncoding, type TableSpec, type TimeUnit, type ValueFormat, type VizModifications, type VizSpec, type VizSpecGenerateInput, type VizSpecGenerateOptions, type VizSpecGeneratorInput, type VizSpecKind, type VizSpecResponse, type VizSpecResult, anonymizeResults };
1966
+ export { ALL_VIZ_CHART_TYPES, type ActiveChartBulkGetResponse, type ActiveChartCreateInput, type ActiveChartListOptions, type ActiveChartUpdateInput, type AggregateOp, type AskOptions, type AskResponse, type AxisField, type AxisFieldInput, BigQueryAdapter, type BigQueryAdapterOptions, type BigQueryClientFn, type BigQueryQueryRequest, type BigQueryQueryResult, CallbackApiClient, type ChartBulkGetResponse, type ChartCreateInput, type ChartEncoding, type ChartEnvelope, type ChartListAllOptions, type ChartListOptions, type ChartModifyInput, type ChartModifyOptions, type ChartModifyResponse, type ChartSpec, type ChartType, type ChartUpdateInput, ClickHouseAdapter, type ClickHouseAdapterOptions, type ClickHouseClientFn, type ContextDocument, type DashboardCreateInput, type DashboardForkInput, type DashboardForkUpdateInput, type DashboardListOptions, type DashboardUpdateInput, type DatabaseAdapter, type DatabaseDialect, type DateRangeInput, type EncodingHints, type FieldRef, type FieldRefInput, type FieldType, type IQueryPanelApi, type IngestResponse, type IntentResult, type MetricEncoding, type MetricField, type MetricSpec, type PaginatedResponse$1 as PaginatedResponse, type PaginationInfo$1 as PaginationInfo, type PaginationQuery$1 as PaginationQuery, type ParamRecord, type ParamValue, type PipelineTrace, PostgresAdapter, type PostgresAdapterOptions, type PostgresClientFn, QueryErrorCode, QueryErrorCode as QueryErrorCodeType, QueryPanelSdkAPI, type QueryPanelSdkAPIOptions, QueryPipelineError, type RequestHandler, type RequestHandlerOptions, type RequestHandlerResult, type SchemaIntrospection, type SchemaSyncOptions, type SdkActiveChart, type SdkChart, type SdkDashboard, type SdkSession, type SdkSessionTurn, type SessionGetOptions, type SessionListOptions, type SessionUpdateInput, type SqlModifications, type StackingMode, type TableColumn, type TableEncoding, type TableSpec, type TimeUnit, type ValueFormat, type VizModifications, type VizSpec, type VizSpecGenerateInput, type VizSpecGenerateOptions, type VizSpecGeneratorInput, type VizSpecKind, type VizSpecResponse, type VizSpecResult, anonymizeResults, mapGeneratedParams, normalizeSqlParamsInput, resolveQueryPipeline };
package/dist/index.js CHANGED
@@ -453,6 +453,37 @@ function toNumber(value) {
453
453
  }
454
454
 
455
455
  // src/adapters/postgres.ts
456
+ function maxPostgresPlaceholderIndex(sql) {
457
+ let max = 0;
458
+ for (const match of sql.matchAll(/\$(\d+)\b/g)) {
459
+ const index = Number.parseInt(match[1], 10);
460
+ if (Number.isFinite(index) && index > max) {
461
+ max = index;
462
+ }
463
+ }
464
+ return max;
465
+ }
466
+ function filterParamsForPostgresSql(sql, params) {
467
+ if (!params || Object.keys(params).length === 0) {
468
+ return void 0;
469
+ }
470
+ const placeholderCount = maxPostgresPlaceholderIndex(sql);
471
+ if (placeholderCount === 0) {
472
+ return void 0;
473
+ }
474
+ const hasNumericKeys = Object.keys(params).some((key) => /^\d+$/.test(key));
475
+ if (hasNumericKeys) {
476
+ const filtered = {};
477
+ for (let index = 1; index <= placeholderCount; index += 1) {
478
+ const key = String(index);
479
+ if (key in params) {
480
+ filtered[key] = params[key];
481
+ }
482
+ }
483
+ return Object.keys(filtered).length > 0 ? filtered : void 0;
484
+ }
485
+ return params;
486
+ }
456
487
  var PostgresAdapter = class {
457
488
  constructor(clientFn, options = {}) {
458
489
  this.clientFn = clientFn;
@@ -470,9 +501,10 @@ var PostgresAdapter = class {
470
501
  if (this.allowedTables) {
471
502
  this.validateQueryTables(sql);
472
503
  }
504
+ const boundParams = filterParamsForPostgresSql(sql, params);
473
505
  let paramArray;
474
- if (params) {
475
- paramArray = this.convertNamedToPositionalParams(params);
506
+ if (boundParams) {
507
+ paramArray = this.convertNamedToPositionalParams(sql, boundParams);
476
508
  }
477
509
  const result = await this.clientFn(sql, paramArray);
478
510
  const fields = result.fields.map((f) => f.name);
@@ -502,36 +534,43 @@ var PostgresAdapter = class {
502
534
  }
503
535
  }
504
536
  /**
505
- * Convert params to positional array for PostgreSQL.
506
- * PostgreSQL expects $1, $2, $3 in SQL and an array of values [val1, val2, val3].
507
- * When the record has numeric keys ("1", "2", "3") — e.g. from mapGeneratedParams —
508
- * use only those in order so placeholder order matches SQL. Otherwise fall back to
509
- * named keys in alphabetical order for backward compatibility.
537
+ * Convert params to positional array for PostgreSQL ($1, $2, …).
538
+ * Values must align with v2 generation order via numeric keys from mapGeneratedParams.
510
539
  */
511
- convertNamedToPositionalParams(params) {
512
- const numericKeys = Object.keys(params).filter((k) => /^\d+$/.test(k)).map((k) => Number.parseInt(k, 10)).sort((a, b) => a - b);
513
- if (numericKeys.length > 0) {
514
- const positionalParams = [];
515
- for (const key of numericKeys) {
516
- let val = params[String(key)];
517
- if (typeof val === "string") {
518
- const match = val.match(/^<([a-zA-Z0-9_]+)>$/);
519
- const namedKey = match?.[1];
520
- if (namedKey && namedKey in params) {
521
- val = params[namedKey];
522
- }
540
+ convertNamedToPositionalParams(sql, params) {
541
+ const placeholderCount = maxPostgresPlaceholderIndex(sql);
542
+ if (placeholderCount === 0) {
543
+ return [];
544
+ }
545
+ const positionalParams = [];
546
+ for (let index = 1; index <= placeholderCount; index += 1) {
547
+ const key = String(index);
548
+ let val = params[key];
549
+ if (val === void 0 && placeholderCount === 1) {
550
+ const namedKeys = Object.keys(params).filter((k) => !/^\d+$/.test(k));
551
+ if (namedKeys.length === 1) {
552
+ val = params[namedKeys[0]];
553
+ }
554
+ }
555
+ if (val === void 0) {
556
+ throw new Error(`Missing value for PostgreSQL parameter $${index}`);
557
+ }
558
+ if (typeof val === "string") {
559
+ const match = val.match(/^<([a-zA-Z0-9_]+)>$/);
560
+ const namedKey = match?.[1];
561
+ if (namedKey && namedKey in params) {
562
+ val = params[namedKey];
523
563
  }
524
- positionalParams.push(val);
525
564
  }
526
- return positionalParams;
565
+ positionalParams.push(val);
527
566
  }
528
- const namedKeys = Object.keys(params).filter((k) => !/^\d+$/.test(k)).sort();
529
- return namedKeys.map((key) => params[key]);
567
+ return positionalParams;
530
568
  }
531
569
  async validate(sql, params) {
570
+ const boundParams = filterParamsForPostgresSql(sql, params);
532
571
  let paramArray;
533
- if (params) {
534
- paramArray = this.convertNamedToPositionalParams(params);
572
+ if (boundParams) {
573
+ paramArray = this.convertNamedToPositionalParams(sql, boundParams);
535
574
  }
536
575
  await this.clientFn(`EXPLAIN ${sql}`, paramArray);
537
576
  }
@@ -1174,6 +1213,45 @@ var CallbackApiClient = class {
1174
1213
  }
1175
1214
  };
1176
1215
 
1216
+ // src/core/map-generated-params.ts
1217
+ function mapGeneratedParams(params) {
1218
+ const record = {};
1219
+ params.forEach((param, index) => {
1220
+ const value = param.value;
1221
+ if (value === void 0) {
1222
+ return;
1223
+ }
1224
+ record[String(index + 1)] = value;
1225
+ const nameCandidate = typeof param.name === "string" && param.name.trim() || typeof param.placeholder === "string" && param.placeholder.trim() || typeof param.position === "number" && String(param.position) || String(index + 1);
1226
+ const key = nameCandidate.replace(/[{}:$]/g, "").trim();
1227
+ record[key] = value;
1228
+ });
1229
+ return record;
1230
+ }
1231
+ function normalizeSqlParamsInput(params) {
1232
+ if (params == null) {
1233
+ return {};
1234
+ }
1235
+ if (Array.isArray(params)) {
1236
+ if (params.length === 0) {
1237
+ return {};
1238
+ }
1239
+ const first = params[0];
1240
+ if (first && typeof first === "object" && "value" in first) {
1241
+ return mapGeneratedParams(params);
1242
+ }
1243
+ const positional = {};
1244
+ params.forEach((value, index) => {
1245
+ positional[String(index + 1)] = value;
1246
+ });
1247
+ return positional;
1248
+ }
1249
+ if (typeof params === "object") {
1250
+ return params;
1251
+ }
1252
+ return {};
1253
+ }
1254
+
1177
1255
  // src/core/query-engine.ts
1178
1256
  var QueryEngine = class {
1179
1257
  constructor() {
@@ -1244,18 +1322,7 @@ var QueryEngine = class {
1244
1322
  * - Named keys remain for tenant isolation / other lookups.
1245
1323
  */
1246
1324
  mapGeneratedParams(params) {
1247
- const record = {};
1248
- params.forEach((param, index) => {
1249
- const value = param.value;
1250
- if (value === void 0) {
1251
- return;
1252
- }
1253
- record[String(index + 1)] = value;
1254
- const nameCandidate = typeof param.name === "string" && param.name.trim() || typeof param.placeholder === "string" && param.placeholder.trim() || typeof param.position === "number" && String(param.position) || String(index + 1);
1255
- const key = nameCandidate.replace(/[{}:$]/g, "").trim();
1256
- record[key] = value;
1257
- });
1258
- return record;
1325
+ return mapGeneratedParams(params);
1259
1326
  }
1260
1327
  ensureTenantIsolation(sql, params, metadata, tenantId) {
1261
1328
  if (!metadata.tenantFieldName || metadata.enforceTenantIsolation === false) {
@@ -1275,8 +1342,10 @@ var QueryEngine = class {
1275
1342
  params[tenantField] = tenantId;
1276
1343
  tenantPredicate = `${tenantField} = @${tenantField}`;
1277
1344
  } else {
1278
- const escapedId = tenantId.replace(/'/g, "''");
1279
- tenantPredicate = `${tenantField} = '${escapedId}'`;
1345
+ const paramIndex = this.nextPostgresPlaceholderIndex(sql, params);
1346
+ params[String(paramIndex)] = tenantId;
1347
+ params[tenantField] = tenantId;
1348
+ tenantPredicate = `${tenantField} = $${paramIndex}`;
1280
1349
  }
1281
1350
  if (/\bwhere\b/i.test(sql)) {
1282
1351
  return sql.replace(
@@ -1286,6 +1355,23 @@ var QueryEngine = class {
1286
1355
  }
1287
1356
  return `${sql} WHERE ${tenantPredicate}`;
1288
1357
  }
1358
+ nextPostgresPlaceholderIndex(sql, params) {
1359
+ let max = 0;
1360
+ for (const match of sql.matchAll(/\$(\d+)\b/g)) {
1361
+ const index = Number.parseInt(match[1], 10);
1362
+ if (Number.isFinite(index) && index > max) {
1363
+ max = index;
1364
+ }
1365
+ }
1366
+ if (max > 0) {
1367
+ return max + 1;
1368
+ }
1369
+ const numericKeys = Object.keys(params).filter((key) => /^\d+$/.test(key)).map((key) => Number.parseInt(key, 10)).filter((index) => Number.isFinite(index));
1370
+ if (numericKeys.length > 0) {
1371
+ return Math.max(...numericKeys) + 1;
1372
+ }
1373
+ return 1;
1374
+ }
1289
1375
  };
1290
1376
 
1291
1377
  // src/routes/charts.ts
@@ -1820,6 +1906,7 @@ function resolveTenantId4(client, tenantId) {
1820
1906
  function buildSchemaRequest(databaseName, adapter, introspection, metadata) {
1821
1907
  const dialect = adapter.getDialect();
1822
1908
  const tables = introspection.tables.map((table) => ({
1909
+ schema_name: table.schema,
1823
1910
  table_name: table.name,
1824
1911
  description: table.comment ?? `Table ${table.name}`,
1825
1912
  columns: table.columns.map((column) => ({
@@ -1849,6 +1936,9 @@ import crypto4 from "crypto";
1849
1936
 
1850
1937
  // src/routes/query.ts
1851
1938
  import crypto3 from "crypto";
1939
+ function resolveQueryPipeline(pipeline) {
1940
+ return pipeline ?? "v2";
1941
+ }
1852
1942
  async function ask(client, queryEngine, question, options, signal) {
1853
1943
  const tenantId = resolveTenantId5(client, options.tenantId);
1854
1944
  const sessionId = crypto3.randomUUID();
@@ -1857,7 +1947,8 @@ async function ask(client, queryEngine, question, options, signal) {
1857
1947
  let attempt = 0;
1858
1948
  let lastError = options.lastError;
1859
1949
  let previousSql = options.previousSql;
1860
- const queryEndpoint = options.pipeline === "v2" ? "/v2/query" : "/query";
1950
+ const pipeline = resolveQueryPipeline(options.pipeline);
1951
+ const queryEndpoint = pipeline === "v2" ? "/v2/query" : "/query";
1861
1952
  while (attempt <= maxRetry) {
1862
1953
  const databaseName = options.database ?? queryEngine.getDefaultDatabase();
1863
1954
  const metadata = databaseName ? queryEngine.getDatabaseMetadata(databaseName) : void 0;
@@ -1881,7 +1972,7 @@ async function ask(client, queryEngine, question, options, signal) {
1881
1972
  ...databaseName ? { database: databaseName } : {},
1882
1973
  ...metadata?.dialect ? { dialect: metadata.dialect } : {},
1883
1974
  ...options.model?.trim() ? { model: options.model.trim() } : {},
1884
- ...options.pipeline === "v2" && options.systemPrompt?.trim() ? { system_prompt: options.systemPrompt.trim() } : {},
1975
+ ...pipeline === "v2" && options.systemPrompt?.trim() ? { system_prompt: options.systemPrompt.trim() } : {},
1885
1976
  debug: options.debug ?? false
1886
1977
  },
1887
1978
  tenantId,
@@ -2196,7 +2287,8 @@ async function modifyChart(client, queryEngine, input, options, signal) {
2196
2287
  const hasSqlMods = !!input.sqlModifications;
2197
2288
  const hasVizMods = !!input.vizModifications;
2198
2289
  const hasCustomSql = !!input.sqlModifications?.customSql;
2199
- const queryEndpoint = options?.pipeline === "v2" ? "/v2/query" : "/query";
2290
+ const pipeline = resolveQueryPipeline(options?.pipeline);
2291
+ const queryEndpoint = pipeline === "v2" ? "/v2/query" : "/query";
2200
2292
  let finalSql = input.sql;
2201
2293
  let finalParams = input.params ?? {};
2202
2294
  let paramMetadata = [];
@@ -2228,10 +2320,10 @@ async function modifyChart(client, queryEngine, input, options, signal) {
2228
2320
  const modifiedQuestion = buildModifiedQuestion(
2229
2321
  input.question,
2230
2322
  input.sqlModifications,
2231
- options?.pipeline,
2323
+ pipeline,
2232
2324
  hasQuerypanelSessionContext
2233
2325
  );
2234
- if (options?.pipeline === "v2") {
2326
+ if (pipeline === "v2") {
2235
2327
  finalQuestion = modifiedQuestion;
2236
2328
  }
2237
2329
  const queryResponse = await client.post(
@@ -2255,7 +2347,7 @@ async function modifyChart(client, queryEngine, input, options, signal) {
2255
2347
  finalSql = queryResponse.sql;
2256
2348
  paramMetadata = Array.isArray(queryResponse.params) ? queryResponse.params : [];
2257
2349
  finalParams = queryEngine.mapGeneratedParams(paramMetadata);
2258
- if (options?.pipeline === "v2") {
2350
+ if (pipeline === "v2") {
2259
2351
  applyDateRangeOverrides(
2260
2352
  input.sqlModifications?.dateRange,
2261
2353
  finalParams,
@@ -3495,6 +3587,9 @@ export {
3495
3587
  QueryErrorCode,
3496
3588
  QueryPanelSdkAPI,
3497
3589
  QueryPipelineError,
3498
- anonymizeResults
3590
+ anonymizeResults,
3591
+ mapGeneratedParams,
3592
+ normalizeSqlParamsInput,
3593
+ resolveQueryPipeline
3499
3594
  };
3500
3595
  //# sourceMappingURL=index.js.map