Advertisement
Guest User

Untitled

a guest
Feb 1st, 2020
183
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Rust 2.22 KB | None | 0 0
  1. extern crate postgres_types;
  2. extern crate tokio_postgres;
  3.  
  4. use std::collections::HashMap;
  5. use std::fmt::Write;
  6. use std::io;
  7.  
  8. use actix::prelude::*;
  9. use futures::stream::futures_unordered::FuturesUnordered;
  10. use futures::{FutureExt, StreamExt, TryStreamExt};
  11. use postgres_types::*;
  12. use tokio_postgres::types::ToSql;
  13. use tokio_postgres::{connect, Client, NoTls, Statement};
  14.  
  15. use crate::models::{RequestedDocument, RequestedDocuments};
  16.  
  17. /// Postgres interface
  18. pub struct PgConnection {
  19.     client: Box<Client>,
  20.     query_documents: Statement,
  21. }
  22.  
  23. impl Actor for PgConnection {
  24.     type Context = Context<Self>;
  25. }
  26.  
  27. impl PgConnection {
  28.     pub async fn connect() -> Result<Addr<PgConnection>, io::Error> {
  29.         let (client, conn) = connect("...", NoTls)
  30.             .await
  31.             .expect("can not connect to postgresql");
  32.         actix_rt::spawn(conn.map(|_| ()));
  33.  
  34.         let query_documents = client.prepare("select id, content::varchar from documents where id = ANY($1)").await.unwrap();
  35.  
  36.         Ok(PgConnection::create(move |_| PgConnection {
  37.             client: Box::new(client),
  38.             query_documents,
  39.         }))
  40.     }
  41. }
  42.  
  43. pub struct QueryDocuments(pub u16);
  44.  
  45. impl Message for QueryDocuments {
  46.     type Result = io::Result<RequestedDocuments>;
  47. }
  48.  
  49. impl Handler<QueryDocuments> for PgConnection {
  50.     type Result = ResponseFuture<Result<RequestedDocuments, io::Error>>;
  51.  
  52.     fn handle(&mut self, msg: QueryDocuments, _: &mut Self::Context) -> Self::Result {
  53.         let documents = FuturesUnordered::new();
  54.         for _ in 0..msg.0 {
  55.             let w_id = 1 as i32;
  56.             documents.push(
  57.                 self.client
  58.                     .query_one(&self.query_documents, &[&w_id])
  59.                     .map(|res| match res {
  60.                         Err(e) => {
  61.                             Err(io::Error::new(io::ErrorKind::Other, format!("{:?}", e)))
  62.                         }
  63.                         Ok(row) => Ok(RequestedDocument {
  64.                             id: 1,
  65.                             content: None,
  66.                             score: 0.0,
  67.                         }),
  68.                     }),
  69.             );
  70.         }
  71.  
  72.         Box::pin(documents.try_collect())
  73.     }
  74. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement