1 /*
2  * Copyright (C) 2022 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 com.android.server.healthconnect.storage.utils;
18 
19 import android.util.Pair;
20 
21 import java.util.ArrayList;
22 import java.util.List;
23 
24 /** @hide */
25 public final class OrderByClause {
26     @SuppressWarnings("NullAway.Init") // TODO(b/317029272): fix this suppression
27     List<Pair<String, Boolean>> mOrderList;
28 
29     /**
30      * Adds Order By condition for the read query.
31      *
32      * @param columnName the column name on which sorting to be done
33      * @param isAscending to specify the sorting order
34      */
addOrderByClause(String columnName, boolean isAscending)35     public OrderByClause addOrderByClause(String columnName, boolean isAscending) {
36         if (mOrderList == null) {
37             mOrderList = new ArrayList<>();
38         }
39         mOrderList.add(new Pair<>(columnName, isAscending));
40         return this;
41     }
42 
43     /**
44      * Returns the Order By clause for the read query
45      *
46      * @return ordery by clause containing all the order by column conditions in order
47      */
getOrderBy()48     public String getOrderBy() {
49         if (mOrderList == null) {
50             return "";
51         }
52         final StringBuilder builder = new StringBuilder(" ORDER BY ");
53         String prefix = "";
54         for (Pair<String, Boolean> column : mOrderList) {
55             builder.append(prefix);
56             prefix = " , ";
57             builder.append(column.first);
58             if (!column.second) {
59                 builder.append(" DESC ");
60             }
61         }
62         return builder.toString();
63     }
64 }
65