ALTER DATABASE BTG_DOS_DEMO
SET CHANGE_TRACKING = ON
(CHANGE_RETENTION = 2 DAYS, AUTO_CLEANUP = ON);

ALTER TABLE dbo.ClientDef
ENABLE CHANGE_TRACKING
WITH (TRACK_COLUMNS_UPDATED = ON);

ALTER TABLE dbo.Commande
ENABLE CHANGE_TRACKING
WITH (TRACK_COLUMNS_UPDATED = ON);

ALTER TABLE dbo.Facture
ENABLE CHANGE_TRACKING
WITH (TRACK_COLUMNS_UPDATED = ON);

ALTER TABLE dbo.Devis
ENABLE CHANGE_TRACKING
WITH (TRACK_COLUMNS_UPDATED = ON);

ALTER TABLE dbo.BonLivraison
ENABLE CHANGE_TRACKING
WITH (TRACK_COLUMNS_UPDATED = ON);

ALTER TABLE dbo.ElementDef
ENABLE CHANGE_TRACKING
WITH (TRACK_COLUMNS_UPDATED = ON);

ALTER TABLE dbo.Contrat
ENABLE CHANGE_TRACKING
WITH (TRACK_COLUMNS_UPDATED = ON);

ALTER TABLE dbo.Interv
ENABLE CHANGE_TRACKING
WITH (TRACK_COLUMNS_UPDATED = ON);

ALTER TABLE dbo.Acompte
ENABLE CHANGE_TRACKING
WITH (TRACK_COLUMNS_UPDATED = ON);

ALTER TABLE dbo.Chantier
ENABLE CHANGE_TRACKING
WITH (TRACK_COLUMNS_UPDATED = ON);

ALTER TABLE dbo.FactureComplement
ENABLE CHANGE_TRACKING
WITH (TRACK_COLUMNS_UPDATED = ON);


-- Exemple de création de table sur MS SQL Server
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SyncState]') AND type in (N'U'))
BEGIN
    CREATE TABLE [dbo].[SyncState](
        [SyncTarget] [nvarchar](100) NOT NULL PRIMARY KEY, -- Ex: 'FolloYou_MySQL'
        [LastSynchVersion] [bigint] NOT NULL,
        [LastUpdateTimestamp] [datetime2](7) DEFAULT GETDATE()
    );
    PRINT 'Table SyncState créée.';

    -- Insérer une ligne initiale pour notre cible si elle n'existe pas
    IF NOT EXISTS (SELECT 1 FROM [dbo].[SyncState] WHERE SyncTarget = 'FolloYou_MySQL')
    BEGIN
         INSERT INTO [dbo].[SyncState] (SyncTarget, LastSynchVersion) VALUES ('FolloYou_MySQL', 0);
         PRINT 'Ligne initiale pour FolloYou_MySQL insérée dans SyncState.';
    END
END
ELSE
BEGIN
    PRINT 'Table SyncState existe déjà.';
    -- Assurer que la ligne pour notre cible existe
    IF NOT EXISTS (SELECT 1 FROM [dbo].[SyncState] WHERE SyncTarget = 'FolloYou_MySQL')
    BEGIN
         INSERT INTO [dbo].[SyncState] (SyncTarget, LastSynchVersion) VALUES ('FolloYou_MySQL', 0);
         PRINT 'Ligne initiale pour FolloYou_MySQL insérée dans SyncState.';
    END
END
GO -- Séparateur de batch SQL Server