summaryrefslogtreecommitdiff
path: root/adservices/service-core/java/com/android/adservices/data/customaudience/CustomAudienceDao.java
blob: 5b9d1f8254fe28a15a41de19d8f9ce2553bfe4d0 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
/*
 * Copyright (C) 2022 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.android.adservices.data.customaudience;

import android.adservices.common.AdTechIdentifier;
import android.content.pm.PackageManager;
import android.net.Uri;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.room.Dao;
import androidx.room.Insert;
import androidx.room.OnConflictStrategy;
import androidx.room.Query;
import androidx.room.Transaction;

import com.android.adservices.LogUtil;
import com.android.adservices.data.enrollment.EnrollmentDao;
import com.android.adservices.service.Flags;
import com.android.adservices.service.common.AllowLists;
import com.android.adservices.service.customaudience.CustomAudienceUpdatableData;
import com.android.internal.annotations.VisibleForTesting;

import java.time.Instant;
import java.util.List;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * DAO abstract class used to access Custom Audience persistent storage.
 *
 * <p>Annotations will generate Room-based SQLite Dao impl.
 */
@Dao
public abstract class CustomAudienceDao {
    /**
     * Add user to a new custom audience. As designed, will override existing one.
     *
     * <p>This method is not meant to be used on its own, since custom audiences must be persisted
     * alongside matching background fetch data. Use {@link
     * #insertOrOverwriteCustomAudience(DBCustomAudience, Uri)} instead.
     */
    @Insert(onConflict = OnConflictStrategy.REPLACE)
    protected abstract void persistCustomAudience(@NonNull DBCustomAudience customAudience);

    /**
     * Adds or updates background fetch data for a custom audience.
     *
     * <p>This method does not update the corresponding custom audience. Use {@link
     * #updateCustomAudienceAndBackgroundFetchData(DBCustomAudienceBackgroundFetchData,
     * CustomAudienceUpdatableData)} to do so safely.
     */
    @Insert(onConflict = OnConflictStrategy.REPLACE)
    public abstract void persistCustomAudienceBackgroundFetchData(
            @NonNull DBCustomAudienceBackgroundFetchData fetchData);

    /**
     * Adds or updates a given custom audience and background fetch data in a single transaction.
     *
     * <p>This transaction is separate in order to minimize the critical region while locking the
     * database. It is not meant to be exposed or used by itself; use {@link
     * #insertOrOverwriteCustomAudience(DBCustomAudience, Uri)} instead.
     */
    @Transaction
    protected void insertOrOverwriteCustomAudienceAndBackgroundFetchData(
            @NonNull DBCustomAudience customAudience,
            @NonNull DBCustomAudienceBackgroundFetchData fetchData) {
        persistCustomAudience(customAudience);
        persistCustomAudienceBackgroundFetchData(fetchData);
    }

    /**
     * Adds the user to the given custom audience.
     *
     * <p>If a custom audience already exists, it is overwritten completely.
     *
     * <p>Background fetch data is also created based on the given {@code customAudience} and {@code
     * dailyUpdateUri} and overwrites any existing background fetch data. This method assumes the
     * input parameters have already been validated and are correct.
     */
    public void insertOrOverwriteCustomAudience(
            @NonNull DBCustomAudience customAudience, @NonNull Uri dailyUpdateUri) {
        Objects.requireNonNull(customAudience);
        Objects.requireNonNull(dailyUpdateUri);

        Instant eligibleUpdateTime;
        if (customAudience.getUserBiddingSignals() == null
                || customAudience.getTrustedBiddingData() == null
                || customAudience.getAds() == null
                || customAudience.getAds().isEmpty()) {
            eligibleUpdateTime = Instant.EPOCH;
        } else {
            eligibleUpdateTime =
                    DBCustomAudienceBackgroundFetchData
                            .computeNextEligibleUpdateTimeAfterSuccessfulUpdate(
                                    customAudience.getCreationTime());
        }

        DBCustomAudienceBackgroundFetchData fetchData =
                DBCustomAudienceBackgroundFetchData.builder()
                        .setOwner(customAudience.getOwner())
                        .setBuyer(customAudience.getBuyer())
                        .setName(customAudience.getName())
                        .setDailyUpdateUri(dailyUpdateUri)
                        .setEligibleUpdateTime(eligibleUpdateTime)
                        .build();

        insertOrOverwriteCustomAudienceAndBackgroundFetchData(customAudience, fetchData);
    }

