You are viewing a plain text version of this content. The canonical link for it is here.
Posted to notifications@skywalking.apache.org by "mrproliu (via GitHub)" <gi...@apache.org> on 2026/07/07 08:25:27 UTC
[PR] Introduce parameter binding (`?` placeholders) into BydbQL [skywalking-banyandb]
mrproliu opened a new pull request, #1209:
URL: https://github.com/apache/skywalking-banyandb/pull/1209
### Introduce positional parameter binding into BydbQL
This PR introduces positional parameter binding (`?` placeholders) into BydbQL so that untrusted values never need to be concatenated into the query string, eliminating QL injection by construction. `bydbql.v1.QueryRequest` gains a `params` field (`repeated model.v1.TagValue`, reusing the existing common value type instead of introducing a new message) whose entries are bound to the `?` placeholders by their order of appearance.
**How it works.** Binding is implemented as a standalone AST pass (`pkg/bydbql/binder.go`) that runs between the parser and the transformer: the lexer gains a `?` token, value nodes in the grammar gain a placeholder branch, and `BindParams` fills the placeholders from the request parameters so that a bound AST is indistinguishable from one parsed with literal values — the 1700-line transformer needs zero placeholder awareness. Since a bound parameter is always a value and can never alter the query structure, injection is impossible by design. As defense in depth, `Transform` rejects any grammar that still contains unbound placeholders, and a reflection-based tripwire test guards that every `@Param` position in the grammar is wired into the binder.
**Supported positions.** Placeholders are accepted in value positions only: TIME values (`str` relative/RFC3339/`now`, or a typed `timestamp` which is validated at bind time), scalar comparisons (`str`/`int`/`null` for all six operators), IN/NOT IN/MATCH/HAVING value lists (`str`/`int`/`null` plus `str_array`/`int_array` which expand in place while the container keeps its literal single-vs-list form), and LIMIT/OFFSET/TOP N counts (`int` only, range-checked to `[0, MaxInt32]`), matching mainstream SQL prepared-statement conventions. Identifier and structural positions (resource/group/stage names, columns, ORDER BY/GROUP BY, MATCH analyzer) remain syntax errors — unlike some SQL implementations where `ORDER BY ?` silently degrades to a no-op, BydbQL rejects it outright. Binding errors (count mismatch, type mismatch, out-of-range) are reported as `InvalidArgument` with the 1-based position of the offending parameter.
**Consumers.** The embedded web UI's BydbQL console gains a parameter input panel (typed rows sent as protojson TagValues), and the error path now surfaces the server's detailed message instead of the bare HTTP status text. The MCP server's `list_resources_bydbql` tool accepts a typed `params` array so LLM-generated queries can pass untrusted values out of band, with the prompt guidance updated accordingly.
<img width="2916" height="1314" alt="BydbQL console with parameter binding: a ? placeholder in the query bound from the typed parameter row below the editor" src="https://github.com/user-attachments/assets/6f5efd89-dbba-4e35-a014-2efd65a70511" />
**Testing.** `pkg/bydbql` grows to 544 specs: a full acceptance matrix (every parameter type x every placeholder path), an equivalence suite asserting that a parameterized query and its literal-valued twin produce byte-identical native query requests through the real transformer (with an `expectError` marker so error cases cannot pass vacuously), parse-time rejection tests for every forbidden position, and injection-payload tests. All six integration test suites (stream/measure/trace/property/topn/tracepipeline) share a new `helpers.ExtractQL` that reads an optional `#!params:` directive from `.ql` files, and each gets an end-to-end `params_bind` case covering a different parameter shape, including `SHOW TOP ?` and `LIMIT ?`. Documentation (`docs/interacting/bydbql.md` §2.6) documents the complete supported/unsupported position tables and type rules.
- [x] If this pull request closes/resolves/fixes an existing issue, replace the issue number. Fixes apache/skywalking#13628.
- [x] Update the [`CHANGES` log](https://github.com/apache/skywalking-banyandb/blob/main/CHANGES.md).
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@skywalking.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Introduce parameter binding (`?` placeholders) into BydbQL [skywalking-banyandb]
Posted by "hanahmily (via GitHub)" <gi...@apache.org>.
hanahmily commented on code in PR #1209:
URL: https://github.com/apache/skywalking-banyandb/pull/1209#discussion_r3541263665
##########
pkg/bydbql/binder.go:
##########
@@ -0,0 +1,310 @@
+// Licensed to Apache Software Foundation (ASF) under one or more contributor
+// license agreements. See the NOTICE file distributed with
+// this work for additional information regarding copyright
+// ownership. Apache Software Foundation (ASF) licenses this file to you under
+// the Apache License, Version 2.0 (the "License"); you may
+// not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+package bydbql
+
+import (
+ "fmt"
+ "math"
+ "time"
+
+ modelv1 "github.com/apache/skywalking-banyandb/api/proto/banyandb/model/v1"
+)
+
+// BindParams binds positional parameters to the `?` placeholders in the parsed grammar,
+// in their order of appearance in the query text. After a successful call, the grammar is
+// indistinguishable from one parsed with literal values, so the transformer needs no
+// placeholder awareness. Callers must invoke it before Transform even when params is empty,
+// so a query holding unbound placeholders is rejected instead of silently misinterpreted.
+// Parameter positions in error messages are 1-based. On error the grammar may be partially
+// bound and must be discarded; binding is not retryable on the same grammar.
+func BindParams(g *Grammar, params []*modelv1.TagValue) error {
Review Comment:
**HIGH — `BindParams` mutates the parsed AST in place, so the parse-once/bind-many reuse this feature is meant to unlock isn't possible. Please track the immutable-bind redesign as a follow-up PR and guard the leak here.**
**Why reuse is the goal.** Positional parameter binding has two payoffs, and this PR banks only one. The first is injection safety (fully delivered). The second — the classic reason prepared statements exist — is amortizing parse/plan cost across many executions of the same query shape with different values: lex + parse + grammar-build happens once, and each request only binds fresh params and transforms. Our own wire contract already models this — `QueryRequest{ query, params }` is a prepared statement — so consumers (high-QPS dashboards re-issuing the same query every refresh, the MCP/LLM loop re-running one query shape with varying values, any client caching parsed queries keyed by query text) will reasonably expect to parse once and rebind. Without reuse we pay full lex+parse on every request and capture only half the feature's value.
**Why it's blocked today.** Binding writes values straight into the grammar nodes and clears the placeholder markers — `bindScalarValue`/`bindTimeValue` do `v.String = … ; v.Param = false` (lines 291, 308), `collectIntSlot` does `*value = … ; *param = false` (line 118), and `expandLists` rewrites the IN/MATCH/HAVING slices via `list.assign(rebuilt)` (line 269). Since `collect` only registers a slot while the marker is set, the parsed AST is one-shot:
- **Rebind the same grammar** → 2nd call collects 0 slots → `parameter count mismatch: query contains 0 placeholder(s) but N parameter(s) provided`.
- **Silent cross-request leak** → if a cached grammar is rebound with empty `params`, the count check passes (0==0), `Transform` sees no unbound placeholders, and the query runs **with the previous request's values still baked in** — no error, wrong/other-tenant results.
**Ask.** This need not block the PR — the injection-safety win is real and self-contained.
1. **This PR:** make the one-shot contract safe and explicit — document the invariant loudly on `Grammar`/`ParseQuery`/`BindParams`, so nobody adds a query cache before reuse lands and trips the silent-leak path.
2. **Follow-up PR:** implement reusable-AST binding so the template is never mutated. Preferred is a positional value **overlay** the transformer reads instead of `GrammarValue` fields (immutable template, true reuse — accepting the transformer gains minimal placeholder awareness); a per-request **deep clone** is the simpler fallback but re-introduces per-request tree allocation, which partly defeats the point. Let's open a tracking issue and link it here.
##########
pkg/bydbql/grammar.go:
##########
@@ -319,13 +323,15 @@ type GrammarOrderByWithIdent struct {
// GrammarLimitClause represents LIMIT clause.
type GrammarLimitClause struct {
Limit string `parser:"@'LIMIT'"`
- Value int `parser:"@Int"`
+ Value int `parser:"( @Int"`
+ Param bool `parser:"| @Param )"`
Review Comment:
**MEDIUM — literal count positions aren't range-checked, so the new `?` path is stricter than a literal.** `BindParams` correctly bounds a bound count to `[0, MaxInt32]` (binder.go:112), but the literal path casts unchecked in the transformer: `uint32(statement.Limit.Value)` / `uint32(statement.Offset.Value)` (transformer.go:184,187) and `int32(statement.N)` / `int32(topn.N)` (transformer.go:590,1565). So `LIMIT ?`=-5 is rejected cleanly, yet `LIMIT -5` wraps to a huge `uint32` and `SHOW TOP 3000000000` wraps negative. Pre-existing, but this PR establishes the correct guard and touches these count fields — good moment to apply the same `[0, MaxInt32]` check to the literal path via a shared helper so the two paths can't diverge.
##########
pkg/bydbql/transformer.go:
##########
@@ -101,6 +101,11 @@ func NewTransformer(registry metadata.Repo) *Transformer {
// Transform transforms a Grammar into a native query request.
func (t *Transformer) Transform(ctx context.Context, grammar *Grammar) (*TransformResult, error) {
+ // Defense in depth: an unbound placeholder would otherwise transform into an
+ // empty string or a zero count silently instead of failing loudly.
+ if unbound := countUnboundParams(grammar); unbound > 0 {
Review Comment:
**MEDIUM (perf) — the whole grammar is walked twice per query.** `BindParams` already walked the tree via `collect`; `Transform` then builds a second `binder` in `countUnboundParams` and reruns the same recursion, allocating `[]func(...)`/`listContainer`s it immediately discards — paid on every query including zero-placeholder ones. Give `countUnboundParams` a closure-free counting walk (increment on `Param==true`), or have `BindParams` stamp the grammar "bound" so `Transform` can skip the re-walk. Note this interacts with the reuse redesign — an overlay/clone approach likely removes this walk entirely.
##########
mcp/src/query/validation.ts:
##########
@@ -119,12 +135,83 @@ export function normalizeQueryHints(args: unknown): QueryHints {
return {
description: typeof rawArgs.description === 'string' ? rawArgs.description.trim() : undefined,
BydbQL: typeof rawArgs.BydbQL === 'string' ? rawArgs.BydbQL.trim() : undefined,
+ params: Array.isArray(rawArgs.params) ? (rawArgs.params as BydbQLParam[]) : undefined,
resource_type: typeof rawArgs.resource_type === 'string' ? rawArgs.resource_type.trim() : undefined,
resource_name: typeof rawArgs.resource_name === 'string' ? rawArgs.resource_name.trim() : undefined,
group: typeof rawArgs.group === 'string' ? rawArgs.group.trim() : undefined,
};
}
+function validateParamString(value: unknown, position: number): string {
+ if (typeof value !== 'string') {
+ throw new Error(`params[${position}]: str value must be a string`);
+ }
+ if (value.length > maxParamValueLength) {
+ throw new Error(`params[${position}]: value exceeds ${maxParamValueLength} characters`);
+ }
+ return value;
+}
+
+function validateParamInteger(value: unknown, position: number): string {
+ if (typeof value === 'number' && Number.isSafeInteger(value)) {
+ return String(value);
+ }
+ if (typeof value === 'string' && value.length <= maxIntParamLength && integerPattern.test(value)) {
+ return value;
+ }
+ throw new Error(`params[${position}]: int value must be an integer of at most ${maxIntParamLength} characters`);
+}
+
+function validateParamArray(value: unknown, position: number): unknown[] {
+ if (!Array.isArray(value) || value.length === 0) {
+ throw new Error(`params[${position}]: array value must be a non-empty array`);
+ }
+ if (value.length > maxParamArrayLength) {
+ throw new Error(`params[${position}]: array value exceeds ${maxParamArrayLength} entries`);
+ }
+ return value;
+}
+
+/**
+ * Validate BydbQL parameters and convert them to protojson TagValue form
+ * accepted by the BanyanDB HTTP API.
+ *
+ * The server-side `timestamp` variant is deliberately not exposed here:
+ * an RFC3339 `str` is equivalent for TIME positions.
+ */
+export function toTagValueParams(params: BydbQLParam[]): TagValueParam[] {
Review Comment:
**MEDIUM — new param validation ships with zero unit tests.** `git diff --stat` shows `validation.ts +90` (this function plus `validateParamString`/`Integer`/`Array` and the new limits) but `validation.test.ts` is untouched, despite the existing MCP test convention (#1036). This is the untrusted, LLM-facing entry point. Add cases for: param-count cap, each type's happy path, type mismatch, empty/oversized array, int overflow (ties to the comment above), and the `{ null: null }` shape. Contrast the Go side's 544 specs.
##########
mcp/src/query/validation.ts:
##########
@@ -119,12 +135,83 @@ export function normalizeQueryHints(args: unknown): QueryHints {
return {
description: typeof rawArgs.description === 'string' ? rawArgs.description.trim() : undefined,
BydbQL: typeof rawArgs.BydbQL === 'string' ? rawArgs.BydbQL.trim() : undefined,
+ params: Array.isArray(rawArgs.params) ? (rawArgs.params as BydbQLParam[]) : undefined,
resource_type: typeof rawArgs.resource_type === 'string' ? rawArgs.resource_type.trim() : undefined,
resource_name: typeof rawArgs.resource_name === 'string' ? rawArgs.resource_name.trim() : undefined,
group: typeof rawArgs.group === 'string' ? rawArgs.group.trim() : undefined,
};
}
+function validateParamString(value: unknown, position: number): string {
+ if (typeof value !== 'string') {
+ throw new Error(`params[${position}]: str value must be a string`);
+ }
+ if (value.length > maxParamValueLength) {
+ throw new Error(`params[${position}]: value exceeds ${maxParamValueLength} characters`);
+ }
+ return value;
+}
+
+function validateParamInteger(value: unknown, position: number): string {
+ if (typeof value === 'number' && Number.isSafeInteger(value)) {
+ return String(value);
+ }
+ if (typeof value === 'string' && value.length <= maxIntParamLength && integerPattern.test(value)) {
Review Comment:
**MEDIUM — `maxIntParamLength = 20` admits int64-overflowing values, deferring the failure to an opaque gateway error.** A 20-char string like `"99999999999999999999"` passes `integerPattern` + the length cap and is emitted as `{ int: { value: "…" } }`, then fails late in protojson int64 decoding on the server instead of returning a clean `params[i]` message. Range-check against int64 bounds (e.g. a `BigInt` compare) here so the error is client-side and specific.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@skywalking.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Introduce parameter binding (`?` placeholders) into BydbQL [skywalking-banyandb]
Posted by "mrproliu (via GitHub)" <gi...@apache.org>.
mrproliu commented on code in PR #1209:
URL: https://github.com/apache/skywalking-banyandb/pull/1209#discussion_r3541589773
##########
mcp/src/query/validation.ts:
##########
@@ -119,12 +135,83 @@ export function normalizeQueryHints(args: unknown): QueryHints {
return {
description: typeof rawArgs.description === 'string' ? rawArgs.description.trim() : undefined,
BydbQL: typeof rawArgs.BydbQL === 'string' ? rawArgs.BydbQL.trim() : undefined,
+ params: Array.isArray(rawArgs.params) ? (rawArgs.params as BydbQLParam[]) : undefined,
resource_type: typeof rawArgs.resource_type === 'string' ? rawArgs.resource_type.trim() : undefined,
resource_name: typeof rawArgs.resource_name === 'string' ? rawArgs.resource_name.trim() : undefined,
group: typeof rawArgs.group === 'string' ? rawArgs.group.trim() : undefined,
};
}
+function validateParamString(value: unknown, position: number): string {
+ if (typeof value !== 'string') {
+ throw new Error(`params[${position}]: str value must be a string`);
+ }
+ if (value.length > maxParamValueLength) {
+ throw new Error(`params[${position}]: value exceeds ${maxParamValueLength} characters`);
+ }
+ return value;
+}
+
+function validateParamInteger(value: unknown, position: number): string {
+ if (typeof value === 'number' && Number.isSafeInteger(value)) {
+ return String(value);
+ }
+ if (typeof value === 'string' && value.length <= maxIntParamLength && integerPattern.test(value)) {
+ return value;
+ }
+ throw new Error(`params[${position}]: int value must be an integer of at most ${maxIntParamLength} characters`);
+}
+
+function validateParamArray(value: unknown, position: number): unknown[] {
+ if (!Array.isArray(value) || value.length === 0) {
+ throw new Error(`params[${position}]: array value must be a non-empty array`);
+ }
+ if (value.length > maxParamArrayLength) {
+ throw new Error(`params[${position}]: array value exceeds ${maxParamArrayLength} entries`);
+ }
+ return value;
+}
+
+/**
+ * Validate BydbQL parameters and convert them to protojson TagValue form
+ * accepted by the BanyanDB HTTP API.
+ *
+ * The server-side `timestamp` variant is deliberately not exposed here:
+ * an RFC3339 `str` is equivalent for TIME positions.
+ */
+export function toTagValueParams(params: BydbQLParam[]): TagValueParam[] {
Review Comment:
Done
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@skywalking.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Introduce parameter binding (`?` placeholders) into BydbQL [skywalking-banyandb]
Posted by "mrproliu (via GitHub)" <gi...@apache.org>.
mrproliu merged PR #1209:
URL: https://github.com/apache/skywalking-banyandb/pull/1209
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@skywalking.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Introduce parameter binding (`?` placeholders) into BydbQL [skywalking-banyandb]
Posted by "Copilot (via GitHub)" <gi...@apache.org>.
Copilot commented on code in PR #1209:
URL: https://github.com/apache/skywalking-banyandb/pull/1209#discussion_r3534882424
##########
ui/src/components/BydbQL/Index.vue:
##########
@@ -584,6 +658,26 @@ SELECT * FROM STREAM log in sw_recordsLog TIME > '-30m'`);
@ready="onCodeMirrorReady"
/>
</div>
+ <div class="query-params-container">
+ <div class="params-header">
+ <span class="params-title">Parameters (bound to ? placeholders in order)</span>
+ <el-button size="small" @click="addParam" :disabled="loading"> Add Parameter </el-button>
+ </div>
+ <div v-for="(param, index) in queryParams" :key="index" class="param-row">
+ <span class="param-index">?{{ index + 1 }}</span>
+ <el-select v-model="param.type" size="small" class="param-type">
Review Comment:
Using the array index as the v-for key can cause row state to “shift” when removing parameters (inputs/selects may appear to change the wrong row). Use a stable per-parameter id (e.g., store an `id` on each param when added) and key by that id instead of `index`.
##########
docs/interacting/bydbql.md:
##########
@@ -154,6 +157,76 @@ TIME < '-1d'
The `parseTime` function automatically determines whether a timestamp is absolute (RFC3339) or relative (duration string) and converts it appropriately.
+## 2.6. Parameter Binding
+
+BydbQL supports positional parameter binding with the `?` placeholder, so untrusted values never need to be concatenated into the query string. This eliminates QL injection: a bound value is always treated as a plain value and can never alter the query structure.
+
+```sql
+SELECT trace_id, message
+FROM STREAM logs IN group1
+TIME > ?
+WHERE message MATCH(?)
+```
+
+Parameters are supplied alongside the query and are bound to the placeholders in their order of appearance. Each parameter is a `model.v1.TagValue`. Over HTTP:
+
+```json
+POST /api/v1/bydbql/query
+{
+ "query": "SELECT trace_id, message FROM STREAM logs IN group1 TIME > ? WHERE message MATCH(?)",
+ "params": [
+ {"str": {"value": "-30m"}},
+ {"str": {"value": "error"}}
+ ]
+}
+```
+
+### 2.6.1. Supported Positions
+
+Placeholders are accepted in *value* positions only. The complete list, with the parameter types each position accepts:
+
+| Position | Example | Accepted parameter types |
+|---|---|---|
+| `TIME` comparison value | `TIME > ?` | `str` (RFC3339, relative like `-30m`, or `now`), `timestamp` |
Review Comment:
The supported-positions table says TIME placeholders accept only `str`/`timestamp`, but later in this same section you note that `int` parameters bind in TIME positions (and binder.go also accepts `TagValue_Int`). This is internally inconsistent and may mislead users; either include `int` in the table (with the existing caveat) or change binding rules to reject it.
##########
mcp/src/query/validation.ts:
##########
@@ -119,12 +133,77 @@ export function normalizeQueryHints(args: unknown): QueryHints {
return {
description: typeof rawArgs.description === 'string' ? rawArgs.description.trim() : undefined,
BydbQL: typeof rawArgs.BydbQL === 'string' ? rawArgs.BydbQL.trim() : undefined,
+ params: Array.isArray(rawArgs.params) ? (rawArgs.params as BydbQLParam[]) : undefined,
resource_type: typeof rawArgs.resource_type === 'string' ? rawArgs.resource_type.trim() : undefined,
resource_name: typeof rawArgs.resource_name === 'string' ? rawArgs.resource_name.trim() : undefined,
group: typeof rawArgs.group === 'string' ? rawArgs.group.trim() : undefined,
};
}
+function validateParamString(value: unknown, position: number): string {
+ if (typeof value !== 'string') {
+ throw new Error(`params[${position}]: str value must be a string`);
+ }
+ if (value.length > maxParamValueLength) {
+ throw new Error(`params[${position}]: value exceeds ${maxParamValueLength} characters`);
+ }
+ return value;
+}
+
+function validateParamInteger(value: unknown, position: number): string {
+ if (typeof value === 'number' && Number.isSafeInteger(value)) {
+ return String(value);
+ }
+ if (typeof value === 'string' && integerPattern.test(value)) {
+ return value;
+ }
+ throw new Error(`params[${position}]: int value must be an integer`);
+}
Review Comment:
validateParamInteger accepts arbitrarily long integer strings (it only regex-checks), even though maxParamValueLength exists. This can allow very large param payloads (e.g., megabytes of digits) to get passed through to the HTTP API, which is unnecessary and can become a resource/DoS vector. Apply the same length limit used for string params after converting the int to its string representation.
##########
docs/api-reference.md:
##########
@@ -2117,6 +2117,7 @@ QueryRequest is the main request message for BydbQL queries
| Field | Type | Label | Description |
| ----- | ---- | ----- | ----------- |
| query | [string](#string) | | query is the BydbQL query string |
+| params | [banyandb.model.v1.TagValue](#banyandb-model-v1-TagValue) | repeated | params are bound to the `?` placeholders in the query string by their order of appearance. The number of params must match the number of placeholders. Accepted variants depend on the placeholder's position: str/timestamp for TIME values, str/int/null for scalar comparisons, str/int/null/str_array/int_array for IN/MATCH/HAVING value lists (arrays expand in place), and int for LIMIT/OFFSET/TOP N counts. binary_data is rejected everywhere. |
Review Comment:
This API reference text says TIME placeholders accept only str/timestamp, but the binder accepts int parameters in TIME positions as well. Keep this description consistent with the actual binding rules (or update the binding rules to match the docs).
##########
api/proto/banyandb/bydbql/v1/query.proto:
##########
@@ -33,6 +34,13 @@ option java_package = "org.apache.skywalking.banyandb.bydbql.v1";
message QueryRequest {
// query is the BydbQL query string
string query = 1 [(validate.rules).string.min_len = 1];
+ // params are bound to the `?` placeholders in the query string by their order of appearance.
+ // The number of params must match the number of placeholders.
+ // Accepted variants depend on the placeholder's position: str/timestamp for TIME values,
+ // str/int/null for scalar comparisons, str/int/null/str_array/int_array for IN/MATCH/HAVING
+ // value lists (arrays expand in place), and int for LIMIT/OFFSET/TOP N counts.
Review Comment:
The QueryRequest `params` comment says TIME placeholders accept only str/timestamp, but the binder accepts int parameters in TIME positions (BindParams.bindTimeValue handles TagValue_Int) and the docs mention that int binds but later fails transformation. Please align this proto comment with actual accepted variants (or adjust binder semantics accordingly).
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@skywalking.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Introduce parameter binding (`?` placeholders) into BydbQL [skywalking-banyandb]
Posted by "mrproliu (via GitHub)" <gi...@apache.org>.
mrproliu commented on code in PR #1209:
URL: https://github.com/apache/skywalking-banyandb/pull/1209#discussion_r3541584387
##########
pkg/bydbql/transformer.go:
##########
@@ -101,6 +101,11 @@ func NewTransformer(registry metadata.Repo) *Transformer {
// Transform transforms a Grammar into a native query request.
func (t *Transformer) Transform(ctx context.Context, grammar *Grammar) (*TransformResult, error) {
+ // Defense in depth: an unbound placeholder would otherwise transform into an
+ // empty string or a zero count silently instead of failing loudly.
+ if unbound := countUnboundParams(grammar); unbound > 0 {
Review Comment:
Added `countUnboundParams`.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@skywalking.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Introduce parameter binding (`?` placeholders) into BydbQL [skywalking-banyandb]
Posted by "mrproliu (via GitHub)" <gi...@apache.org>.
mrproliu commented on code in PR #1209:
URL: https://github.com/apache/skywalking-banyandb/pull/1209#discussion_r3541586895
##########
mcp/src/query/validation.ts:
##########
@@ -119,12 +135,83 @@ export function normalizeQueryHints(args: unknown): QueryHints {
return {
description: typeof rawArgs.description === 'string' ? rawArgs.description.trim() : undefined,
BydbQL: typeof rawArgs.BydbQL === 'string' ? rawArgs.BydbQL.trim() : undefined,
+ params: Array.isArray(rawArgs.params) ? (rawArgs.params as BydbQLParam[]) : undefined,
resource_type: typeof rawArgs.resource_type === 'string' ? rawArgs.resource_type.trim() : undefined,
resource_name: typeof rawArgs.resource_name === 'string' ? rawArgs.resource_name.trim() : undefined,
group: typeof rawArgs.group === 'string' ? rawArgs.group.trim() : undefined,
};
}
+function validateParamString(value: unknown, position: number): string {
+ if (typeof value !== 'string') {
+ throw new Error(`params[${position}]: str value must be a string`);
+ }
+ if (value.length > maxParamValueLength) {
+ throw new Error(`params[${position}]: value exceeds ${maxParamValueLength} characters`);
+ }
+ return value;
+}
+
+function validateParamInteger(value: unknown, position: number): string {
+ if (typeof value === 'number' && Number.isSafeInteger(value)) {
+ return String(value);
+ }
+ if (typeof value === 'string' && value.length <= maxIntParamLength && integerPattern.test(value)) {
Review Comment:
Add a checker after parameter bound.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@skywalking.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Introduce parameter binding (`?` placeholders) into BydbQL [skywalking-banyandb]
Posted by "mrproliu (via GitHub)" <gi...@apache.org>.
mrproliu commented on code in PR #1209:
URL: https://github.com/apache/skywalking-banyandb/pull/1209#discussion_r3541582451
##########
pkg/bydbql/binder.go:
##########
@@ -0,0 +1,310 @@
+// Licensed to Apache Software Foundation (ASF) under one or more contributor
+// license agreements. See the NOTICE file distributed with
+// this work for additional information regarding copyright
+// ownership. Apache Software Foundation (ASF) licenses this file to you under
+// the Apache License, Version 2.0 (the "License"); you may
+// not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+package bydbql
+
+import (
+ "fmt"
+ "math"
+ "time"
+
+ modelv1 "github.com/apache/skywalking-banyandb/api/proto/banyandb/model/v1"
+)
+
+// BindParams binds positional parameters to the `?` placeholders in the parsed grammar,
+// in their order of appearance in the query text. After a successful call, the grammar is
+// indistinguishable from one parsed with literal values, so the transformer needs no
+// placeholder awareness. Callers must invoke it before Transform even when params is empty,
+// so a query holding unbound placeholders is rejected instead of silently misinterpreted.
+// Parameter positions in error messages are 1-based. On error the grammar may be partially
+// bound and must be discarded; binding is not retryable on the same grammar.
+func BindParams(g *Grammar, params []*modelv1.TagValue) error {
Review Comment:
Added a `paramBound` bool for this for check the parameter already bound or not.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@skywalking.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Introduce parameter binding (`?` placeholders) into BydbQL [skywalking-banyandb]
Posted by "mrproliu (via GitHub)" <gi...@apache.org>.
mrproliu commented on code in PR #1209:
URL: https://github.com/apache/skywalking-banyandb/pull/1209#discussion_r3541586108
##########
pkg/bydbql/grammar.go:
##########
@@ -319,13 +323,15 @@ type GrammarOrderByWithIdent struct {
// GrammarLimitClause represents LIMIT clause.
type GrammarLimitClause struct {
Limit string `parser:"@'LIMIT'"`
- Value int `parser:"@Int"`
+ Value int `parser:"( @Int"`
+ Param bool `parser:"| @Param )"`
Review Comment:
Add a checker after parameter bound.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@skywalking.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org