Convert postgres migration connection to pool
This change makes the postgres CLI migration code similar to the sqlite
migrations by creating a connection pool.
// See the License for the specific language governing permissions and
// limitations under the License.
-use diesel::{connection::Connection as _, pg::PgConnection};
+use diesel::{
+ pg::PgConnection,
+ r2d2::{ConnectionManager, Pool},
+};
#[cfg(feature = "scabbard-receipt-store")]
use sawtooth::migrations::run_postgres_migrations as run_receipt_store_postgres_migrations;
use splinter::migrations::run_postgres_migrations;
use crate::error::CliError;
+macro_rules! conn {
+ ($pool:ident) => {
+ &*$pool.get().map_err(|_| {
+ CliError::ActionError("Failed to get connection for migrations".to_string())
+ })?
+ };
+}
+
pub fn postgres_migrations(url: &str) -> Result<(), CliError> {
- let connection = PgConnection::establish(url).map_err(|err| {
- CliError::ActionError(format!(
- "Failed to establish database connection to '{}': {}",
- url, err
- ))
- })?;
+ let connection_manager = ConnectionManager::<PgConnection>::new(url);
+ let pool = Pool::builder()
+ .max_size(1)
+ .build(connection_manager)
+ .map_err(|_| CliError::ActionError("Failed to build connection pool".to_string()))?;
+
info!("Running migrations against PostgreSQL database: {}", url);
- run_postgres_migrations(&connection).map_err(|err| {
+ run_postgres_migrations(conn!(pool)).map_err(|err| {
CliError::ActionError(format!("Unable to run Postgres migrations: {}", err))
})?;
#[cfg(feature = "scabbard-receipt-store")]
@@ -36,7 +47,7 @@ pub fn postgres_migrations(url: &str) -> Result<(), CliError> {
"Running migrations against PostgreSQL database for receipt store: {}",
url
);
- run_receipt_store_postgres_migrations(&connection).map_err(|err| {
+ run_receipt_store_postgres_migrations(conn!(pool)).map_err(|err| {
CliError::ActionError(format!(
"Unable to run Postgres migrations for receipt store: {}",
err
