2025-03-13 23:06:32 +01:00
// Copyright (C) 2025, The Duplicati Team
// https://duplicati.com, hello@duplicati.com
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
2024-02-28 15:45:30 +01:00
// DEALINGS IN THE SOFTWARE.
2025-04-03 15:46:20 +02:00
#nullable enable
2016-12-29 22:41:13 +01:00
using System ;
2025-03-14 14:34:56 +01:00
using System.Data ;
2016-12-29 22:41:13 +01:00
using System.Collections.Generic ;
2019-09-29 20:16:28 -07:00
using Duplicati.Library.Utility ;
2016-12-29 22:41:13 +01:00
namespace Duplicati.Library.Main.Database
{
internal class LocalPurgeDatabase : LocalDeleteDatabase
{
2025-04-22 14:26:46 +02:00
public LocalPurgeDatabase ( string path , long pagecachesize )
: base ( path , "Purge" , pagecachesize )
2016-12-29 22:41:13 +01:00
{
ShouldCloseConnection = true ;
}
2017-01-05 16:46:01 +01:00
public LocalPurgeDatabase ( LocalDatabase db )
: base ( db )
{
}
2025-03-14 14:34:56 +01:00
public ITemporaryFileset CreateTemporaryFileset ( long parentid , IDbTransaction transaction )
2016-12-29 22:41:13 +01:00
{
return new TemporaryFileset ( parentid , this , m_connection , transaction );
}
2025-03-14 14:34:56 +01:00
public string GetRemoteVolumeNameForFileset ( long id , IDbTransaction transaction )
2016-12-29 22:41:13 +01:00
{
2025-04-02 16:20:12 +02:00
using var cmd = m_connection . CreateCommand ( transaction , @"SELECT ""B"".""Name"" FROM ""Fileset"" A, ""RemoteVolume"" B WHERE ""A"".""VolumeID"" = ""B"".""ID"" AND ""A"".""ID"" = @FilesetId " )
. SetParameterValue ( "@FilesetId" , id );
using ( var rd = cmd . ExecuteReader ())
2016-12-29 22:41:13 +01:00
if (! rd . Read ())
2025-03-13 23:06:32 +01:00
throw new Exception ( $"No remote volume found for fileset with id {id}" );
2016-12-29 22:41:13 +01:00
else
2025-04-03 15:46:20 +02:00
return rd . ConvertValueToString ( 0 ) ?? throw new Exception ( $"Remote volume name for fileset with id {id} is null" );
2016-12-29 22:41:13 +01:00
}
2025-03-14 14:34:56 +01:00
internal long CountOrphanFiles ( IDbTransaction transaction )
2016-12-29 22:41:13 +01:00
{
using ( var cmd = m_connection . CreateCommand ( transaction ))
2018-06-14 10:12:24 +02:00
using ( var rd = cmd . ExecuteReader ( @"SELECT COUNT(*) FROM ""FileLookup"" WHERE ""ID"" NOT IN (SELECT DISTINCT ""FileID"" FROM ""FilesetEntry"")" ))
2016-12-29 22:41:13 +01:00
if ( rd . Read ())
return rd . ConvertValueToInt64 ( 0 , 0 );
else
return 0 ;
}
public interface ITemporaryFileset : IDisposable
{
long ParentID { get ; }
long RemovedFileCount { get ; }
long RemovedFileSize { get ; }
void ApplyFilter ( Library . Utility . IFilter filter );
2025-03-14 14:34:56 +01:00
void ApplyFilter ( Action < IDbCommand , long , string > filtercommand );
2019-09-01 13:13:45 -04:00
Tuple < long , long > ConvertToPermanentFileset ( string name , DateTime timestamp , bool isFullBackup );
2016-12-29 22:41:13 +01:00
IEnumerable < KeyValuePair < string , long >> ListAllDeletedFiles ();
}
private class TemporaryFileset : ITemporaryFileset
{
2025-03-14 14:34:56 +01:00
private readonly IDbConnection m_connection ;
private readonly IDbTransaction m_transaction ;
2016-12-29 22:41:13 +01:00
private readonly string m_tablename ;
2018-05-23 21:18:01 -07:00
private readonly LocalPurgeDatabase m_parentdb ;
2016-12-29 22:41:13 +01:00
public long ParentID { get ; private set ; }
public long RemovedFileCount { get ; private set ; }
public long RemovedFileSize { get ; private set ; }
2025-03-14 14:34:56 +01:00
public TemporaryFileset ( long parentid , LocalPurgeDatabase parentdb , IDbConnection connection , IDbTransaction transaction )
2016-12-29 22:41:13 +01:00
{
2025-03-14 14:34:56 +01:00
ParentID = parentid ;
2016-12-29 22:41:13 +01:00
m_parentdb = parentdb ;
m_connection = connection ;
m_transaction = transaction ;
m_tablename = "TempDeletedFilesTable-" + Library . Utility . Utility . ByteArrayAsHexString ( Guid . NewGuid (). ToByteArray ());
using ( var cmd = m_connection . CreateCommand ( m_transaction ))
2025-03-14 12:13:17 +01:00
cmd . ExecuteNonQuery ( FormatInvariant ( $@"CREATE TEMPORARY TABLE ""{m_tablename}"" (""FileID"" INTEGER PRIMARY KEY) " ));
2016-12-29 22:41:13 +01:00
}
2025-03-14 14:34:56 +01:00
public void ApplyFilter ( Action < IDbCommand , long , string > filtercommand )
2016-12-29 22:41:13 +01:00
{
using ( var cmd = m_connection . CreateCommand ( m_transaction ))
filtercommand ( cmd , ParentID , m_tablename );
2025-03-14 12:13:17 +01:00
2016-12-29 22:41:13 +01:00
PostFilterChecks ();
}
public void ApplyFilter ( Library . Utility . IFilter filter )
{
2019-09-29 20:16:28 -07:00
if ( Library . Utility . Utility . IsFSCaseSensitive && filter is FilterExpression expression && expression . Type == Duplicati . Library . Utility . FilterType . Simple )
2016-12-29 22:41:13 +01:00
{
// File list based
2019-09-29 09:51:14 -07:00
// unfortunately we cannot do this if the filesystem is not case-sensitive as
2016-12-29 22:41:13 +01:00
// SQLite only supports ASCII compares
2019-09-29 20:16:28 -07:00
var p = expression . GetSimpleList ();
2016-12-29 22:41:13 +01:00
var filenamestable = "Filenames-" + Library . Utility . Utility . ByteArrayAsHexString ( Guid . NewGuid (). ToByteArray ());
using ( var cmd = m_connection . CreateCommand ( m_transaction ))
{
2025-03-14 12:13:17 +01:00
cmd . ExecuteNonQuery ( FormatInvariant ( $@"CREATE TEMPORARY TABLE ""{filenamestable}"" (""Path"" TEXT NOT NULL) " ));
2025-04-03 16:38:51 +02:00
cmd . SetCommandAndParameters ( FormatInvariant ( $@"INSERT INTO ""{filenamestable}"" (""Path"") VALUES (@Path)" ));
2016-12-29 22:41:13 +01:00
foreach ( var s in p )
2025-04-02 16:20:12 +02:00
cmd . SetParameterValue ( "@Path" , s )
. ExecuteNonQuery ();
2016-12-29 22:41:13 +01:00
2025-04-02 16:20:12 +02:00
cmd . SetCommandAndParameters ( FormatInvariant ( $@"INSERT INTO ""{m_tablename}"" (""FileID"") SELECT DISTINCT ""A"".""FileID"" FROM ""FilesetEntry"" A, ""File"" B WHERE ""A"".""FilesetID"" = @FilesetId AND ""A"".""FileID"" = ""B"".""ID"" AND ""B"".""Path"" IN ""{filenamestable}""" ))
. SetParameterValue ( "@FilesetId" , ParentID )
. ExecuteNonQuery ();
2025-03-14 12:13:17 +01:00
cmd . ExecuteNonQuery ( FormatInvariant ( $@"DROP TABLE IF EXISTS ""{filenamestable}"" " ));
2016-12-29 22:41:13 +01:00
}
}
else
{
// Do row-wise iteration
2025-03-14 14:34:56 +01:00
var values = new object [ 2 ];
2016-12-29 22:41:13 +01:00
using ( var cmd = m_connection . CreateCommand ( m_transaction ))
using ( var cmd2 = m_connection . CreateCommand ( m_transaction ))
{
2025-04-02 16:20:12 +02:00
cmd2 . SetCommandAndParameters ( FormatInvariant ( $@"INSERT INTO ""{m_tablename}"" (""FileID"") VALUES (@FileId)" ));
2025-04-02 23:20:58 +02:00
cmd . SetCommandAndParameters ( @"SELECT ""B"".""Path"", ""A"".""FileID"" FROM ""FilesetEntry"" A, ""File"" B WHERE ""A"".""FilesetID"" = @FilesetId AND ""A"".""FileID"" = ""B"".""ID"" " )
2025-04-02 16:20:12 +02:00
. SetParameterValue ( "@FilesetId" , ParentID );
using ( var rd = cmd . ExecuteReader ())
2016-12-29 22:41:13 +01:00
while ( rd . Read ())
{
rd . GetValues ( values );
if ( values [ 0 ] != null && values [ 0 ] != DBNull . Value && Library . Utility . FilterExpression . Matches ( filter , values [ 0 ]. ToString ()))
{
2025-04-02 16:20:12 +02:00
cmd2 . SetParameterValue ( "@FileId" , values [ 1 ])
. ExecuteNonQuery ();
2016-12-29 22:41:13 +01:00
}
}
}
}
PostFilterChecks ();
}
private void PostFilterChecks ()
{
using ( var cmd = m_connection . CreateCommand ( m_transaction ))
{
2025-03-14 12:13:17 +01:00
RemovedFileCount = cmd . ExecuteScalarInt64 ( FormatInvariant ( $@"SELECT COUNT(*) FROM ""{m_tablename}""" ), 0 );
RemovedFileSize = cmd . ExecuteScalarInt64 ( FormatInvariant ( $@"SELECT SUM(""C"".""Length"") FROM ""{m_tablename}"" A, ""FileLookup"" B, ""Blockset"" C WHERE ""A"".""FileID"" = ""B"".""ID"" AND ""B"".""BlocksetID"" = ""C"".""ID"" " ), 0 );
var filesetcount = cmd . ExecuteScalarInt64 ( FormatInvariant ( $@"SELECT COUNT(*) FROM ""FilesetEntry"" WHERE ""FilesetID"" = {ParentID}" ), 0 );
2016-12-29 22:41:13 +01:00
if ( filesetcount == RemovedFileCount )
2025-03-14 14:34:56 +01:00
throw new Interface . UserInformationException ( $"Refusing to purge {RemovedFileCount} files from fileset with ID {ParentID}, as that would remove the entire fileset.\nTo delete a fileset, use the \" delete \ " command." , "PurgeWouldRemoveEntireFileset" );
2016-12-29 22:41:13 +01:00
}
}
2019-09-01 13:13:45 -04:00
public Tuple < long , long > ConvertToPermanentFileset ( string name , DateTime timestamp , bool isFullBackup )
{
2016-12-29 22:41:13 +01:00
var remotevolid = m_parentdb . RegisterRemoteVolume ( name , RemoteVolumeType . Files , RemoteVolumeState . Temporary , m_transaction );
var filesetid = m_parentdb . CreateFileset ( remotevolid , timestamp , m_transaction );
2019-09-10 12:55:29 -04:00
m_parentdb . UpdateFullBackupStateInFileset ( filesetid , isFullBackup );
2016-12-29 22:41:13 +01:00
using ( var cmd = m_connection . CreateCommand ( m_transaction ))
2025-04-02 16:20:12 +02:00
cmd . SetCommandAndParameters ( FormatInvariant ( $@"INSERT INTO ""FilesetEntry"" (""FilesetID"", ""FileID"", ""Lastmodified"") SELECT @TargetFilesetId, ""FileID"", ""LastModified"" FROM ""FilesetEntry"" WHERE ""FilesetID"" = @SourceFilesetId AND ""FileID"" NOT IN ""{m_tablename}"" " ))
. SetParameterValue ( "@TargetFilesetId" , filesetid )
. SetParameterValue ( "@SourceFilesetId" , ParentID )
. ExecuteNonQuery ();
2016-12-29 22:41:13 +01:00
return new Tuple < long , long >( remotevolid , filesetid );
}
2025-03-14 12:13:17 +01:00
2016-12-29 22:41:13 +01:00
public IEnumerable < KeyValuePair < string , long >> ListAllDeletedFiles ()
{
using ( var cmd = m_connection . CreateCommand ( m_transaction ))
2025-03-14 12:13:17 +01:00
using ( var rd = cmd . ExecuteReader ( FormatInvariant ( $@"SELECT ""B"".""Path"", ""C"".""Length"" FROM ""{m_tablename}"" A, ""File"" B, ""Blockset"" C WHERE ""A"".""FileID"" = ""B"".""ID"" AND ""B"".""BlocksetID"" = ""C"".""ID"" " )))
2016-12-29 22:41:13 +01:00
while ( rd . Read ())
2025-04-03 15:46:20 +02:00
yield return new KeyValuePair < string , long >( rd . ConvertValueToString ( 0 ) ?? "" , rd . ConvertValueToInt64 ( 1 ));
2016-12-29 22:41:13 +01:00
}
public void Dispose ()
{
try
{
using ( var cmd = m_connection . CreateCommand ( m_transaction ))
2025-03-14 12:13:17 +01:00
cmd . ExecuteNonQuery ( FormatInvariant ( $@"DROP TABLE IF EXISTS ""{m_tablename}""" ));
2016-12-29 22:41:13 +01:00
}
catch
{
}
}
}
2025-03-14 12:13:17 +01:00
}
2016-12-29 22:41:13 +01:00
}