1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
//! An adapter enabling use of the schemer schema migration library with
//! PostgreSQL.
//!
//! # Examples:
//!
//! ```rust
//! extern crate postgres;
//! #[macro_use]
//! extern crate schemer;
//! extern crate schemer_postgres;
//! extern crate uuid;
//!
//! use std::collections::HashSet;
//!
//! use postgres::Connection;
//! use postgres::transaction::Transaction;
//! use schemer::{Migration, Migrator};
//! use schemer_postgres::{PostgresAdapter, PostgresAdapterError, PostgresMigration};
//! use uuid::Uuid;
//!
//! struct MyExampleMigration;
//! migration!(
//!     MyExampleMigration,
//!     "4885e8ab-dafa-4d76-a565-2dee8b04ef60",
//!     [],
//!     "An example migration without dependencies.");
//!
//! impl PostgresMigration for MyExampleMigration {
//!     fn up(&self, transaction: &Transaction) -> Result<(), PostgresAdapterError> {
//!         transaction.execute("CREATE TABLE my_example (id integer PRIMARY KEY);", &[])?;
//!         Ok(())
//!     }
//!
//!     fn down(&self, transaction: &Transaction) -> Result<(), PostgresAdapterError> {
//!         transaction.execute("DROP TABLE my_example;", &[])?;
//!         Ok(())
//!     }
//! }
//!
//! fn main() {
//!     let conn = Connection::connect(
//!         "postgresql://postgres@localhost/?search_path=pg_temp",
//!         postgres::TlsMode::None).unwrap();
//!     let adapter = PostgresAdapter::new(&conn, None);
//!
//!     let mut migrator = Migrator::new(adapter);
//!
//!     let migration = Box::new(MyExampleMigration {});
//!     migrator.register(migration);
//!     migrator.up(None);
//! }
//! ```
#![cfg_attr(feature = "cargo-clippy", allow(doc_markdown))]

extern crate postgres;
#[cfg(test)]
#[macro_use]
extern crate schemer;
#[cfg(not(test))]
extern crate schemer;
extern crate uuid;


use std::collections::HashSet;

use postgres::{Connection, Error as PostgresError};
use postgres::transaction::Transaction;
use uuid::Uuid;

use schemer::{Adapter, Migration};


/// PostgreSQL-specific trait for schema migrations.
pub trait PostgresMigration: Migration {
    /// Apply a migration to the database using a transaction.
    fn up(&self, _transaction: &Transaction) -> Result<(), PostgresError> {
        Ok(())
    }

    /// Revert a migration to the database using a transaction.
    fn down(&self, _transaction: &Transaction) -> Result<(), PostgresError> {
        Ok(())
    }
}

pub type PostgresAdapterError = PostgresError;

/// Adapter between schemer and PostgreSQL.
pub struct PostgresAdapter<'a> {
    conn: &'a Connection,
    migration_metadata_table: String,
}

impl<'a> PostgresAdapter<'a> {
    /// Construct a PostgreSQL schemer adapter.
    ///
    /// `table_name` specifies the name of the table that schemer will use
    /// for storing metadata about applied migrations. If `None`, a default
    /// will be used.
    ///
    /// ```rust
    /// # extern crate postgres;
    /// # extern crate schemer_postgres;
    /// #
    /// # fn main() {
    /// let conn = postgres::Connection::connect(
    ///     "postgresql://postgres@localhost/?search_path=pg_temp",
    ///     postgres::TlsMode::None).unwrap();
    /// let adapter = schemer_postgres::PostgresAdapter::new(&conn, None);
    /// # }
    /// ```
    pub fn new(
        conn: &'a Connection,
        table_name: Option<String>,
    ) -> PostgresAdapter<'a> {
        PostgresAdapter {
            conn: conn,
            migration_metadata_table: table_name.unwrap_or_else(|| "_schemer".into()),
        }
    }

    /// Initialize the schemer metadata schema. This must be called before
    /// using `Migrator` with this adapter. This is safe to call multiple times.
    pub fn init(&self) -> Result<(), PostgresError> {
        self.conn.execute(
            &format!(
                r#"
                    CREATE TABLE IF NOT EXISTS {} (
                        id uuid PRIMARY KEY
                    ) WITH (
                        OIDS=FALSE
                    )
                "#,
                self.migration_metadata_table
            ),
            &[],
        )?;
        Ok(())
    }
}

impl<'a> Adapter for PostgresAdapter<'a> {
    type MigrationType = PostgresMigration;

    type Error = PostgresAdapterError;

    fn applied_migrations(&self) -> Result<HashSet<Uuid>, Self::Error> {
        let rows = self.conn.query(
            &format!(
                "SELECT id FROM {};",
                self.migration_metadata_table
            ),
            &[],
        )?;
        Ok(rows.iter().map(|row| row.get(0)).collect())
    }

    fn apply_migration(&mut self, migration: &Self::MigrationType) -> Result<(), Self::Error> {
        let trans = self.conn.transaction()?;
        migration.up(&trans)?;
        trans.execute(
            &format!(
                "INSERT INTO {} (id) VALUES ($1::uuid);",
                self.migration_metadata_table
            ),
            &[&migration.id()],
        )?;
        Ok(trans.commit()?)
    }

    fn revert_migration(&mut self, migration: &Self::MigrationType) -> Result<(), Self::Error> {
        let trans = self.conn.transaction()?;
        migration.down(&trans)?;
        trans.execute(
            &format!(
                "DELETE FROM {} WHERE id = $1::uuid;",
                self.migration_metadata_table
            ),
            &[&migration.id()],
        )?;
        Ok(trans.commit()?)
    }
}


#[cfg(test)]
mod tests {
    use super::*;
    use postgres::TlsMode;
    use schemer::testing::*;

    impl PostgresMigration for TestMigration {}

    impl<'a> TestAdapter for PostgresAdapter<'a> {
        fn mock(id: Uuid, dependencies: HashSet<Uuid>) -> Box<Self::MigrationType> {
            Box::new(TestMigration::new(id, dependencies))
        }
    }

    fn build_test_connection () -> Connection {
        Connection::connect("postgresql://postgres@localhost/?search_path=pg_temp", TlsMode::None)
            .unwrap()
    }

    fn build_test_adapter(conn: &Connection) -> PostgresAdapter {
        let adapter = PostgresAdapter::new(conn, None);
        adapter.init().unwrap();
        adapter
    }

    test_schemer_adapter!(
        let conn = build_test_connection(),
        build_test_adapter(&conn));
}