Skip to main content

datasources_postgres/
lib.rs

1mod alter_table_statement_renderer;
2mod bind;
3mod command;
4mod connection;
5mod converters;
6mod create_table_statement_renderer;
7mod create_trigger_statement_renderer;
8mod drop_routine_statement_renderer;
9mod driver;
10mod identity_insert_statement_renderer;
11mod default_value_converter;
12mod default_value_options;
13mod sql_generate;
14mod type_map;
15mod pg_value;
16mod reader;
17mod select_inserted_id_statement_text_renderer;
18mod sql_seed_statement_renderer;
19mod statement_renderer;
20mod stored_procedure_statement_renderer;
21mod transaction;
22
23pub use driver::PostgresDriver;
24
25#[cfg(test)]
26#[path = "../tests/isolate.rs"]
27mod isolate;
28#[cfg(test)]
29#[path = "../tests/contacts.rs"]
30mod contacts;
31#[cfg(test)]
32#[path = "../tests/integration.rs"]
33mod integration;
34#[cfg(test)]
35#[path = "../tests/repository_spec.rs"]
36mod repository_spec;
37#[cfg(test)]
38#[path = "../tests/generate_sql.rs"]
39mod generate_sql;
40#[cfg(test)]
41#[path = "../tests/driver_converters.rs"]
42mod driver_converters;
43#[cfg(test)]
44#[path = "../tests/mapping_cell.rs"]
45mod mapping_cell;
46#[cfg(test)]
47#[path = "../tests/generate_sql_casing.rs"]
48mod generate_sql_casing;
49#[cfg(test)]
50#[path = "../tests/generate_sql_mapping.rs"]
51mod generate_sql_mapping;
52
53#[cfg(test)]
54mod tests {
55    use crate::bind::{param_type, to_postgres};
56    use crate::connection::isolation_sql;
57    use crate::converters::BinaryConverter;
58    use tokio_postgres::types::Type;
59    use crate::command::PostgresCommand;
60    use crate::connection::PostgresConnection;
61    use crate::transaction::PostgresTransaction;
62    use datasources::{
63        Row, create, downcast_connection, register, reset, Command, Connection,
64        Driver, IsolationLevel, Transaction, TypeConverter, Value,
65    };
66    use std::collections::HashMap;
67    use std::sync::Arc;
68
69    struct With(Option<String>);
70
71    impl Driver for With {
72        fn connection(&self, _: Option<&HashMap<String, String>>) -> Arc<dyn Connection> {
73            Arc::new(PostgresConnection::new(self.0.clone(), None))
74        }
75
76        fn command(&self, connection: Arc<dyn Connection>) -> Arc<dyn Command> {
77            connection.create_command()
78        }
79
80        fn transaction(
81            &self,
82            connection: Arc<dyn Connection>,
83            isolation: IsolationLevel,
84        ) -> Arc<dyn Transaction> {
85            let conn = downcast_connection::<PostgresConnection>(connection).expect("postgres");
86            Arc::new(PostgresTransaction::new(conn.share(), isolation))
87        }
88
89        fn row_type_converters(
90            &self,
91        ) -> HashMap<
92            String,
93            Box<
94                dyn datasources::TypeConverter<datasources::Value, datasources::Value>
95                    + Send
96                    + Sync,
97            >,
98        > {
99            crate::converters::row_type_converters()
100        }
101    }
102
103    #[tokio::test]
104    async fn postgres_command_and_repository() {
105        let (sql, values) = to_postgres(
106            "SELECT * FROM t WHERE id = $id AND n = $id",
107            &HashMap::from([("id".into(), Value::Int(1))]),
108        );
109        assert_eq!(sql, "SELECT * FROM t WHERE id = $1 AND n = $1");
110        assert_eq!(values, vec![Value::Int(1)]);
111        let (seed, _) = to_postgres(
112            "INSERT INTO \"contact_sources\" (\"name\") VALUES ('Manual')",
113            &HashMap::new(),
114        );
115        assert_eq!(seed, "INSERT INTO \"contact_sources\" (\"name\") VALUES ('Manual')");
116        let (legacy, _) = to_postgres("SELECT * FROM OldContactsTbl", &HashMap::new());
117        assert_eq!(legacy, "SELECT * FROM \"OldContactsTbl\"");
118        let (_, missing) = to_postgres("SELECT $missing", &HashMap::new());
119        assert_eq!(missing, vec![Value::Null]);
120        let stamp = Value::from("2020-01-02T03:04:05.000Z");
121        assert_eq!(param_type(&stamp).oid(), 0);
122        assert_eq!(
123            param_type(&Value::DateTime(
124                chrono::DateTime::parse_from_rfc3339("2020-01-02T03:04:05.000Z")
125                    .unwrap()
126                    .with_timezone(&chrono::Utc)
127            )),
128            Type::TIMESTAMPTZ
129        );
130        assert_eq!(param_type(&Value::from("ada")).oid(), 0);
131        assert_eq!(
132            param_type(&Value::from("550e8400-e29b-41d4-a716-446655440000")).oid(),
133            0
134        );
135        assert!(matches!(
136            BinaryConverter.convert(&Value::from("AQ==")).unwrap(),
137            Value::Binary(_)
138        ));
139        assert_eq!(param_type(&Value::from("AA==")).oid(), 0);
140        assert_eq!(param_type(&Value::Binary(vec![0])), Type::BYTEA);
141        assert_eq!(param_type(&Value::Int(1)).oid(), 0);
142        assert_eq!(param_type(&Value::Int(i64::MAX)).oid(), 0);
143        assert_eq!(
144            isolation_sql(IsolationLevel::ReadUncommitted),
145            "READ UNCOMMITTED"
146        );
147        assert_eq!(
148            isolation_sql(IsolationLevel::ReadCommitted),
149            "READ COMMITTED"
150        );
151        assert_eq!(
152            isolation_sql(IsolationLevel::RepeatableRead),
153            "REPEATABLE READ"
154        );
155        assert_eq!(isolation_sql(IsolationLevel::Serializable), "SERIALIZABLE");
156        let conn = Arc::new(PostgresConnection::new(
157            Some("postgres://db/app".into()),
158            Some("s".into()),
159        ));
160        assert_eq!(conn.schema.as_deref(), Some("s"));
161        let command = PostgresCommand::new(conn.clone());
162        command
163            .execute_native(&datasources::Native::new(""), None)
164            .await
165            .unwrap();
166        command
167            .execute_reader_native(&datasources::Native::new(""), None)
168            .await
169            .unwrap();
170        assert!(conn.start_transaction(None).await.is_err());
171        conn.close().await.unwrap();
172        assert!(conn.ensure_open().is_err());
173        let defaulted = PostgresConnection::new(None, None);
174        assert_eq!(defaulted.url, "");
175        let options = HashMap::from([(
176            "DATASOURCE_URL".into(),
177            "postgres://db/app?schema=s".into(),
178        )]);
179        let from = downcast_connection::<PostgresConnection>(PostgresConnection::from_options(
180            Some(&options),
181        ))
182        .expect("postgres");
183        assert_eq!(from.url, "postgres://db/app?schema=s");
184        assert_eq!(from.schema.as_deref(), Some("s"));
185        assert_eq!(
186            crate::connection::connect_url("postgres://db/app?schema=s"),
187            "postgres://db/app"
188        );
189        assert_eq!(
190            crate::connection::connect_url(
191                "postgres://ds:ds@127.0.0.1:15432/datasources?schema=ds_x"
192            ),
193            "postgres://ds:ds@127.0.0.1:15432/datasources"
194        );
195        reset();
196        register("postgres", Arc::new(With(Some("postgres://db/app".into()))));
197        let ds = create(Some(&HashMap::from([(
198            "PROVIDER".into(),
199            "postgres".into(),
200        )])))
201        .unwrap();
202        assert_eq!(ds.provider(), "postgres");
203        assert!(ds.create_command(None).await.is_err());
204        ds.create_repository::<Row>(None, None);
205        let closed = Arc::new(PostgresConnection::new(None, None));
206        assert!(PostgresCommand::new(closed)
207            .execute_native(&datasources::Native::new("x"), None)
208            .await
209            .is_err());
210    }
211}