summaryrefslogtreecommitdiff
path: root/libzeitgeist/where-clause.vala
blob: 204e9b1ac64253338e1565eebac74232692829f3 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
/* where-clause.vala
 *
 * Copyright © 2011-2012 Collabora Ltd.
 *             By Siegfried-Angel Gevatter Pujals <siegfried@gevatter.com>
 *
 * Based upon a Python implementation (2009-2011) by:
 *  Markus Korn <thekorn@gmx.net>
 *  Mikkel Kamstrup Erlandsen <mikkel.kamstrup@gmail.com>
 *  Seif Lotfy <seif@lotfy.com>
 *  Siegfried-Angel Gevatter Pujals <siegfried@gevatter.com>
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation, either version 2.1 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 */

using Zeitgeist;

namespace Zeitgeist
{

    /**
     * This class provides a convenient representation a SQL `WHERE' clause,
     * composed of a set of conditions joined together.
     *
     * The relation between conditions can be either of type *AND* or *OR*, but
     * not both. To create more complex clauses, use several `WhereClause`
     * instances and joining them together using `extend`.
     *
     * Instances of this class can then be used to obtain a line of SQL code and
     * a list of arguments, for use with SQLite 3.
     */
    public class WhereClause : Object
    {

        public enum Type
        {
            AND,
            OR
        }

        private static string[] RELATION_SIGNS = { " AND ", " OR " };

        private WhereClause.Type clause_type;
        private bool negated;
        private GenericArray<string> conditions;
        private GenericArray<string> arguments;
        private bool is_simple;

        public WhereClause (WhereClause.Type type, bool negate=false)
        {
            clause_type = type;
            negated = negate;
            is_simple = true;
            conditions = new GenericArray<string> ();
            arguments = new GenericArray<string> ();
        }

        public int get_conditions_length()
        {
            return conditions.length;
        }

        public bool has_non_timestamp_condition() {
            for (int i=0; i<conditions.length; i++) {
                if (!conditions[i].has_prefix("timestamp"))
                    return true;
            }
            return false;
        }

        public void add (string condition, string? argument=null)
        {
            conditions.add (condition);
            if (argument != null)
                arguments.add (argument);
        }

        public void add_with_array (string condition,
            GenericArray<string> args)
        {
            conditions.add (condition);
            for (int i = 0; i < args.length; ++i)
                arguments.add (args[i]);
        }

        private static string get_search_table_for_column (string column)
        {
            string search_table;
            switch (column)
            {
                // For use in add_text_condition_subquery and
                // add_wildcard_condition:
                case "origin":
                case "subj_origin":
                case "subj_origin_current":
                case "subj_id":
                case "subj_id_current":
                    search_table = "uri";
                    break;
                case "subj_mimetype":
                    search_table = "mimetype";
                    break;

                // For use only in add_text_condition_subquery:
                case "subj_text_id":
                    search_table = "text";
                    break;
                case "subj_storage_id":
                    search_table = "storage";
                    break;

                // --
                default:
                    search_table = column;
                    break;
            }
            return search_table;
        }

        public void add_match_condition (string column, int val,
            bool negation=false)
        {
            string sql = "%s %s= %d".printf (column, (negation) ? "!" : "", val);
            add (sql);
        }

        public void add_text_condition_subquery (string column, string val,
            bool negation=false)
        {
            string search_table = get_search_table_for_column (column);
            string sql = "%s %s= (SELECT id FROM %s WHERE value = ?)".printf (
                column, (negation) ? "!" : "", search_table);
            add (sql, val);
            is_simple = false;
        }

        public void add_text_condition (string column, string val,
            bool negation=false)
        {
            string sql = "%s %s= ?".printf (column, (negation) ? "!" : "");
            add (sql, val);
        }

        public void add_wildcard_condition (string column, string needle,
            bool negation=false)
        {
            string search_table = get_search_table_for_column (column);

            var values = new GenericArray<string> ();
            values.add(needle);
            string optimized_glob = optimize_glob (
                "id", search_table, ref values);

            string sql;
            if (!negation)
                sql = "%s IN (%s)".printf (column, optimized_glob);
            else
                sql = "(%s NOT IN (%s) OR %s is NULL)".printf (column,
                    optimized_glob, column);
            add_with_array (sql, values);
            is_simple = false;
        }

        public void extend (WhereClause clause)
        {
            if (clause.is_empty ())
                return;
            string sql = clause.get_sql_conditions ();
            add_with_array (sql, clause.arguments);
            is_simple = clause.get_is_simple ();
            /*if not where.may_have_results():
            if self._relation == self.AND:
                self.clear()
            self.register_no_result()
            */
        }

        public bool is_empty ()
        {
            return conditions.length == 0;
        }

        public bool may_have_results ()
        {
            return conditions.length > 0; // or not self._no_result_member
        }

        public bool get_is_simple ()
        {
            return is_simple;
        }

        public void set_is_simple (bool simple)
        {
            is_simple = simple;
        }

        /**
         * This is dangerous. Only use it if you're made full of awesome.
         */
        private T[] generic_array_to_unowned_array<T> (GenericArray<T> gptrarr)
        {
#if VALA_0_24
            long[] pointers = new long[gptrarr.length];
#else
            long[] pointers = new long[gptrarr.length + 1];
#endif
            Memory.copy(pointers, ((PtrArray *) gptrarr)->pdata,
                gptrarr.length * sizeof (void *));
            return (T[]) pointers;
        }

        public string get_sql_conditions ()
        {
            assert (conditions.length > 0);
            string negation_sign = (negated) ? "NOT " : "";
            string relation_sign = RELATION_SIGNS[clause_type];

            if (conditions.length == 1)
                return "%s%s".printf (negation_sign, conditions[0]);
            string conditions_string = string.joinv (relation_sign,
                generic_array_to_unowned_array<string> (conditions));
            return "%s(%s)".printf (negation_sign, conditions_string);
        }

        public unowned GenericArray<string> get_bind_arguments ()
        {
            return arguments;
        }

        /**
         * Return an optimized version of the GLOB statement as described in
         * http://www.sqlite.org/optoverview.html "4.0 The LIKE optimization".
         */
        private static string optimize_glob (string column, string table,
            ref GenericArray<string> args)
            requires (args.length == 1)
        {
            string sql;
            string prefix = args[0];
            if (prefix == "") {
                sql = "SELECT %s FROM %s".printf (column, table);
            }
            else if (false) // ...
            {
                // FIXME: check for all(i == unichr(0x10ffff)...)
            }
            else
            {
                sql = "SELECT %s FROM %s WHERE (value >= ? AND value < ?)"
                    .printf (column, table);
                args.add (get_right_boundary (prefix));
            }
            return sql;
        }

        /**
         * Return the smallest string which is greater than the given `text`.
         */
        protected static string get_right_boundary (string text)
        {
            if (text == "")
                return new StringBuilder ().append_unichar(0x10ffff).str;
            int len = text.char_count () - 1;
            unichar charpoint = text.get_char (text.index_of_nth_char (len));
            string head = text.substring (0, text.index_of_nth_char (len));
            if (charpoint == 0x10ffff)
            {
                // If the last char is the biggest possible char we need to
                // look at the second last.
                return get_right_boundary (head);
            }
            return head +
                new StringBuilder ().append_unichar(charpoint + 1).str;
        }

    }

}

// vim:expandtab:ts=4:sw=4