Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- extern crate postgres_types;
- extern crate tokio_postgres;
- use std::collections::HashMap;
- use std::fmt::Write;
- use std::io;
- use actix::prelude::*;
- use futures::stream::futures_unordered::FuturesUnordered;
- use futures::{FutureExt, StreamExt, TryStreamExt};
- use postgres_types::*;
- use tokio_postgres::types::ToSql;
- use tokio_postgres::{connect, Client, NoTls, Statement};
- use crate::models::{RequestedDocument, RequestedDocuments};
- /// Postgres interface
- pub struct PgConnection {
- client: Box<Client>,
- query_documents: Statement,
- }
- impl Actor for PgConnection {
- type Context = Context<Self>;
- }
- impl PgConnection {
- pub async fn connect() -> Result<Addr<PgConnection>, io::Error> {
- let (client, conn) = connect("...", NoTls)
- .await
- .expect("can not connect to postgresql");
- actix_rt::spawn(conn.map(|_| ()));
- let query_documents = client.prepare("select id, content::varchar from documents where id = ANY($1)").await.unwrap();
- Ok(PgConnection::create(move |_| PgConnection {
- client: Box::new(client),
- query_documents,
- }))
- }
- }
- pub struct QueryDocuments(pub u16);
- impl Message for QueryDocuments {
- type Result = io::Result<RequestedDocuments>;
- }
- impl Handler<QueryDocuments> for PgConnection {
- type Result = ResponseFuture<Result<RequestedDocuments, io::Error>>;
- fn handle(&mut self, msg: QueryDocuments, _: &mut Self::Context) -> Self::Result {
- let documents = FuturesUnordered::new();
- for _ in 0..msg.0 {
- let w_id = 1 as i32;
- documents.push(
- self.client
- .query_one(&self.query_documents, &[&w_id])
- .map(|res| match res {
- Err(e) => {
- Err(io::Error::new(io::ErrorKind::Other, format!("{:?}", e)))
- }
- Ok(row) => Ok(RequestedDocument {
- id: 1,
- content: None,
- score: 0.0,
- }),
- }),
- );
- }
- Box::pin(documents.try_collect())
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement