1010namespace OCA \DAV \Migration ;
1111
1212use Closure ;
13+ use OCP \AppFramework \Services \IAppConfig ;
1314use OCP \DB \ISchemaWrapper ;
1415use OCP \DB \QueryBuilder \IQueryBuilder ;
1516use OCP \DB \Types ;
1920
2021class Version1025Date20240308063933 extends SimpleMigrationStep {
2122
23+ private IAppConfig $ appConfig ;
2224 private IDBConnection $ db ;
2325
24- public function __construct (IDBConnection $ db ) {
26+ public function __construct (IAppConfig $ appConfig ,
27+ IDBConnection $ db ) {
2528 $ this ->db = $ db ;
29+ $ this ->appConfig = $ appConfig ;
2630 }
2731
2832 /**
@@ -50,7 +54,22 @@ public function changeSchema(IOutput $output, Closure $schemaClosure, array $opt
5054 }
5155
5256 public function postSchemaChange (IOutput $ output , \Closure $ schemaClosure , array $ options ): void {
57+ // The threshold is higher than the default of \OCA\DAV\BackgroundJob\PruneOutdatedSyncTokensJob
58+ // but small enough to fit into a cluster transaction size.
59+ // For a 50k users instance that would still keep 10 changes on average.
60+ $ limit = max (1 , (int ) $ this ->appConfig ->getAppValue ('totalNumberOfSyncTokensToKeep ' , '500000 ' ));
61+
5362 foreach (['addressbookchanges ' , 'calendarchanges ' ] as $ tableName ) {
63+ $ thresholdSelect = $ this ->db ->getQueryBuilder ();
64+ $ thresholdSelect ->select ('id ' )
65+ ->from ($ tableName )
66+ ->orderBy ('id ' , 'desc ' )
67+ ->setFirstResult ($ limit )
68+ ->setMaxResults (1 );
69+ $ oldestIdResult = $ thresholdSelect ->executeQuery ();
70+ $ oldestId = $ oldestIdResult ->fetchColumn ();
71+ $ oldestIdResult ->closeCursor ();
72+
5473 $ qb = $ this ->db ->getQueryBuilder ();
5574
5675 $ update = $ qb ->update ($ tableName )
@@ -59,7 +78,15 @@ public function postSchemaChange(IOutput $output, \Closure $schemaClosure, array
5978 $ qb ->expr ()->eq ('created_at ' , $ qb ->createNamedParameter (0 , IQueryBuilder::PARAM_INT )),
6079 );
6180
81+ // If there is a lot of data we only set timestamp for the most recent rows
82+ // because the rest will be deleted by \OCA\DAV\BackgroundJob\PruneOutdatedSyncTokensJob
83+ // anyway.
84+ if ($ oldestId !== false ) {
85+ $ update ->andWhere ($ qb ->expr ()->gt ('id ' , $ qb ->createNamedParameter ($ oldestId , IQueryBuilder::PARAM_INT ), IQueryBuilder::PARAM_INT ));
86+ }
87+
6288 $ updated = $ update ->executeStatement ();
89+
6390 $ output ->debug ('Added a default creation timestamp to ' . $ updated . ' rows in ' . $ tableName );
6491 }
6592 }
0 commit comments