blob: c359178cf22981565e544e43368488b81f86e542 [file] [log] [blame]
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001/*
2 * Copyright (C) 2006 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package android.database.sqlite;
18
Jeff Sharkey50699422018-07-25 14:52:14 -060019import android.annotation.NonNull;
20import android.annotation.Nullable;
Mathew Inwoodf86bea92018-08-10 16:10:20 +010021import android.annotation.UnsupportedAppUsage;
Jeff Sharkey50699422018-07-25 14:52:14 -060022import android.content.ContentValues;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070023import android.database.Cursor;
24import android.database.DatabaseUtils;
Jeff Sharkey50699422018-07-25 14:52:14 -060025import android.os.Build;
Jeff Browna7771df2012-05-07 20:06:46 -070026import android.os.CancellationSignal;
27import android.os.OperationCanceledException;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070028import android.provider.BaseColumns;
29import android.text.TextUtils;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070030import android.util.Log;
31
Jeff Sharkey50699422018-07-25 14:52:14 -060032import libcore.util.EmptyArray;
33
34import java.util.Arrays;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070035import java.util.Iterator;
36import java.util.Map;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070037import java.util.Map.Entry;
Jeff Sharkey50699422018-07-25 14:52:14 -060038import java.util.Objects;
Daniel Lehmann50b1f8d2011-06-01 15:24:23 -070039import java.util.Set;
Owen Linab18d1f2009-05-06 16:45:59 -070040import java.util.regex.Pattern;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070041
42/**
Joshua Baxter3639e2f2018-03-26 14:55:14 -070043 * This is a convenience class that helps build SQL queries to be sent to
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070044 * {@link SQLiteDatabase} objects.
45 */
Jeff Sharkey0da04832018-07-26 14:36:59 -060046public class SQLiteQueryBuilder {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070047 private static final String TAG = "SQLiteQueryBuilder";
Owen Linab18d1f2009-05-06 16:45:59 -070048 private static final Pattern sLimitPattern =
49 Pattern.compile("\\s*\\d+\\s*(,\\s*\\d+\\s*)?");
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070050
51 private Map<String, String> mProjectionMap = null;
Mathew Inwood55418ea2018-12-20 15:30:45 +000052 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070053 private String mTables = "";
Mathew Inwood55418ea2018-12-20 15:30:45 +000054 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
Brad Fitzpatrickae6cdd12010-03-14 11:38:06 -070055 private StringBuilder mWhereClause = null; // lazily created
Mathew Inwood55418ea2018-12-20 15:30:45 +000056 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070057 private boolean mDistinct;
58 private SQLiteDatabase.CursorFactory mFactory;
Daniel Lehmann50b1f8d2011-06-01 15:24:23 -070059 private boolean mStrict;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070060
61 public SQLiteQueryBuilder() {
62 mDistinct = false;
63 mFactory = null;
64 }
65
66 /**
67 * Mark the query as DISTINCT.
68 *
69 * @param distinct if true the query is DISTINCT, otherwise it isn't
70 */
71 public void setDistinct(boolean distinct) {
72 mDistinct = distinct;
73 }
74
75 /**
76 * Returns the list of tables being queried
77 *
78 * @return the list of tables being queried
79 */
80 public String getTables() {
81 return mTables;
82 }
83
84 /**
85 * Sets the list of tables to query. Multiple tables can be specified to perform a join.
86 * For example:
87 * setTables("foo, bar")
88 * setTables("foo LEFT OUTER JOIN bar ON (foo.id = bar.foo_id)")
89 *
90 * @param inTables the list of tables to query on
91 */
92 public void setTables(String inTables) {
93 mTables = inTables;
94 }
95
96 /**
97 * Append a chunk to the WHERE clause of the query. All chunks appended are surrounded
98 * by parenthesis and ANDed with the selection passed to {@link #query}. The final
99 * WHERE clause looks like:
100 *
101 * WHERE (&lt;append chunk 1>&lt;append chunk2>) AND (&lt;query() selection parameter>)
102 *
103 * @param inWhere the chunk of text to append to the WHERE clause.
104 */
Jeff Sharkey0da04832018-07-26 14:36:59 -0600105 public void appendWhere(@NonNull CharSequence inWhere) {
Brad Fitzpatrickae6cdd12010-03-14 11:38:06 -0700106 if (mWhereClause == null) {
107 mWhereClause = new StringBuilder(inWhere.length() + 16);
108 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700109 mWhereClause.append(inWhere);
110 }
111
112 /**
113 * Append a chunk to the WHERE clause of the query. All chunks appended are surrounded
114 * by parenthesis and ANDed with the selection passed to {@link #query}. The final
115 * WHERE clause looks like:
116 *
117 * WHERE (&lt;append chunk 1>&lt;append chunk2>) AND (&lt;query() selection parameter>)
118 *
119 * @param inWhere the chunk of text to append to the WHERE clause. it will be escaped
120 * to avoid SQL injection attacks
121 */
Jeff Sharkey0da04832018-07-26 14:36:59 -0600122 public void appendWhereEscapeString(@NonNull String inWhere) {
Brad Fitzpatrickae6cdd12010-03-14 11:38:06 -0700123 if (mWhereClause == null) {
124 mWhereClause = new StringBuilder(inWhere.length() + 16);
125 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700126 DatabaseUtils.appendEscapedSQLString(mWhereClause, inWhere);
127 }
128
129 /**
Jeff Sharkey0da04832018-07-26 14:36:59 -0600130 * Add a standalone chunk to the {@code WHERE} clause of this query.
131 * <p>
132 * This method differs from {@link #appendWhere(CharSequence)} in that it
133 * automatically appends {@code AND} to any existing {@code WHERE} clause
134 * already under construction before appending the given standalone
135 * expression wrapped in parentheses.
136 *
137 * @param inWhere the standalone expression to append to the {@code WHERE}
138 * clause. It will be wrapped in parentheses when it's appended.
139 */
140 public void appendWhereStandalone(@NonNull CharSequence inWhere) {
141 if (mWhereClause == null) {
142 mWhereClause = new StringBuilder(inWhere.length() + 16);
143 }
144 if (mWhereClause.length() > 0) {
145 mWhereClause.append(" AND ");
146 }
147 mWhereClause.append('(').append(inWhere).append(')');
148 }
149
150 /**
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700151 * Sets the projection map for the query. The projection map maps
152 * from column names that the caller passes into query to database
153 * column names. This is useful for renaming columns as well as
154 * disambiguating column names when doing joins. For example you
155 * could map "name" to "people.name". If a projection map is set
156 * it must contain all column names the user may request, even if
157 * the key and value are the same.
158 *
159 * @param columnMap maps from the user column names to the database column names
160 */
161 public void setProjectionMap(Map<String, String> columnMap) {
162 mProjectionMap = columnMap;
163 }
164
165 /**
166 * Sets the cursor factory to be used for the query. You can use
167 * one factory for all queries on a database but it is normally
Jeff Brown75ea64f2012-01-25 19:37:13 -0800168 * easier to specify the factory when doing this query.
169 *
170 * @param factory the factory to use.
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700171 */
172 public void setCursorFactory(SQLiteDatabase.CursorFactory factory) {
173 mFactory = factory;
174 }
175
176 /**
Daniel Lehmann50b1f8d2011-06-01 15:24:23 -0700177 * When set, the selection is verified against malicious arguments.
178 * When using this class to create a statement using
179 * {@link #buildQueryString(boolean, String, String[], String, String, String, String, String)},
180 * non-numeric limits will raise an exception. If a projection map is specified, fields
181 * not in that map will be ignored.
182 * If this class is used to execute the statement directly using
183 * {@link #query(SQLiteDatabase, String[], String, String[], String, String, String)}
184 * or
185 * {@link #query(SQLiteDatabase, String[], String, String[], String, String, String, String)},
186 * additionally also parenthesis escaping selection are caught.
187 *
188 * To summarize: To get maximum protection against malicious third party apps (for example
189 * content provider consumers), make sure to do the following:
190 * <ul>
191 * <li>Set this value to true</li>
192 * <li>Use a projection map</li>
193 * <li>Use one of the query overloads instead of getting the statement as a sql string</li>
194 * </ul>
195 * By default, this value is false.
196 */
197 public void setStrict(boolean flag) {
198 mStrict = flag;
Dmitri Plotnikov40eb4aa2010-04-14 16:09:46 -0700199 }
200
201 /**
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700202 * Build an SQL query string from the given clauses.
203 *
204 * @param distinct true if you want each row to be unique, false otherwise.
205 * @param tables The table names to compile the query against.
206 * @param columns A list of which columns to return. Passing null will
207 * return all columns, which is discouraged to prevent reading
208 * data from storage that isn't going to be used.
209 * @param where A filter declaring which rows to return, formatted as an SQL
210 * WHERE clause (excluding the WHERE itself). Passing null will
211 * return all rows for the given URL.
212 * @param groupBy A filter declaring how to group rows, formatted as an SQL
213 * GROUP BY clause (excluding the GROUP BY itself). Passing null
214 * will cause the rows to not be grouped.
215 * @param having A filter declare which row groups to include in the cursor,
216 * if row grouping is being used, formatted as an SQL HAVING
217 * clause (excluding the HAVING itself). Passing null will cause
218 * all row groups to be included, and is required when row
219 * grouping is not being used.
220 * @param orderBy How to order the rows, formatted as an SQL ORDER BY clause
221 * (excluding the ORDER BY itself). Passing null will use the
222 * default sort order, which may be unordered.
223 * @param limit Limits the number of rows returned by the query,
224 * formatted as LIMIT clause. Passing null denotes no LIMIT clause.
225 * @return the SQL query string
226 */
227 public static String buildQueryString(
228 boolean distinct, String tables, String[] columns, String where,
229 String groupBy, String having, String orderBy, String limit) {
230 if (TextUtils.isEmpty(groupBy) && !TextUtils.isEmpty(having)) {
231 throw new IllegalArgumentException(
232 "HAVING clauses are only permitted when using a groupBy clause");
233 }
Owen Linab18d1f2009-05-06 16:45:59 -0700234 if (!TextUtils.isEmpty(limit) && !sLimitPattern.matcher(limit).matches()) {
235 throw new IllegalArgumentException("invalid LIMIT clauses:" + limit);
236 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700237
238 StringBuilder query = new StringBuilder(120);
239
240 query.append("SELECT ");
241 if (distinct) {
242 query.append("DISTINCT ");
243 }
244 if (columns != null && columns.length != 0) {
245 appendColumns(query, columns);
246 } else {
247 query.append("* ");
248 }
249 query.append("FROM ");
250 query.append(tables);
251 appendClause(query, " WHERE ", where);
252 appendClause(query, " GROUP BY ", groupBy);
253 appendClause(query, " HAVING ", having);
254 appendClause(query, " ORDER BY ", orderBy);
Owen Linab18d1f2009-05-06 16:45:59 -0700255 appendClause(query, " LIMIT ", limit);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700256
257 return query.toString();
258 }
259
260 private static void appendClause(StringBuilder s, String name, String clause) {
261 if (!TextUtils.isEmpty(clause)) {
262 s.append(name);
263 s.append(clause);
264 }
265 }
266
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700267 /**
268 * Add the names that are non-null in columns to s, separating
269 * them with commas.
270 */
271 public static void appendColumns(StringBuilder s, String[] columns) {
272 int n = columns.length;
273
274 for (int i = 0; i < n; i++) {
275 String column = columns[i];
276
277 if (column != null) {
278 if (i > 0) {
279 s.append(", ");
280 }
281 s.append(column);
282 }
283 }
284 s.append(' ');
285 }
286
287 /**
288 * Perform a query by combining all current settings and the
289 * information passed into this method.
290 *
291 * @param db the database to query on
292 * @param projectionIn A list of which columns to return. Passing
293 * null will return all columns, which is discouraged to prevent
294 * reading data from storage that isn't going to be used.
295 * @param selection A filter declaring which rows to return,
296 * formatted as an SQL WHERE clause (excluding the WHERE
297 * itself). Passing null will return all rows for the given URL.
298 * @param selectionArgs You may include ?s in selection, which
299 * will be replaced by the values from selectionArgs, in order
300 * that they appear in the selection. The values will be bound
301 * as Strings.
302 * @param groupBy A filter declaring how to group rows, formatted
303 * as an SQL GROUP BY clause (excluding the GROUP BY
304 * itself). Passing null will cause the rows to not be grouped.
305 * @param having A filter declare which row groups to include in
306 * the cursor, if row grouping is being used, formatted as an
307 * SQL HAVING clause (excluding the HAVING itself). Passing
308 * null will cause all row groups to be included, and is
309 * required when row grouping is not being used.
310 * @param sortOrder How to order the rows, formatted as an SQL
311 * ORDER BY clause (excluding the ORDER BY itself). Passing null
312 * will use the default sort order, which may be unordered.
313 * @return a cursor over the result set
314 * @see android.content.ContentResolver#query(android.net.Uri, String[],
315 * String, String[], String)
316 */
317 public Cursor query(SQLiteDatabase db, String[] projectionIn,
318 String selection, String[] selectionArgs, String groupBy,
319 String having, String sortOrder) {
320 return query(db, projectionIn, selection, selectionArgs, groupBy, having, sortOrder,
Jeff Brown4c1241d2012-02-02 17:05:00 -0800321 null /* limit */, null /* cancellationSignal */);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700322 }
323
324 /**
325 * Perform a query by combining all current settings and the
326 * information passed into this method.
327 *
328 * @param db the database to query on
329 * @param projectionIn A list of which columns to return. Passing
330 * null will return all columns, which is discouraged to prevent
331 * reading data from storage that isn't going to be used.
332 * @param selection A filter declaring which rows to return,
333 * formatted as an SQL WHERE clause (excluding the WHERE
334 * itself). Passing null will return all rows for the given URL.
335 * @param selectionArgs You may include ?s in selection, which
336 * will be replaced by the values from selectionArgs, in order
337 * that they appear in the selection. The values will be bound
338 * as Strings.
339 * @param groupBy A filter declaring how to group rows, formatted
340 * as an SQL GROUP BY clause (excluding the GROUP BY
341 * itself). Passing null will cause the rows to not be grouped.
342 * @param having A filter declare which row groups to include in
343 * the cursor, if row grouping is being used, formatted as an
344 * SQL HAVING clause (excluding the HAVING itself). Passing
345 * null will cause all row groups to be included, and is
346 * required when row grouping is not being used.
347 * @param sortOrder How to order the rows, formatted as an SQL
348 * ORDER BY clause (excluding the ORDER BY itself). Passing null
349 * will use the default sort order, which may be unordered.
350 * @param limit Limits the number of rows returned by the query,
351 * formatted as LIMIT clause. Passing null denotes no LIMIT clause.
352 * @return a cursor over the result set
353 * @see android.content.ContentResolver#query(android.net.Uri, String[],
354 * String, String[], String)
355 */
356 public Cursor query(SQLiteDatabase db, String[] projectionIn,
357 String selection, String[] selectionArgs, String groupBy,
358 String having, String sortOrder, String limit) {
Jeff Brown75ea64f2012-01-25 19:37:13 -0800359 return query(db, projectionIn, selection, selectionArgs,
360 groupBy, having, sortOrder, limit, null);
361 }
362
363 /**
364 * Perform a query by combining all current settings and the
365 * information passed into this method.
366 *
367 * @param db the database to query on
368 * @param projectionIn A list of which columns to return. Passing
369 * null will return all columns, which is discouraged to prevent
370 * reading data from storage that isn't going to be used.
371 * @param selection A filter declaring which rows to return,
372 * formatted as an SQL WHERE clause (excluding the WHERE
373 * itself). Passing null will return all rows for the given URL.
374 * @param selectionArgs You may include ?s in selection, which
375 * will be replaced by the values from selectionArgs, in order
376 * that they appear in the selection. The values will be bound
377 * as Strings.
378 * @param groupBy A filter declaring how to group rows, formatted
379 * as an SQL GROUP BY clause (excluding the GROUP BY
380 * itself). Passing null will cause the rows to not be grouped.
381 * @param having A filter declare which row groups to include in
382 * the cursor, if row grouping is being used, formatted as an
383 * SQL HAVING clause (excluding the HAVING itself). Passing
384 * null will cause all row groups to be included, and is
385 * required when row grouping is not being used.
386 * @param sortOrder How to order the rows, formatted as an SQL
387 * ORDER BY clause (excluding the ORDER BY itself). Passing null
388 * will use the default sort order, which may be unordered.
389 * @param limit Limits the number of rows returned by the query,
390 * formatted as LIMIT clause. Passing null denotes no LIMIT clause.
Jeff Brown4c1241d2012-02-02 17:05:00 -0800391 * @param cancellationSignal A signal to cancel the operation in progress, or null if none.
Jeff Brown75ea64f2012-01-25 19:37:13 -0800392 * If the operation is canceled, then {@link OperationCanceledException} will be thrown
393 * when the query is executed.
394 * @return a cursor over the result set
395 * @see android.content.ContentResolver#query(android.net.Uri, String[],
396 * String, String[], String)
397 */
398 public Cursor query(SQLiteDatabase db, String[] projectionIn,
399 String selection, String[] selectionArgs, String groupBy,
Jeff Brown4c1241d2012-02-02 17:05:00 -0800400 String having, String sortOrder, String limit, CancellationSignal cancellationSignal) {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700401 if (mTables == null) {
402 return null;
403 }
404
Jeff Sharkey57b04a82018-07-25 14:01:59 -0600405 final String sql;
406 final String unwrappedSql = buildQuery(
407 projectionIn, selection, groupBy, having,
408 sortOrder, limit);
409
Daniel Lehmann50b1f8d2011-06-01 15:24:23 -0700410 if (mStrict && selection != null && selection.length() > 0) {
411 // Validate the user-supplied selection to detect syntactic anomalies
412 // in the selection string that could indicate a SQL injection attempt.
413 // The idea is to ensure that the selection clause is a valid SQL expression
414 // by compiling it twice: once wrapped in parentheses and once as
415 // originally specified. An attacker cannot create an expression that
416 // would escape the SQL expression while maintaining balanced parentheses
417 // in both the wrapped and original forms.
Daniel Lehmann50b1f8d2011-06-01 15:24:23 -0700418
Jeff Sharkey57b04a82018-07-25 14:01:59 -0600419 // NOTE: The ordering of the below operations is important; we must
420 // execute the wrapped query to ensure the untrusted clause has been
421 // fully isolated.
422
423 // Validate the unwrapped query
424 db.validateSql(unwrappedSql, cancellationSignal); // will throw if query is invalid
425
426 // Execute wrapped query for extra protection
Jeff Sharkey50699422018-07-25 14:52:14 -0600427 final String wrappedSql = buildQuery(projectionIn, wrap(selection), groupBy,
Jeff Sharkey57b04a82018-07-25 14:01:59 -0600428 having, sortOrder, limit);
429 sql = wrappedSql;
430 } else {
431 // Execute unwrapped query
432 sql = unwrappedSql;
433 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700434
Jeff Sharkey50699422018-07-25 14:52:14 -0600435 final String[] sqlArgs = selectionArgs;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700436 if (Log.isLoggable(TAG, Log.DEBUG)) {
Jeff Sharkey50699422018-07-25 14:52:14 -0600437 if (Build.IS_DEBUGGABLE) {
438 Log.d(TAG, sql + " with args " + Arrays.toString(sqlArgs));
439 } else {
440 Log.d(TAG, sql);
441 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700442 }
443 return db.rawQueryWithFactory(
Jeff Sharkey50699422018-07-25 14:52:14 -0600444 mFactory, sql, sqlArgs,
Jeff Brown75ea64f2012-01-25 19:37:13 -0800445 SQLiteDatabase.findEditTable(mTables),
Jeff Brown4c1241d2012-02-02 17:05:00 -0800446 cancellationSignal); // will throw if query is invalid
Daniel Lehmann50b1f8d2011-06-01 15:24:23 -0700447 }
448
449 /**
Jeff Sharkey50699422018-07-25 14:52:14 -0600450 * Perform an update by combining all current settings and the
451 * information passed into this method.
452 *
453 * @param db the database to update on
454 * @param selection A filter declaring which rows to return,
455 * formatted as an SQL WHERE clause (excluding the WHERE
456 * itself). Passing null will return all rows for the given URL.
457 * @param selectionArgs You may include ?s in selection, which
458 * will be replaced by the values from selectionArgs, in order
459 * that they appear in the selection. The values will be bound
460 * as Strings.
461 * @return the number of rows updated
462 * @hide
463 */
464 public int update(@NonNull SQLiteDatabase db, @NonNull ContentValues values,
465 @Nullable String selection, @Nullable String[] selectionArgs) {
466 Objects.requireNonNull(mTables, "No tables defined");
467 Objects.requireNonNull(db, "No database defined");
468 Objects.requireNonNull(values, "No values defined");
469
470 final String sql;
471 final String unwrappedSql = buildUpdate(values, selection);
472
473 if (mStrict) {
474 // Validate the user-supplied selection to detect syntactic anomalies
475 // in the selection string that could indicate a SQL injection attempt.
476 // The idea is to ensure that the selection clause is a valid SQL expression
477 // by compiling it twice: once wrapped in parentheses and once as
478 // originally specified. An attacker cannot create an expression that
479 // would escape the SQL expression while maintaining balanced parentheses
480 // in both the wrapped and original forms.
481
482 // NOTE: The ordering of the below operations is important; we must
483 // execute the wrapped query to ensure the untrusted clause has been
484 // fully isolated.
485
486 // Validate the unwrapped query
487 db.validateSql(unwrappedSql, null); // will throw if query is invalid
488
489 // Execute wrapped query for extra protection
490 final String wrappedSql = buildUpdate(values, wrap(selection));
491 sql = wrappedSql;
492 } else {
493 // Execute unwrapped query
494 sql = unwrappedSql;
495 }
496
497 if (selectionArgs == null) {
498 selectionArgs = EmptyArray.STRING;
499 }
500 final String[] rawKeys = values.keySet().toArray(EmptyArray.STRING);
501 final int valuesLength = rawKeys.length;
502 final Object[] sqlArgs = new Object[valuesLength + selectionArgs.length];
503 for (int i = 0; i < sqlArgs.length; i++) {
504 if (i < valuesLength) {
505 sqlArgs[i] = values.get(rawKeys[i]);
506 } else {
507 sqlArgs[i] = selectionArgs[i - valuesLength];
508 }
509 }
510 if (Log.isLoggable(TAG, Log.DEBUG)) {
511 if (Build.IS_DEBUGGABLE) {
512 Log.d(TAG, sql + " with args " + Arrays.toString(sqlArgs));
513 } else {
514 Log.d(TAG, sql);
515 }
516 }
517 return db.executeSql(sql, sqlArgs);
518 }
519
520 /**
521 * Perform a delete by combining all current settings and the
522 * information passed into this method.
523 *
524 * @param db the database to delete on
525 * @param selection A filter declaring which rows to return,
526 * formatted as an SQL WHERE clause (excluding the WHERE
527 * itself). Passing null will return all rows for the given URL.
528 * @param selectionArgs You may include ?s in selection, which
529 * will be replaced by the values from selectionArgs, in order
530 * that they appear in the selection. The values will be bound
531 * as Strings.
532 * @return the number of rows deleted
533 * @hide
534 */
535 public int delete(@NonNull SQLiteDatabase db, @Nullable String selection,
536 @Nullable String[] selectionArgs) {
537 Objects.requireNonNull(mTables, "No tables defined");
538 Objects.requireNonNull(db, "No database defined");
539
540 final String sql;
541 final String unwrappedSql = buildDelete(selection);
542
543 if (mStrict) {
544 // Validate the user-supplied selection to detect syntactic anomalies
545 // in the selection string that could indicate a SQL injection attempt.
546 // The idea is to ensure that the selection clause is a valid SQL expression
547 // by compiling it twice: once wrapped in parentheses and once as
548 // originally specified. An attacker cannot create an expression that
549 // would escape the SQL expression while maintaining balanced parentheses
550 // in both the wrapped and original forms.
551
552 // NOTE: The ordering of the below operations is important; we must
553 // execute the wrapped query to ensure the untrusted clause has been
554 // fully isolated.
555
556 // Validate the unwrapped query
557 db.validateSql(unwrappedSql, null); // will throw if query is invalid
558
559 // Execute wrapped query for extra protection
560 final String wrappedSql = buildDelete(wrap(selection));
561 sql = wrappedSql;
562 } else {
563 // Execute unwrapped query
564 sql = unwrappedSql;
565 }
566
567 final String[] sqlArgs = selectionArgs;
568 if (Log.isLoggable(TAG, Log.DEBUG)) {
569 if (Build.IS_DEBUGGABLE) {
570 Log.d(TAG, sql + " with args " + Arrays.toString(sqlArgs));
571 } else {
572 Log.d(TAG, sql);
573 }
574 }
575 return db.executeSql(sql, sqlArgs);
576 }
577
578 /**
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700579 * Construct a SELECT statement suitable for use in a group of
580 * SELECT statements that will be joined through UNION operators
581 * in buildUnionQuery.
582 *
583 * @param projectionIn A list of which columns to return. Passing
584 * null will return all columns, which is discouraged to
585 * prevent reading data from storage that isn't going to be
586 * used.
587 * @param selection A filter declaring which rows to return,
588 * formatted as an SQL WHERE clause (excluding the WHERE
589 * itself). Passing null will return all rows for the given
590 * URL.
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700591 * @param groupBy A filter declaring how to group rows, formatted
592 * as an SQL GROUP BY clause (excluding the GROUP BY itself).
593 * Passing null will cause the rows to not be grouped.
594 * @param having A filter declare which row groups to include in
595 * the cursor, if row grouping is being used, formatted as an
596 * SQL HAVING clause (excluding the HAVING itself). Passing
597 * null will cause all row groups to be included, and is
598 * required when row grouping is not being used.
599 * @param sortOrder How to order the rows, formatted as an SQL
600 * ORDER BY clause (excluding the ORDER BY itself). Passing null
601 * will use the default sort order, which may be unordered.
602 * @param limit Limits the number of rows returned by the query,
603 * formatted as LIMIT clause. Passing null denotes no LIMIT clause.
604 * @return the resulting SQL SELECT statement
605 */
606 public String buildQuery(
Jonas Schwertfeger84029032010-11-12 11:42:28 +0100607 String[] projectionIn, String selection, String groupBy,
608 String having, String sortOrder, String limit) {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700609 String[] projection = computeProjection(projectionIn);
Jeff Sharkey50699422018-07-25 14:52:14 -0600610 String where = computeWhere(selection);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700611
612 return buildQueryString(
Jeff Sharkey50699422018-07-25 14:52:14 -0600613 mDistinct, mTables, projection, where,
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700614 groupBy, having, sortOrder, limit);
615 }
616
617 /**
Jonas Schwertfeger84029032010-11-12 11:42:28 +0100618 * @deprecated This method's signature is misleading since no SQL parameter
619 * substitution is carried out. The selection arguments parameter does not get
620 * used at all. To avoid confusion, call
621 * {@link #buildQuery(String[], String, String, String, String, String)} instead.
622 */
623 @Deprecated
624 public String buildQuery(
625 String[] projectionIn, String selection, String[] selectionArgs,
626 String groupBy, String having, String sortOrder, String limit) {
627 return buildQuery(projectionIn, selection, groupBy, having, sortOrder, limit);
628 }
629
Jeff Sharkey50699422018-07-25 14:52:14 -0600630 /** {@hide} */
631 public String buildUpdate(ContentValues values, String selection) {
632 if (values == null || values.size() == 0) {
633 throw new IllegalArgumentException("Empty values");
634 }
635
636 StringBuilder sql = new StringBuilder(120);
637 sql.append("UPDATE ");
638 sql.append(mTables);
639 sql.append(" SET ");
640
641 final String[] rawKeys = values.keySet().toArray(EmptyArray.STRING);
642 for (int i = 0; i < rawKeys.length; i++) {
643 if (i > 0) {
644 sql.append(',');
645 }
646 sql.append(rawKeys[i]);
647 sql.append("=?");
648 }
649
650 final String where = computeWhere(selection);
651 appendClause(sql, " WHERE ", where);
652 return sql.toString();
653 }
654
655 /** {@hide} */
656 public String buildDelete(String selection) {
657 StringBuilder sql = new StringBuilder(120);
658 sql.append("DELETE FROM ");
659 sql.append(mTables);
660
661 final String where = computeWhere(selection);
662 appendClause(sql, " WHERE ", where);
663 return sql.toString();
664 }
665
Jonas Schwertfeger84029032010-11-12 11:42:28 +0100666 /**
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700667 * Construct a SELECT statement suitable for use in a group of
668 * SELECT statements that will be joined through UNION operators
669 * in buildUnionQuery.
670 *
671 * @param typeDiscriminatorColumn the name of the result column
672 * whose cells will contain the name of the table from which
673 * each row was drawn.
674 * @param unionColumns the names of the columns to appear in the
675 * result. This may include columns that do not appear in the
676 * table this SELECT is querying (i.e. mTables), but that do
677 * appear in one of the other tables in the UNION query that we
678 * are constructing.
679 * @param columnsPresentInTable a Set of the names of the columns
680 * that appear in this table (i.e. in the table whose name is
681 * mTables). Since columns in unionColumns include columns that
682 * appear only in other tables, we use this array to distinguish
683 * which ones actually are present. Other columns will have
684 * NULL values for results from this subquery.
685 * @param computedColumnsOffset all columns in unionColumns before
686 * this index are included under the assumption that they're
687 * computed and therefore won't appear in columnsPresentInTable,
688 * e.g. "date * 1000 as normalized_date"
689 * @param typeDiscriminatorValue the value used for the
690 * type-discriminator column in this subquery
691 * @param selection A filter declaring which rows to return,
692 * formatted as an SQL WHERE clause (excluding the WHERE
693 * itself). Passing null will return all rows for the given
694 * URL.
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700695 * @param groupBy A filter declaring how to group rows, formatted
696 * as an SQL GROUP BY clause (excluding the GROUP BY itself).
697 * Passing null will cause the rows to not be grouped.
698 * @param having A filter declare which row groups to include in
699 * the cursor, if row grouping is being used, formatted as an
700 * SQL HAVING clause (excluding the HAVING itself). Passing
701 * null will cause all row groups to be included, and is
702 * required when row grouping is not being used.
703 * @return the resulting SQL SELECT statement
704 */
705 public String buildUnionSubQuery(
706 String typeDiscriminatorColumn,
707 String[] unionColumns,
708 Set<String> columnsPresentInTable,
709 int computedColumnsOffset,
710 String typeDiscriminatorValue,
711 String selection,
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700712 String groupBy,
713 String having) {
714 int unionColumnsCount = unionColumns.length;
715 String[] projectionIn = new String[unionColumnsCount];
716
717 for (int i = 0; i < unionColumnsCount; i++) {
718 String unionColumn = unionColumns[i];
719
720 if (unionColumn.equals(typeDiscriminatorColumn)) {
721 projectionIn[i] = "'" + typeDiscriminatorValue + "' AS "
722 + typeDiscriminatorColumn;
723 } else if (i <= computedColumnsOffset
724 || columnsPresentInTable.contains(unionColumn)) {
725 projectionIn[i] = unionColumn;
726 } else {
727 projectionIn[i] = "NULL AS " + unionColumn;
728 }
729 }
730 return buildQuery(
Jonas Schwertfeger84029032010-11-12 11:42:28 +0100731 projectionIn, selection, groupBy, having,
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700732 null /* sortOrder */,
733 null /* limit */);
734 }
735
736 /**
Jonas Schwertfeger84029032010-11-12 11:42:28 +0100737 * @deprecated This method's signature is misleading since no SQL parameter
738 * substitution is carried out. The selection arguments parameter does not get
739 * used at all. To avoid confusion, call
Jean-Baptiste Queruf4072fc2010-11-17 16:47:59 -0800740 * {@link #buildUnionSubQuery}
Jonas Schwertfeger84029032010-11-12 11:42:28 +0100741 * instead.
742 */
743 @Deprecated
744 public String buildUnionSubQuery(
745 String typeDiscriminatorColumn,
746 String[] unionColumns,
747 Set<String> columnsPresentInTable,
748 int computedColumnsOffset,
749 String typeDiscriminatorValue,
750 String selection,
751 String[] selectionArgs,
752 String groupBy,
753 String having) {
754 return buildUnionSubQuery(
755 typeDiscriminatorColumn, unionColumns, columnsPresentInTable,
756 computedColumnsOffset, typeDiscriminatorValue, selection,
757 groupBy, having);
758 }
759
760 /**
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700761 * Given a set of subqueries, all of which are SELECT statements,
762 * construct a query that returns the union of what those
763 * subqueries return.
764 * @param subQueries an array of SQL SELECT statements, all of
765 * which must have the same columns as the same positions in
766 * their results
767 * @param sortOrder How to order the rows, formatted as an SQL
768 * ORDER BY clause (excluding the ORDER BY itself). Passing
769 * null will use the default sort order, which may be unordered.
770 * @param limit The limit clause, which applies to the entire union result set
771 *
772 * @return the resulting SQL SELECT statement
773 */
774 public String buildUnionQuery(String[] subQueries, String sortOrder, String limit) {
775 StringBuilder query = new StringBuilder(128);
776 int subQueryCount = subQueries.length;
777 String unionOperator = mDistinct ? " UNION " : " UNION ALL ";
778
779 for (int i = 0; i < subQueryCount; i++) {
780 if (i > 0) {
781 query.append(unionOperator);
782 }
783 query.append(subQueries[i]);
784 }
785 appendClause(query, " ORDER BY ", sortOrder);
786 appendClause(query, " LIMIT ", limit);
787 return query.toString();
788 }
789
Mathew Inwood55418ea2018-12-20 15:30:45 +0000790 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700791 private String[] computeProjection(String[] projectionIn) {
792 if (projectionIn != null && projectionIn.length > 0) {
793 if (mProjectionMap != null) {
794 String[] projection = new String[projectionIn.length];
795 int length = projectionIn.length;
796
797 for (int i = 0; i < length; i++) {
798 String userColumn = projectionIn[i];
799 String column = mProjectionMap.get(userColumn);
800
Michael Chan99c44832009-04-27 16:28:51 -0700801 if (column != null) {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700802 projection[i] = column;
Michael Chan99c44832009-04-27 16:28:51 -0700803 continue;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700804 }
Michael Chan99c44832009-04-27 16:28:51 -0700805
Daniel Lehmann50b1f8d2011-06-01 15:24:23 -0700806 if (!mStrict &&
Dmitri Plotnikov40eb4aa2010-04-14 16:09:46 -0700807 ( userColumn.contains(" AS ") || userColumn.contains(" as "))) {
Michael Chan99c44832009-04-27 16:28:51 -0700808 /* A column alias already exist */
809 projection[i] = userColumn;
810 continue;
811 }
812
813 throw new IllegalArgumentException("Invalid column "
814 + projectionIn[i]);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700815 }
816 return projection;
817 } else {
818 return projectionIn;
819 }
820 } else if (mProjectionMap != null) {
821 // Return all columns in projection map.
822 Set<Entry<String, String>> entrySet = mProjectionMap.entrySet();
823 String[] projection = new String[entrySet.size()];
824 Iterator<Entry<String, String>> entryIter = entrySet.iterator();
825 int i = 0;
826
827 while (entryIter.hasNext()) {
828 Entry<String, String> entry = entryIter.next();
829
830 // Don't include the _count column when people ask for no projection.
831 if (entry.getKey().equals(BaseColumns._COUNT)) {
832 continue;
833 }
834 projection[i++] = entry.getValue();
835 }
836 return projection;
837 }
838 return null;
839 }
Jeff Sharkey50699422018-07-25 14:52:14 -0600840
841 private @Nullable String computeWhere(@Nullable String selection) {
842 final boolean hasInternal = !TextUtils.isEmpty(mWhereClause);
843 final boolean hasExternal = !TextUtils.isEmpty(selection);
844
845 if (hasInternal || hasExternal) {
846 final StringBuilder where = new StringBuilder();
847 if (hasInternal) {
848 where.append('(').append(mWhereClause).append(')');
849 }
850 if (hasInternal && hasExternal) {
851 where.append(" AND ");
852 }
853 if (hasExternal) {
854 where.append('(').append(selection).append(')');
855 }
856 return where.toString();
857 } else {
858 return null;
859 }
860 }
861
862 /**
863 * Wrap given argument in parenthesis, unless it's {@code null} or
864 * {@code ()}, in which case return it verbatim.
865 */
866 private @Nullable String wrap(@Nullable String arg) {
867 if (TextUtils.isEmpty(arg)) {
868 return arg;
869 } else {
870 return "(" + arg + ")";
871 }
872 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700873}