lib: constify arguments to notmuch_query_get_*
[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     notmuch_database_t *notmuch = query->notmuch;
191     const char *query_string = query->query_string;
192     notmuch_mset_messages_t *messages;
193
194     messages = talloc (query, notmuch_mset_messages_t);
195     if (unlikely (messages == NULL))
196         return NOTMUCH_STATUS_OUT_OF_MEMORY;
197
198     try {
199
200         messages->base.is_of_list_type = FALSE;
201         messages->base.iterator = NULL;
202         messages->notmuch = notmuch;
203         new (&messages->iterator) Xapian::MSetIterator ();
204         new (&messages->iterator_end) Xapian::MSetIterator ();
205
206         talloc_set_destructor (messages, _notmuch_messages_destructor);
207
208         Xapian::Enquire enquire (*notmuch->xapian_db);
209         Xapian::Query mail_query (talloc_asprintf (query, "%s%s",
210                                                    _find_prefix ("type"),
211                                                    "mail"));
212         Xapian::Query string_query, final_query, exclude_query;
213         Xapian::MSet mset;
214         Xapian::MSetIterator iterator;
215         unsigned int flags = (Xapian::QueryParser::FLAG_BOOLEAN |
216                               Xapian::QueryParser::FLAG_PHRASE |
217                               Xapian::QueryParser::FLAG_LOVEHATE |
218                               Xapian::QueryParser::FLAG_BOOLEAN_ANY_CASE |
219                               Xapian::QueryParser::FLAG_WILDCARD |
220                               Xapian::QueryParser::FLAG_PURE_NOT);
221
222         if (strcmp (query_string, "") == 0 ||
223             strcmp (query_string, "*") == 0)
224         {
225             final_query = mail_query;
226         } else {
227             string_query = notmuch->query_parser->
228                 parse_query (query_string, flags);
229             final_query = Xapian::Query (Xapian::Query::OP_AND,
230                                          mail_query, string_query);
231         }
232         messages->base.excluded_doc_ids = NULL;
233
234         if ((query->omit_excluded != NOTMUCH_EXCLUDE_FALSE) && (query->exclude_terms)) {
235             exclude_query = _notmuch_exclude_tags (query, final_query);
236
237             if (query->omit_excluded == NOTMUCH_EXCLUDE_TRUE ||
238                 query->omit_excluded == NOTMUCH_EXCLUDE_ALL)
239             {
240                 final_query = Xapian::Query (Xapian::Query::OP_AND_NOT,
241                                              final_query, exclude_query);
242             } else { /* NOTMUCH_EXCLUDE_FLAG */
243                 exclude_query = Xapian::Query (Xapian::Query::OP_AND,
244                                            exclude_query, final_query);
245
246                 enquire.set_weighting_scheme (Xapian::BoolWeight());
247                 enquire.set_query (exclude_query);
248
249                 mset = enquire.get_mset (0, notmuch->xapian_db->get_doccount ());
250
251                 GArray *excluded_doc_ids = g_array_new (FALSE, FALSE, sizeof (unsigned int));
252
253                 for (iterator = mset.begin (); iterator != mset.end (); iterator++) {
254                     unsigned int doc_id = *iterator;
255                     g_array_append_val (excluded_doc_ids, doc_id);
256                 }
257                 messages->base.excluded_doc_ids = talloc (messages, _notmuch_doc_id_set);
258                 _notmuch_doc_id_set_init (query, messages->base.excluded_doc_ids,
259                                           excluded_doc_ids);
260                 g_array_unref (excluded_doc_ids);
261             }
262         }
263
264
265         enquire.set_weighting_scheme (Xapian::BoolWeight());
266
267         switch (query->sort) {
268         case NOTMUCH_SORT_OLDEST_FIRST:
269             enquire.set_sort_by_value (NOTMUCH_VALUE_TIMESTAMP, FALSE);
270             break;
271         case NOTMUCH_SORT_NEWEST_FIRST:
272             enquire.set_sort_by_value (NOTMUCH_VALUE_TIMESTAMP, TRUE);
273             break;
274         case NOTMUCH_SORT_MESSAGE_ID:
275             enquire.set_sort_by_value (NOTMUCH_VALUE_MESSAGE_ID, FALSE);
276             break;
277         case NOTMUCH_SORT_UNSORTED:
278             break;
279         }
280
281         if (_debug_query ()) {
282             fprintf (stderr, "Exclude query is:\n%s\n",
283                      exclude_query.get_description ().c_str ());
284             fprintf (stderr, "Final query is:\n%s\n",
285                      final_query.get_description ().c_str ());
286         }
287
288         enquire.set_query (final_query);
289
290         mset = enquire.get_mset (0, notmuch->xapian_db->get_doccount ());
291
292         messages->iterator = mset.begin ();
293         messages->iterator_end = mset.end ();
294
295         *out = &messages->base;
296         return NOTMUCH_STATUS_SUCCESS;
297
298     } catch (const Xapian::Error &error) {
299         _notmuch_database_log (notmuch,
300                                "A Xapian exception occurred performing query: %s\n"
301                                "Query string was: %s\n",
302                                error.get_msg().c_str(),
303                                query->query_string);
304
305         notmuch->exception_reported = TRUE;
306         talloc_free (messages);
307         return NOTMUCH_STATUS_XAPIAN_EXCEPTION;
308     }
309 }
310
311 notmuch_bool_t
312 _notmuch_mset_messages_valid (notmuch_messages_t *messages)
313 {
314     notmuch_mset_messages_t *mset_messages;
315
316     mset_messages = (notmuch_mset_messages_t *) messages;
317
318     return (mset_messages->iterator != mset_messages->iterator_end);
319 }
320
321 static Xapian::docid
322 _notmuch_mset_messages_get_doc_id (notmuch_messages_t *messages)
323 {
324     notmuch_mset_messages_t *mset_messages;
325
326     mset_messages = (notmuch_mset_messages_t *) messages;
327
328     if (! _notmuch_mset_messages_valid (&mset_messages->base))
329         return 0;
330
331     return *mset_messages->iterator;
332 }
333
334 notmuch_message_t *
335 _notmuch_mset_messages_get (notmuch_messages_t *messages)
336 {
337     notmuch_message_t *message;
338     Xapian::docid doc_id;
339     notmuch_private_status_t status;
340     notmuch_mset_messages_t *mset_messages;
341
342     mset_messages = (notmuch_mset_messages_t *) messages;
343
344     if (! _notmuch_mset_messages_valid (&mset_messages->base))
345         return NULL;
346
347     doc_id = *mset_messages->iterator;
348
349     message = _notmuch_message_create (mset_messages,
350                                        mset_messages->notmuch, doc_id,
351                                        &status);
352
353     if (message == NULL &&
354        status == NOTMUCH_PRIVATE_STATUS_NO_DOCUMENT_FOUND)
355     {
356         INTERNAL_ERROR ("a messages iterator contains a non-existent document ID.\n");
357     }
358
359     if (messages->excluded_doc_ids &&
360         _notmuch_doc_id_set_contains (messages->excluded_doc_ids, doc_id))
361         notmuch_message_set_flag (message, NOTMUCH_MESSAGE_FLAG_EXCLUDED, TRUE);
362
363     return message;
364 }
365
366 void
367 _notmuch_mset_messages_move_to_next (notmuch_messages_t *messages)
368 {
369     notmuch_mset_messages_t *mset_messages;
370
371     mset_messages = (notmuch_mset_messages_t *) messages;
372
373     mset_messages->iterator++;
374 }
375
376 static notmuch_bool_t
377 _notmuch_doc_id_set_init (void *ctx,
378                           notmuch_doc_id_set_t *doc_ids,
379                           GArray *arr)
380 {
381     unsigned int max = 0;
382     unsigned char *bitmap;
383
384     for (unsigned int i = 0; i < arr->len; i++)
385         max = MAX(max, g_array_index (arr, unsigned int, i));
386     bitmap = talloc_zero_array (ctx, unsigned char, DOCIDSET_WORD(max) + 1);
387
388     if (bitmap == NULL)
389         return FALSE;
390
391     doc_ids->bitmap = bitmap;
392     doc_ids->bound = max + 1;
393
394     for (unsigned int i = 0; i < arr->len; i++) {
395         unsigned int doc_id = g_array_index (arr, unsigned int, i);
396         bitmap[DOCIDSET_WORD(doc_id)] |= 1 << DOCIDSET_BIT(doc_id);
397     }
398
399     return TRUE;
400 }
401
402 notmuch_bool_t
403 _notmuch_doc_id_set_contains (notmuch_doc_id_set_t *doc_ids,
404                               unsigned int doc_id)
405 {
406     if (doc_id >= doc_ids->bound)
407         return FALSE;
408     return doc_ids->bitmap[DOCIDSET_WORD(doc_id)] & (1 << DOCIDSET_BIT(doc_id));
409 }
410
411 void
412 _notmuch_doc_id_set_remove (notmuch_doc_id_set_t *doc_ids,
413                             unsigned int doc_id)
414 {
415     if (doc_id < doc_ids->bound)
416         doc_ids->bitmap[DOCIDSET_WORD(doc_id)] &= ~(1 << DOCIDSET_BIT(doc_id));
417 }
418
419 /* Glib objects force use to use a talloc destructor as well, (but not
420  * nearly as ugly as the for messages due to C++ objects). At
421  * this point, I'd really like to have some talloc-friendly
422  * equivalents for the few pieces of glib that I'm using. */
423 static int
424 _notmuch_threads_destructor (notmuch_threads_t *threads)
425 {
426     if (threads->doc_ids)
427         g_array_unref (threads->doc_ids);
428
429     return 0;
430 }
431
432
433 notmuch_threads_t *
434 notmuch_query_search_threads (notmuch_query_t *query)
435 {
436     notmuch_status_t status;
437     notmuch_threads_t *threads;
438     status = notmuch_query_search_threads_st (query, &threads);
439     if (status)
440         return NULL;
441     else
442         return threads;
443 }
444
445 notmuch_status_t
446 notmuch_query_search_threads_st (notmuch_query_t *query,
447                                  notmuch_threads_t **out)
448 {
449     notmuch_threads_t *threads;
450     notmuch_messages_t *messages;
451     notmuch_status_t status;
452
453     threads = talloc (query, notmuch_threads_t);
454     if (threads == NULL)
455         return NOTMUCH_STATUS_OUT_OF_MEMORY;
456     threads->doc_ids = NULL;
457     talloc_set_destructor (threads, _notmuch_threads_destructor);
458
459     threads->query = query;
460
461     status = notmuch_query_search_messages_st (query, &messages);
462     if (status) {
463         talloc_free (threads);
464         return status;
465     }
466
467     threads->doc_ids = g_array_new (FALSE, FALSE, sizeof (unsigned int));
468     while (notmuch_messages_valid (messages)) {
469         unsigned int doc_id = _notmuch_mset_messages_get_doc_id (messages);
470         g_array_append_val (threads->doc_ids, doc_id);
471         notmuch_messages_move_to_next (messages);
472     }
473     threads->doc_id_pos = 0;
474
475     talloc_free (messages);
476
477     if (! _notmuch_doc_id_set_init (threads, &threads->match_set,
478                                     threads->doc_ids)) {
479         talloc_free (threads);
480         return NOTMUCH_STATUS_OUT_OF_MEMORY;
481     }
482
483     *out = threads;
484     return NOTMUCH_STATUS_SUCCESS;
485 }
486
487 void
488 notmuch_query_destroy (notmuch_query_t *query)
489 {
490     talloc_free (query);
491 }
492
493 notmuch_bool_t
494 notmuch_threads_valid (notmuch_threads_t *threads)
495 {
496     unsigned int doc_id;
497
498     if (! threads)
499         return FALSE;
500
501     while (threads->doc_id_pos < threads->doc_ids->len) {
502         doc_id = g_array_index (threads->doc_ids, unsigned int,
503                                 threads->doc_id_pos);
504         if (_notmuch_doc_id_set_contains (&threads->match_set, doc_id))
505             break;
506
507         threads->doc_id_pos++;
508     }
509
510     return threads->doc_id_pos < threads->doc_ids->len;
511 }
512
513 notmuch_thread_t *
514 notmuch_threads_get (notmuch_threads_t *threads)
515 {
516     unsigned int doc_id;
517
518     if (! notmuch_threads_valid (threads))
519         return NULL;
520
521     doc_id = g_array_index (threads->doc_ids, unsigned int,
522                             threads->doc_id_pos);
523     return _notmuch_thread_create (threads->query,
524                                    threads->query->notmuch,
525                                    doc_id,
526                                    &threads->match_set,
527                                    threads->query->exclude_terms,
528                                    threads->query->omit_excluded,
529                                    threads->query->sort);
530 }
531
532 void
533 notmuch_threads_move_to_next (notmuch_threads_t *threads)
534 {
535     threads->doc_id_pos++;
536 }
537
538 void
539 notmuch_threads_destroy (notmuch_threads_t *threads)
540 {
541     talloc_free (threads);
542 }
543
544 unsigned
545 notmuch_query_count_messages (notmuch_query_t *query)
546 {
547     notmuch_database_t *notmuch = query->notmuch;
548     const char *query_string = query->query_string;
549     Xapian::doccount count = 0;
550
551     try {
552         Xapian::Enquire enquire (*notmuch->xapian_db);
553         Xapian::Query mail_query (talloc_asprintf (query, "%s%s",
554                                                    _find_prefix ("type"),
555                                                    "mail"));
556         Xapian::Query string_query, final_query, exclude_query;
557         Xapian::MSet mset;
558         unsigned int flags = (Xapian::QueryParser::FLAG_BOOLEAN |
559                               Xapian::QueryParser::FLAG_PHRASE |
560                               Xapian::QueryParser::FLAG_LOVEHATE |
561                               Xapian::QueryParser::FLAG_BOOLEAN_ANY_CASE |
562                               Xapian::QueryParser::FLAG_WILDCARD |
563                               Xapian::QueryParser::FLAG_PURE_NOT);
564
565         if (strcmp (query_string, "") == 0 ||
566             strcmp (query_string, "*") == 0)
567         {
568             final_query = mail_query;
569         } else {
570             string_query = notmuch->query_parser->
571                 parse_query (query_string, flags);
572             final_query = Xapian::Query (Xapian::Query::OP_AND,
573                                          mail_query, string_query);
574         }
575
576         exclude_query = _notmuch_exclude_tags (query, final_query);
577
578         final_query = Xapian::Query (Xapian::Query::OP_AND_NOT,
579                                          final_query, exclude_query);
580
581         enquire.set_weighting_scheme(Xapian::BoolWeight());
582         enquire.set_docid_order(Xapian::Enquire::ASCENDING);
583
584         if (_debug_query ()) {
585             fprintf (stderr, "Exclude query is:\n%s\n",
586                      exclude_query.get_description ().c_str ());
587             fprintf (stderr, "Final query is:\n%s\n",
588                      final_query.get_description ().c_str ());
589         }
590
591         enquire.set_query (final_query);
592
593         /*
594          * Set the checkatleast parameter to the number of documents
595          * in the database to make get_matches_estimated() exact.
596          */
597         mset = enquire.get_mset (0, notmuch->xapian_db->get_doccount (),
598                                  notmuch->xapian_db->get_doccount ());
599
600         count = mset.get_matches_estimated();
601
602     } catch (const Xapian::Error &error) {
603         _notmuch_database_log (notmuch,
604                                "A Xapian exception occurred performing query: %s\n"
605                                "Query string was: %s\n",
606                                error.get_msg().c_str(),
607                                query->query_string);
608
609     }
610
611     return count;
612 }
613
614 unsigned
615 notmuch_query_count_threads (notmuch_query_t *query)
616 {
617     notmuch_messages_t *messages;
618     GHashTable *hash;
619     unsigned int count;
620     notmuch_sort_t sort;
621     notmuch_status_t status;
622
623     sort = query->sort;
624     query->sort = NOTMUCH_SORT_UNSORTED;
625     status = notmuch_query_search_messages_st (query, &messages);
626     if (status)
627         return 0;
628
629     query->sort = sort;
630     if (messages == NULL)
631         return 0;
632
633     hash = g_hash_table_new_full (g_str_hash, g_str_equal, NULL, NULL);
634     if (hash == NULL) {
635         talloc_free (messages);
636         return 0;
637     }
638
639     while (notmuch_messages_valid (messages)) {
640         notmuch_message_t *message = notmuch_messages_get (messages);
641         const char *thread_id = notmuch_message_get_thread_id (message);
642         char *thread_id_copy = talloc_strdup (messages, thread_id);
643         if (unlikely (thread_id_copy == NULL)) {
644             notmuch_message_destroy (message);
645             count = 0;
646             goto DONE;
647         }
648         g_hash_table_insert (hash, thread_id_copy, NULL);
649         notmuch_message_destroy (message);
650         notmuch_messages_move_to_next (messages);
651     }
652
653     count = g_hash_table_size (hash);
654
655   DONE:
656     g_hash_table_unref (hash);
657     talloc_free (messages);
658
659     return count;
660 }
661
662 notmuch_database_t *
663 notmuch_query_get_database (const notmuch_query_t *query)
664 {
665     return query->notmuch;
666 }