Monday, August 19, 2019

a coworker's trigger to prevent manual database changes

We only want database changes to occur via continuous integration and Octopus rolling out from Visual Studio 2017 database projects so a coworker put this together:

USE [EnterpriseConsumption]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TRIGGER [block_changes]
   ON DATABASE
   FOR CREATE_PROCEDURE
   , ALTER_PROCEDURE
   , DROP_PROCEDURE
   , CREATE_TABLE
   , ALTER_TABLE
   , DROP_TABLE
   , CREATE_FUNCTION
   , ALTER_FUNCTION
   , DROP_FUNCTION
   , CREATE_INDEX
   , ALTER_INDEX
   , DROP_INDEX
   , CREATE_VIEW
   , ALTER_VIEW
   , DROP_VIEW
   , CREATE_TRIGGER
   , ALTER_TRIGGER
   , DROP_TRIGGER
AS
   SET NOCOUNT ON ;   
   Declare @UserName varchar(50) = lower(SUSER_SNAME())
   Declare @ServerName varchar(50) = @@ServerName
   Declare @DatabaseName varchar(50) = DB_Name()
   IF lower(UserName) NOT IN
      (
         lower('foo\bar')
         , lower('foo\baz')
         , lower('foo\qux')
      )
   BEGIN
      IF EVENTDATA().value('(/EVENT_INSTANCE/EventType)[1]', 'varchar(50)') LIKE
            '%CREATE%'
      BEGIN
         RAISERROR('you are not allowed to add', 18, 1);
         ROLLBACK;
      END;
      
      IF EVENTDATA().value('(/EVENT_INSTANCE/EventType)[1]', 'varchar(50)') LIKE
            '%DROP%'
      BEGIN
         RAISERROR('the %s server cannot drop', 18, 1, @ServerName);
         ROLLBACK;
      END;
      
      IF EVENTDATA().value('(/EVENT_INSTANCE/EventType)[1]', 'varchar(50)') LIKE
            '%ALTER%'
      BEGIN
         RAISERROR('no alters at %s database', 18, 1, @DatabaseName);
         ROLLBACK;
      END;
   END;
GO
ENABLE TRIGGER [block_changes] ON DATABASE
GO

 
 

I thought it was cool. I've "cleaned" it up in my own goofy way. I included the @ServerName and @DatabaseName variables just because he had them and I thought they were cool too. Um, obviously you can just turn this trigger off in SSMS at "Database Triggers" under "Programmability" under the database under "Databases" under the server, but... well, again, it's cool.

No comments:

Post a Comment