Search code examples
liquibase

Practical example of using embedded sql files for stored procedures as a Liquibase changeset


May I have an examples on how to use embedded sql files for stored procedures? Should using the sql embedded files in changelog with --changeset syntax.

I've tried looking in the docs and it shows how to write the changesets but not in particular for a stored procedure and I don't see the actual source sql file.


Solution

  • An example embedded sql file with stored procedure:

    DROP FUNCTION IF EXISTS split_token;
    //
    
    CREATE FUNCTION split_token(txt text, delimiter_text VARCHAR(255), token_index INT UNSIGNED) RETURNS TEXT DETERMINISTIC
    BEGIN
    /*! Return substring by index in delimited text */
    IF CHAR_LENGTH(delimiter_text) = ''
    THEN return SUBSTRING(txt, token_index, 1);
    ELSE return SUBSTRING_INDEX(SUBSTRING_INDEX(txt, delimiter_text, token_index),delimiter_text,-1);
    END IF;
    END
    //
    
    DROP FUNCTION IF EXISTS split_token2;
    //
    
    CREATE FUNCTION split_token2(txt text, delimiter_text VARCHAR(255), token_index INT UNSIGNED) RETURNS TEXT DETERMINISTIC
    BEGIN
    /*! Return substring by index in delimited text */
    IF CHAR_LENGTH(delimiter_text) = ''
    THEN return SUBSTRING(txt, token_index, 1);
    ELSE return SUBSTRING_INDEX(SUBSTRING_INDEX(txt, delimiter_text, token_index),delimiter_text,-1);
    END IF;
    END
    

    The rollback script would look like this:

    DROP FUNCTION IF EXISTS split_token;
    //
    
    DROP FUNCTION IF EXISTS split_token2;
    

    Changelog would look like this:

    <?xml version="1.1" encoding="UTF-8" standalone="no"?>
    <databaseChangeLog xmlns="http://www.liquibase.org/xml/ns/dbchangelog" xmlns:ext="http://www.liquibase.org/xml/ns/dbchangelog-ext" xmlns:pro="http://www.liquibase.org/xml/ns/pro" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.liquibase.org/xml/ns/dbchangelog-ext http://www.liquibase.org/xml/ns/dbchangelog/dbchangelog-ext.xsd http://www.liquibase.org/xml/ns/pro http://www.liquibase.org/xml/ns/pro/liquibase-pro-3.8.xsd http://www.liquibase.org/xml/ns/dbchangelog http://www.liquibase.org/xml/ns/dbchangelog/dbchangelog-3.8.xsd">
      
     <!-- <changeSet author="SteveZ" id="external-sql+rollback-script-example" context="QA" labels="Jira1000">
       <sqlFile dbms="mysql" splitStatements="true" endDelimiter="//" stripComments="true" path="objects/function/split_token.sql"/>
       <rollback>
        <sqlFile dbms="mysql" splitStatements="true" endDelimiter="//" stripComments="true" path="objects/function/split_token_rollback.sql"/>
       </rollback>
     </changeSet> -->
      ....
    </databaseChangeLog>