The Android Open Source Project | 54b6cfa | 2008-10-21 07:00:00 -0700 | [diff] [blame] | 1 | /* |
| 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 | |
| 17 | package android.database.sqlite; |
| 18 | |
Jeff Sharkey | b13ea30 | 2018-07-25 14:52:14 -0600 | [diff] [blame] | 19 | import android.annotation.NonNull; |
| 20 | import android.annotation.Nullable; |
Mathew Inwood | 41b3194 | 2018-08-10 16:00:53 +0100 | [diff] [blame] | 21 | import android.annotation.UnsupportedAppUsage; |
Jeff Sharkey | b13ea30 | 2018-07-25 14:52:14 -0600 | [diff] [blame] | 22 | import android.content.ContentValues; |
The Android Open Source Project | 54b6cfa | 2008-10-21 07:00:00 -0700 | [diff] [blame] | 23 | import android.database.Cursor; |
| 24 | import android.database.DatabaseUtils; |
Jeff Sharkey | b13ea30 | 2018-07-25 14:52:14 -0600 | [diff] [blame] | 25 | import android.os.Build; |
Jeff Brown | a7771df | 2012-05-07 20:06:46 -0700 | [diff] [blame] | 26 | import android.os.CancellationSignal; |
| 27 | import android.os.OperationCanceledException; |
The Android Open Source Project | 54b6cfa | 2008-10-21 07:00:00 -0700 | [diff] [blame] | 28 | import android.provider.BaseColumns; |
| 29 | import android.text.TextUtils; |
Jeff Sharkey | b13ea30 | 2018-07-25 14:52:14 -0600 | [diff] [blame] | 30 | import android.util.ArrayMap; |
The Android Open Source Project | 54b6cfa | 2008-10-21 07:00:00 -0700 | [diff] [blame] | 31 | import android.util.Log; |
| 32 | |
Jeff Sharkey | 42122bf | 2018-07-26 09:39:18 -0600 | [diff] [blame] | 33 | import libcore.util.EmptyArray; |
Jeff Sharkey | b13ea30 | 2018-07-25 14:52:14 -0600 | [diff] [blame] | 34 | |
| 35 | import java.util.Arrays; |
The Android Open Source Project | 54b6cfa | 2008-10-21 07:00:00 -0700 | [diff] [blame] | 36 | import java.util.Iterator; |
Jeff Sharkey | 7049e65 | 2018-09-13 17:05:07 -0600 | [diff] [blame] | 37 | import java.util.List; |
The Android Open Source Project | 54b6cfa | 2008-10-21 07:00:00 -0700 | [diff] [blame] | 38 | import java.util.Map; |
The Android Open Source Project | 54b6cfa | 2008-10-21 07:00:00 -0700 | [diff] [blame] | 39 | import java.util.Map.Entry; |
Jeff Sharkey | b13ea30 | 2018-07-25 14:52:14 -0600 | [diff] [blame] | 40 | import java.util.Objects; |
Daniel Lehmann | 50b1f8d | 2011-06-01 15:24:23 -0700 | [diff] [blame] | 41 | import java.util.Set; |
Owen Lin | ab18d1f | 2009-05-06 16:45:59 -0700 | [diff] [blame] | 42 | import java.util.regex.Pattern; |
The Android Open Source Project | 54b6cfa | 2008-10-21 07:00:00 -0700 | [diff] [blame] | 43 | |
| 44 | /** |
Joshua Baxter | 3639e2f | 2018-03-26 14:55:14 -0700 | [diff] [blame] | 45 | * This is a convenience class that helps build SQL queries to be sent to |
The Android Open Source Project | 54b6cfa | 2008-10-21 07:00:00 -0700 | [diff] [blame] | 46 | * {@link SQLiteDatabase} objects. |
| 47 | */ |
Jeff Sharkey | b89df9e | 2018-07-26 14:36:59 -0600 | [diff] [blame] | 48 | public class SQLiteQueryBuilder { |
The Android Open Source Project | 54b6cfa | 2008-10-21 07:00:00 -0700 | [diff] [blame] | 49 | private static final String TAG = "SQLiteQueryBuilder"; |
Owen Lin | ab18d1f | 2009-05-06 16:45:59 -0700 | [diff] [blame] | 50 | private static final Pattern sLimitPattern = |
| 51 | Pattern.compile("\\s*\\d+\\s*(,\\s*\\d+\\s*)?"); |
The Android Open Source Project | 54b6cfa | 2008-10-21 07:00:00 -0700 | [diff] [blame] | 52 | |
| 53 | private Map<String, String> mProjectionMap = null; |
Jeff Sharkey | 7049e65 | 2018-09-13 17:05:07 -0600 | [diff] [blame] | 54 | private List<Pattern> mProjectionGreylist = null; |
| 55 | |
Mathew Inwood | 31755f9 | 2018-12-20 13:53:36 +0000 | [diff] [blame] | 56 | @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023) |
The Android Open Source Project | 54b6cfa | 2008-10-21 07:00:00 -0700 | [diff] [blame] | 57 | private String mTables = ""; |
Mathew Inwood | 31755f9 | 2018-12-20 13:53:36 +0000 | [diff] [blame] | 58 | @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023) |
Brad Fitzpatrick | ae6cdd1 | 2010-03-14 11:38:06 -0700 | [diff] [blame] | 59 | private StringBuilder mWhereClause = null; // lazily created |
Mathew Inwood | 31755f9 | 2018-12-20 13:53:36 +0000 | [diff] [blame] | 60 | @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023) |
The Android Open Source Project | 54b6cfa | 2008-10-21 07:00:00 -0700 | [diff] [blame] | 61 | private boolean mDistinct; |
| 62 | private SQLiteDatabase.CursorFactory mFactory; |
Daniel Lehmann | 50b1f8d | 2011-06-01 15:24:23 -0700 | [diff] [blame] | 63 | private boolean mStrict; |
The Android Open Source Project | 54b6cfa | 2008-10-21 07:00:00 -0700 | [diff] [blame] | 64 | |
| 65 | public SQLiteQueryBuilder() { |
| 66 | mDistinct = false; |
| 67 | mFactory = null; |
| 68 | } |
| 69 | |
| 70 | /** |
Jeff Sharkey | b91eaa5 | 2019-02-19 11:09:13 -0700 | [diff] [blame] | 71 | * Mark the query as {@code DISTINCT}. |
The Android Open Source Project | 54b6cfa | 2008-10-21 07:00:00 -0700 | [diff] [blame] | 72 | * |
Jeff Sharkey | b91eaa5 | 2019-02-19 11:09:13 -0700 | [diff] [blame] | 73 | * @param distinct if true the query is {@code DISTINCT}, otherwise it isn't |
The Android Open Source Project | 54b6cfa | 2008-10-21 07:00:00 -0700 | [diff] [blame] | 74 | */ |
| 75 | public void setDistinct(boolean distinct) { |
| 76 | mDistinct = distinct; |
| 77 | } |
| 78 | |
| 79 | /** |
Jeff Sharkey | b91eaa5 | 2019-02-19 11:09:13 -0700 | [diff] [blame] | 80 | * Get if the query is marked as {@code DISTINCT}, as last configured by |
Jeff Sharkey | 0ec586b | 2019-02-14 15:29:16 -0700 | [diff] [blame] | 81 | * {@link #setDistinct(boolean)}. |
| 82 | */ |
| 83 | public boolean getDistinct() { |
| 84 | return mDistinct; |
| 85 | } |
| 86 | |
| 87 | /** |
The Android Open Source Project | 54b6cfa | 2008-10-21 07:00:00 -0700 | [diff] [blame] | 88 | * Returns the list of tables being queried |
| 89 | * |
| 90 | * @return the list of tables being queried |
| 91 | */ |
| 92 | public String getTables() { |
| 93 | return mTables; |
| 94 | } |
| 95 | |
| 96 | /** |
| 97 | * Sets the list of tables to query. Multiple tables can be specified to perform a join. |
| 98 | * For example: |
| 99 | * setTables("foo, bar") |
| 100 | * setTables("foo LEFT OUTER JOIN bar ON (foo.id = bar.foo_id)") |
| 101 | * |
| 102 | * @param inTables the list of tables to query on |
| 103 | */ |
| 104 | public void setTables(String inTables) { |
| 105 | mTables = inTables; |
| 106 | } |
| 107 | |
The Android Open Source Project | 54b6cfa | 2008-10-21 07:00:00 -0700 | [diff] [blame] | 108 | /** |
Jeff Sharkey | b91eaa5 | 2019-02-19 11:09:13 -0700 | [diff] [blame] | 109 | * Append a chunk to the {@code WHERE} clause of the query. All chunks appended are surrounded |
| 110 | * by parenthesis and {@code AND}ed with the selection passed to {@link #query}. The final |
| 111 | * {@code WHERE} clause looks like: |
| 112 | * <p> |
The Android Open Source Project | 54b6cfa | 2008-10-21 07:00:00 -0700 | [diff] [blame] | 113 | * WHERE (<append chunk 1><append chunk2>) AND (<query() selection parameter>) |
| 114 | * |
Jeff Sharkey | b91eaa5 | 2019-02-19 11:09:13 -0700 | [diff] [blame] | 115 | * @param inWhere the chunk of text to append to the {@code WHERE} clause. |
The Android Open Source Project | 54b6cfa | 2008-10-21 07:00:00 -0700 | [diff] [blame] | 116 | */ |
Jeff Sharkey | b89df9e | 2018-07-26 14:36:59 -0600 | [diff] [blame] | 117 | public void appendWhere(@NonNull CharSequence inWhere) { |
Brad Fitzpatrick | ae6cdd1 | 2010-03-14 11:38:06 -0700 | [diff] [blame] | 118 | if (mWhereClause == null) { |
| 119 | mWhereClause = new StringBuilder(inWhere.length() + 16); |
| 120 | } |
Jeff Sharkey | 6adc98c | 2018-07-12 19:47:49 -0600 | [diff] [blame] | 121 | mWhereClause.append(inWhere); |
Jeff Sharkey | 6adc98c | 2018-07-12 19:47:49 -0600 | [diff] [blame] | 122 | } |
| 123 | |
| 124 | /** |
Jeff Sharkey | b91eaa5 | 2019-02-19 11:09:13 -0700 | [diff] [blame] | 125 | * Append a chunk to the {@code WHERE} clause of the query. All chunks appended are surrounded |
Jeff Sharkey | 91be926 | 2018-07-19 09:30:16 -0600 | [diff] [blame] | 126 | * by parenthesis and ANDed with the selection passed to {@link #query}. The final |
Jeff Sharkey | b91eaa5 | 2019-02-19 11:09:13 -0700 | [diff] [blame] | 127 | * {@code WHERE} clause looks like: |
| 128 | * <p> |
Jeff Sharkey | 91be926 | 2018-07-19 09:30:16 -0600 | [diff] [blame] | 129 | * WHERE (<append chunk 1><append chunk2>) AND (<query() selection parameter>) |
Jeff Sharkey | 99cc118 | 2018-07-16 14:34:21 -0600 | [diff] [blame] | 130 | * |
Jeff Sharkey | b91eaa5 | 2019-02-19 11:09:13 -0700 | [diff] [blame] | 131 | * @param inWhere the chunk of text to append to the {@code WHERE} clause. it will be escaped |
Jeff Sharkey | 91be926 | 2018-07-19 09:30:16 -0600 | [diff] [blame] | 132 | * to avoid SQL injection attacks |
Jeff Sharkey | 99cc118 | 2018-07-16 14:34:21 -0600 | [diff] [blame] | 133 | */ |
Jeff Sharkey | b89df9e | 2018-07-26 14:36:59 -0600 | [diff] [blame] | 134 | public void appendWhereEscapeString(@NonNull String inWhere) { |
Jeff Sharkey | 99cc118 | 2018-07-16 14:34:21 -0600 | [diff] [blame] | 135 | if (mWhereClause == null) { |
| 136 | mWhereClause = new StringBuilder(inWhere.length() + 16); |
| 137 | } |
The Android Open Source Project | 54b6cfa | 2008-10-21 07:00:00 -0700 | [diff] [blame] | 138 | DatabaseUtils.appendEscapedSQLString(mWhereClause, inWhere); |
| 139 | } |
| 140 | |
| 141 | /** |
Jeff Sharkey | b89df9e | 2018-07-26 14:36:59 -0600 | [diff] [blame] | 142 | * Add a standalone chunk to the {@code WHERE} clause of this query. |
| 143 | * <p> |
| 144 | * This method differs from {@link #appendWhere(CharSequence)} in that it |
| 145 | * automatically appends {@code AND} to any existing {@code WHERE} clause |
| 146 | * already under construction before appending the given standalone |
| 147 | * expression wrapped in parentheses. |
| 148 | * |
| 149 | * @param inWhere the standalone expression to append to the {@code WHERE} |
| 150 | * clause. It will be wrapped in parentheses when it's appended. |
| 151 | */ |
| 152 | public void appendWhereStandalone(@NonNull CharSequence inWhere) { |
| 153 | if (mWhereClause == null) { |
| 154 | mWhereClause = new StringBuilder(inWhere.length() + 16); |
| 155 | } |
| 156 | if (mWhereClause.length() > 0) { |
| 157 | mWhereClause.append(" AND "); |
| 158 | } |
| 159 | mWhereClause.append('(').append(inWhere).append(')'); |
| 160 | } |
| 161 | |
| 162 | /** |
The Android Open Source Project | 54b6cfa | 2008-10-21 07:00:00 -0700 | [diff] [blame] | 163 | * Sets the projection map for the query. The projection map maps |
| 164 | * from column names that the caller passes into query to database |
| 165 | * column names. This is useful for renaming columns as well as |
| 166 | * disambiguating column names when doing joins. For example you |
| 167 | * could map "name" to "people.name". If a projection map is set |
| 168 | * it must contain all column names the user may request, even if |
| 169 | * the key and value are the same. |
| 170 | * |
| 171 | * @param columnMap maps from the user column names to the database column names |
| 172 | */ |
| 173 | public void setProjectionMap(Map<String, String> columnMap) { |
| 174 | mProjectionMap = columnMap; |
| 175 | } |
| 176 | |
| 177 | /** |
Jeff Sharkey | 0ec586b | 2019-02-14 15:29:16 -0700 | [diff] [blame] | 178 | * Gets the projection map for the query, as last configured by |
| 179 | * {@link #setProjectionMap(Map)}. |
| 180 | */ |
| 181 | public Map<String, String> getProjectionMap() { |
| 182 | return mProjectionMap; |
| 183 | } |
| 184 | |
| 185 | /** |
Jeff Sharkey | 7049e65 | 2018-09-13 17:05:07 -0600 | [diff] [blame] | 186 | * Sets a projection greylist of columns that will be allowed through, even |
| 187 | * when {@link #setStrict(boolean)} is enabled. This provides a way for |
| 188 | * abusive custom columns like {@code COUNT(*)} to continue working. |
| 189 | * |
| 190 | * @hide |
| 191 | */ |
| 192 | public void setProjectionGreylist(List<Pattern> projectionGreylist) { |
| 193 | mProjectionGreylist = projectionGreylist; |
| 194 | } |
| 195 | |
| 196 | /** |
Jeff Sharkey | 0ec586b | 2019-02-14 15:29:16 -0700 | [diff] [blame] | 197 | * Gets the projection greylist for the query, as last configured by |
| 198 | * {@link #setProjectionGreylist(List)}. |
| 199 | * |
| 200 | * @hide |
| 201 | */ |
| 202 | public List<Pattern> getProjectionGreylist() { |
| 203 | return mProjectionGreylist; |
| 204 | } |
| 205 | |
| 206 | /** |
The Android Open Source Project | 54b6cfa | 2008-10-21 07:00:00 -0700 | [diff] [blame] | 207 | * Sets the cursor factory to be used for the query. You can use |
| 208 | * one factory for all queries on a database but it is normally |
Jeff Brown | 75ea64f | 2012-01-25 19:37:13 -0800 | [diff] [blame] | 209 | * easier to specify the factory when doing this query. |
| 210 | * |
| 211 | * @param factory the factory to use. |
The Android Open Source Project | 54b6cfa | 2008-10-21 07:00:00 -0700 | [diff] [blame] | 212 | */ |
| 213 | public void setCursorFactory(SQLiteDatabase.CursorFactory factory) { |
| 214 | mFactory = factory; |
| 215 | } |
| 216 | |
| 217 | /** |
Jeff Sharkey | 0ec586b | 2019-02-14 15:29:16 -0700 | [diff] [blame] | 218 | * Sets the cursor factory to be used for the query, as last configured by |
| 219 | * {@link #setCursorFactory(android.database.sqlite.SQLiteDatabase.CursorFactory)}. |
| 220 | */ |
| 221 | public SQLiteDatabase.CursorFactory getCursorFactory() { |
| 222 | return mFactory; |
| 223 | } |
| 224 | |
| 225 | /** |
Daniel Lehmann | 50b1f8d | 2011-06-01 15:24:23 -0700 | [diff] [blame] | 226 | * When set, the selection is verified against malicious arguments. |
| 227 | * When using this class to create a statement using |
| 228 | * {@link #buildQueryString(boolean, String, String[], String, String, String, String, String)}, |
| 229 | * non-numeric limits will raise an exception. If a projection map is specified, fields |
| 230 | * not in that map will be ignored. |
| 231 | * If this class is used to execute the statement directly using |
| 232 | * {@link #query(SQLiteDatabase, String[], String, String[], String, String, String)} |
| 233 | * or |
| 234 | * {@link #query(SQLiteDatabase, String[], String, String[], String, String, String, String)}, |
| 235 | * additionally also parenthesis escaping selection are caught. |
| 236 | * |
| 237 | * To summarize: To get maximum protection against malicious third party apps (for example |
| 238 | * content provider consumers), make sure to do the following: |
| 239 | * <ul> |
| 240 | * <li>Set this value to true</li> |
| 241 | * <li>Use a projection map</li> |
| 242 | * <li>Use one of the query overloads instead of getting the statement as a sql string</li> |
| 243 | * </ul> |
| 244 | * By default, this value is false. |
| 245 | */ |
Jeff Sharkey | 91be926 | 2018-07-19 09:30:16 -0600 | [diff] [blame] | 246 | public void setStrict(boolean flag) { |
| 247 | mStrict = flag; |
Dmitri Plotnikov | 40eb4aa | 2010-04-14 16:09:46 -0700 | [diff] [blame] | 248 | } |
| 249 | |
| 250 | /** |
Jeff Sharkey | 0ec586b | 2019-02-14 15:29:16 -0700 | [diff] [blame] | 251 | * Get if the query is marked as strict, as last configured by |
| 252 | * {@link #setStrict(boolean)}. |
| 253 | */ |
| 254 | public boolean getStrict() { |
| 255 | return mStrict; |
| 256 | } |
| 257 | |
| 258 | /** |
The Android Open Source Project | 54b6cfa | 2008-10-21 07:00:00 -0700 | [diff] [blame] | 259 | * Build an SQL query string from the given clauses. |
| 260 | * |
| 261 | * @param distinct true if you want each row to be unique, false otherwise. |
| 262 | * @param tables The table names to compile the query against. |
| 263 | * @param columns A list of which columns to return. Passing null will |
| 264 | * return all columns, which is discouraged to prevent reading |
| 265 | * data from storage that isn't going to be used. |
| 266 | * @param where A filter declaring which rows to return, formatted as an SQL |
Jeff Sharkey | b91eaa5 | 2019-02-19 11:09:13 -0700 | [diff] [blame] | 267 | * {@code WHERE} clause (excluding the {@code WHERE} itself). Passing {@code null} will |
The Android Open Source Project | 54b6cfa | 2008-10-21 07:00:00 -0700 | [diff] [blame] | 268 | * return all rows for the given URL. |
| 269 | * @param groupBy A filter declaring how to group rows, formatted as an SQL |
Jeff Sharkey | b91eaa5 | 2019-02-19 11:09:13 -0700 | [diff] [blame] | 270 | * {@code GROUP BY} clause (excluding the {@code GROUP BY} itself). Passing {@code null} |
The Android Open Source Project | 54b6cfa | 2008-10-21 07:00:00 -0700 | [diff] [blame] | 271 | * will cause the rows to not be grouped. |
| 272 | * @param having A filter declare which row groups to include in the cursor, |
Jeff Sharkey | b91eaa5 | 2019-02-19 11:09:13 -0700 | [diff] [blame] | 273 | * if row grouping is being used, formatted as an SQL {@code HAVING} |
| 274 | * clause (excluding the {@code HAVING} itself). Passing null will cause |
The Android Open Source Project | 54b6cfa | 2008-10-21 07:00:00 -0700 | [diff] [blame] | 275 | * all row groups to be included, and is required when row |
| 276 | * grouping is not being used. |
Jeff Sharkey | b91eaa5 | 2019-02-19 11:09:13 -0700 | [diff] [blame] | 277 | * @param orderBy How to order the rows, formatted as an SQL {@code ORDER BY} clause |
| 278 | * (excluding the {@code ORDER BY} itself). Passing null will use the |
The Android Open Source Project | 54b6cfa | 2008-10-21 07:00:00 -0700 | [diff] [blame] | 279 | * default sort order, which may be unordered. |
| 280 | * @param limit Limits the number of rows returned by the query, |
Jeff Sharkey | b91eaa5 | 2019-02-19 11:09:13 -0700 | [diff] [blame] | 281 | * formatted as {@code LIMIT} clause. Passing null denotes no {@code LIMIT} clause. |
The Android Open Source Project | 54b6cfa | 2008-10-21 07:00:00 -0700 | [diff] [blame] | 282 | * @return the SQL query string |
| 283 | */ |
| 284 | public static String buildQueryString( |
| 285 | boolean distinct, String tables, String[] columns, String where, |
| 286 | String groupBy, String having, String orderBy, String limit) { |
| 287 | if (TextUtils.isEmpty(groupBy) && !TextUtils.isEmpty(having)) { |
| 288 | throw new IllegalArgumentException( |
| 289 | "HAVING clauses are only permitted when using a groupBy clause"); |
| 290 | } |
Owen Lin | ab18d1f | 2009-05-06 16:45:59 -0700 | [diff] [blame] | 291 | if (!TextUtils.isEmpty(limit) && !sLimitPattern.matcher(limit).matches()) { |
| 292 | throw new IllegalArgumentException("invalid LIMIT clauses:" + limit); |
| 293 | } |
The Android Open Source Project | 54b6cfa | 2008-10-21 07:00:00 -0700 | [diff] [blame] | 294 | |
| 295 | StringBuilder query = new StringBuilder(120); |
| 296 | |
| 297 | query.append("SELECT "); |
| 298 | if (distinct) { |
| 299 | query.append("DISTINCT "); |
| 300 | } |
| 301 | if (columns != null && columns.length != 0) { |
| 302 | appendColumns(query, columns); |
| 303 | } else { |
| 304 | query.append("* "); |
| 305 | } |
| 306 | query.append("FROM "); |
| 307 | query.append(tables); |
| 308 | appendClause(query, " WHERE ", where); |
| 309 | appendClause(query, " GROUP BY ", groupBy); |
| 310 | appendClause(query, " HAVING ", having); |
| 311 | appendClause(query, " ORDER BY ", orderBy); |
Owen Lin | ab18d1f | 2009-05-06 16:45:59 -0700 | [diff] [blame] | 312 | appendClause(query, " LIMIT ", limit); |
The Android Open Source Project | 54b6cfa | 2008-10-21 07:00:00 -0700 | [diff] [blame] | 313 | |
| 314 | return query.toString(); |
| 315 | } |
| 316 | |
| 317 | private static void appendClause(StringBuilder s, String name, String clause) { |
| 318 | if (!TextUtils.isEmpty(clause)) { |
| 319 | s.append(name); |
| 320 | s.append(clause); |
| 321 | } |
| 322 | } |
| 323 | |
The Android Open Source Project | 54b6cfa | 2008-10-21 07:00:00 -0700 | [diff] [blame] | 324 | /** |
| 325 | * Add the names that are non-null in columns to s, separating |
| 326 | * them with commas. |
| 327 | */ |
| 328 | public static void appendColumns(StringBuilder s, String[] columns) { |
| 329 | int n = columns.length; |
| 330 | |
| 331 | for (int i = 0; i < n; i++) { |
| 332 | String column = columns[i]; |
| 333 | |
| 334 | if (column != null) { |
| 335 | if (i > 0) { |
| 336 | s.append(", "); |
| 337 | } |
| 338 | s.append(column); |
| 339 | } |
| 340 | } |
| 341 | s.append(' '); |
| 342 | } |
| 343 | |
| 344 | /** |
| 345 | * Perform a query by combining all current settings and the |
| 346 | * information passed into this method. |
| 347 | * |
| 348 | * @param db the database to query on |
Jeff Sharkey | 91be926 | 2018-07-19 09:30:16 -0600 | [diff] [blame] | 349 | * @param projectionIn A list of which columns to return. Passing |
The Android Open Source Project | 54b6cfa | 2008-10-21 07:00:00 -0700 | [diff] [blame] | 350 | * null will return all columns, which is discouraged to prevent |
| 351 | * reading data from storage that isn't going to be used. |
| 352 | * @param selection A filter declaring which rows to return, |
Jeff Sharkey | b91eaa5 | 2019-02-19 11:09:13 -0700 | [diff] [blame] | 353 | * formatted as an SQL {@code WHERE} clause (excluding the {@code WHERE} |
The Android Open Source Project | 54b6cfa | 2008-10-21 07:00:00 -0700 | [diff] [blame] | 354 | * itself). Passing null will return all rows for the given URL. |
| 355 | * @param selectionArgs You may include ?s in selection, which |
| 356 | * will be replaced by the values from selectionArgs, in order |
| 357 | * that they appear in the selection. The values will be bound |
| 358 | * as Strings. |
| 359 | * @param groupBy A filter declaring how to group rows, formatted |
Jeff Sharkey | b91eaa5 | 2019-02-19 11:09:13 -0700 | [diff] [blame] | 360 | * as an SQL {@code GROUP BY} clause (excluding the {@code GROUP BY} |
The Android Open Source Project | 54b6cfa | 2008-10-21 07:00:00 -0700 | [diff] [blame] | 361 | * itself). Passing null will cause the rows to not be grouped. |
| 362 | * @param having A filter declare which row groups to include in |
| 363 | * the cursor, if row grouping is being used, formatted as an |
Jeff Sharkey | b91eaa5 | 2019-02-19 11:09:13 -0700 | [diff] [blame] | 364 | * SQL {@code HAVING} clause (excluding the {@code HAVING} itself). Passing |
The Android Open Source Project | 54b6cfa | 2008-10-21 07:00:00 -0700 | [diff] [blame] | 365 | * null will cause all row groups to be included, and is |
| 366 | * required when row grouping is not being used. |
| 367 | * @param sortOrder How to order the rows, formatted as an SQL |
Jeff Sharkey | b91eaa5 | 2019-02-19 11:09:13 -0700 | [diff] [blame] | 368 | * {@code ORDER BY} clause (excluding the {@code ORDER BY} itself). Passing null |
The Android Open Source Project | 54b6cfa | 2008-10-21 07:00:00 -0700 | [diff] [blame] | 369 | * will use the default sort order, which may be unordered. |
| 370 | * @return a cursor over the result set |
| 371 | * @see android.content.ContentResolver#query(android.net.Uri, String[], |
| 372 | * String, String[], String) |
| 373 | */ |
Jeff Sharkey | 91be926 | 2018-07-19 09:30:16 -0600 | [diff] [blame] | 374 | public Cursor query(SQLiteDatabase db, String[] projectionIn, |
| 375 | String selection, String[] selectionArgs, String groupBy, |
| 376 | String having, String sortOrder) { |
| 377 | return query(db, projectionIn, selection, selectionArgs, groupBy, having, sortOrder, |
Jeff Brown | 4c1241d | 2012-02-02 17:05:00 -0800 | [diff] [blame] | 378 | null /* limit */, null /* cancellationSignal */); |
The Android Open Source Project | 54b6cfa | 2008-10-21 07:00:00 -0700 | [diff] [blame] | 379 | } |
| 380 | |
| 381 | /** |
| 382 | * Perform a query by combining all current settings and the |
| 383 | * information passed into this method. |
| 384 | * |
| 385 | * @param db the database to query on |
Jeff Sharkey | 91be926 | 2018-07-19 09:30:16 -0600 | [diff] [blame] | 386 | * @param projectionIn A list of which columns to return. Passing |
The Android Open Source Project | 54b6cfa | 2008-10-21 07:00:00 -0700 | [diff] [blame] | 387 | * null will return all columns, which is discouraged to prevent |
| 388 | * reading data from storage that isn't going to be used. |
| 389 | * @param selection A filter declaring which rows to return, |
Jeff Sharkey | b91eaa5 | 2019-02-19 11:09:13 -0700 | [diff] [blame] | 390 | * formatted as an SQL {@code WHERE} clause (excluding the {@code WHERE} |
The Android Open Source Project | 54b6cfa | 2008-10-21 07:00:00 -0700 | [diff] [blame] | 391 | * itself). Passing null will return all rows for the given URL. |
| 392 | * @param selectionArgs You may include ?s in selection, which |
| 393 | * will be replaced by the values from selectionArgs, in order |
| 394 | * that they appear in the selection. The values will be bound |
| 395 | * as Strings. |
| 396 | * @param groupBy A filter declaring how to group rows, formatted |
Jeff Sharkey | b91eaa5 | 2019-02-19 11:09:13 -0700 | [diff] [blame] | 397 | * as an SQL {@code GROUP BY} clause (excluding the {@code GROUP BY} |
The Android Open Source Project | 54b6cfa | 2008-10-21 07:00:00 -0700 | [diff] [blame] | 398 | * itself). Passing null will cause the rows to not be grouped. |
| 399 | * @param having A filter declare which row groups to include in |
| 400 | * the cursor, if row grouping is being used, formatted as an |
Jeff Sharkey | b91eaa5 | 2019-02-19 11:09:13 -0700 | [diff] [blame] | 401 | * SQL {@code HAVING} clause (excluding the {@code HAVING} itself). Passing |
The Android Open Source Project | 54b6cfa | 2008-10-21 07:00:00 -0700 | [diff] [blame] | 402 | * null will cause all row groups to be included, and is |
| 403 | * required when row grouping is not being used. |
| 404 | * @param sortOrder How to order the rows, formatted as an SQL |
Jeff Sharkey | b91eaa5 | 2019-02-19 11:09:13 -0700 | [diff] [blame] | 405 | * {@code ORDER BY} clause (excluding the {@code ORDER BY} itself). Passing null |
The Android Open Source Project | 54b6cfa | 2008-10-21 07:00:00 -0700 | [diff] [blame] | 406 | * will use the default sort order, which may be unordered. |
| 407 | * @param limit Limits the number of rows returned by the query, |
Jeff Sharkey | b91eaa5 | 2019-02-19 11:09:13 -0700 | [diff] [blame] | 408 | * formatted as {@code LIMIT} clause. Passing null denotes no {@code LIMIT} clause. |
The Android Open Source Project | 54b6cfa | 2008-10-21 07:00:00 -0700 | [diff] [blame] | 409 | * @return a cursor over the result set |
| 410 | * @see android.content.ContentResolver#query(android.net.Uri, String[], |
| 411 | * String, String[], String) |
| 412 | */ |
Jeff Sharkey | 91be926 | 2018-07-19 09:30:16 -0600 | [diff] [blame] | 413 | public Cursor query(SQLiteDatabase db, String[] projectionIn, |
| 414 | String selection, String[] selectionArgs, String groupBy, |
| 415 | String having, String sortOrder, String limit) { |
| 416 | return query(db, projectionIn, selection, selectionArgs, |
Jeff Brown | 75ea64f | 2012-01-25 19:37:13 -0800 | [diff] [blame] | 417 | groupBy, having, sortOrder, limit, null); |
| 418 | } |
| 419 | |
| 420 | /** |
| 421 | * Perform a query by combining all current settings and the |
| 422 | * information passed into this method. |
| 423 | * |
| 424 | * @param db the database to query on |
Jeff Sharkey | 91be926 | 2018-07-19 09:30:16 -0600 | [diff] [blame] | 425 | * @param projectionIn A list of which columns to return. Passing |
Jeff Brown | 75ea64f | 2012-01-25 19:37:13 -0800 | [diff] [blame] | 426 | * null will return all columns, which is discouraged to prevent |
| 427 | * reading data from storage that isn't going to be used. |
| 428 | * @param selection A filter declaring which rows to return, |
Jeff Sharkey | b91eaa5 | 2019-02-19 11:09:13 -0700 | [diff] [blame] | 429 | * formatted as an SQL {@code WHERE} clause (excluding the {@code WHERE} |
Jeff Brown | 75ea64f | 2012-01-25 19:37:13 -0800 | [diff] [blame] | 430 | * itself). Passing null will return all rows for the given URL. |
| 431 | * @param selectionArgs You may include ?s in selection, which |
| 432 | * will be replaced by the values from selectionArgs, in order |
| 433 | * that they appear in the selection. The values will be bound |
| 434 | * as Strings. |
| 435 | * @param groupBy A filter declaring how to group rows, formatted |
Jeff Sharkey | b91eaa5 | 2019-02-19 11:09:13 -0700 | [diff] [blame] | 436 | * as an SQL {@code GROUP BY} clause (excluding the {@code GROUP BY} |
Jeff Brown | 75ea64f | 2012-01-25 19:37:13 -0800 | [diff] [blame] | 437 | * itself). Passing null will cause the rows to not be grouped. |
| 438 | * @param having A filter declare which row groups to include in |
| 439 | * the cursor, if row grouping is being used, formatted as an |
Jeff Sharkey | b91eaa5 | 2019-02-19 11:09:13 -0700 | [diff] [blame] | 440 | * SQL {@code HAVING} clause (excluding the {@code HAVING} itself). Passing |
Jeff Brown | 75ea64f | 2012-01-25 19:37:13 -0800 | [diff] [blame] | 441 | * null will cause all row groups to be included, and is |
| 442 | * required when row grouping is not being used. |
| 443 | * @param sortOrder How to order the rows, formatted as an SQL |
Jeff Sharkey | b91eaa5 | 2019-02-19 11:09:13 -0700 | [diff] [blame] | 444 | * {@code ORDER BY} clause (excluding the {@code ORDER BY} itself). Passing null |
Jeff Brown | 75ea64f | 2012-01-25 19:37:13 -0800 | [diff] [blame] | 445 | * will use the default sort order, which may be unordered. |
| 446 | * @param limit Limits the number of rows returned by the query, |
Jeff Sharkey | b91eaa5 | 2019-02-19 11:09:13 -0700 | [diff] [blame] | 447 | * formatted as {@code LIMIT} clause. Passing null denotes no {@code LIMIT} clause. |
Jeff Brown | 4c1241d | 2012-02-02 17:05:00 -0800 | [diff] [blame] | 448 | * @param cancellationSignal A signal to cancel the operation in progress, or null if none. |
Jeff Brown | 75ea64f | 2012-01-25 19:37:13 -0800 | [diff] [blame] | 449 | * If the operation is canceled, then {@link OperationCanceledException} will be thrown |
| 450 | * when the query is executed. |
| 451 | * @return a cursor over the result set |
| 452 | * @see android.content.ContentResolver#query(android.net.Uri, String[], |
| 453 | * String, String[], String) |
| 454 | */ |
Jeff Sharkey | 91be926 | 2018-07-19 09:30:16 -0600 | [diff] [blame] | 455 | public Cursor query(SQLiteDatabase db, String[] projectionIn, |
| 456 | String selection, String[] selectionArgs, String groupBy, |
| 457 | String having, String sortOrder, String limit, CancellationSignal cancellationSignal) { |
| 458 | if (mTables == null) { |
The Android Open Source Project | 54b6cfa | 2008-10-21 07:00:00 -0700 | [diff] [blame] | 459 | return null; |
| 460 | } |
| 461 | |
Jeff Sharkey | be8e0d0 | 2018-07-25 14:01:59 -0600 | [diff] [blame] | 462 | final String sql; |
| 463 | final String unwrappedSql = buildQuery( |
| 464 | projectionIn, selection, groupBy, having, |
| 465 | sortOrder, limit); |
| 466 | |
Jeff Sharkey | 91be926 | 2018-07-19 09:30:16 -0600 | [diff] [blame] | 467 | if (mStrict && selection != null && selection.length() > 0) { |
Daniel Lehmann | 50b1f8d | 2011-06-01 15:24:23 -0700 | [diff] [blame] | 468 | // Validate the user-supplied selection to detect syntactic anomalies |
| 469 | // in the selection string that could indicate a SQL injection attempt. |
| 470 | // The idea is to ensure that the selection clause is a valid SQL expression |
| 471 | // by compiling it twice: once wrapped in parentheses and once as |
| 472 | // originally specified. An attacker cannot create an expression that |
| 473 | // would escape the SQL expression while maintaining balanced parentheses |
| 474 | // in both the wrapped and original forms. |
The Android Open Source Project | 54b6cfa | 2008-10-21 07:00:00 -0700 | [diff] [blame] | 475 | |
Jeff Sharkey | be8e0d0 | 2018-07-25 14:01:59 -0600 | [diff] [blame] | 476 | // NOTE: The ordering of the below operations is important; we must |
| 477 | // execute the wrapped query to ensure the untrusted clause has been |
| 478 | // fully isolated. |
| 479 | |
| 480 | // Validate the unwrapped query |
| 481 | db.validateSql(unwrappedSql, cancellationSignal); // will throw if query is invalid |
| 482 | |
| 483 | // Execute wrapped query for extra protection |
Jeff Sharkey | b13ea30 | 2018-07-25 14:52:14 -0600 | [diff] [blame] | 484 | final String wrappedSql = buildQuery(projectionIn, wrap(selection), groupBy, |
Jeff Sharkey | be8e0d0 | 2018-07-25 14:01:59 -0600 | [diff] [blame] | 485 | having, sortOrder, limit); |
| 486 | sql = wrappedSql; |
| 487 | } else { |
| 488 | // Execute unwrapped query |
| 489 | sql = unwrappedSql; |
| 490 | } |
Jeff Sharkey | 6adc98c | 2018-07-12 19:47:49 -0600 | [diff] [blame] | 491 | |
Jeff Sharkey | b13ea30 | 2018-07-25 14:52:14 -0600 | [diff] [blame] | 492 | final String[] sqlArgs = selectionArgs; |
Jeff Sharkey | 91be926 | 2018-07-19 09:30:16 -0600 | [diff] [blame] | 493 | if (Log.isLoggable(TAG, Log.DEBUG)) { |
Jeff Sharkey | b13ea30 | 2018-07-25 14:52:14 -0600 | [diff] [blame] | 494 | if (Build.IS_DEBUGGABLE) { |
| 495 | Log.d(TAG, sql + " with args " + Arrays.toString(sqlArgs)); |
| 496 | } else { |
| 497 | Log.d(TAG, sql); |
| 498 | } |
The Android Open Source Project | 54b6cfa | 2008-10-21 07:00:00 -0700 | [diff] [blame] | 499 | } |
| 500 | return db.rawQueryWithFactory( |
Jeff Sharkey | b13ea30 | 2018-07-25 14:52:14 -0600 | [diff] [blame] | 501 | mFactory, sql, sqlArgs, |
Jeff Brown | 75ea64f | 2012-01-25 19:37:13 -0800 | [diff] [blame] | 502 | SQLiteDatabase.findEditTable(mTables), |
Jeff Brown | 4c1241d | 2012-02-02 17:05:00 -0800 | [diff] [blame] | 503 | cancellationSignal); // will throw if query is invalid |
Daniel Lehmann | 50b1f8d | 2011-06-01 15:24:23 -0700 | [diff] [blame] | 504 | } |
| 505 | |
| 506 | /** |
Jeff Sharkey | b13ea30 | 2018-07-25 14:52:14 -0600 | [diff] [blame] | 507 | * Perform an update by combining all current settings and the |
| 508 | * information passed into this method. |
| 509 | * |
| 510 | * @param db the database to update on |
| 511 | * @param selection A filter declaring which rows to return, |
Jeff Sharkey | b91eaa5 | 2019-02-19 11:09:13 -0700 | [diff] [blame] | 512 | * formatted as an SQL {@code WHERE} clause (excluding the {@code WHERE} |
Jeff Sharkey | b13ea30 | 2018-07-25 14:52:14 -0600 | [diff] [blame] | 513 | * itself). Passing null will return all rows for the given URL. |
| 514 | * @param selectionArgs You may include ?s in selection, which |
| 515 | * will be replaced by the values from selectionArgs, in order |
| 516 | * that they appear in the selection. The values will be bound |
| 517 | * as Strings. |
| 518 | * @return the number of rows updated |
Jeff Sharkey | b13ea30 | 2018-07-25 14:52:14 -0600 | [diff] [blame] | 519 | */ |
| 520 | public int update(@NonNull SQLiteDatabase db, @NonNull ContentValues values, |
| 521 | @Nullable String selection, @Nullable String[] selectionArgs) { |
| 522 | Objects.requireNonNull(mTables, "No tables defined"); |
| 523 | Objects.requireNonNull(db, "No database defined"); |
| 524 | Objects.requireNonNull(values, "No values defined"); |
| 525 | |
| 526 | final String sql; |
| 527 | final String unwrappedSql = buildUpdate(values, selection); |
| 528 | |
| 529 | if (mStrict) { |
| 530 | // Validate the user-supplied selection to detect syntactic anomalies |
| 531 | // in the selection string that could indicate a SQL injection attempt. |
| 532 | // The idea is to ensure that the selection clause is a valid SQL expression |
| 533 | // by compiling it twice: once wrapped in parentheses and once as |
| 534 | // originally specified. An attacker cannot create an expression that |
| 535 | // would escape the SQL expression while maintaining balanced parentheses |
| 536 | // in both the wrapped and original forms. |
| 537 | |
| 538 | // NOTE: The ordering of the below operations is important; we must |
| 539 | // execute the wrapped query to ensure the untrusted clause has been |
| 540 | // fully isolated. |
| 541 | |
| 542 | // Validate the unwrapped query |
| 543 | db.validateSql(unwrappedSql, null); // will throw if query is invalid |
| 544 | |
| 545 | // Execute wrapped query for extra protection |
| 546 | final String wrappedSql = buildUpdate(values, wrap(selection)); |
| 547 | sql = wrappedSql; |
| 548 | } else { |
| 549 | // Execute unwrapped query |
| 550 | sql = unwrappedSql; |
| 551 | } |
| 552 | |
Jeff Sharkey | 42122bf | 2018-07-26 09:39:18 -0600 | [diff] [blame] | 553 | if (selectionArgs == null) { |
| 554 | selectionArgs = EmptyArray.STRING; |
Jeff Sharkey | b13ea30 | 2018-07-25 14:52:14 -0600 | [diff] [blame] | 555 | } |
Jeff Sharkey | 42122bf | 2018-07-26 09:39:18 -0600 | [diff] [blame] | 556 | final ArrayMap<String, Object> rawValues = values.getValues(); |
| 557 | final int valuesLength = rawValues.size(); |
| 558 | final Object[] sqlArgs = new Object[valuesLength + selectionArgs.length]; |
| 559 | for (int i = 0; i < sqlArgs.length; i++) { |
| 560 | if (i < valuesLength) { |
| 561 | sqlArgs[i] = rawValues.valueAt(i); |
| 562 | } else { |
| 563 | sqlArgs[i] = selectionArgs[i - valuesLength]; |
| 564 | } |
| 565 | } |
Jeff Sharkey | b13ea30 | 2018-07-25 14:52:14 -0600 | [diff] [blame] | 566 | if (Log.isLoggable(TAG, Log.DEBUG)) { |
| 567 | if (Build.IS_DEBUGGABLE) { |
| 568 | Log.d(TAG, sql + " with args " + Arrays.toString(sqlArgs)); |
| 569 | } else { |
| 570 | Log.d(TAG, sql); |
| 571 | } |
| 572 | } |
| 573 | return db.executeSql(sql, sqlArgs); |
| 574 | } |
| 575 | |
| 576 | /** |
| 577 | * Perform a delete by combining all current settings and the |
| 578 | * information passed into this method. |
| 579 | * |
| 580 | * @param db the database to delete on |
| 581 | * @param selection A filter declaring which rows to return, |
Jeff Sharkey | b91eaa5 | 2019-02-19 11:09:13 -0700 | [diff] [blame] | 582 | * formatted as an SQL {@code WHERE} clause (excluding the {@code WHERE} |
Jeff Sharkey | b13ea30 | 2018-07-25 14:52:14 -0600 | [diff] [blame] | 583 | * itself). Passing null will return all rows for the given URL. |
| 584 | * @param selectionArgs You may include ?s in selection, which |
| 585 | * will be replaced by the values from selectionArgs, in order |
| 586 | * that they appear in the selection. The values will be bound |
| 587 | * as Strings. |
| 588 | * @return the number of rows deleted |
Jeff Sharkey | b13ea30 | 2018-07-25 14:52:14 -0600 | [diff] [blame] | 589 | */ |
| 590 | public int delete(@NonNull SQLiteDatabase db, @Nullable String selection, |
| 591 | @Nullable String[] selectionArgs) { |
| 592 | Objects.requireNonNull(mTables, "No tables defined"); |
| 593 | Objects.requireNonNull(db, "No database defined"); |
| 594 | |
| 595 | final String sql; |
| 596 | final String unwrappedSql = buildDelete(selection); |
| 597 | |
| 598 | if (mStrict) { |
| 599 | // Validate the user-supplied selection to detect syntactic anomalies |
| 600 | // in the selection string that could indicate a SQL injection attempt. |
| 601 | // The idea is to ensure that the selection clause is a valid SQL expression |
| 602 | // by compiling it twice: once wrapped in parentheses and once as |
| 603 | // originally specified. An attacker cannot create an expression that |
| 604 | // would escape the SQL expression while maintaining balanced parentheses |
| 605 | // in both the wrapped and original forms. |
| 606 | |
| 607 | // NOTE: The ordering of the below operations is important; we must |
| 608 | // execute the wrapped query to ensure the untrusted clause has been |
| 609 | // fully isolated. |
| 610 | |
| 611 | // Validate the unwrapped query |
| 612 | db.validateSql(unwrappedSql, null); // will throw if query is invalid |
| 613 | |
| 614 | // Execute wrapped query for extra protection |
| 615 | final String wrappedSql = buildDelete(wrap(selection)); |
| 616 | sql = wrappedSql; |
| 617 | } else { |
| 618 | // Execute unwrapped query |
| 619 | sql = unwrappedSql; |
| 620 | } |
| 621 | |
| 622 | final String[] sqlArgs = selectionArgs; |
| 623 | if (Log.isLoggable(TAG, Log.DEBUG)) { |
| 624 | if (Build.IS_DEBUGGABLE) { |
| 625 | Log.d(TAG, sql + " with args " + Arrays.toString(sqlArgs)); |
| 626 | } else { |
| 627 | Log.d(TAG, sql); |
| 628 | } |
| 629 | } |
| 630 | return db.executeSql(sql, sqlArgs); |
| 631 | } |
| 632 | |
| 633 | /** |
Jeff Sharkey | b91eaa5 | 2019-02-19 11:09:13 -0700 | [diff] [blame] | 634 | * Construct a {@code SELECT} statement suitable for use in a group of |
| 635 | * {@code SELECT} statements that will be joined through {@code UNION} operators |
The Android Open Source Project | 54b6cfa | 2008-10-21 07:00:00 -0700 | [diff] [blame] | 636 | * in buildUnionQuery. |
| 637 | * |
| 638 | * @param projectionIn A list of which columns to return. Passing |
| 639 | * null will return all columns, which is discouraged to |
| 640 | * prevent reading data from storage that isn't going to be |
| 641 | * used. |
| 642 | * @param selection A filter declaring which rows to return, |
Jeff Sharkey | b91eaa5 | 2019-02-19 11:09:13 -0700 | [diff] [blame] | 643 | * formatted as an SQL {@code WHERE} clause (excluding the {@code WHERE} |
The Android Open Source Project | 54b6cfa | 2008-10-21 07:00:00 -0700 | [diff] [blame] | 644 | * itself). Passing null will return all rows for the given |
| 645 | * URL. |
The Android Open Source Project | 54b6cfa | 2008-10-21 07:00:00 -0700 | [diff] [blame] | 646 | * @param groupBy A filter declaring how to group rows, formatted |
Jeff Sharkey | b91eaa5 | 2019-02-19 11:09:13 -0700 | [diff] [blame] | 647 | * as an SQL {@code GROUP BY} clause (excluding the {@code GROUP BY} itself). |
The Android Open Source Project | 54b6cfa | 2008-10-21 07:00:00 -0700 | [diff] [blame] | 648 | * Passing null will cause the rows to not be grouped. |
| 649 | * @param having A filter declare which row groups to include in |
| 650 | * the cursor, if row grouping is being used, formatted as an |
Jeff Sharkey | b91eaa5 | 2019-02-19 11:09:13 -0700 | [diff] [blame] | 651 | * SQL {@code HAVING} clause (excluding the {@code HAVING} itself). Passing |
The Android Open Source Project | 54b6cfa | 2008-10-21 07:00:00 -0700 | [diff] [blame] | 652 | * null will cause all row groups to be included, and is |
| 653 | * required when row grouping is not being used. |
| 654 | * @param sortOrder How to order the rows, formatted as an SQL |
Jeff Sharkey | b91eaa5 | 2019-02-19 11:09:13 -0700 | [diff] [blame] | 655 | * {@code ORDER BY} clause (excluding the {@code ORDER BY} itself). Passing null |
The Android Open Source Project | 54b6cfa | 2008-10-21 07:00:00 -0700 | [diff] [blame] | 656 | * will use the default sort order, which may be unordered. |
| 657 | * @param limit Limits the number of rows returned by the query, |
Jeff Sharkey | b91eaa5 | 2019-02-19 11:09:13 -0700 | [diff] [blame] | 658 | * formatted as {@code LIMIT} clause. Passing null denotes no {@code LIMIT} clause. |
| 659 | * @return the resulting SQL {@code SELECT} statement |
The Android Open Source Project | 54b6cfa | 2008-10-21 07:00:00 -0700 | [diff] [blame] | 660 | */ |
| 661 | public String buildQuery( |
Jonas Schwertfeger | 8402903 | 2010-11-12 11:42:28 +0100 | [diff] [blame] | 662 | String[] projectionIn, String selection, String groupBy, |
| 663 | String having, String sortOrder, String limit) { |
The Android Open Source Project | 54b6cfa | 2008-10-21 07:00:00 -0700 | [diff] [blame] | 664 | String[] projection = computeProjection(projectionIn); |
Jeff Sharkey | b13ea30 | 2018-07-25 14:52:14 -0600 | [diff] [blame] | 665 | String where = computeWhere(selection); |
The Android Open Source Project | 54b6cfa | 2008-10-21 07:00:00 -0700 | [diff] [blame] | 666 | |
| 667 | return buildQueryString( |
Jeff Sharkey | b13ea30 | 2018-07-25 14:52:14 -0600 | [diff] [blame] | 668 | mDistinct, mTables, projection, where, |
The Android Open Source Project | 54b6cfa | 2008-10-21 07:00:00 -0700 | [diff] [blame] | 669 | groupBy, having, sortOrder, limit); |
| 670 | } |
| 671 | |
| 672 | /** |
Jonas Schwertfeger | 8402903 | 2010-11-12 11:42:28 +0100 | [diff] [blame] | 673 | * @deprecated This method's signature is misleading since no SQL parameter |
| 674 | * substitution is carried out. The selection arguments parameter does not get |
| 675 | * used at all. To avoid confusion, call |
| 676 | * {@link #buildQuery(String[], String, String, String, String, String)} instead. |
| 677 | */ |
| 678 | @Deprecated |
| 679 | public String buildQuery( |
| 680 | String[] projectionIn, String selection, String[] selectionArgs, |
| 681 | String groupBy, String having, String sortOrder, String limit) { |
| 682 | return buildQuery(projectionIn, selection, groupBy, having, sortOrder, limit); |
| 683 | } |
| 684 | |
Jeff Sharkey | b13ea30 | 2018-07-25 14:52:14 -0600 | [diff] [blame] | 685 | /** {@hide} */ |
| 686 | public String buildUpdate(ContentValues values, String selection) { |
| 687 | if (values == null || values.isEmpty()) { |
| 688 | throw new IllegalArgumentException("Empty values"); |
| 689 | } |
| 690 | |
| 691 | StringBuilder sql = new StringBuilder(120); |
| 692 | sql.append("UPDATE "); |
| 693 | sql.append(mTables); |
| 694 | sql.append(" SET "); |
| 695 | |
| 696 | final ArrayMap<String, Object> rawValues = values.getValues(); |
| 697 | for (int i = 0; i < rawValues.size(); i++) { |
| 698 | if (i > 0) { |
| 699 | sql.append(','); |
| 700 | } |
| 701 | sql.append(rawValues.keyAt(i)); |
| 702 | sql.append("=?"); |
| 703 | } |
| 704 | |
| 705 | final String where = computeWhere(selection); |
| 706 | appendClause(sql, " WHERE ", where); |
| 707 | return sql.toString(); |
| 708 | } |
| 709 | |
| 710 | /** {@hide} */ |
| 711 | public String buildDelete(String selection) { |
| 712 | StringBuilder sql = new StringBuilder(120); |
| 713 | sql.append("DELETE FROM "); |
| 714 | sql.append(mTables); |
| 715 | |
| 716 | final String where = computeWhere(selection); |
| 717 | appendClause(sql, " WHERE ", where); |
| 718 | return sql.toString(); |
| 719 | } |
| 720 | |
Jonas Schwertfeger | 8402903 | 2010-11-12 11:42:28 +0100 | [diff] [blame] | 721 | /** |
Jeff Sharkey | b91eaa5 | 2019-02-19 11:09:13 -0700 | [diff] [blame] | 722 | * Construct a {@code SELECT} statement suitable for use in a group of |
| 723 | * {@code SELECT} statements that will be joined through {@code UNION} operators |
The Android Open Source Project | 54b6cfa | 2008-10-21 07:00:00 -0700 | [diff] [blame] | 724 | * in buildUnionQuery. |
| 725 | * |
| 726 | * @param typeDiscriminatorColumn the name of the result column |
| 727 | * whose cells will contain the name of the table from which |
| 728 | * each row was drawn. |
| 729 | * @param unionColumns the names of the columns to appear in the |
| 730 | * result. This may include columns that do not appear in the |
Jeff Sharkey | b91eaa5 | 2019-02-19 11:09:13 -0700 | [diff] [blame] | 731 | * table this {@code SELECT} is querying (i.e. mTables), but that do |
| 732 | * appear in one of the other tables in the {@code UNION} query that we |
The Android Open Source Project | 54b6cfa | 2008-10-21 07:00:00 -0700 | [diff] [blame] | 733 | * are constructing. |
| 734 | * @param columnsPresentInTable a Set of the names of the columns |
| 735 | * that appear in this table (i.e. in the table whose name is |
| 736 | * mTables). Since columns in unionColumns include columns that |
| 737 | * appear only in other tables, we use this array to distinguish |
| 738 | * which ones actually are present. Other columns will have |
| 739 | * NULL values for results from this subquery. |
| 740 | * @param computedColumnsOffset all columns in unionColumns before |
| 741 | * this index are included under the assumption that they're |
| 742 | * computed and therefore won't appear in columnsPresentInTable, |
| 743 | * e.g. "date * 1000 as normalized_date" |
| 744 | * @param typeDiscriminatorValue the value used for the |
| 745 | * type-discriminator column in this subquery |
| 746 | * @param selection A filter declaring which rows to return, |
Jeff Sharkey | b91eaa5 | 2019-02-19 11:09:13 -0700 | [diff] [blame] | 747 | * formatted as an SQL {@code WHERE} clause (excluding the {@code WHERE} |
The Android Open Source Project | 54b6cfa | 2008-10-21 07:00:00 -0700 | [diff] [blame] | 748 | * itself). Passing null will return all rows for the given |
| 749 | * URL. |
The Android Open Source Project | 54b6cfa | 2008-10-21 07:00:00 -0700 | [diff] [blame] | 750 | * @param groupBy A filter declaring how to group rows, formatted |
Jeff Sharkey | b91eaa5 | 2019-02-19 11:09:13 -0700 | [diff] [blame] | 751 | * as an SQL {@code GROUP BY} clause (excluding the {@code GROUP BY} itself). |
The Android Open Source Project | 54b6cfa | 2008-10-21 07:00:00 -0700 | [diff] [blame] | 752 | * Passing null will cause the rows to not be grouped. |
| 753 | * @param having A filter declare which row groups to include in |
| 754 | * the cursor, if row grouping is being used, formatted as an |
Jeff Sharkey | b91eaa5 | 2019-02-19 11:09:13 -0700 | [diff] [blame] | 755 | * SQL {@code HAVING} clause (excluding the {@code HAVING} itself). Passing |
The Android Open Source Project | 54b6cfa | 2008-10-21 07:00:00 -0700 | [diff] [blame] | 756 | * null will cause all row groups to be included, and is |
| 757 | * required when row grouping is not being used. |
Jeff Sharkey | b91eaa5 | 2019-02-19 11:09:13 -0700 | [diff] [blame] | 758 | * @return the resulting SQL {@code SELECT} statement |
The Android Open Source Project | 54b6cfa | 2008-10-21 07:00:00 -0700 | [diff] [blame] | 759 | */ |
| 760 | public String buildUnionSubQuery( |
| 761 | String typeDiscriminatorColumn, |
| 762 | String[] unionColumns, |
| 763 | Set<String> columnsPresentInTable, |
| 764 | int computedColumnsOffset, |
| 765 | String typeDiscriminatorValue, |
| 766 | String selection, |
The Android Open Source Project | 54b6cfa | 2008-10-21 07:00:00 -0700 | [diff] [blame] | 767 | String groupBy, |
| 768 | String having) { |
| 769 | int unionColumnsCount = unionColumns.length; |
| 770 | String[] projectionIn = new String[unionColumnsCount]; |
| 771 | |
| 772 | for (int i = 0; i < unionColumnsCount; i++) { |
| 773 | String unionColumn = unionColumns[i]; |
| 774 | |
| 775 | if (unionColumn.equals(typeDiscriminatorColumn)) { |
| 776 | projectionIn[i] = "'" + typeDiscriminatorValue + "' AS " |
| 777 | + typeDiscriminatorColumn; |
| 778 | } else if (i <= computedColumnsOffset |
| 779 | || columnsPresentInTable.contains(unionColumn)) { |
| 780 | projectionIn[i] = unionColumn; |
| 781 | } else { |
| 782 | projectionIn[i] = "NULL AS " + unionColumn; |
| 783 | } |
| 784 | } |
| 785 | return buildQuery( |
Jonas Schwertfeger | 8402903 | 2010-11-12 11:42:28 +0100 | [diff] [blame] | 786 | projectionIn, selection, groupBy, having, |
The Android Open Source Project | 54b6cfa | 2008-10-21 07:00:00 -0700 | [diff] [blame] | 787 | null /* sortOrder */, |
| 788 | null /* limit */); |
| 789 | } |
| 790 | |
| 791 | /** |
Jonas Schwertfeger | 8402903 | 2010-11-12 11:42:28 +0100 | [diff] [blame] | 792 | * @deprecated This method's signature is misleading since no SQL parameter |
| 793 | * substitution is carried out. The selection arguments parameter does not get |
| 794 | * used at all. To avoid confusion, call |
Jean-Baptiste Queru | f4072fc | 2010-11-17 16:47:59 -0800 | [diff] [blame] | 795 | * {@link #buildUnionSubQuery} |
Jonas Schwertfeger | 8402903 | 2010-11-12 11:42:28 +0100 | [diff] [blame] | 796 | * instead. |
| 797 | */ |
| 798 | @Deprecated |
| 799 | public String buildUnionSubQuery( |
| 800 | String typeDiscriminatorColumn, |
| 801 | String[] unionColumns, |
| 802 | Set<String> columnsPresentInTable, |
| 803 | int computedColumnsOffset, |
| 804 | String typeDiscriminatorValue, |
| 805 | String selection, |
| 806 | String[] selectionArgs, |
| 807 | String groupBy, |
| 808 | String having) { |
| 809 | return buildUnionSubQuery( |
| 810 | typeDiscriminatorColumn, unionColumns, columnsPresentInTable, |
| 811 | computedColumnsOffset, typeDiscriminatorValue, selection, |
| 812 | groupBy, having); |
| 813 | } |
| 814 | |
| 815 | /** |
Jeff Sharkey | b91eaa5 | 2019-02-19 11:09:13 -0700 | [diff] [blame] | 816 | * Given a set of subqueries, all of which are {@code SELECT} statements, |
The Android Open Source Project | 54b6cfa | 2008-10-21 07:00:00 -0700 | [diff] [blame] | 817 | * construct a query that returns the union of what those |
| 818 | * subqueries return. |
Jeff Sharkey | b91eaa5 | 2019-02-19 11:09:13 -0700 | [diff] [blame] | 819 | * @param subQueries an array of SQL {@code SELECT} statements, all of |
The Android Open Source Project | 54b6cfa | 2008-10-21 07:00:00 -0700 | [diff] [blame] | 820 | * which must have the same columns as the same positions in |
| 821 | * their results |
| 822 | * @param sortOrder How to order the rows, formatted as an SQL |
Jeff Sharkey | b91eaa5 | 2019-02-19 11:09:13 -0700 | [diff] [blame] | 823 | * {@code ORDER BY} clause (excluding the {@code ORDER BY} itself). Passing |
The Android Open Source Project | 54b6cfa | 2008-10-21 07:00:00 -0700 | [diff] [blame] | 824 | * null will use the default sort order, which may be unordered. |
| 825 | * @param limit The limit clause, which applies to the entire union result set |
| 826 | * |
Jeff Sharkey | b91eaa5 | 2019-02-19 11:09:13 -0700 | [diff] [blame] | 827 | * @return the resulting SQL {@code SELECT} statement |
The Android Open Source Project | 54b6cfa | 2008-10-21 07:00:00 -0700 | [diff] [blame] | 828 | */ |
| 829 | public String buildUnionQuery(String[] subQueries, String sortOrder, String limit) { |
| 830 | StringBuilder query = new StringBuilder(128); |
| 831 | int subQueryCount = subQueries.length; |
| 832 | String unionOperator = mDistinct ? " UNION " : " UNION ALL "; |
| 833 | |
| 834 | for (int i = 0; i < subQueryCount; i++) { |
| 835 | if (i > 0) { |
| 836 | query.append(unionOperator); |
| 837 | } |
| 838 | query.append(subQueries[i]); |
| 839 | } |
| 840 | appendClause(query, " ORDER BY ", sortOrder); |
| 841 | appendClause(query, " LIMIT ", limit); |
| 842 | return query.toString(); |
| 843 | } |
| 844 | |
Mathew Inwood | 31755f9 | 2018-12-20 13:53:36 +0000 | [diff] [blame] | 845 | @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023) |
Jeff Sharkey | 91be926 | 2018-07-19 09:30:16 -0600 | [diff] [blame] | 846 | private String[] computeProjection(String[] projectionIn) { |
The Android Open Source Project | 54b6cfa | 2008-10-21 07:00:00 -0700 | [diff] [blame] | 847 | if (projectionIn != null && projectionIn.length > 0) { |
| 848 | if (mProjectionMap != null) { |
| 849 | String[] projection = new String[projectionIn.length]; |
| 850 | int length = projectionIn.length; |
| 851 | |
| 852 | for (int i = 0; i < length; i++) { |
| 853 | String userColumn = projectionIn[i]; |
| 854 | String column = mProjectionMap.get(userColumn); |
| 855 | |
Michael Chan | 99c4483 | 2009-04-27 16:28:51 -0700 | [diff] [blame] | 856 | if (column != null) { |
The Android Open Source Project | 54b6cfa | 2008-10-21 07:00:00 -0700 | [diff] [blame] | 857 | projection[i] = column; |
Michael Chan | 99c4483 | 2009-04-27 16:28:51 -0700 | [diff] [blame] | 858 | continue; |
The Android Open Source Project | 54b6cfa | 2008-10-21 07:00:00 -0700 | [diff] [blame] | 859 | } |
Michael Chan | 99c4483 | 2009-04-27 16:28:51 -0700 | [diff] [blame] | 860 | |
Daniel Lehmann | 50b1f8d | 2011-06-01 15:24:23 -0700 | [diff] [blame] | 861 | if (!mStrict && |
Dmitri Plotnikov | 40eb4aa | 2010-04-14 16:09:46 -0700 | [diff] [blame] | 862 | ( userColumn.contains(" AS ") || userColumn.contains(" as "))) { |
Michael Chan | 99c4483 | 2009-04-27 16:28:51 -0700 | [diff] [blame] | 863 | /* A column alias already exist */ |
| 864 | projection[i] = userColumn; |
| 865 | continue; |
| 866 | } |
| 867 | |
Jeff Sharkey | 7049e65 | 2018-09-13 17:05:07 -0600 | [diff] [blame] | 868 | // If greylist is configured, we might be willing to let |
| 869 | // this custom column bypass our strict checks. |
| 870 | if (mProjectionGreylist != null) { |
| 871 | boolean match = false; |
| 872 | for (Pattern p : mProjectionGreylist) { |
| 873 | if (p.matcher(userColumn).matches()) { |
| 874 | match = true; |
| 875 | break; |
| 876 | } |
| 877 | } |
| 878 | |
| 879 | if (match) { |
| 880 | Log.w(TAG, "Allowing abusive custom column: " + userColumn); |
| 881 | projection[i] = userColumn; |
| 882 | continue; |
| 883 | } |
| 884 | } |
| 885 | |
Michael Chan | 99c4483 | 2009-04-27 16:28:51 -0700 | [diff] [blame] | 886 | throw new IllegalArgumentException("Invalid column " |
Jeff Sharkey | 91be926 | 2018-07-19 09:30:16 -0600 | [diff] [blame] | 887 | + projectionIn[i]); |
The Android Open Source Project | 54b6cfa | 2008-10-21 07:00:00 -0700 | [diff] [blame] | 888 | } |
| 889 | return projection; |
| 890 | } else { |
| 891 | return projectionIn; |
| 892 | } |
| 893 | } else if (mProjectionMap != null) { |
| 894 | // Return all columns in projection map. |
| 895 | Set<Entry<String, String>> entrySet = mProjectionMap.entrySet(); |
| 896 | String[] projection = new String[entrySet.size()]; |
| 897 | Iterator<Entry<String, String>> entryIter = entrySet.iterator(); |
| 898 | int i = 0; |
| 899 | |
| 900 | while (entryIter.hasNext()) { |
| 901 | Entry<String, String> entry = entryIter.next(); |
| 902 | |
| 903 | // Don't include the _count column when people ask for no projection. |
| 904 | if (entry.getKey().equals(BaseColumns._COUNT)) { |
| 905 | continue; |
| 906 | } |
| 907 | projection[i++] = entry.getValue(); |
| 908 | } |
| 909 | return projection; |
| 910 | } |
| 911 | return null; |
| 912 | } |
Jeff Sharkey | b13ea30 | 2018-07-25 14:52:14 -0600 | [diff] [blame] | 913 | |
| 914 | private @Nullable String computeWhere(@Nullable String selection) { |
| 915 | final boolean hasInternal = !TextUtils.isEmpty(mWhereClause); |
| 916 | final boolean hasExternal = !TextUtils.isEmpty(selection); |
| 917 | |
| 918 | if (hasInternal || hasExternal) { |
| 919 | final StringBuilder where = new StringBuilder(); |
| 920 | if (hasInternal) { |
| 921 | where.append('(').append(mWhereClause).append(')'); |
| 922 | } |
| 923 | if (hasInternal && hasExternal) { |
| 924 | where.append(" AND "); |
| 925 | } |
| 926 | if (hasExternal) { |
| 927 | where.append('(').append(selection).append(')'); |
| 928 | } |
| 929 | return where.toString(); |
| 930 | } else { |
| 931 | return null; |
| 932 | } |
| 933 | } |
| 934 | |
| 935 | /** |
| 936 | * Wrap given argument in parenthesis, unless it's {@code null} or |
| 937 | * {@code ()}, in which case return it verbatim. |
| 938 | */ |
| 939 | private @Nullable String wrap(@Nullable String arg) { |
| 940 | if (TextUtils.isEmpty(arg)) { |
| 941 | return arg; |
| 942 | } else { |
| 943 | return "(" + arg + ")"; |
| 944 | } |
| 945 | } |
The Android Open Source Project | 54b6cfa | 2008-10-21 07:00:00 -0700 | [diff] [blame] | 946 | } |