    /**
     * Updates a custom audience and its background fetch data based on the given {@link
     * CustomAudienceUpdatableData} in a single transaction.
     *
     * <p>If no custom audience is found corresponding to the given {@link
     * DBCustomAudienceBackgroundFetchData}, no action is taken.
     */
    @Transaction
    public void updateCustomAudienceAndBackgroundFetchData(
            @NonNull DBCustomAudienceBackgroundFetchData fetchData,
            @NonNull CustomAudienceUpdatableData updatableData) {
        Objects.requireNonNull(fetchData);
        Objects.requireNonNull(updatableData);

        DBCustomAudience customAudience =
                getCustomAudienceByPrimaryKey(
                        fetchData.getOwner(), fetchData.getBuyer(), fetchData.getName());

        if (customAudience == null) {
            // This custom audience could have been cleaned up while it was being updated
            return;
        }

        customAudience = customAudience.copyWithUpdatableData(updatableData);

        persistCustomAudience(customAudience);
        persistCustomAudienceBackgroundFetchData(fetchData);
    }

    /** Get count of custom audience. */
    @Query("SELECT COUNT(*) FROM custom_audience")
    public abstract long getCustomAudienceCount();

    /** Get count of custom audience of a given owner. */
    @Query("SELECT COUNT(*) FROM custom_audience WHERE owner=:owner")
    public abstract long getCustomAudienceCountForOwner(String owner);

    /** Get the total number of distinct custom audience owner. */
    @Query("SELECT COUNT(DISTINCT owner) FROM custom_audience")
    public abstract long getCustomAudienceOwnerCount();

    /**
     * Get the count of total custom audience, the count for the given owner and the count of
     * distinct owner in one transaction.
     *
     * @param owner the owner we need check the count against.
     * @return the aggregated data of custom audience count
     */
    @Transaction
    @NonNull
    public CustomAudienceStats getCustomAudienceStats(@NonNull String owner) {
        Objects.requireNonNull(owner);

        long customAudienceCount = getCustomAudienceCount();
        long customAudienceCountPerOwner = getCustomAudienceCountForOwner(owner);
        long ownerCount = getCustomAudienceOwnerCount();

        // TODO(b/255780705): Add buyer and per-buyer stats
        return CustomAudienceStats.builder()
                .setOwner(owner)
                .setTotalCustomAudienceCount(customAudienceCount)
                .setPerOwnerCustomAudienceCount(customAudienceCountPerOwner)
                .setTotalOwnerCount(ownerCount)
                .build();
    }

    /**
     * Add a custom audience override into the table custom_audience_overrides
     *
     * @param customAudienceOverride is the CustomAudienceOverride to add to table
     *     custom_audience_overrides. If a {@link DBCustomAudienceOverride} object with the primary
     *     key already exists, this will replace the existing object.
     */
    @Insert(onConflict = OnConflictStrategy.REPLACE)
    public abstract void persistCustomAudienceOverride(
            DBCustomAudienceOverride customAudienceOverride);

    /**
     * Checks if there is a row in the custom audience override data with the unique key combination
     * of owner, buyer, and name
     *
     * @return true if row exists, false otherwise
     */
    @Query(
            "SELECT EXISTS(SELECT 1 FROM custom_audience_overrides WHERE owner = :owner "
                    + "AND buyer = :buyer AND name = :name LIMIT 1)")
    public abstract boolean doesCustomAudienceOverrideExist(
            @NonNull String owner, @NonNull AdTechIdentifier buyer, @NonNull String name);

    /**
     * Get custom audience by its unique key.
     *
     * @return custom audience result if exists.
     */
    @Query("SELECT * FROM custom_audience WHERE owner = :owner AND buyer = :buyer AND name = :name")
    @Nullable
    @VisibleForTesting
    public abstract DBCustomAudience getCustomAudienceByPrimaryKey(
            @NonNull String owner, @NonNull AdTechIdentifier buyer, @NonNull String name);

