gobby-code 0.9.9

Fast Rust CLI for Gobby's code index — AST-aware search, symbol navigation, and dependency graph
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
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
58
59
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
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
use std::collections::HashSet;

use postgres::Client;

use crate::config::Context;
use crate::models::{SearchResult, Symbol};
use crate::visibility;

use super::common::{
    FILTERED_FETCH_CAP, PgParam, SymbolFilters, SymbolOrder, append_unique_symbols, escape_like,
    push_param, query_symbols_by_conditions, sanitize_pg_search_query,
};

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct VisibleSearchOutcome<T> {
    pub results: Vec<T>,
    pub degraded: bool,
}

impl<T> VisibleSearchOutcome<T> {
    fn ok(results: Vec<T>) -> Self {
        Self {
            results,
            degraded: false,
        }
    }

    fn degraded(results: Vec<T>) -> Self {
        Self {
            results,
            degraded: true,
        }
    }
}

pub fn search_symbols_fts(
    conn: &mut Client,
    query: &str,
    project_id: &str,
    kind: Option<&str>,
    language: Option<&str>,
    paths: &[String],
    limit: usize,
) -> Vec<Symbol> {
    let bm25_query = sanitize_pg_search_query(query);
    if bm25_query.is_empty() || limit == 0 {
        return Vec::new();
    }

    let mut params = Vec::new();
    let query_placeholder = push_param(&mut params, bm25_query);
    let project_placeholder = push_param(&mut params, project_id.to_string());
    let conditions = vec![
        format!(
            "(cs.name @@@ {q} OR cs.qualified_name @@@ {q} OR cs.signature @@@ {q} OR cs.docstring @@@ {q} OR cs.summary @@@ {q})",
            q = query_placeholder
        ),
        format!("cs.project_id = {project_placeholder}"),
    ];
    let filters = SymbolFilters {
        kind,
        language,
        paths,
    };
    query_symbols_by_conditions(
        conn,
        conditions,
        params,
        filters,
        limit,
        SymbolOrder::Bm25Score,
    )
}

/// Fallback LIKE search on symbol names.
pub fn search_symbols_by_name(
    conn: &mut Client,
    query: &str,
    project_id: &str,
    kind: Option<&str>,
    language: Option<&str>,
    paths: &[String],
    limit: usize,
) -> Vec<Symbol> {
    if query.trim().is_empty() || limit == 0 {
        return Vec::new();
    }
    let escaped_query = escape_like(query);
    let pattern = format!("%{escaped_query}%");
    let mut params = Vec::new();
    let project_placeholder = push_param(&mut params, project_id.to_string());
    let name_placeholder = push_param(&mut params, pattern.clone());
    let qualified_placeholder = push_param(&mut params, pattern);
    let conditions = vec![
        format!("cs.project_id = {project_placeholder}"),
        format!(
            "(cs.name LIKE {name_placeholder} ESCAPE '\\' OR cs.qualified_name LIKE {qualified_placeholder} ESCAPE '\\')"
        ),
    ];
    query_symbols_by_conditions(
        conn,
        conditions,
        params,
        SymbolFilters {
            kind,
            language,
            paths,
        },
        limit,
        SymbolOrder::Name,
    )
}

