1 /*
2 * Copyright 2020 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 @file:JvmName("RawQueries")
17
18 package androidx.work.impl.utils
19
20 import androidx.sqlite.db.SimpleSQLiteQuery
21 import androidx.sqlite.db.SupportSQLiteQuery
22 import androidx.work.WorkQuery
23 import androidx.work.impl.model.WorkTypeConverters.stateToInt
24
25 /**
26 * Converts a [WorkQuery] to a raw [SupportSQLiteQuery].
27 *
28 * @return a [SupportSQLiteQuery] instance
29 */
toRawQuerynull30 fun WorkQuery.toRawQuery(): SupportSQLiteQuery {
31 val arguments = mutableListOf<Any>()
32 val builder = StringBuilder("SELECT * FROM workspec")
33 var conjunction = " WHERE"
34 if (states.isNotEmpty()) {
35 val stateIds = states.map { stateToInt(it) }
36 builder.append("$conjunction state IN (")
37 bindings(builder, stateIds.size)
38 builder.append(")")
39 arguments.addAll(stateIds)
40 conjunction = " AND"
41 }
42 if (ids.isNotEmpty()) {
43 val workSpecIds = ids.map { it.toString() }
44 builder.append("$conjunction id IN (")
45 bindings(builder, ids.size)
46 builder.append(")")
47 arguments.addAll(workSpecIds)
48 conjunction = " AND"
49 }
50 if (tags.isNotEmpty()) {
51 builder.append("$conjunction id IN (SELECT work_spec_id FROM worktag WHERE tag IN (")
52 bindings(builder, tags.size)
53 builder.append("))")
54 arguments.addAll(tags)
55 conjunction = " AND"
56 }
57 if (uniqueWorkNames.isNotEmpty()) {
58 builder.append("$conjunction id IN (SELECT work_spec_id FROM workname WHERE name IN (")
59 bindings(builder, uniqueWorkNames.size)
60 builder.append("))")
61 arguments.addAll(uniqueWorkNames)
62 }
63 builder.append(";")
64 return SimpleSQLiteQuery(builder.toString(), arguments.toTypedArray())
65 }
66
bindingsnull67 private fun bindings(builder: StringBuilder, count: Int) {
68 if (count <= 0) {
69 return
70 }
71 builder.append((List(count) { "?" }.joinToString(",")))
72 }
73