Home > Software engineering >  How to describe files using mask in Spring Boot Test @Sql annotation?
How to describe files using mask in Spring Boot Test @Sql annotation?

Time:11-21

There is @Sql annotation which is placed under @Test methods to execute Sql scripts.

Ordinary usage:

    @Sql(scripts = "/folder/my_favourite_script.sql")
    @Test

Let's imagine there are 1000 sql files in the folder and I would like to execute all of them at once. How to describe the files using mask?

Desired result:

    @Sql(scripts = "/folder/*.sql")
    @Test

Unfortunately it doesn't work this way:

org.springframework.jdbc.datasource.init.CannotReadScriptException: Cannot read SQL script from class path resource [folder/*.sql]; nested exception is java.io.FileNotFoundException: class path resource [folder/*.sql] cannot be opened because it does not exist

CodePudding user response:

The @Sql annotation (as well as @SqlGroup which takes an array of @Sql) you cannot pass a file mask and have it handled. AFIK there is no such annotation offered by Spring with the purpose of loading SQL files.

Therefore, your options are:

  1. PostgreSQL: As already said, you cannot include files through masking with any existing annotations. However, check this link out to learn how to do it imperatively. Basically, you have to add an @Autowired DataSource ds and execute the scripts by calling operations on it instead of the annotation magic... This way you can also add file mask logic for any particular folder.

  2. H2: runscript command if you are using H2 for your test db. You would use this by creating an .sql (let's call it scripts.sql) file in your resources with content such as:

    RUNSCRIPT FROM 'file1.sql';
    RUNSCRIPT FROM 'file2.sql';
    etc...
    

    and then include only said file with the annotation like so: @Sql("scripts.sql")

  • Related