]> git.notmuchmail.org Git - notmuch/blob - lib/query.cc
Add internal functions to search for alternate doc types
[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_exclude_t omit_excluded;
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 char *bitmap;
43     unsigned int bound;
44 };
45
46 #define DOCIDSET_WORD(bit) ((bit) / CHAR_BIT)
47 #define DOCIDSET_BIT(bit) ((bit) % CHAR_BIT)
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 (notmuch, 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 = NOTMUCH_EXCLUDE_TRUE;
96
97     return query;
98 }
99
100 const char *
101 notmuch_query_get_query_string (const notmuch_query_t *query)
102 {
103     return query->query_string;
104 }
105
106 void
107 notmuch_query_set_omit_excluded (notmuch_query_t *query,
108                                  notmuch_exclude_t omit_excluded)
109 {
110     query->omit_excluded = omit_excluded;
111 }
112
113 void
114 notmuch_query_set_sort (notmuch_query_t *query, notmuch_sort_t sort)
115 {
116     query->sort = sort;
117 }
118
119 notmuch_sort_t
120 notmuch_query_get_sort (const notmuch_query_t *query)
121 {
122     return query->sort;
123 }
124
125 void
126 notmuch_query_add_tag_exclude (notmuch_query_t *query, const char *tag)
127 {
128     char *term = talloc_asprintf (query, "%s%s", _find_prefix ("tag"), tag);
129     _notmuch_string_list_append (query->exclude_terms, term);
130 }
131
132 /* We end up having to call the destructors explicitly because we had
133  * to use "placement new" in order to initialize C++ objects within a
134  * block that we allocated with talloc. So C++ is making talloc
135  * slightly less simple to use, (we wouldn't need
136  * talloc_set_destructor at all otherwise).
137  */
138 static int
139 _notmuch_messages_destructor (notmuch_mset_messages_t *messages)
140 {
141     messages->iterator.~MSetIterator ();
142     messages->iterator_end.~MSetIterator ();
143
144     return 0;
145 }
146
147 /* Return a query that matches messages with the excluded tags
148  * registered with query.  Any tags that explicitly appear in xquery
149  * will not be excluded, and will be removed from the list of exclude
150  * tags.  The caller of this function has to combine the returned
151  * query appropriately.*/
152 static Xapian::Query
153 _notmuch_exclude_tags (notmuch_query_t *query, Xapian::Query xquery)
154 {
155     Xapian::Query exclude_query = Xapian::Query::MatchNothing;
156
157     for (notmuch_string_node_t *term = query->exclude_terms->head; term;
158          term = term->next) {
159         Xapian::TermIterator it = xquery.get_terms_begin ();
160         Xapian::TermIterator end = xquery.get_terms_end ();
161         for (; it != end; it++) {
162             if ((*it).compare (term->string) == 0)
163                 break;
164         }
165         if (it == end)
166             exclude_query = Xapian::Query (Xapian::Query::OP_OR,
167                                     exclude_query, Xapian::Query (term->string));
168         else
169             term->string = talloc_strdup (query, "");
170     }
171     return exclude_query;
172 }
173
174 notmuch_messages_t *
175 notmuch_query_search_messages (notmuch_query_t *query)
176 {
177     notmuch_status_t status;
178     notmuch_messages_t *messages;
179     status = notmuch_query_search_messages_st (query, &messages);
180     if (status)
181         return NULL;
182     else
183         return messages;
184 }
185
186 notmuch_status_t
187 notmuch_query_search_messages_st (notmuch_query_t *query,
188                                   notmuch_messages_t **out)
189 {
190     return _notmuch_query_search_documents (query, "mail", out);
191 }
192
193 notmuch_status_t
194 _notmuch_query_search_documents (notmuch_query_t *query,
195                                  const char *type,
196                                  notmuch_messages_t **out)
197 {
198     notmuch_database_t *notmuch = query->notmuch;
199     const char *query_string = query->query_string;
200     notmuch_mset_messages_t *messages;
201
202     messages = talloc (query, notmuch_mset_messages_t);
203     if (unlikely (messages == NULL))
204         return NOTMUCH_STATUS_OUT_OF_MEMORY;
205
206     try {
207
208         messages->base.is_of_list_type = FALSE;
209         messages->base.iterator = NULL;
210         messages->notmuch = notmuch;
211         new (&messages->iterator) Xapian::MSetIterator ();
212         new (&messages->iterator_end) Xapian::MSetIterator ();
213
214         talloc_set_destructor (messages, _notmuch_messages_destructor);
215
216         Xapian::Enquire enquire (*notmuch->xapian_db);
217         Xapian::Query mail_query (talloc_asprintf (query, "%s%s",
218                                                    _find_prefix ("type"),
219                                                    type));
220         Xapian::Query string_query, final_query, exclude_query;
221         Xapian::MSet mset;
222         Xapian::MSetIterator iterator;
223         unsigned int flags = (Xapian::QueryParser::FLAG_BOOLEAN |
224                               Xapian::QueryParser::FLAG_PHRASE |
225                               Xapian::QueryParser::FLAG_LOVEHATE |
226                               Xapian::QueryParser::FLAG_BOOLEAN_ANY_CASE |
227                               Xapian::QueryParser::FLAG_WILDCARD |
228                               Xapian::QueryParser::FLAG_PURE_NOT);
229
230         if (strcmp (query_string, "") == 0 ||
231             strcmp (query_string, "*") == 0)
232         {
233             final_query = mail_query;
234         } else {
235             string_query = notmuch->query_parser->
236                 parse_query (query_string, flags);
237             final_query = Xapian::Query (Xapian::Query::OP_AND,
238                                          mail_query, string_query);
239         }
240         messages->base.excluded_doc_ids = NULL;
241
242         if ((query->omit_excluded != NOTMUCH_EXCLUDE_FALSE) && (query->exclude_terms)) {
243             exclude_query = _notmuch_exclude_tags (query, final_query);
244
245             if (query->omit_excluded == NOTMUCH_EXCLUDE_TRUE ||
246                 query->omit_excluded == NOTMUCH_EXCLUDE_ALL)
247             {
248                 final_query = Xapian::Query (Xapian::Query::OP_AND_NOT,
249                                              final_query, exclude_query);
250             } else { /* NOTMUCH_EXCLUDE_FLAG */
251                 exclude_query = Xapian::Query (Xapian::Query::OP_AND,
252                                            exclude_query, final_query);
253
254                 enquire.set_weighting_scheme (Xapian::BoolWeight());
255                 enquire.set_query (exclude_query);
256
257                 mset = enquire.get_mset (0, notmuch->xapian_db->get_doccount ());
258
259                 GArray *excluded_doc_ids = g_array_new (FALSE, FALSE, sizeof (unsigned int));
260
261                 for (iterator = mset.begin (); iterator != mset.end (); iterator++) {
262                     unsigned int doc_id = *iterator;
263                     g_array_append_val (excluded_doc_ids, doc_id);
264                 }
265                 messages->base.excluded_doc_ids = talloc (messages, _notmuch_doc_id_set);
266                 _notmuch_doc_id_set_init (query, messages->base.excluded_doc_ids,
267                                           excluded_doc_ids);
268                 g_array_unref (excluded_doc_ids);
269             }
270         }
271
272
273         enquire.set_weighting_scheme (Xapian::BoolWeight());
274
275         switch (query->sort) {
276         case NOTMUCH_SORT_OLDEST_FIRST:
277             enquire.set_sort_by_value (NOTMUCH_VALUE_TIMESTAMP, FALSE);
278             break;
279         case NOTMUCH_SORT_NEWEST_FIRST:
280             enquire.set_sort_by_value (NOTMUCH_VALUE_TIMESTAMP, TRUE);
281             break;
282         case NOTMUCH_SORT_MESSAGE_ID:
283             enquire.set_sort_by_value (NOTMUCH_VALUE_MESSAGE_ID, FALSE);
284             break;
285         case NOTMUCH_SORT_UNSORTED:
286             break;
287         }
288
289         if (_debug_query ()) {
290             fprintf (stderr, "Exclude query is:\n%s\n",
291                      exclude_query.get_description ().c_str ());
292             fprintf (stderr, "Final query is:\n%s\n",
293                      final_query.get_description ().c_str ());
294         }
295
296         enquire.set_query (final_query);
297
298         mset = enquire.get_mset (0, notmuch->xapian_db->get_doccount ());
299
300         messages->iterator = mset.begin ();
301         messages->iterator_end = mset.end ();
302
303         *out = &messages->base;
304         return NOTMUCH_STATUS_SUCCESS;
305
306     } catch (const Xapian::Error &error) {
307         _notmuch_database_log (notmuch,
308                                "A Xapian exception occurred performing query: %s\n"
309                                "Query string was: %s\n",
310                                error.get_msg().c_str(),
311                                query->query_string);
312
313         notmuch->exception_reported = TRUE;
314         talloc_free (messages);
315         return NOTMUCH_STATUS_XAPIAN_EXCEPTION;
316     }
317 }
318
319 notmuch_bool_t
320 _notmuch_mset_messages_valid (notmuch_messages_t *messages)
321 {
322     notmuch_mset_messages_t *mset_messages;
323
324     mset_messages = (notmuch_mset_messages_t *) messages;
325
326     return (mset_messages->iterator != mset_messages->iterator_end);
327 }
328
329 static Xapian::docid
330 _notmuch_mset_messages_get_doc_id (notmuch_messages_t *messages)
331 {
332     notmuch_mset_messages_t *mset_messages;
333
334     mset_messages = (notmuch_mset_messages_t *) messages;
335
336     if (! _notmuch_mset_messages_valid (&mset_messages->base))
337         return 0;
338
339     return *mset_messages->iterator;
340 }
341
342 notmuch_message_t *
343 _notmuch_mset_messages_get (notmuch_messages_t *messages)
344 {
345     notmuch_message_t *message;
346     Xapian::docid doc_id;
347     notmuch_private_status_t status;
348     notmuch_mset_messages_t *mset_messages;
349
350     mset_messages = (notmuch_mset_messages_t *) messages;
351
352     if (! _notmuch_mset_messages_valid (&mset_messages->base))
353         return NULL;
354
355     doc_id = *mset_messages->iterator;
356
357     message = _notmuch_message_create (mset_messages,
358                                        mset_messages->notmuch, doc_id,
359                                        &status);
360
361     if (message == NULL &&
362        status == NOTMUCH_PRIVATE_STATUS_NO_DOCUMENT_FOUND)
363     {
364         INTERNAL_ERROR ("a messages iterator contains a non-existent document ID.\n");
365     }
366
367     if (messages->excluded_doc_ids &&
368         _notmuch_doc_id_set_contains (messages->excluded_doc_ids, doc_id))
369         notmuch_message_set_flag (message, NOTMUCH_MESSAGE_FLAG_EXCLUDED, TRUE);
370
371     return message;
372 }
373
374 void
375 _notmuch_mset_messages_move_to_next (notmuch_messages_t *messages)
376 {
377     notmuch_mset_messages_t *mset_messages;
378
379     mset_messages = (notmuch_mset_messages_t *) messages;
380
381     mset_messages->iterator++;
382 }
383
384 static notmuch_bool_t
385 _notmuch_doc_id_set_init (void *ctx,
386                           notmuch_doc_id_set_t *doc_ids,
387                           GArray *arr)
388 {
389     unsigned int max = 0;
390     unsigned char *bitmap;
391
392     for (unsigned int i = 0; i < arr->len; i++)
393         max = MAX(max, g_array_index (arr, unsigned int, i));
394     bitmap = talloc_zero_array (ctx, unsigned char, DOCIDSET_WORD(max) + 1);
395
396     if (bitmap == NULL)
397         return FALSE;
398
399     doc_ids->bitmap = bitmap;
400     doc_ids->bound = max + 1;
401
402     for (unsigned int i = 0; i < arr->len; i++) {
403         unsigned int doc_id = g_array_index (arr, unsigned int, i);
404         bitmap[DOCIDSET_WORD(doc_id)] |= 1 << DOCIDSET_BIT(doc_id);
405     }
406
407     return TRUE;
408 }
409
410 notmuch_bool_t
411 _notmuch_doc_id_set_contains (notmuch_doc_id_set_t *doc_ids,
412                               unsigned int doc_id)
413 {
414     if (doc_id >= doc_ids->bound)
415         return FALSE;
416     return doc_ids->bitmap[DOCIDSET_WORD(doc_id)] & (1 << DOCIDSET_BIT(doc_id));
417 }
418
419 void
420 _notmuch_doc_id_set_remove (notmuch_doc_id_set_t *doc_ids,
421                             unsigned int doc_id)
422 {
423     if (doc_id < doc_ids->bound)
424         doc_ids->bitmap[DOCIDSET_WORD(doc_id)] &= ~(1 << DOCIDSET_BIT(doc_id));
425 }
426
427 /* Glib objects force use to use a talloc destructor as well, (but not
428  * nearly as ugly as the for messages due to C++ objects). At
429  * this point, I'd really like to have some talloc-friendly
430  * equivalents for the few pieces of glib that I'm using. */
431 static int
432 _notmuch_threads_destructor (notmuch_threads_t *threads)
433 {
434     if (threads->doc_ids)
435         g_array_unref (threads->doc_ids);
436
437     return 0;
438 }
439
440
441 notmuch_threads_t *
442 notmuch_query_search_threads (notmuch_query_t *query)
443 {
444     notmuch_status_t status;
445     notmuch_threads_t *threads;
446     status = notmuch_query_search_threads_st (query, &threads);
447     if (status)
448         return NULL;
449     else
450         return threads;
451 }
452
453 notmuch_status_t
454 notmuch_query_search_threads_st (notmuch_query_t *query,
455                                  notmuch_threads_t **out)
456 {
457     notmuch_threads_t *threads;
458     notmuch_messages_t *messages;
459     notmuch_status_t status;
460
461     threads = talloc (query, notmuch_threads_t);
462     if (threads == NULL)
463         return NOTMUCH_STATUS_OUT_OF_MEMORY;
464     threads->doc_ids = NULL;
465     talloc_set_destructor (threads, _notmuch_threads_destructor);
466
467     threads->query = query;
468
469     status = notmuch_query_search_messages_st (query, &messages);
470     if (status) {
471         talloc_free (threads);
472         return status;
473     }
474
475     threads->doc_ids = g_array_new (FALSE, FALSE, sizeof (unsigned int));
476     while (notmuch_messages_valid (messages)) {
477         unsigned int doc_id = _notmuch_mset_messages_get_doc_id (messages);
478         g_array_append_val (threads->doc_ids, doc_id);
479         notmuch_messages_move_to_next (messages);
480     }
481     threads->doc_id_pos = 0;
482
483     talloc_free (messages);
484
485     if (! _notmuch_doc_id_set_init (threads, &threads->match_set,
486                                     threads->doc_ids)) {
487         talloc_free (threads);
488         return NOTMUCH_STATUS_OUT_OF_MEMORY;
489     }
490
491     *out = threads;
492     return NOTMUCH_STATUS_SUCCESS;
493 }
494
495 void
496 notmuch_query_destroy (notmuch_query_t *query)
497 {
498     talloc_free (query);
499 }
500
501 notmuch_bool_t
502 notmuch_threads_valid (notmuch_threads_t *threads)
503 {
504     unsigned int doc_id;
505
506     if (! threads)
507         return FALSE;
508
509     while (threads->doc_id_pos < threads->doc_ids->len) {
510         doc_id = g_array_index (threads->doc_ids, unsigned int,
511                                 threads->doc_id_pos);
512         if (_notmuch_doc_id_set_contains (&threads->match_set, doc_id))
513             break;
514
515         threads->doc_id_pos++;
516     }
517
518     return threads->doc_id_pos < threads->doc_ids->len;
519 }
520
521 notmuch_thread_t *
522 notmuch_threads_get (notmuch_threads_t *threads)
523 {
524     unsigned int doc_id;
525
526     if (! notmuch_threads_valid (threads))
527         return NULL;
528
529     doc_id = g_array_index (threads->doc_ids, unsigned int,
530                             threads->doc_id_pos);
531     return _notmuch_thread_create (threads->query,
532                                    threads->query->notmuch,
533                                    doc_id,
534                                    &threads->match_set,
535                                    threads->query->exclude_terms,
536                                    threads->query->omit_excluded,
537                                    threads->query->sort);
538 }
539
540 void
541 notmuch_threads_move_to_next (notmuch_threads_t *threads)
542 {
543     threads->doc_id_pos++;
544 }
545
546 void
547 notmuch_threads_destroy (notmuch_threads_t *threads)
548 {
549     talloc_free (threads);
550 }
551
552 unsigned int
553 notmuch_query_count_messages (notmuch_query_t *query)
554 {
555     notmuch_status_t status;
556     unsigned int count;
557
558     status = notmuch_query_count_messages_st (query, &count);
559     return status ? 0 : count;
560 }
561
562 notmuch_status_t
563 notmuch_query_count_messages_st (notmuch_query_t *query, unsigned *count_out)
564 {
565     return _notmuch_query_count_documents (query, "mail", count_out);
566 }
567
568 notmuch_status_t
569 _notmuch_query_count_documents (notmuch_query_t *query, const char *type, unsigned *count_out)
570 {
571     notmuch_database_t *notmuch = query->notmuch;
572     const char *query_string = query->query_string;
573     Xapian::doccount count = 0;
574
575     try {
576         Xapian::Enquire enquire (*notmuch->xapian_db);
577         Xapian::Query mail_query (talloc_asprintf (query, "%s%s",
578                                                    _find_prefix ("type"),
579                                                    type));
580         Xapian::Query string_query, final_query, exclude_query;
581         Xapian::MSet mset;
582         unsigned int flags = (Xapian::QueryParser::FLAG_BOOLEAN |
583                               Xapian::QueryParser::FLAG_PHRASE |
584                               Xapian::QueryParser::FLAG_LOVEHATE |
585                               Xapian::QueryParser::FLAG_BOOLEAN_ANY_CASE |
586                               Xapian::QueryParser::FLAG_WILDCARD |
587                               Xapian::QueryParser::FLAG_PURE_NOT);
588
589         if (strcmp (query_string, "") == 0 ||
590             strcmp (query_string, "*") == 0)
591         {
592             final_query = mail_query;
593         } else {
594             string_query = notmuch->query_parser->
595                 parse_query (query_string, flags);
596             final_query = Xapian::Query (Xapian::Query::OP_AND,
597                                          mail_query, string_query);
598         }
599
600         exclude_query = _notmuch_exclude_tags (query, final_query);
601
602         final_query = Xapian::Query (Xapian::Query::OP_AND_NOT,
603                                          final_query, exclude_query);
604
605         enquire.set_weighting_scheme(Xapian::BoolWeight());
606         enquire.set_docid_order(Xapian::Enquire::ASCENDING);
607
608         if (_debug_query ()) {
609             fprintf (stderr, "Exclude query is:\n%s\n",
610                      exclude_query.get_description ().c_str ());
611             fprintf (stderr, "Final query is:\n%s\n",
612                      final_query.get_description ().c_str ());
613         }
614
615         enquire.set_query (final_query);
616
617         /*
618          * Set the checkatleast parameter to the number of documents
619          * in the database to make get_matches_estimated() exact.
620          */
621         mset = enquire.get_mset (0, notmuch->xapian_db->get_doccount (),
622                                  notmuch->xapian_db->get_doccount ());
623
624         count = mset.get_matches_estimated();
625
626     } catch (const Xapian::Error &error) {
627         _notmuch_database_log (notmuch,
628                                "A Xapian exception occurred performing query: %s\n"
629                                "Query string was: %s\n",
630                                error.get_msg().c_str(),
631                                query->query_string);
632         return NOTMUCH_STATUS_XAPIAN_EXCEPTION;
633     }
634
635     *count_out = count;
636     return NOTMUCH_STATUS_SUCCESS;
637 }
638
639 unsigned
640 notmuch_query_count_threads (notmuch_query_t *query)
641 {
642     notmuch_status_t status;
643     unsigned int count;
644
645     status = notmuch_query_count_threads_st (query, &count);
646     return status ? 0 : count;
647 }
648
649 notmuch_status_t
650 notmuch_query_count_threads_st (notmuch_query_t *query, unsigned *count)
651 {
652     notmuch_messages_t *messages;
653     GHashTable *hash;
654     notmuch_sort_t sort;
655     notmuch_status_t ret = NOTMUCH_STATUS_SUCCESS;
656
657     sort = query->sort;
658     query->sort = NOTMUCH_SORT_UNSORTED;
659     ret = notmuch_query_search_messages_st (query, &messages);
660     if (ret)
661         return ret;
662     query->sort = sort;
663     if (messages == NULL)
664         return NOTMUCH_STATUS_XAPIAN_EXCEPTION;
665
666     hash = g_hash_table_new_full (g_str_hash, g_str_equal, NULL, NULL);
667     if (hash == NULL) {
668         talloc_free (messages);
669         return NOTMUCH_STATUS_OUT_OF_MEMORY;
670     }
671
672     while (notmuch_messages_valid (messages)) {
673         notmuch_message_t *message = notmuch_messages_get (messages);
674         const char *thread_id = notmuch_message_get_thread_id (message);
675         char *thread_id_copy = talloc_strdup (messages, thread_id);
676         if (unlikely (thread_id_copy == NULL)) {
677             notmuch_message_destroy (message);
678             ret = NOTMUCH_STATUS_OUT_OF_MEMORY;
679             goto DONE;
680         }
681         g_hash_table_insert (hash, thread_id_copy, NULL);
682         notmuch_message_destroy (message);
683         notmuch_messages_move_to_next (messages);
684     }
685
686     *count = g_hash_table_size (hash);
687
688   DONE:
689     g_hash_table_unref (hash);
690     talloc_free (messages);
691
692     return ret;
693 }
694
695 notmuch_database_t *
696 notmuch_query_get_database (const notmuch_query_t *query)
697 {
698     return query->notmuch;
699 }