    /**
     * Get custom audience background fetch data by its unique key.
     *
     * @return custom audience background fetch data if it exists
     */
    @Query(
            "SELECT * FROM custom_audience_background_fetch_data "
                    + "WHERE owner = :owner AND buyer = :buyer AND name = :name")
    @Nullable
    @VisibleForTesting
    public abstract DBCustomAudienceBackgroundFetchData
            getCustomAudienceBackgroundFetchDataByPrimaryKey(
                    @NonNull String owner, @NonNull AdTechIdentifier buyer, @NonNull String name);

    /**
     * Get custom audience JS override by its unique key.
     *
     * @return custom audience override result if exists.
     */
    @Query(
            "SELECT bidding_logic FROM custom_audience_overrides WHERE owner = :owner "
                    + "AND buyer = :buyer AND name = :name AND app_package_name= :appPackageName")
    @Nullable
    public abstract String getBiddingLogicUriOverride(
            @NonNull String owner,
            @NonNull AdTechIdentifier buyer,
            @NonNull String name,
            @NonNull String appPackageName);

    /**
     * Get trusted bidding data override by its unique key.
     *
     * @return custom audience override result if exists.
     */
    @Query(
            "SELECT trusted_bidding_data FROM custom_audience_overrides WHERE owner = :owner "
                    + "AND buyer = :buyer AND name = :name AND app_package_name= :appPackageName")
    @Nullable
    public abstract String getTrustedBiddingDataOverride(
            @NonNull String owner,
            @NonNull AdTechIdentifier buyer,
            @NonNull String name,
            @NonNull String appPackageName);

    /** Delete the custom audience given owner, buyer, and name. */
    @Query("DELETE FROM custom_audience WHERE owner = :owner AND buyer = :buyer AND name = :name")
    protected abstract void deleteCustomAudienceByPrimaryKey(
            @NonNull String owner, @NonNull AdTechIdentifier buyer, @NonNull String name);

    /** Delete background fetch data for the custom audience given owner, buyer, and name. */
    @Query(
            "DELETE FROM custom_audience_background_fetch_data WHERE owner = :owner "
                    + "AND buyer = :buyer AND name = :name")
    protected abstract void deleteCustomAudienceBackgroundFetchDataByPrimaryKey(
            @NonNull String owner, @NonNull AdTechIdentifier buyer, @NonNull String name);

    /**
     * Delete all custom audience data corresponding to the given {@code owner}, {@code buyer}, and
     * {@code name} in a single transaction.
     */
    @Transaction
    public void deleteAllCustomAudienceDataByPrimaryKey(
            @NonNull String owner, @NonNull AdTechIdentifier buyer, @NonNull String name) {
        deleteCustomAudienceByPrimaryKey(owner, buyer, name);
        deleteCustomAudienceBackgroundFetchDataByPrimaryKey(owner, buyer, name);
    }

    /**
     * Deletes all custom audiences which are expired, where the custom audiences' expiration times
     * match or precede the given {@code expiryTime}.
     *
     * <p>This method is not intended to be called on its own. Please use {@link
     * #deleteAllExpiredCustomAudienceData(Instant)} instead.
     *
     * @return the number of deleted custom audiences
     */
    @Query("DELETE FROM custom_audience WHERE expiration_time <= :expiryTime")
    protected abstract int deleteAllExpiredCustomAudiences(@NonNull Instant expiryTime);

    /**
     * Deletes background fetch data for all custom audiences which are expired, where the custom
     * audiences' expiration times match or precede the given {@code expiryTime}.
     *
     * <p>This method is not intended to be called on its own. Please use {@link
     * #deleteAllExpiredCustomAudienceData(Instant)} instead.
     */
    @Query(
            "DELETE FROM custom_audience_background_fetch_data WHERE ROWID IN "
                    + "(SELECT bgf.ROWID FROM custom_audience_background_fetch_data AS bgf "
                    + "INNER JOIN custom_audience AS ca "
                    + "ON bgf.buyer = ca.buyer AND bgf.owner = ca.owner AND bgf.name = ca.name "
                    + "WHERE expiration_time <= :expiryTime)")
    protected abstract void deleteAllExpiredCustomAudienceBackgroundFetchData(
            @NonNull Instant expiryTime);

    /**
     * Deletes all expired custom audience data in a single transaction, where the custom audiences'
     * expiration times match or precede the given {@code expiryTime}.
     *
     * @return the number of deleted custom audiences
     */
    @Transaction
    public int deleteAllExpiredCustomAudienceData(@NonNull Instant expiryTime) {
        deleteAllExpiredCustomAudienceBackgroundFetchData(expiryTime);
        return deleteAllExpiredCustomAudiences(expiryTime);
    }