pub fn search_symbols_exact_first(
    conn: &mut Client,
    query: &str,
    project_id: &str,
    kind: Option<&str>,
    language: Option<&str>,
    paths: &[String],
    limit: usize,
) -> Vec<Symbol> {
    if query.trim().is_empty() || limit == 0 {
        return Vec::new();
    }

    let mut results = Vec::new();
    let mut seen = HashSet::new();
    let filters = SymbolFilters {
        kind,
        language,
        paths,
    };

    let mut params = Vec::new();
    let project = push_param(&mut params, project_id.to_string());
    let query_param = push_param(&mut params, query.to_string());
    let order = SymbolOrder::ExactCaseFirst(query_param.clone());
    let exact = query_symbols_by_conditions(
        conn,
        vec![
            format!("cs.project_id = {project}"),
            format!(
                "(cs.name = {q} OR cs.qualified_name = {q} OR lower(cs.name) = lower({q}) OR lower(cs.qualified_name) = lower({q}))",
                q = query_param
            ),
        ],
        params,
        filters,
        limit,
        order,
    );
    append_unique_symbols(&mut results, &mut seen, exact, limit);
    if results.len() >= limit {
        return results;
    }

    let prefix_pattern = format!("{}%", escape_like(query));
    let mut params = Vec::new();
    let project = push_param(&mut params, project_id.to_string());
    let prefix = push_param(&mut params, prefix_pattern);
    let prefix_matches = query_symbols_by_conditions(
        conn,
        vec![
            format!("cs.project_id = {project}"),
            format!(
                "(cs.name LIKE {prefix} ESCAPE '\\' OR cs.qualified_name LIKE {prefix} ESCAPE '\\')"
            ),
        ],
        params,
        filters,
        limit,
        SymbolOrder::Name,
    );
    append_unique_symbols(&mut results, &mut seen, prefix_matches, limit);
    if results.len() >= limit {
        return results;
    }

    let contains = search_symbols_by_name(conn, query, project_id, kind, language, paths, limit);
    append_unique_symbols(&mut results, &mut seen, contains, limit);
    if results.len() >= limit {
        return results;
    }

    let fts = search_symbols_fts(conn, query, project_id, kind, language, paths, limit);
    append_unique_symbols(&mut results, &mut seen, fts, limit);

    results
}

pub fn search_symbols_fts_visible(
    conn: &mut Client,
    query: &str,
    ctx: &Context,
    kind: Option<&str>,
    language: Option<&str>,
    paths: &[String],
    limit: usize,
) -> VisibleSearchOutcome<Symbol> {
    let bm25_query = sanitize_pg_search_query(query);
    if bm25_query.is_empty() || limit == 0 {
        return VisibleSearchOutcome::ok(Vec::new());
    }

    let mut params = Vec::new();
    let query_placeholder = push_param(&mut params, bm25_query);
    let conditions = vec![format!(
        "(cs.name @@@ {q} OR cs.qualified_name @@@ {q} OR cs.signature @@@ {q} OR cs.docstring @@@ {q} OR cs.summary @@@ {q})",
        q = query_placeholder
    )];
    query_visible_symbols_by_conditions(
        conn,
        ctx,
        conditions,
        params,
        SymbolFilters {
            kind,
            language,
            paths,
        },
        limit,
        SymbolOrder::Bm25Score,
    )
}

pub fn search_symbols_by_name_visible(
    conn: &mut Client,
    query: &str,
    ctx: &Context,
    kind: Option<&str>,
    language: Option<&str>,
    paths: &[String],
    limit: usize,
) -> VisibleSearchOutcome<Symbol> {
    if query.trim().is_empty() || limit == 0 {
        return VisibleSearchOutcome::ok(Vec::new());
    }
    let escaped_query = escape_like(query);
    let pattern = format!("%{escaped_query}%");
    let mut params = Vec::new();
    let name_placeholder = push_param(&mut params, pattern.clone());
    let qualified_placeholder = push_param(&mut params, pattern);
    let conditions = vec![format!(
        "(cs.name LIKE {name_placeholder} ESCAPE '\\' OR cs.qualified_name LIKE {qualified_placeholder} ESCAPE '\\')"
    )];
    query_visible_symbols_by_conditions(
        conn,
        ctx,
        conditions,
        params,
        SymbolFilters {
            kind,
            language,
            paths,
        },
        limit,
        SymbolOrder::Name,
    )
}

