2727namespace OCA \DAV \Migration ;
2828
2929use Closure ;
30+ use OCP \AppFramework \Services \IAppConfig ;
3031use OCP \DB \ISchemaWrapper ;
3132use OCP \DB \QueryBuilder \IQueryBuilder ;
3233use OCP \DB \Types ;
3637
3738class Version1025Date20240308063933 extends SimpleMigrationStep {
3839
40+ private IAppConfig $ appConfig ;
3941 private IDBConnection $ db ;
4042
41- public function __construct (IDBConnection $ db ) {
43+ public function __construct (IAppConfig $ appConfig ,
44+ IDBConnection $ db ) {
4245 $ this ->db = $ db ;
46+ $ this ->appConfig = $ appConfig ;
4347 }
4448
4549 /**
@@ -67,7 +71,22 @@ public function changeSchema(IOutput $output, Closure $schemaClosure, array $opt
6771 }
6872
6973 public function postSchemaChange (IOutput $ output , \Closure $ schemaClosure , array $ options ): void {
74+ // The threshold is higher than the default of \OCA\DAV\BackgroundJob\PruneOutdatedSyncTokensJob
75+ // but small enough to fit into a cluster transaction size.
76+ // For a 50k users instance that would still keep 10 changes on average.
77+ $ limit = max (1 , (int ) $ this ->appConfig ->getAppValue ('totalNumberOfSyncTokensToKeep ' , '500000 ' ));
78+
7079 foreach (['addressbookchanges ' , 'calendarchanges ' ] as $ tableName ) {
80+ $ thresholdSelect = $ this ->db ->getQueryBuilder ();
81+ $ thresholdSelect ->select ('id ' )
82+ ->from ($ tableName )
83+ ->orderBy ('id ' , 'desc ' )
84+ ->setFirstResult ($ limit )
85+ ->setMaxResults (1 );
86+ $ oldestIdResult = $ thresholdSelect ->executeQuery ();
87+ $ oldestId = $ oldestIdResult ->fetchColumn ();
88+ $ oldestIdResult ->closeCursor ();
89+
7190 $ qb = $ this ->db ->getQueryBuilder ();
7291
7392 $ update = $ qb ->update ($ tableName )
@@ -76,7 +95,15 @@ public function postSchemaChange(IOutput $output, \Closure $schemaClosure, array
7695 $ qb ->expr ()->eq ('created_at ' , $ qb ->createNamedParameter (0 , IQueryBuilder::PARAM_INT )),
7796 );
7897
98+ // If there is a lot of data we only set timestamp for the most recent rows
99+ // because the rest will be deleted by \OCA\DAV\BackgroundJob\PruneOutdatedSyncTokensJob
100+ // anyway.
101+ if ($ oldestId !== false ) {
102+ $ update ->andWhere ($ qb ->expr ()->gt ('id ' , $ qb ->createNamedParameter ($ oldestId , IQueryBuilder::PARAM_INT ), IQueryBuilder::PARAM_INT ));
103+ }
104+
79105 $ updated = $ update ->executeStatement ();
106+
80107 $ output ->debug ('Added a default creation timestamp to ' . $ updated . ' rows in ' . $ tableName );
81108 }
82109 }
0 commit comments