    /** Returns the set of all unique owner apps in the custom audience table. */
    @Query("SELECT DISTINCT owner FROM custom_audience")
    public abstract List<String> getAllCustomAudienceOwners();

    /**
     * Deletes all custom audiences belonging to any app in the given set of {@code ownersToRemove}.
     *
     * <p>This method is not intended to be called on its own. Please use {@link
     * #deleteAllDisallowedOwnerCustomAudienceData(PackageManager, Flags)} instead.
     *
     * @return the number of deleted custom audiences
     */
    @Query("DELETE FROM custom_audience WHERE owner IN (:ownersToRemove)")
    protected abstract int deleteCustomAudiencesByOwner(@NonNull List<String> ownersToRemove);

    /**
     * Deletes all custom audience background fetch data belonging to any app in the given set of
     * {@code ownersToRemove}.
     *
     * <p>This method is not intended to be called on its own. Please use {@link
     * #deleteAllDisallowedOwnerCustomAudienceData(PackageManager, Flags)} instead.
     */
    @Query("DELETE FROM custom_audience_background_fetch_data WHERE owner IN (:ownersToRemove)")
    protected abstract void deleteCustomAudienceBackgroundFetchDataByOwner(
            @NonNull List<String> ownersToRemove);

    /**
     * Deletes all custom audience data belonging to disallowed owner apps in a single transaction,
     * where the custom audiences' owner apps cannot be found in the installed list or where the
     * owner apps are not found in the app allowlist.
     *
     * @return a {@link CustomAudienceStats} object containing only the number of deleted custom
     *     audiences and the number of disallowed owner apps found
     */
    @Transaction
    @NonNull
    public CustomAudienceStats deleteAllDisallowedOwnerCustomAudienceData(
            @NonNull PackageManager packageManager, @NonNull Flags flags) {
        Objects.requireNonNull(packageManager);
        Objects.requireNonNull(flags);
        List<String> ownersToRemove = getAllCustomAudienceOwners();

        if (!ownersToRemove.isEmpty()) {
            Set<String> allowedPackages =
                    packageManager
                            .getInstalledApplications(PackageManager.ApplicationInfoFlags.of(0))
                            .stream()
                            .map(applicationInfo -> applicationInfo.packageName)
                            .collect(Collectors.toSet());

            String appAllowList = flags.getPpapiAppAllowList();
            if (!AllowLists.doesAllowListAllowAll(appAllowList)) {
                allowedPackages.retainAll(AllowLists.splitAllowList(appAllowList));
            }

            // Packages must be both installed and allowlisted, or else they should be removed
            ownersToRemove.removeAll(allowedPackages);
        }

        long numDisallowedOwnersFound = ownersToRemove.size();
        long numRemovedCustomAudiences = 0;
        if (!ownersToRemove.isEmpty()) {
            deleteCustomAudienceBackgroundFetchDataByOwner(ownersToRemove);
            numRemovedCustomAudiences = deleteCustomAudiencesByOwner(ownersToRemove);
        }

        return CustomAudienceStats.builder()
                .setTotalCustomAudienceCount(numRemovedCustomAudiences)
                .setTotalOwnerCount(numDisallowedOwnersFound)
                .build();
    }

    /** Returns the set of all unique buyer ad techs in the custom audience table. */
    @Query("SELECT DISTINCT buyer FROM custom_audience")
    public abstract List<AdTechIdentifier> getAllCustomAudienceBuyers();

    /**
     * Deletes all custom audiences belonging to any ad tech in the given set of {@code
     * buyersToRemove}.
     *
     * <p>This method is not intended to be called on its own. Please use {@link
     * #deleteAllDisallowedBuyerCustomAudienceData(EnrollmentDao, Flags)} instead.
     *
     * @return the number of deleted custom audiences
     */
    @Query("DELETE FROM custom_audience WHERE buyer IN (:buyersToRemove)")
    protected abstract int deleteCustomAudiencesByBuyer(
            @NonNull List<AdTechIdentifier> buyersToRemove);

