]> git.notmuchmail.org Git - notmuch/blob - lib/query.cc
lib: Add exclude query debug output
[notmuch] / lib / query.cc
1 /* query.cc - Support for searching a notmuch database
2  *
3  * Copyright © 2009 Carl Worth
4  *
5  * This program is free software: you can redistribute it and/or modify
6  * it under the terms of the GNU General Public License as published by
7  * the Free Software Foundation, either version 3 of the License, or
8  * (at your option) any later version.
9  *
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  * GNU General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License
16  * along with this program.  If not, see http://www.gnu.org/licenses/ .
17  *
18  * Author: Carl Worth <cworth@cworth.org>
19  */
20
21 #include "notmuch-private.h"
22 #include "database-private.h"
23
24 #include <glib.h> /* GHashTable, GPtrArray */
25
26 struct _notmuch_query {
27     notmuch_database_t *notmuch;
28     const char *query_string;
29     notmuch_sort_t sort;
30     notmuch_string_list_t *exclude_terms;
31     notmuch_bool_t omit_excluded_messages;
32 };
33
34 typedef struct _notmuch_mset_messages {
35     notmuch_messages_t base;
36     notmuch_database_t *notmuch;
37     Xapian::MSetIterator iterator;
38     Xapian::MSetIterator iterator_end;
39 } notmuch_mset_messages_t;
40
41 struct _notmuch_doc_id_set {
42     unsigned int *bitmap;
43     unsigned int bound;
44 };
45
46 #define DOCIDSET_WORD(bit) ((bit) / sizeof (unsigned int))
47 #define DOCIDSET_BIT(bit) ((bit) % sizeof (unsigned int))
48
49 struct visible _notmuch_threads {
50     notmuch_query_t *query;
51
52     /* The ordered list of doc ids matched by the query. */
53     GArray *doc_ids;
54     /* Our iterator's current position in doc_ids. */
55     unsigned int doc_id_pos;
56     /* The set of matched docid's that have not been assigned to a
57      * thread. Initially, this contains every docid in doc_ids. */
58     notmuch_doc_id_set_t match_set;
59 };
60
61 /* We need this in the message functions so forward declare. */
62 static notmuch_bool_t
63 _notmuch_doc_id_set_init (void *ctx,
64                           notmuch_doc_id_set_t *doc_ids,
65                           GArray *arr);
66
67 static notmuch_bool_t
68 _debug_query (void)
69 {
70     char *env = getenv ("NOTMUCH_DEBUG_QUERY");
71     return (env && strcmp (env, "") != 0);
72 }
73
74 notmuch_query_t *
75 notmuch_query_create (notmuch_database_t *notmuch,
76                       const char *query_string)
77 {
78     notmuch_query_t *query;
79
80     if (_debug_query ())
81         fprintf (stderr, "Query string is:\n%s\n", query_string);
82
83     query = talloc (NULL, notmuch_query_t);
84     if (unlikely (query == NULL))
85         return NULL;
86
87     query->notmuch = notmuch;
88
89     query->query_string = talloc_strdup (query, query_string);
90
91     query->sort = NOTMUCH_SORT_NEWEST_FIRST;
92
93     query->exclude_terms = _notmuch_string_list_create (query);
94
95     query->omit_excluded_messages = FALSE;
96
97     return query;
98 }
99
100 const char *
101 notmuch_query_get_query_string (notmuch_query_t *query)
102 {
103     return query->query_string;
104 }
105
106 void
107 notmuch_query_set_omit_excluded_messages (notmuch_query_t *query, notmuch_bool_t omit)
108 {
109     query->omit_excluded_messages = omit;
110 }
111
112 void
113 notmuch_query_set_sort (notmuch_query_t *query, notmuch_sort_t sort)
114 {
115     query->sort = sort;
116 }
117
118 notmuch_sort_t
119 notmuch_query_get_sort (notmuch_query_t *query)
120 {
121     return query->sort;
122 }
123
124 void
125 notmuch_query_add_tag_exclude (notmuch_query_t *query, const char *tag)
126 {
127     char *term = talloc_asprintf (query, "%s%s", _find_prefix ("tag"), tag);
128     _notmuch_string_list_append (query->exclude_terms, term);
129 }
130
131 /* We end up having to call the destructors explicitly because we had
132  * to use "placement new" in order to initialize C++ objects within a
133  * block that we allocated with talloc. So C++ is making talloc
134  * slightly less simple to use, (we wouldn't need
135  * talloc_set_destructor at all otherwise).
136  */
137 static int
138 _notmuch_messages_destructor (notmuch_mset_messages_t *messages)
139 {
140     messages->iterator.~MSetIterator ();
141     messages->iterator_end.~MSetIterator ();
142
143     return 0;
144 }
145
146 /* Return a query that matches messages with the excluded tags
147  * registered with query.  Any tags that explicitly appear in xquery
148  * will not be excluded, and will be removed from the list of exclude
149  * tags.  The caller of this function has to combine the returned
150  * query appropriately.*/
151 static Xapian::Query
152 _notmuch_exclude_tags (notmuch_query_t *query, Xapian::Query xquery)
153 {
154     Xapian::Query exclude_query = Xapian::Query::MatchNothing;
155
156     for (notmuch_string_node_t *term = query->exclude_terms->head; term;
157          term = term->next) {
158         Xapian::TermIterator it = xquery.get_terms_begin ();
159         Xapian::TermIterator end = xquery.get_terms_end ();
160         for (; it != end; it++) {
161             if ((*it).compare (term->string) == 0)
162                 break;
163         }
164         if (it == end)
165             exclude_query = Xapian::Query (Xapian::Query::OP_OR,
166                                     exclude_query, Xapian::Query (term->string));
167         else
168             term->string = talloc_strdup (query, "");
169     }
170     return exclude_query;
171 }
172
173 notmuch_messages_t *
174 notmuch_query_search_messages (notmuch_query_t *query)
175 {
176     notmuch_database_t *notmuch = query->notmuch;
177     const char *query_string = query->query_string;
178     notmuch_mset_messages_t *messages;
179
180     messages = talloc (query, notmuch_mset_messages_t);
181     if (unlikely (messages == NULL))
182         return NULL;
183
184     try {
185
186         messages->base.is_of_list_type = FALSE;
187         messages->base.iterator = NULL;
188         messages->notmuch = notmuch;
189         new (&messages->iterator) Xapian::MSetIterator ();
190         new (&messages->iterator_end) Xapian::MSetIterator ();
191
192         talloc_set_destructor (messages, _notmuch_messages_destructor);
193
194         Xapian::Enquire enquire (*notmuch->xapian_db);
195         Xapian::Query mail_query (talloc_asprintf (query, "%s%s",
196                                                    _find_prefix ("type"),
197                                                    "mail"));
198         Xapian::Query string_query, final_query, exclude_query;
199         Xapian::MSet mset;
200         Xapian::MSetIterator iterator;
201         unsigned int flags = (Xapian::QueryParser::FLAG_BOOLEAN |
202                               Xapian::QueryParser::FLAG_PHRASE |
203                               Xapian::QueryParser::FLAG_LOVEHATE |
204                               Xapian::QueryParser::FLAG_BOOLEAN_ANY_CASE |
205                               Xapian::QueryParser::FLAG_WILDCARD |
206                               Xapian::QueryParser::FLAG_PURE_NOT);
207
208         if (strcmp (query_string, "") == 0 ||
209             strcmp (query_string, "*") == 0)
210         {
211             final_query = mail_query;
212         } else {
213             string_query = notmuch->query_parser->
214                 parse_query (query_string, flags);
215             final_query = Xapian::Query (Xapian::Query::OP_AND,
216                                          mail_query, string_query);
217         }
218         messages->base.excluded_doc_ids = NULL;
219
220         if (query->exclude_terms) {
221             exclude_query = _notmuch_exclude_tags (query, final_query);
222             exclude_query = Xapian::Query (Xapian::Query::OP_AND,
223                                            exclude_query, final_query);
224
225             if (query->omit_excluded_messages)
226                 final_query = Xapian::Query (Xapian::Query::OP_AND_NOT,
227                                              final_query, exclude_query);
228             else {
229                 enquire.set_weighting_scheme (Xapian::BoolWeight());
230                 enquire.set_query (exclude_query);
231
232                 mset = enquire.get_mset (0, notmuch->xapian_db->get_doccount ());
233
234                 GArray *excluded_doc_ids = g_array_new (FALSE, FALSE, sizeof (unsigned int));
235
236                 for (iterator = mset.begin (); iterator != mset.end (); iterator++) {
237                     unsigned int doc_id = *iterator;
238                     g_array_append_val (excluded_doc_ids, doc_id);
239                 }
240                 messages->base.excluded_doc_ids = talloc (messages, _notmuch_doc_id_set);
241                 _notmuch_doc_id_set_init (query, messages->base.excluded_doc_ids,
242                                           excluded_doc_ids);
243                 g_array_unref (excluded_doc_ids);
244             }
245         }
246
247
248         enquire.set_weighting_scheme (Xapian::BoolWeight());
249
250         switch (query->sort) {
251         case NOTMUCH_SORT_OLDEST_FIRST:
252             enquire.set_sort_by_value (NOTMUCH_VALUE_TIMESTAMP, FALSE);
253             break;
254         case NOTMUCH_SORT_NEWEST_FIRST:
255             enquire.set_sort_by_value (NOTMUCH_VALUE_TIMESTAMP, TRUE);
256             break;
257         case NOTMUCH_SORT_MESSAGE_ID:
258             enquire.set_sort_by_value (NOTMUCH_VALUE_MESSAGE_ID, FALSE);
259             break;
260         case NOTMUCH_SORT_UNSORTED:
261             break;
262         }
263
264         if (_debug_query ()) {
265             fprintf (stderr, "Exclude query is:\n%s\n",
266                      exclude_query.get_description ().c_str ());
267             fprintf (stderr, "Final query is:\n%s\n",
268                      final_query.get_description ().c_str ());
269         }
270
271         enquire.set_query (final_query);
272
273         mset = enquire.get_mset (0, notmuch->xapian_db->get_doccount ());
274
275         messages->iterator = mset.begin ();
276         messages->iterator_end = mset.end ();
277
278         return &messages->base;
279
280     } catch (const Xapian::Error &error) {
281         fprintf (stderr, "A Xapian exception occurred performing query: %s\n",
282                  error.get_msg().c_str());
283         fprintf (stderr, "Query string was: %s\n", query->query_string);
284         notmuch->exception_reported = TRUE;
285         talloc_free (messages);
286         return NULL;
287     }
288 }
289
290 notmuch_bool_t
291 _notmuch_mset_messages_valid (notmuch_messages_t *messages)
292 {
293     notmuch_mset_messages_t *mset_messages;
294
295     mset_messages = (notmuch_mset_messages_t *) messages;
296
297     return (mset_messages->iterator != mset_messages->iterator_end);
298 }
299
300 static Xapian::docid
301 _notmuch_mset_messages_get_doc_id (notmuch_messages_t *messages)
302 {
303     notmuch_mset_messages_t *mset_messages;
304
305     mset_messages = (notmuch_mset_messages_t *) messages;
306
307     if (! _notmuch_mset_messages_valid (&mset_messages->base))
308         return 0;
309
310     return *mset_messages->iterator;
311 }
312
313 notmuch_message_t *
314 _notmuch_mset_messages_get (notmuch_messages_t *messages)
315 {
316     notmuch_message_t *message;
317     Xapian::docid doc_id;
318     notmuch_private_status_t status;
319     notmuch_mset_messages_t *mset_messages;
320
321     mset_messages = (notmuch_mset_messages_t *) messages;
322
323     if (! _notmuch_mset_messages_valid (&mset_messages->base))
324         return NULL;
325
326     doc_id = *mset_messages->iterator;
327
328     message = _notmuch_message_create (mset_messages,
329                                        mset_messages->notmuch, doc_id,
330                                        &status);
331
332     if (message == NULL &&
333        status == NOTMUCH_PRIVATE_STATUS_NO_DOCUMENT_FOUND)
334     {
335         INTERNAL_ERROR ("a messages iterator contains a non-existent document ID.\n");
336     }
337
338     if (messages->excluded_doc_ids &&
339         _notmuch_doc_id_set_contains (messages->excluded_doc_ids, doc_id))
340         notmuch_message_set_flag (message, NOTMUCH_MESSAGE_FLAG_EXCLUDED, TRUE);
341
342     return message;
343 }
344
345 void
346 _notmuch_mset_messages_move_to_next (notmuch_messages_t *messages)
347 {
348     notmuch_mset_messages_t *mset_messages;
349
350     mset_messages = (notmuch_mset_messages_t *) messages;
351
352     mset_messages->iterator++;
353 }
354
355 static notmuch_bool_t
356 _notmuch_doc_id_set_init (void *ctx,
357                           notmuch_doc_id_set_t *doc_ids,
358                           GArray *arr)
359 {
360     unsigned int max = 0;
361     unsigned int *bitmap;
362
363     for (unsigned int i = 0; i < arr->len; i++)
364         max = MAX(max, g_array_index (arr, unsigned int, i));
365     bitmap = talloc_zero_array (ctx, unsigned int, 1 + max / sizeof (*bitmap));
366
367     if (bitmap == NULL)
368         return FALSE;
369
370     doc_ids->bitmap = bitmap;
371     doc_ids->bound = max + 1;
372
373     for (unsigned int i = 0; i < arr->len; i++) {
374         unsigned int doc_id = g_array_index (arr, unsigned int, i);
375         bitmap[DOCIDSET_WORD(doc_id)] |= 1 << DOCIDSET_BIT(doc_id);
376     }
377
378     return TRUE;
379 }
380
381 notmuch_bool_t
382 _notmuch_doc_id_set_contains (notmuch_doc_id_set_t *doc_ids,
383                               unsigned int doc_id)
384 {
385     if (doc_id >= doc_ids->bound)
386         return FALSE;
387     return doc_ids->bitmap[DOCIDSET_WORD(doc_id)] & (1 << DOCIDSET_BIT(doc_id));
388 }
389
390 void
391 _notmuch_doc_id_set_remove (notmuch_doc_id_set_t *doc_ids,
392                             unsigned int doc_id)
393 {
394     if (doc_id < doc_ids->bound)
395         doc_ids->bitmap[DOCIDSET_WORD(doc_id)] &= ~(1 << DOCIDSET_BIT(doc_id));
396 }
397
398 /* Glib objects force use to use a talloc destructor as well, (but not
399  * nearly as ugly as the for messages due to C++ objects). At
400  * this point, I'd really like to have some talloc-friendly
401  * equivalents for the few pieces of glib that I'm using. */
402 static int
403 _notmuch_threads_destructor (notmuch_threads_t *threads)
404 {
405     if (threads->doc_ids)
406         g_array_unref (threads->doc_ids);
407
408     return 0;
409 }
410
411 notmuch_threads_t *
412 notmuch_query_search_threads (notmuch_query_t *query)
413 {
414     notmuch_threads_t *threads;
415     notmuch_messages_t *messages;
416
417     threads = talloc (query, notmuch_threads_t);
418     if (threads == NULL)
419         return NULL;
420     threads->doc_ids = NULL;
421     talloc_set_destructor (threads, _notmuch_threads_destructor);
422
423     threads->query = query;
424
425     messages = notmuch_query_search_messages (query);
426     if (messages == NULL) {
427             talloc_free (threads);
428             return NULL;
429     }
430
431     threads->doc_ids = g_array_new (FALSE, FALSE, sizeof (unsigned int));
432     while (notmuch_messages_valid (messages)) {
433         unsigned int doc_id = _notmuch_mset_messages_get_doc_id (messages);
434         g_array_append_val (threads->doc_ids, doc_id);
435         notmuch_messages_move_to_next (messages);
436     }
437     threads->doc_id_pos = 0;
438
439     talloc_free (messages);
440
441     if (! _notmuch_doc_id_set_init (threads, &threads->match_set,
442                                     threads->doc_ids)) {
443         talloc_free (threads);
444         return NULL;
445     }
446
447     return threads;
448 }
449
450 void
451 notmuch_query_destroy (notmuch_query_t *query)
452 {
453     talloc_free (query);
454 }
455
456 notmuch_bool_t
457 notmuch_threads_valid (notmuch_threads_t *threads)
458 {
459     unsigned int doc_id;
460
461     while (threads->doc_id_pos < threads->doc_ids->len) {
462         doc_id = g_array_index (threads->doc_ids, unsigned int,
463                                 threads->doc_id_pos);
464         if (_notmuch_doc_id_set_contains (&threads->match_set, doc_id))
465             break;
466
467         threads->doc_id_pos++;
468     }
469
470     return threads->doc_id_pos < threads->doc_ids->len;
471 }
472
473 notmuch_thread_t *
474 notmuch_threads_get (notmuch_threads_t *threads)
475 {
476     unsigned int doc_id;
477
478     if (! notmuch_threads_valid (threads))
479         return NULL;
480
481     doc_id = g_array_index (threads->doc_ids, unsigned int,
482                             threads->doc_id_pos);
483     return _notmuch_thread_create (threads->query,
484                                    threads->query->notmuch,
485                                    doc_id,
486                                    &threads->match_set,
487                                    threads->query->exclude_terms,
488                                    threads->query->sort);
489 }
490
491 void
492 notmuch_threads_move_to_next (notmuch_threads_t *threads)
493 {
494     threads->doc_id_pos++;
495 }
496
497 void
498 notmuch_threads_destroy (notmuch_threads_t *threads)
499 {
500     talloc_free (threads);
501 }
502
503 unsigned
504 notmuch_query_count_messages (notmuch_query_t *query)
505 {
506     notmuch_database_t *notmuch = query->notmuch;
507     const char *query_string = query->query_string;
508     Xapian::doccount count = 0;
509
510     try {
511         Xapian::Enquire enquire (*notmuch->xapian_db);
512         Xapian::Query mail_query (talloc_asprintf (query, "%s%s",
513                                                    _find_prefix ("type"),
514                                                    "mail"));
515         Xapian::Query string_query, final_query, exclude_query;
516         Xapian::MSet mset;
517         unsigned int flags = (Xapian::QueryParser::FLAG_BOOLEAN |
518                               Xapian::QueryParser::FLAG_PHRASE |
519                               Xapian::QueryParser::FLAG_LOVEHATE |
520                               Xapian::QueryParser::FLAG_BOOLEAN_ANY_CASE |
521                               Xapian::QueryParser::FLAG_WILDCARD |
522                               Xapian::QueryParser::FLAG_PURE_NOT);
523
524         if (strcmp (query_string, "") == 0 ||
525             strcmp (query_string, "*") == 0)
526         {
527             final_query = mail_query;
528         } else {
529             string_query = notmuch->query_parser->
530                 parse_query (query_string, flags);
531             final_query = Xapian::Query (Xapian::Query::OP_AND,
532                                          mail_query, string_query);
533         }
534
535         exclude_query = _notmuch_exclude_tags (query, final_query);
536
537         final_query = Xapian::Query (Xapian::Query::OP_AND_NOT,
538                                          final_query, exclude_query);
539
540         enquire.set_weighting_scheme(Xapian::BoolWeight());
541         enquire.set_docid_order(Xapian::Enquire::ASCENDING);
542
543         if (_debug_query ()) {
544             fprintf (stderr, "Exclude query is:\n%s\n",
545                      exclude_query.get_description ().c_str ());
546             fprintf (stderr, "Final query is:\n%s\n",
547                      final_query.get_description ().c_str ());
548         }
549
550         enquire.set_query (final_query);
551
552         mset = enquire.get_mset (0, notmuch->xapian_db->get_doccount ());
553
554         count = mset.get_matches_estimated();
555
556     } catch (const Xapian::Error &error) {
557         fprintf (stderr, "A Xapian exception occurred: %s\n",
558                  error.get_msg().c_str());
559         fprintf (stderr, "Query string was: %s\n", query->query_string);
560     }
561
562     return count;
563 }
564
565 unsigned
566 notmuch_query_count_threads (notmuch_query_t *query)
567 {
568     notmuch_messages_t *messages;
569     GHashTable *hash;
570     unsigned int count;
571     notmuch_sort_t sort;
572
573     sort = query->sort;
574     query->sort = NOTMUCH_SORT_UNSORTED;
575     messages = notmuch_query_search_messages (query);
576     query->sort = sort;
577     if (messages == NULL)
578         return 0;
579
580     hash = g_hash_table_new_full (g_str_hash, g_str_equal, NULL, NULL);
581     if (hash == NULL) {
582         talloc_free (messages);
583         return 0;
584     }
585
586     while (notmuch_messages_valid (messages)) {
587         notmuch_message_t *message = notmuch_messages_get (messages);
588         const char *thread_id = notmuch_message_get_thread_id (message);
589         char *thread_id_copy = talloc_strdup (messages, thread_id);
590         if (unlikely (thread_id_copy == NULL)) {
591             notmuch_message_destroy (message);
592             count = 0;
593             goto DONE;
594         }
595         g_hash_table_insert (hash, thread_id_copy, NULL);
596         notmuch_message_destroy (message);
597         notmuch_messages_move_to_next (messages);
598     }
599
600     count = g_hash_table_size (hash);
601
602   DONE:
603     g_hash_table_unref (hash);
604     talloc_free (messages);
605
606     return count;
607 }