pub fn search_symbols_exact_first_visible(
    conn: &mut Client,
    query: &str,
    ctx: &Context,
    kind: Option<&str>,
    language: Option<&str>,
    paths: &[String],
    limit: usize,
) -> VisibleSearchOutcome<Symbol> {
    if query.trim().is_empty() || limit == 0 {
        return VisibleSearchOutcome::ok(Vec::new());
    }

    let mut results = Vec::new();
    let mut seen = HashSet::new();
    let mut degraded = false;
    let filters = SymbolFilters {
        kind,
        language,
        paths,
    };

    let mut params = Vec::new();
    let query_param = push_param(&mut params, query.to_string());
    let order = SymbolOrder::ExactCaseFirst(query_param.clone());
    let exact = query_visible_symbols_by_conditions(
        conn,
        ctx,
        vec![format!(
            "(cs.name = {q} OR cs.qualified_name = {q} OR lower(cs.name) = lower({q}) OR lower(cs.qualified_name) = lower({q}))",
            q = query_param
        )],
        params,
        filters,
        limit,
        order,
    );
    degraded |= exact.degraded;
    append_unique_symbols(&mut results, &mut seen, exact.results, limit);
    if results.len() >= limit {
        return VisibleSearchOutcome { results, degraded };
    }

    let prefix_pattern = format!("{}%", escape_like(query));
    let mut params = Vec::new();
    let prefix = push_param(&mut params, prefix_pattern);
    let prefix_matches = query_visible_symbols_by_conditions(
        conn,
        ctx,
        vec![format!(
            "(cs.name LIKE {prefix} ESCAPE '\\' OR cs.qualified_name LIKE {prefix} ESCAPE '\\')"
        )],
        params,
        filters,
        limit,
        SymbolOrder::Name,
    );
    degraded |= prefix_matches.degraded;
    append_unique_symbols(&mut results, &mut seen, prefix_matches.results, limit);
    if results.len() >= limit {
        return VisibleSearchOutcome { results, degraded };
    }

    let contains = search_symbols_by_name_visible(conn, query, ctx, kind, language, paths, limit);
    degraded |= contains.degraded;
    append_unique_symbols(&mut results, &mut seen, contains.results, limit);
    if results.len() >= limit {
        return VisibleSearchOutcome { results, degraded };
    }

    let fts = search_symbols_fts_visible(conn, query, ctx, kind, language, paths, limit);
    degraded |= fts.degraded;
    append_unique_symbols(&mut results, &mut seen, fts.results, limit);

    VisibleSearchOutcome { results, degraded }
}

fn query_visible_symbols_by_conditions(
    conn: &mut Client,
    ctx: &Context,
    mut conditions: Vec<String>,
    mut params: Vec<PgParam>,
    filters: SymbolFilters<'_>,
    limit: usize,
    order: SymbolOrder,
) -> VisibleSearchOutcome<Symbol> {
    let project_ids = visibility::visible_project_ids(ctx);
    if project_ids.is_empty() || limit == 0 {
        return VisibleSearchOutcome::ok(Vec::new());
    }
    let project_placeholder = push_param(&mut params, project_ids);
    conditions.push(format!("cs.project_id = ANY({project_placeholder})"));
    let symbols = query_symbols_by_conditions(
        conn,
        conditions,
        params,
        filters,
        limit.max(FILTERED_FETCH_CAP),
        order,
    );
    let mut symbols = match visibility::filter_visible_symbols(conn, ctx, symbols) {
        Ok(symbols) => symbols,
        Err(error) => {
            log::error!("visible symbol filtering failed: {error}");
            return VisibleSearchOutcome::degraded(Vec::new());
        }
    };
    symbols.truncate(limit);
    VisibleSearchOutcome::ok(symbols)
}

/// Full-text search for symbols: BM25 with LIKE fallback.
pub fn search_text(
    conn: &mut Client,
    query: &str,
    project_id: &str,
    language: Option<&str>,
    paths: &[String],
    limit: usize,
) -> Vec<SearchResult> {
    let mut results = search_symbols_fts(conn, query, project_id, None, language, paths, limit);
    if results.is_empty() {
        results = search_symbols_by_name(conn, query, project_id, None, language, paths, limit);
    }
    results.into_iter().map(|s| s.to_brief()).collect()
}

pub fn search_text_visible(
    conn: &mut Client,
    query: &str,
    ctx: &Context,
    language: Option<&str>,
    paths: &[String],
    limit: usize,
) -> VisibleSearchOutcome<SearchResult> {
    let mut results = search_symbols_fts_visible(conn, query, ctx, None, language, paths, limit);
    if results.results.is_empty() {
        results = search_symbols_by_name_visible(conn, query, ctx, None, language, paths, limit);
    }
    VisibleSearchOutcome {
        results: results.results.into_iter().map(|s| s.to_brief()).collect(),
        degraded: results.degraded,
    }
}