1
2
3
4
5
6
7
8
9
10
11
12
13
14
15 package de.softwareforge.testing.postgres.embedded;
16
17 import static com.google.common.base.Preconditions.checkNotNull;
18
19 import jakarta.annotation.Nonnull;
20 import java.io.IOException;
21 import java.util.Set;
22 import java.util.function.Consumer;
23 import javax.sql.DataSource;
24
25 import com.google.common.collect.ImmutableList;
26 import org.flywaydb.core.Flyway;
27 import org.flywaydb.core.api.FlywayException;
28 import org.flywaydb.core.api.configuration.FluentConfiguration;
29
30
31
32
33
34 public final class FlywayPreparer implements EmbeddedPostgresPreparer<DataSource> {
35
36 private final ImmutableList.Builder<Consumer<FluentConfiguration>> customizers = ImmutableList.builder();
37
38
39
40
41
42
43
44 @Nonnull
45 public static FlywayPreparer forClasspathLocation(String... locations) {
46 FlywayPreparer preparer = new FlywayPreparer();
47 preparer.addCustomizer(c -> c.locations(locations));
48 return preparer;
49 }
50
51
52
53
54
55 public FlywayPreparer() {
56 }
57
58
59
60
61
62
63
64
65
66 @Nonnull
67 public FlywayPreparer addCustomizer(@Nonnull Consumer<FluentConfiguration> customizer) {
68 checkNotNull(customizer, "customizer is null");
69 customizers.add(customizer);
70
71 return this;
72 }
73
74
75
76
77
78
79
80
81
82 @Nonnull
83 public FlywayPreparer addCustomizers(@Nonnull Set<Consumer<FluentConfiguration>> customizers) {
84 checkNotNull(customizers, "customizers is null");
85 customizers.addAll(customizers);
86
87 return this;
88 }
89
90 @Override
91 public void prepare(@Nonnull DataSource dataSource) throws IOException {
92 checkNotNull(dataSource, "dataSource is null");
93
94 try {
95 final FluentConfiguration config = Flyway.configure();
96
97 customizers.build().forEach(c -> c.accept(config));
98
99 config.dataSource(dataSource);
100 Flyway flyway = config.load();
101 flyway.migrate();
102
103 } catch (FlywayException e) {
104 throw new IOException(e);
105 }
106 }
107 }