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
  614
  615
  616
  617
  618
  619
  620
  621
  622
  623
  624
  625
  626
  627
  628
  629
  630
  631
  632
  633
  634
  635
  636
  637
  638
  639
  640
  641
  642
  643
  644
  645
  646
  647
  648
  649
  650
  651
  652
  653
  654
  655
  656
  657
  658
  659
  660
  661
  662
  663
  664
  665
  666
  667
  668
  669
  670
  671
  672
  673
  674
  675
  676
  677
  678
  679
  680
  681
  682
  683
  684
  685
  686
  687
  688
  689
  690
  691
  692
  693
  694
  695
  696
  697
  698
  699
  700
  701
  702
  703
  704
  705
  706
  707
  708
  709
  710
  711
  712
  713
  714
  715
  716
  717
  718
  719
  720
  721
  722
  723
  724
  725
  726
  727
  728
  729
  730
  731
  732
  733
  734
  735
  736
  737
  738
  739
  740
  741
  742
  743
  744
  745
  746
  747
  748
  749
  750
  751
  752

content / browser / attribution_reporting / attribution_storage_sql_migrations.cc [blame]

// Copyright 2020 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "content/browser/attribution_reporting/attribution_storage_sql_migrations.h"

#include <string_view>
#include <vector>

#include "base/functional/function_ref.h"
#include "base/metrics/histogram_functions.h"
#include "base/time/time.h"
#include "components/attribution_reporting/event_report_windows.h"
#include "components/attribution_reporting/max_event_level_reports.h"
#include "components/attribution_reporting/source_type.mojom.h"
#include "content/browser/attribution_reporting/attribution_reporting.pb.h"
#include "content/browser/attribution_reporting/attribution_storage_sql.h"
#include "content/browser/attribution_reporting/sql_utils.h"
#include "net/base/schemeful_site.h"
#include "sql/database.h"
#include "sql/meta_table.h"
#include "sql/statement.h"
#include "sql/transaction.h"
#include "url/origin.h"

