Redgate Flyway

Tutorial - Using placeholders in SQL Migration scripts for Linked Servers

Placeholders are like variables in SQL migrations and Script migrations.  They are just holding the place in the script and will be updated with a value provided at execution time.  The placeholders and their values can be defined in the TOML configuration file, via environment variables, or passed in as arguments on the command line. 

Placeholders help with differences between environments.  One
common use case is when working with Linked Servers in SQL Server. Rather than hardcoding names like [TestLinkedServer] or [ProdLinkedServer], you can define a placeholder like ${LinkedServer}, which would be replaced with the corresponding value when funning flyway migrate on the different environments.

Doing this helps improves visibility and ensures your script works across all environments (E.g Test, Pre-Prod, and Prod) without needing a different script for each environment. In order to configure Environment placeholders, start by opening up your Flyway.toml project file. Then either locate your existing environments, or create them new:

flway.toml

[environments.test]
url = "jdbc:sqlserver://<localhost;databaseName=MyDatabaseName_test;encrypt=false;integratedSecurity=true;trustServerCertificate=true>"
schemas = [ ]
displayName = "Test"
flyway.placeholders.LinkedServer = "<TestLinkServerName>"


[environments.prod]
url = "jdbc:sqlserver://prodserver;databaseName=MyDatabaseName;encrypt=true;integratedSecurity=true;trustServerCertificate=true"
schemas = [ ]
displayName = "Production"
flyway.placeholders.LinkedServer = "<ProdLinkServerName>"

In the example above, each distinct environment can set unique values for the placeholder named LinkedServer. Any number of placeholders can be setup in this way, as long as the structure flyway.placeholders.MyPlaceholderName = " " is used.


Using the placeholder in a migration script

Now within your migration script (e.g V001__GetRemoteCustomers.sql), use the placeholder ${LinkedServer} syntax:

V001__GetRemoteCustomers.sql

CREATE PROCEDURE GetRemoteCustomers
AS
BEGIN
     SELECT *
     FROM [${LinkedServer}].[RemoteDatabase].[dbo].[Customers];
END;

When this script is executed with the flyway migrate command, Flyway will automatically substitute ${LinkedServer} with the value from the environment configuration. 


Hint: Use use the flyway check -dryrun command to preview the script and see how the placeholders will be replaced before running flyway migrate. 


Didn't find what you were looking for?

OSZAR »