    /**
     * Deletes all custom audience background fetch data belonging to any ad tech in the given set
     * of {@code buyersToRemove}.
     *
     * <p>This method is not intended to be called on its own. Please use {@link
     * #deleteAllDisallowedBuyerCustomAudienceData(EnrollmentDao, Flags)} instead.
     */
    @Query("DELETE FROM custom_audience_background_fetch_data WHERE buyer IN (:buyersToRemove)")
    protected abstract void deleteCustomAudienceBackgroundFetchDataByBuyer(
            @NonNull List<AdTechIdentifier> buyersToRemove);

    /**
     * Deletes all custom audience data belonging to disallowed buyer ad techs in a single
     * transaction, where the custom audiences' buyer ad techs cannot be found in the enrollment
     * database.
     *
     * @return a {@link CustomAudienceStats} object containing only the number of deleted custom
     *     audiences and the number of disallowed owner apps found
     */
    @Transaction
    @NonNull
    public CustomAudienceStats deleteAllDisallowedBuyerCustomAudienceData(
            @NonNull EnrollmentDao enrollmentDao, @NonNull Flags flags) {
        Objects.requireNonNull(enrollmentDao);
        Objects.requireNonNull(flags);

        if (flags.getDisableFledgeEnrollmentCheck()) {
            LogUtil.d("FLEDGE enrollment check disabled; skipping enrolled buyer cleanup");
            return CustomAudienceStats.builder()
                    .setTotalCustomAudienceCount(0)
                    .setTotalBuyerCount(0)
                    .build();
        }

        List<AdTechIdentifier> buyersToRemove = getAllCustomAudienceBuyers();

        if (!buyersToRemove.isEmpty()) {
            Set<AdTechIdentifier> allowedAdTechs = enrollmentDao.getAllFledgeEnrolledAdTechs();
            buyersToRemove.removeAll(allowedAdTechs);
        }

        long numDisallowedBuyersFound = buyersToRemove.size();
        long numRemovedCustomAudiences = 0;
        if (!buyersToRemove.isEmpty()) {
            deleteCustomAudienceBackgroundFetchDataByBuyer(buyersToRemove);
            numRemovedCustomAudiences = deleteCustomAudiencesByBuyer(buyersToRemove);
        }

        return CustomAudienceStats.builder()
                .setTotalCustomAudienceCount(numRemovedCustomAudiences)
                .setTotalBuyerCount(numDisallowedBuyersFound)
                .build();
    }

    /**
     * Deletes ALL custom audiences from the table.
     *
     * <p>This method is not intended to be called on its own. Please use {@link
     * #deleteAllCustomAudienceData()} instead.
     */
    @Query("DELETE FROM custom_audience")
    protected abstract void deleteAllCustomAudiences();

    /**
     * Deletes ALL custom audience background fetch data from the table.
     *
     * <p>This method is not intended to be called on its own. Please use {@link
     * #deleteAllCustomAudienceData()} instead.
     */
    @Query("DELETE FROM custom_audience_background_fetch_data")
    protected abstract void deleteAllCustomAudienceBackgroundFetchData();

    /**
     * Deletes ALL custom audience overrides from the table.
     *
     * <p>This method is not intended to be called on its own. Please use {@link
     * #deleteAllCustomAudienceData()} instead.
     */
    @Query("DELETE FROM custom_audience_overrides")
    protected abstract void deleteAllCustomAudienceOverrides();

    /** Deletes ALL custom audience data from the database in a single transaction. */
    @Transaction
    public void deleteAllCustomAudienceData() {
        deleteAllCustomAudiences();
        deleteAllCustomAudienceBackgroundFetchData();
        deleteAllCustomAudienceOverrides();
    }

    /**
     * Deletes all custom audiences belonging to the {@code owner} application from the table.
     *
     * <p>This method is not intended to be called on its own. Please use {@link
     * #deleteCustomAudienceDataByOwner(String)} instead.
     */
    @Query("DELETE FROM custom_audience WHERE owner = :owner")
    protected abstract void deleteCustomAudiencesByOwner(@NonNull String owner);

    /**
     * Deletes all custom audience background fetch data belonging to the {@code owner} application
     * from the table.
     *
     * <p>This method is not intended to be called on its own. Please use {@link
     * #deleteCustomAudienceDataByOwner(String)} instead.
     */
    @Query("DELETE FROM custom_audience_background_fetch_data WHERE owner = :owner")
    protected abstract void deleteCustomAudienceBackgroundFetchDataByOwner(@NonNull String owner);

