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