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