namespace content {

namespace {

// Ensure that both version numbers are updated together to prevent crashes on
// downgrades as in crbug.com/1413728.
[[nodiscard]] bool SetVersionNumbers(sql::MetaTable& meta_table, int version) {
  return meta_table.SetVersionNumber(version) &&
         meta_table.SetCompatibleVersionNumber(version);
}

// Wrap each migration in its own transaction. This results in smaller
// transactions, so it's less likely that a transaction's buffer will need to
// spill to disk. Also, if the database grows a lot and Chrome stops (user
// quit, process kill, etc.) during the migration process, per-migration
// transactions make it more likely that we'll make forward progress each time
// Chrome stops.
[[nodiscard]] bool MaybeMigrate(
    sql::Database& db,
    sql::MetaTable& meta_table,
    int old_version,
    base::FunctionRef<bool(sql::Database&)> migrate) {
  if (meta_table.GetVersionNumber() != old_version) {
    return true;
  }

  sql::Transaction transaction(&db);

  return transaction.Begin() &&                             //
         migrate(db) &&                                     //
         SetVersionNumbers(meta_table, old_version + 1) &&  //
         transaction.Commit();
}

bool To53(sql::Database& db) {
  static constexpr char kNewSourcesTableSql[] =
      "CREATE TABLE new_sources("
      "source_id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,"
      "source_event_id INTEGER NOT NULL,"
      "source_origin TEXT NOT NULL,"
      "reporting_origin TEXT NOT NULL,"
      "source_time INTEGER NOT NULL,"
      "expiry_time INTEGER NOT NULL,"
      "event_report_window_time INTEGER NOT NULL,"
      "aggregatable_report_window_time INTEGER NOT NULL,"
      "num_attributions INTEGER NOT NULL,"
      "event_level_active INTEGER NOT NULL,"
      "aggregatable_active INTEGER NOT NULL,"
      "source_type INTEGER NOT NULL,"
      "attribution_logic INTEGER NOT NULL,"
      "priority INTEGER NOT NULL,"
      "source_site TEXT NOT NULL,"
      "debug_key INTEGER,"
      "aggregatable_budget_consumed INTEGER NOT NULL,"
      "num_aggregatable_reports INTEGER NOT NULL,"
      "aggregatable_source BLOB NOT NULL,"
      "filter_data BLOB NOT NULL)";
  if (!db.Execute(kNewSourcesTableSql)) {
    return false;
  }

  // Transfer the existing rows to the new table. Set a value of
  // `num_aggregatable_reports` as 1 if the source has a non-zero value of
  // `aggregatable_budget_consumed`.
  static constexpr char kPopulateNewSourcesTableSql[] =
      "INSERT INTO new_sources SELECT "
      "source_id,source_event_id,source_origin,"
      "reporting_origin,source_time,"
      "expiry_time,event_report_window_time,aggregatable_report_window_time,"
      "num_attributions,event_level_active,aggregatable_active,"
      "source_type,attribution_logic,priority,source_site,debug_key,"
      "aggregatable_budget_consumed,"
      "IIF(aggregatable_budget_consumed>0,1,0),"
      "aggregatable_source,filter_data FROM sources";
  if (!db.Execute(kPopulateNewSourcesTableSql)) {
    return false;
  }

  static constexpr char kDropOldSourcesTableSql[] = "DROP TABLE sources";
  if (!db.Execute(kDropOldSourcesTableSql)) {
    return false;
  }

  static constexpr char kRenameSourcesTableSql[] =
      "ALTER TABLE new_sources RENAME TO sources";
  if (!db.Execute(kRenameSourcesTableSql)) {
    return false;
  }

  // Create the sources table indices on the new table.
  static constexpr char kSourcesByActiveReportingOriginIndexSql[] =
      "CREATE INDEX sources_by_active_reporting_origin "
      "ON sources(event_level_active,"
      "aggregatable_active,reporting_origin)";
  if (!db.Execute(kSourcesByActiveReportingOriginIndexSql)) {
    return false;
  }

  static constexpr char kImpressionExpiryIndexSql[] =
      "CREATE INDEX sources_by_expiry_time "
      "ON sources(expiry_time)";
  if (!db.Execute(kImpressionExpiryIndexSql)) {
    return false;
  }

  static constexpr char kImpressionOriginIndexSql[] =
      "CREATE INDEX active_sources_by_source_origin "
      "ON sources(source_origin)"
      "WHERE event_level_active=1 OR aggregatable_active=1";
  if (!db.Execute(kImpressionOriginIndexSql)) {
    return false;
  }

  static constexpr char kSourcesSourceTimeIndexSql[] =
      "CREATE INDEX sources_by_source_time "
      "ON sources(source_time)";
  if (!db.Execute(kSourcesSourceTimeIndexSql)) {
    return false;
  }

  return true;
}

bool To54(sql::Database& db) {
  static constexpr char kRateLimitTableSql[] =
      "CREATE TABLE new_rate_limits("
      "id INTEGER PRIMARY KEY NOT NULL,"
      "scope INTEGER NOT NULL,"
      "source_id INTEGER NOT NULL,"
      "source_site TEXT NOT NULL,"
      "destination_site TEXT NOT NULL,"
      "context_origin TEXT NOT NULL,"
      "reporting_origin TEXT NOT NULL,"
      "reporting_site TEXT NOT NULL,"
      "time INTEGER NOT NULL,"
      "source_expiry_or_attribution_time INTEGER NOT NULL)";
  if (!db.Execute(kRateLimitTableSql)) {
    return false;
  }

  static constexpr char kPopulateSql[] =
      "INSERT INTO new_rate_limits SELECT "
      "id,scope,source_id,source_site,destination_site,context_origin,"
      "reporting_origin,'',time,source_expiry_or_attribution_time "
      "FROM rate_limits";
  if (!db.Execute(kPopulateSql)) {
    return false;
  }

  if (!db.Execute("DROP TABLE rate_limits")) {
    return false;
  }

  if (!db.Execute("ALTER TABLE new_rate_limits RENAME TO rate_limits")) {
    return false;
  }

  static constexpr char kGetReportingOriginSql[] =
      "SELECT id,reporting_origin FROM rate_limits";
  sql::Statement get_statement(db.GetUniqueStatement(kGetReportingOriginSql));

  static constexpr char kSetReportingSiteSql[] =
      "UPDATE rate_limits SET reporting_site=? WHERE id=?";
  sql::Statement set_statement(db.GetUniqueStatement(kSetReportingSiteSql));

  while (get_statement.Step()) {
    int64_t id = get_statement.ColumnInt64(0);
    auto reporting_origin =
        DeserializeOrigin(get_statement.ColumnStringView(1));

    set_statement.Reset(/*clear_bound_vars=*/true);
    set_statement.BindString(0,
                             net::SchemefulSite(reporting_origin).Serialize());
    set_statement.BindInt64(1, id);
    if (!set_statement.Run()) {
      return false;
    }
  }
  if (!get_statement.Succeeded()) {
    return false;
  }

  static constexpr char kRateLimitSourceSiteReportingSiteIndexSql[] =
      "CREATE INDEX rate_limit_source_site_reporting_site_idx "
      "ON rate_limits(source_site,reporting_site)"
      "WHERE scope=0";
  if (!db.Execute(kRateLimitSourceSiteReportingSiteIndexSql)) {
    return false;
  }

  static constexpr char kRateLimitReportingOriginIndexSql[] =
      "CREATE INDEX rate_limit_reporting_origin_idx "
      "ON rate_limits(scope,destination_site,source_site)";
  if (!db.Execute(kRateLimitReportingOriginIndexSql)) {
    return false;
  }

  static constexpr char kRateLimitTimeIndexSql[] =
      "CREATE INDEX rate_limit_time_idx ON rate_limits(time)";
  if (!db.Execute(kRateLimitTimeIndexSql)) {
    return false;
  }

  static constexpr char kRateLimitImpressionIdIndexSql[] =
      "CREATE INDEX rate_limit_source_id_idx "
      "ON rate_limits(source_id)";
  return db.Execute(kRateLimitImpressionIdIndexSql);
}

bool To55(sql::Database& db) {
  if (!db.Execute("DROP INDEX rate_limit_source_site_reporting_site_idx")) {
    return false;
  }

  if (!db.Execute("DROP INDEX rate_limit_reporting_origin_idx")) {
    return false;
  }

  static constexpr char kRateLimitReportingOriginIndexSql[] =
      "CREATE INDEX rate_limit_reporting_origin_idx "
      "ON rate_limits(scope,source_site,destination_site)";
  return db.Execute(kRateLimitReportingOriginIndexSql);
}

bool To56(sql::Database& db) {
  static constexpr char kNewSourcesTableSql[] =
      "CREATE TABLE new_sources("
      "source_id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,"
      "source_event_id INTEGER NOT NULL,"
      "source_origin TEXT NOT NULL,"
      "reporting_origin TEXT NOT NULL,"
      "source_time INTEGER NOT NULL,"
      "expiry_time INTEGER NOT NULL,"
      "aggregatable_report_window_time INTEGER NOT NULL,"
      "num_attributions INTEGER NOT NULL,"
      "event_level_active INTEGER NOT NULL,"
      "aggregatable_active INTEGER NOT NULL,"
      "source_type INTEGER NOT NULL,"
      "attribution_logic INTEGER NOT NULL,"
      "priority INTEGER NOT NULL,"
      "source_site TEXT NOT NULL,"
      "debug_key INTEGER,"
      "aggregatable_budget_consumed INTEGER NOT NULL,"
      "num_aggregatable_reports INTEGER NOT NULL,"
      "aggregatable_source BLOB NOT NULL,"
      "filter_data BLOB NOT NULL,"
      "read_only_source_data BLOB NOT NULL)";
  if (!db.Execute(kNewSourcesTableSql)) {
    return false;
  }

  // Transfer the existing rows to the new table. Set a value of
  // `read_only_source_data` as '' to be replaced.
  static constexpr char kPopulateNewSourcesTableSql[] =
      "INSERT INTO new_sources SELECT "
      "source_id,source_event_id,source_origin,"
      "reporting_origin,source_time,expiry_time,"
      "aggregatable_report_window_time,"
      "num_attributions,event_level_active,aggregatable_active,"
      "source_type,attribution_logic,priority,source_site,debug_key,"
      "aggregatable_budget_consumed,"
      "num_aggregatable_reports,aggregatable_source,"
      "filter_data,'' FROM sources";
  if (!db.Execute(kPopulateNewSourcesTableSql)) {
    return false;
  }

  static constexpr char kGetEventReportWindowTime[] =
      "SELECT source_id,source_time,event_report_window_time,source_type FROM "
      "sources";
  sql::Statement get_statement(
      db.GetUniqueStatement(kGetEventReportWindowTime));

  static constexpr char kSetFlexEventConfig[] =
      "UPDATE new_sources SET read_only_source_data=? WHERE source_id=?";
  sql::Statement set_statement(db.GetUniqueStatement(kSetFlexEventConfig));

  while (get_statement.Step()) {
    int64_t id = get_statement.ColumnInt64(0);
    base::Time source_time = get_statement.ColumnTime(1);
    base::Time event_report_window_time = get_statement.ColumnTime(2);
    auto source_type = DeserializeSourceType(get_statement.ColumnInt(3));
    if (!source_type.has_value()) {
      continue;
    }

    auto event_report_windows =
        attribution_reporting::EventReportWindows::FromDefaults(
            event_report_window_time - source_time, *source_type);
    if (!event_report_windows.has_value()) {
      continue;
    }

    proto::AttributionReadOnlySourceData msg;
    SetReadOnlySourceData(
        &*event_report_windows,
        attribution_reporting::MaxEventLevelReports(*source_type), msg);

    set_statement.Reset(/*clear_bound_vars=*/true);
    set_statement.BindBlob(0, msg.SerializeAsString());
    set_statement.BindInt64(1, id);
    if (!set_statement.Run()) {
      return false;
    }
  }

  if (!db.Execute("DROP TABLE sources")) {
    return false;
  }

  if (!db.Execute("ALTER TABLE new_sources RENAME TO sources")) {
    return false;
  }

  // Create the sources table indices on the new table.
  static constexpr char kSourcesByActiveReportingOriginIndexSql[] =
      "CREATE INDEX sources_by_active_reporting_origin "
      "ON sources(event_level_active,"
      "aggregatable_active,reporting_origin)";
  if (!db.Execute(kSourcesByActiveReportingOriginIndexSql)) {
    return false;
  }

  static constexpr char kImpressionExpiryIndexSql[] =
      "CREATE INDEX sources_by_expiry_time "
      "ON sources(expiry_time)";
  if (!db.Execute(kImpressionExpiryIndexSql)) {
    return false;
  }

  static constexpr char kImpressionOriginIndexSql[] =
      "CREATE INDEX active_sources_by_source_origin "
      "ON sources(source_origin)"
      "WHERE event_level_active=1 OR aggregatable_active=1";
  if (!db.Execute(kImpressionOriginIndexSql)) {
    return false;
  }

  static constexpr char kSourcesSourceTimeIndexSql[] =
      "CREATE INDEX sources_by_source_time "
      "ON sources(source_time)";
  if (!db.Execute(kSourcesSourceTimeIndexSql)) {
    return false;
  }
  return true;
}

void DeleteCorruptedReports(AttributionStorageSql& storage) {
  AttributionStorageSql::DeletionCounts counts;
  // Performs its own per item transaction when deleting.
  storage.VerifyReports(&counts);
  base::UmaHistogramCounts100000("Conversions.CorruptSourcesDeletedOnMigration",
                                 counts.sources);
  base::UmaHistogramCounts100000("Conversions.CorruptReportsDeletedOnMigration",
                                 counts.reports);
}

// Version bump only, it was initially added to delete corrupted reports.
// However, given that the corrupted reports logic requires the latest schema,
// it was instead moved to a standalone operation `DeleteCorruptedReports`
// performed after all migrations.
bool To57(sql::Database&) {
  return true;
}

// Version bump only: We avoid having to populate the new trigger_data proto
// field for existing sources by treating absence of the field as equivalent to
// specifying the default trigger-data cardinality for the source's source
// type. We nonetheless bump the DB version to ensure that browser
// downgrades do not result in this new field being ignored for sources
// that *do* use non-default trigger data, because we raze the DB if the
// version is too new.
bool To58(sql::Database&) {
  return true;
}

bool To59(sql::Database& db) {
  static constexpr char kRateLimitTableSql[] =
      "CREATE TABLE new_rate_limits("
      "id INTEGER PRIMARY KEY NOT NULL,"
      "scope INTEGER NOT NULL,"
      "source_id INTEGER NOT NULL,"
      "source_site TEXT NOT NULL,"
      "destination_site TEXT NOT NULL,"
      "context_origin TEXT NOT NULL,"
      "reporting_origin TEXT NOT NULL,"
      "reporting_site TEXT NOT NULL,"
      "time INTEGER NOT NULL,"
      "source_expiry_or_attribution_time INTEGER NOT NULL,"
      "report_id INTEGER NOT NULL)";
  if (!db.Execute(kRateLimitTableSql)) {
    return false;
  }

  static constexpr char kPopulateExistingRecordsSql[] =
      "INSERT INTO new_rate_limits SELECT "
      "id,scope,source_id,source_site,destination_site,context_origin,"
      "reporting_origin,reporting_site,time,source_expiry_or_attribution_time,"
      "-1 "
      "FROM rate_limits";
  if (!db.Execute(kPopulateExistingRecordsSql)) {
    return false;
  }

  static constexpr char kPopulateAggregatableAttributionsSql[] =
      "INSERT INTO new_rate_limits "
      "(scope,source_id,source_site,destination_site,context_origin,"
      "reporting_origin,reporting_site,time,source_expiry_or_attribution_time,"
      "report_id)"
      "SELECT "
      "2,source_id,source_site,destination_site,context_origin,"
      "reporting_origin,reporting_site,time,source_expiry_or_attribution_time,"
      "-1 "
      "FROM rate_limits WHERE scope=1";
  if (!db.Execute(kPopulateAggregatableAttributionsSql)) {
    return false;
  }

  if (!db.Execute("DROP TABLE rate_limits")) {
    return false;
  }

  if (!db.Execute("ALTER TABLE new_rate_limits RENAME TO rate_limits")) {
    return false;
  }

  static constexpr char kRateLimitReportingOriginIndexSql[] =
      "CREATE INDEX rate_limit_reporting_origin_idx "
      "ON rate_limits(scope,source_site,destination_site)";
  if (!db.Execute(kRateLimitReportingOriginIndexSql)) {
    return false;
  }

  static constexpr char kRateLimitTimeIndexSql[] =
      "CREATE INDEX rate_limit_time_idx ON rate_limits(time)";
  if (!db.Execute(kRateLimitTimeIndexSql)) {
    return false;
  }

  static constexpr char kRateLimitImpressionIdIndexSql[] =
      "CREATE INDEX rate_limit_source_id_idx "
      "ON rate_limits(source_id)";
  if (!db.Execute(kRateLimitImpressionIdIndexSql)) {
    return false;
  }

  static constexpr char kRateLimitReportIdIndexSql[] =
      "CREATE INDEX rate_limit_report_id_idx "
      "ON rate_limits(scope,report_id)"
      "WHERE (scope=1 OR scope=2) AND report_id!=-1";
  if (!db.Execute(kRateLimitReportIdIndexSql)) {
    return false;
  }

  return true;
}

bool To60(sql::Database& db) {
  static constexpr char kRenameNumAggregatableReportsSql[] =
      "ALTER TABLE sources "
      "RENAME num_aggregatable_reports TO num_aggregatable_attribution_reports";
  if (!db.Execute(kRenameNumAggregatableReportsSql)) {
    return false;
  }

  static constexpr char kRenameAggregatableBudgetConsumedSql[] =
      "ALTER TABLE sources "
      "RENAME aggregatable_budget_consumed TO "
      "remaining_aggregatable_attribution_budget";
  if (!db.Execute(kRenameAggregatableBudgetConsumedSql)) {
    return false;
  }

  static constexpr char kComputeRemainingAggregatableBudgetSql[] =
      "UPDATE sources "
      "SET remaining_aggregatable_attribution_budget="
      "65536-remaining_aggregatable_attribution_budget";
  if (!db.Execute(kComputeRemainingAggregatableBudgetSql)) {
    return false;
  }

  return true;
}

bool To61(sql::Database& db) {
  static constexpr char kNewSourcesTableSql[] =
      "CREATE TABLE new_sources("
      "source_id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,"
      "source_event_id INTEGER NOT NULL,"
      "source_origin TEXT NOT NULL,"
      "reporting_origin TEXT NOT NULL,"
      "source_time INTEGER NOT NULL,"
      "expiry_time INTEGER NOT NULL,"
      "aggregatable_report_window_time INTEGER NOT NULL,"
      "num_attributions INTEGER NOT NULL,"
      "event_level_active INTEGER NOT NULL,"
      "aggregatable_active INTEGER NOT NULL,"
      "source_type INTEGER NOT NULL,"
      "attribution_logic INTEGER NOT NULL,"
      "priority INTEGER NOT NULL,"
      "source_site TEXT NOT NULL,"
      "debug_key INTEGER,"
      "remaining_aggregatable_attribution_budget INTEGER NOT NULL,"
      "num_aggregatable_attribution_reports INTEGER NOT NULL,"
      "aggregatable_source BLOB NOT NULL,"
      "filter_data BLOB NOT NULL,"
      "read_only_source_data BLOB NOT NULL,"
      "remaining_aggregatable_debug_budget INTEGER NOT NULL,"
      "num_aggregatable_debug_reports INTEGER NOT NULL)";
  if (!db.Execute(kNewSourcesTableSql)) {
    return false;
  }

  static constexpr char kPopulateNewSourcesTableSql[] =
      "INSERT INTO new_sources SELECT "
      "source_id,source_event_id,source_origin,"
      "reporting_origin,source_time,expiry_time,"
      "aggregatable_report_window_time,"
      "num_attributions,event_level_active,aggregatable_active,"
      "source_type,attribution_logic,priority,source_site,debug_key,"
      "remaining_aggregatable_attribution_budget,"
      "num_aggregatable_attribution_reports,aggregatable_source,"
      "filter_data,read_only_source_data,0,0 FROM sources";
  if (!db.Execute(kPopulateNewSourcesTableSql)) {
    return false;
  }

  if (!db.Execute("DROP TABLE sources")) {
    return false;
  }

  if (!db.Execute("ALTER TABLE new_sources RENAME TO sources")) {
    return false;
  }

  // Create the sources table indices on the new table.
  static constexpr char kSourcesByActiveReportingOriginIndexSql[] =
      "CREATE INDEX sources_by_active_reporting_origin "
      "ON sources(event_level_active,"
      "aggregatable_active,reporting_origin)";
  if (!db.Execute(kSourcesByActiveReportingOriginIndexSql)) {
    return false;
  }

  static constexpr char kImpressionExpiryIndexSql[] =
      "CREATE INDEX sources_by_expiry_time "
      "ON sources(expiry_time)";
  if (!db.Execute(kImpressionExpiryIndexSql)) {
    return false;
  }

  static constexpr char kImpressionOriginIndexSql[] =
      "CREATE INDEX active_sources_by_source_origin "
      "ON sources(source_origin)"
      "WHERE event_level_active=1 OR aggregatable_active=1";
  if (!db.Execute(kImpressionOriginIndexSql)) {
    return false;
  }

  static constexpr char kSourcesSourceTimeIndexSql[] =
      "CREATE INDEX sources_by_source_time "
      "ON sources(source_time)";
  if (!db.Execute(kSourcesSourceTimeIndexSql)) {
    return false;
  }

  return true;
}

bool To62(sql::Database& db) {
  static constexpr char kAggregatableDebugRateLimitsTableSql[] =
      "CREATE TABLE aggregatable_debug_rate_limits("
      "id INTEGER PRIMARY KEY NOT NULL,"
      "context_site TEXT NOT NULL,"
      "reporting_origin TEXT NOT NULL,"
      "reporting_site TEXT NOT NULL,"
      "time INTEGER NOT NULL,"
      "consumed_budget INTEGER NOT NULL)";
  if (!db.Execute(kAggregatableDebugRateLimitsTableSql)) {
    return false;
  }

  static constexpr char kAggregatableDebugRateLimitsContextSiteIndex[] =
      "CREATE INDEX aggregatable_debug_rate_limits_context_site_idx "
      "ON aggregatable_debug_rate_limits(context_site)";
  if (!db.Execute(kAggregatableDebugRateLimitsContextSiteIndex)) {
    return false;
  }

  static constexpr char kAggregatableDebugRateLimitsTimeIndex[] =
      "CREATE INDEX aggregatable_debug_rate_limits_time_idx "
      "ON aggregatable_debug_rate_limits(time)";
  if (!db.Execute(kAggregatableDebugRateLimitsTimeIndex)) {
    return false;
  }

  return true;
}

bool To63(sql::Database& db) {
  static constexpr char kRateLimitTableSql[] =
      "CREATE TABLE new_rate_limits("
      "id INTEGER PRIMARY KEY NOT NULL,"
      "scope INTEGER NOT NULL,"
      "source_id INTEGER NOT NULL,"
      "source_site TEXT NOT NULL,"
      "destination_site TEXT NOT NULL,"
      "context_origin TEXT NOT NULL,"
      "reporting_origin TEXT NOT NULL,"
      "reporting_site TEXT NOT NULL,"
      "time INTEGER NOT NULL,"
      "source_expiry_or_attribution_time INTEGER NOT NULL,"
      "report_id INTEGER NOT NULL,"
      "deactivated_for_source_destination_limit INTEGER NOT NULL,"
      "destination_limit_priority INTEGER NOT NULL)";
  if (!db.Execute(kRateLimitTableSql)) {
    return false;
  }

  static constexpr char kPopulateExistingRecordsSql[] =
      "INSERT INTO new_rate_limits SELECT "
      "id,scope,source_id,source_site,destination_site,context_origin,"
      "reporting_origin,reporting_site,time,source_expiry_or_attribution_time,"
      "report_id,0,0 "
      "FROM rate_limits";
  if (!db.Execute(kPopulateExistingRecordsSql)) {
    return false;
  }

  if (!db.Execute("DROP TABLE rate_limits")) {
    return false;
  }

  if (!db.Execute("ALTER TABLE new_rate_limits RENAME TO rate_limits")) {
    return false;
  }

  static constexpr char kRateLimitReportingOriginIndexSql[] =
      "CREATE INDEX rate_limit_reporting_origin_idx "
      "ON rate_limits(scope,source_site,destination_site)";
  if (!db.Execute(kRateLimitReportingOriginIndexSql)) {
    return false;
  }

  static constexpr char kRateLimitTimeIndexSql[] =
      "CREATE INDEX rate_limit_time_idx ON rate_limits(time)";
  if (!db.Execute(kRateLimitTimeIndexSql)) {
    return false;
  }

  static constexpr char kRateLimitImpressionIdIndexSql[] =
      "CREATE INDEX rate_limit_source_id_idx "
      "ON rate_limits(source_id)";
  if (!db.Execute(kRateLimitImpressionIdIndexSql)) {
    return false;
  }

  static constexpr char kRateLimitReportIdIndexSql[] =
      "CREATE INDEX rate_limit_report_id_idx "
      "ON rate_limits(scope,report_id)"
      "WHERE (scope=1 OR scope=2) AND report_id!=-1";
  if (!db.Execute(kRateLimitReportIdIndexSql)) {
    return false;
  }

  return true;
}

bool To64(sql::Database& db) {
  static constexpr char kScopesDataColumnSql[] =
      "ALTER TABLE sources ADD attribution_scopes_data BLOB";
  return db.Execute(kScopesDataColumnSql);
}

bool To65(sql::Database& db) {
  static constexpr char
      kRateLimitAttributionDestinationReportingSiteIndexSql[] =
          "CREATE INDEX rate_limit_attribution_destination_reporting_site_idx "
          "ON rate_limits(scope,destination_site,reporting_site)"
          "WHERE(scope=1 OR scope=2)";
  return db.Execute(kRateLimitAttributionDestinationReportingSiteIndexSql);
}

}  // namespace

bool UpgradeAttributionStorageSqlSchema(AttributionStorageSql& storage,
                                        sql::Database& db,
                                        sql::MetaTable& meta_table) {
  base::ThreadTicks start_timestamp;
  if (base::ThreadTicks::IsSupported()) {
    start_timestamp = base::ThreadTicks::Now();
  }

  static_assert(AttributionStorageSql::kDeprecatedVersionNumber + 1 == 52,
                "Remove migration(s) below.");

  bool ok = MaybeMigrate(db, meta_table, 52, &To53) &&  //
            MaybeMigrate(db, meta_table, 53, &To54) &&  //
            MaybeMigrate(db, meta_table, 54, &To55) &&  //
            MaybeMigrate(db, meta_table, 55, &To56) &&  //
            MaybeMigrate(db, meta_table, 56, &To57) &&
            MaybeMigrate(db, meta_table, 57, &To58) &&
            MaybeMigrate(db, meta_table, 58, &To59) &&
            MaybeMigrate(db, meta_table, 59, &To60) &&
            MaybeMigrate(db, meta_table, 60, &To61) &&
            MaybeMigrate(db, meta_table, 61, &To62) &&
            MaybeMigrate(db, meta_table, 62, &To63) &&
            MaybeMigrate(db, meta_table, 63, &To64) &&
            MaybeMigrate(db, meta_table, 64, &To65);
  if (!ok) {
    return false;
  }

  DeleteCorruptedReports(storage);

  static_assert(AttributionStorageSql::kCurrentVersionNumber == 65,
                "Add migration(s) above.");

  if (base::ThreadTicks::IsSupported()) {
    base::UmaHistogramMediumTimes("Conversions.Storage.MigrationTime",
                                  base::ThreadTicks::Now() - start_timestamp);
  }

  return true;
}

}  // namespace content