| 
 | 1 | +/*  | 
 | 2 | + * Copyright 2016 the original author or authors.  | 
 | 3 | + *  | 
 | 4 | + * Licensed under the Apache License, Version 2.0 (the "License");  | 
 | 5 | + * you may not use this file except in compliance with the License.  | 
 | 6 | + * You may obtain a copy of the License at  | 
 | 7 | + *  | 
 | 8 | + *      http://www.apache.org/licenses/LICENSE-2.0  | 
 | 9 | + *  | 
 | 10 | + * Unless required by applicable law or agreed to in writing, software  | 
 | 11 | + * distributed under the License is distributed on an "AS IS" BASIS,  | 
 | 12 | + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.  | 
 | 13 | + * See the License for the specific language governing permissions and  | 
 | 14 | + * limitations under the License.  | 
 | 15 | + */  | 
 | 16 | + | 
 | 17 | +package io.zonky.test.db.flyway;  | 
 | 18 | + | 
 | 19 | +import com.google.common.cache.CacheBuilder;  | 
 | 20 | +import com.google.common.cache.CacheLoader;  | 
 | 21 | +import com.google.common.cache.LoadingCache;  | 
 | 22 | +import com.opentable.db.postgres.embedded.DatabasePreparer;  | 
 | 23 | +import com.opentable.db.postgres.embedded.PreparedDbProvider;  | 
 | 24 | +import org.apache.commons.lang3.ArrayUtils;  | 
 | 25 | +import org.flywaydb.core.Flyway;  | 
 | 26 | +import org.postgresql.ds.PGSimpleDataSource;  | 
 | 27 | + | 
 | 28 | +import javax.sql.DataSource;  | 
 | 29 | +import java.sql.SQLException;  | 
 | 30 | +import java.util.Objects;  | 
 | 31 | +import java.util.concurrent.Semaphore;  | 
 | 32 | + | 
 | 33 | +import static com.google.common.base.Preconditions.checkState;  | 
 | 34 | + | 
 | 35 | +/**  | 
 | 36 | + * Default implementation of {@link FlywayDataSourceContext} that is used for deferred initialization of the embedded database.  | 
 | 37 | + * Note that this target source is dynamic and supports hot reloading while the application is running.  | 
 | 38 | + * <p/>  | 
 | 39 | + * For the reloading of the underlying data source is used cacheable {@link com.opentable.db.postgres.embedded.DatabasePreparer},  | 
 | 40 | + * which can utilize a special template database to effective copy data into multiple independent databases.  | 
 | 41 | + *  | 
 | 42 | + * @see io.zonky.test.db.postgres.FlywayEmbeddedPostgresDataSourceFactoryBean  | 
 | 43 | + * @see OptimizedFlywayTestExecutionListener  | 
 | 44 | + * @see <a href="https://www.postgresql.org/docs/9.6/static/manage-ag-templatedbs.html">Template Databases</a>  | 
 | 45 | + */  | 
 | 46 | +public class DefaultFlywayDataSourceContext implements FlywayDataSourceContext {  | 
 | 47 | + | 
 | 48 | +    protected static final LoadingCache<Integer, Semaphore> CONNECTION_SEMAPHORES = CacheBuilder.newBuilder()  | 
 | 49 | +            .build(new CacheLoader<Integer, Semaphore>() {  | 
 | 50 | +                public Semaphore load(Integer key) {  | 
 | 51 | +                    return new Semaphore(100); // the maximum number of simultaneous connections to the database  | 
 | 52 | +                }  | 
 | 53 | +            });  | 
 | 54 | + | 
 | 55 | +    protected static final ThreadLocal<DataSource> preparerDataSourceHolder = new ThreadLocal<>();  | 
 | 56 | + | 
 | 57 | +    protected volatile DataSource dataSource;  | 
 | 58 | + | 
 | 59 | +    @Override  | 
 | 60 | +    public Class<?> getTargetClass() {  | 
 | 61 | +        return DataSource.class;  | 
 | 62 | +    }  | 
 | 63 | + | 
 | 64 | +    @Override  | 
 | 65 | +    public boolean isStatic() {  | 
 | 66 | +        return false;  | 
 | 67 | +    }  | 
 | 68 | + | 
 | 69 | +    @Override  | 
 | 70 | +    public Object getTarget() throws Exception {  | 
 | 71 | +        DataSource dataSource = preparerDataSourceHolder.get();  | 
 | 72 | + | 
 | 73 | +        if (dataSource == null) {  | 
 | 74 | +            dataSource = this.dataSource;  | 
 | 75 | +        }  | 
 | 76 | + | 
 | 77 | +        checkState(dataSource != null, "dataSource is not initialized yet");  | 
 | 78 | +        return dataSource;  | 
 | 79 | +    }  | 
 | 80 | + | 
 | 81 | +    @Override  | 
 | 82 | +    public void releaseTarget(Object target) throws Exception {  | 
 | 83 | +        // nothing to do  | 
 | 84 | +    }  | 
 | 85 | + | 
 | 86 | +    @Override  | 
 | 87 | +    public void reload(Flyway flyway) throws Exception {  | 
 | 88 | +        FlywayDatabasePreparer preparer = new FlywayDatabasePreparer(flyway);  | 
 | 89 | +        PreparedDbProvider provider = PreparedDbProvider.forPreparer(preparer);  | 
 | 90 | + | 
 | 91 | +        PGSimpleDataSource dataSource = ((PGSimpleDataSource) provider.createDataSource());  | 
 | 92 | +        Semaphore semaphore = CONNECTION_SEMAPHORES.get(dataSource.getPortNumber());  | 
 | 93 | +        this.dataSource = new BlockingDataSourceWrapper(dataSource, semaphore);  | 
 | 94 | +    }  | 
 | 95 | + | 
 | 96 | +    protected FlywayConfigSnapshot createConfigSnapshot(Flyway flyway) {  | 
 | 97 | +        FlywayConfigSnapshot configSnapshot = new FlywayConfigSnapshot(flyway);  | 
 | 98 | +        checkState(ArrayUtils.isNotEmpty(configSnapshot.getSchemas()),  | 
 | 99 | +                "org.flywaydb.core.Flyway#schemaNames must be specified");  | 
 | 100 | +        return configSnapshot;  | 
 | 101 | +    }  | 
 | 102 | + | 
 | 103 | +    protected class FlywayDatabasePreparer implements DatabasePreparer {  | 
 | 104 | + | 
 | 105 | +        private final FlywayConfigSnapshot configSnapshot;  | 
 | 106 | +        private final Flyway flyway;  | 
 | 107 | + | 
 | 108 | +        public FlywayDatabasePreparer(Flyway flyway) {  | 
 | 109 | +            this.configSnapshot = createConfigSnapshot(flyway);  | 
 | 110 | +            this.flyway = flyway;  | 
 | 111 | +        }  | 
 | 112 | + | 
 | 113 | +        @Override  | 
 | 114 | +        public void prepare(DataSource ds) throws SQLException {  | 
 | 115 | +            preparerDataSourceHolder.set(ds);  | 
 | 116 | +            try {  | 
 | 117 | +                flyway.migrate();  | 
 | 118 | +            } finally {  | 
 | 119 | +                preparerDataSourceHolder.remove();  | 
 | 120 | +            }  | 
 | 121 | +        }  | 
 | 122 | + | 
 | 123 | +        @Override  | 
 | 124 | +        public boolean equals(Object o) {  | 
 | 125 | +            if (this == o) return true;  | 
 | 126 | +            if (o == null || getClass() != o.getClass()) return false;  | 
 | 127 | +            FlywayDatabasePreparer that = (FlywayDatabasePreparer) o;  | 
 | 128 | +            return Objects.equals(configSnapshot, that.configSnapshot);  | 
 | 129 | +        }  | 
 | 130 | + | 
 | 131 | +        @Override  | 
 | 132 | +        public int hashCode() {  | 
 | 133 | +            return Objects.hash(configSnapshot);  | 
 | 134 | +        }  | 
 | 135 | +    }  | 
 | 136 | +}  | 
0 commit comments