    /**
     * Deletes all custom audience overrides belonging to the {@code owner} application from the
     * table.
     *
     * <p>This method is not intended to be called on its own. Please use {@link
     * #deleteCustomAudienceDataByOwner(String)} instead.
     */
    @Query("DELETE FROM custom_audience_overrides WHERE owner = :owner")
    protected abstract void deleteCustomAudienceOverridesByOwner(@NonNull String owner);

    /**
     * Deletes all custom audience data belonging to the {@code owner} application from the database
     * in a single transaction.
     */
    @Transaction
    public void deleteCustomAudienceDataByOwner(@NonNull String owner) {
        deleteCustomAudiencesByOwner(owner);
        deleteCustomAudienceBackgroundFetchDataByOwner(owner);
        deleteCustomAudienceOverridesByOwner(owner);
    }

    /** Clean up selected custom audience override data by its primary key */
    @Query(
            "DELETE FROM custom_audience_overrides WHERE owner = :owner AND buyer = :buyer "
                    + "AND name = :name AND app_package_name = :appPackageName")
    public abstract void removeCustomAudienceOverrideByPrimaryKeyAndPackageName(
            @NonNull String owner,
            @NonNull AdTechIdentifier buyer,
            @NonNull String name,
            @NonNull String appPackageName);

    /** Clean up all custom audience override data for the given package name. */
    @Query("DELETE FROM custom_audience_overrides WHERE app_package_name = :appPackageName")
    public abstract void removeCustomAudienceOverridesByPackageName(@NonNull String appPackageName);

    /**
     * Fetch all the Custom Audience corresponding to the buyers
     *
     * @param buyers associated with the Custom Audience
     * @param currentTime to compare against CA time values and find an active CA
     * @return All the Custom Audience that represent given buyers
     */
    @Query(
            "SELECT * FROM custom_audience WHERE buyer in (:buyers) AND activation_time <="
                    + " (:currentTime) AND (:currentTime) < expiration_time AND"
                    + " (last_ads_and_bidding_data_updated_time + (:activeWindowTimeMs)) >="
                    + " (:currentTime) AND user_bidding_signals IS NOT NULL AND"
                    + " trusted_bidding_data_uri IS NOT NULL AND ads IS NOT NULL ")
    @Nullable
    public abstract List<DBCustomAudience> getActiveCustomAudienceByBuyers(
            List<AdTechIdentifier> buyers, Instant currentTime, long activeWindowTimeMs);

    /**
     * Gets up to {@code maxRowsReturned} rows of {@link DBCustomAudienceBackgroundFetchData} which
     * correspond to custom audiences that are active, not expired, and eligible for update.
     */
    @Query(
            "SELECT bgf.* FROM custom_audience_background_fetch_data AS bgf "
                    + "INNER JOIN custom_audience AS ca "
                    + "ON bgf.buyer = ca.buyer AND bgf.owner = ca.owner AND bgf.name = ca.name "
                    + "WHERE bgf.eligible_update_time <= :currentTime "
                    + "AND ca.activation_time <= :currentTime "
                    + "AND :currentTime < ca.expiration_time "
                    + "ORDER BY ca.last_ads_and_bidding_data_updated_time ASC "
                    + "LIMIT :maxRowsReturned")
    @NonNull
    public abstract List<DBCustomAudienceBackgroundFetchData>
            getActiveEligibleCustomAudienceBackgroundFetchData(
                    @NonNull Instant currentTime, long maxRowsReturned);

    /**
     * Gets the number of all {@link DBCustomAudienceBackgroundFetchData} for custom audiences that
     * are active, not expired, and eligible for update.
     */
    @Query(
            "SELECT COUNT(DISTINCT bgf.ROWID) FROM custom_audience_background_fetch_data AS bgf "
                    + "INNER JOIN custom_audience AS ca "
                    + "ON bgf.buyer = ca.buyer AND bgf.owner = ca.owner AND bgf.name = ca.name "
                    + "WHERE bgf.eligible_update_time <= :currentTime "
                    + "AND ca.activation_time <= :currentTime "
                    + "AND :currentTime < ca.expiration_time")
    public abstract int getNumActiveEligibleCustomAudienceBackgroundFetchData(
            @NonNull Instant currentTime);
}