From fb030ce42986bec775261c9085b2965dca640d71 Mon Sep 17 00:00:00 2001 From: fede Date: Fri, 10 Nov 2023 17:25:16 -0300 Subject: [PATCH] initial commit --- .env | 1 + .gitignore | 2 ++ Cargo.toml | 10 ++++++ diesel.toml | 9 +++++ migrations/.keep | 0 .../down.sql | 6 ++++ .../up.sql | 36 +++++++++++++++++++ .../2023-11-10-193109_crear_posts/down.sql | 2 ++ .../2023-11-10-193109_crear_posts/up.sql | 7 ++++ src/bin/escribir_post.rs | 28 +++++++++++++++ src/bin/mostrar_posts.rs | 22 ++++++++++++ src/bin/publicar_posts.rs | 23 ++++++++++++ src/lib.rs | 31 ++++++++++++++++ src/modelos.rs | 20 +++++++++++ src/schema.rs | 10 ++++++ 15 files changed, 207 insertions(+) create mode 100644 .env create mode 100644 .gitignore create mode 100644 Cargo.toml create mode 100644 diesel.toml create mode 100644 migrations/.keep create mode 100644 migrations/00000000000000_diesel_initial_setup/down.sql create mode 100644 migrations/00000000000000_diesel_initial_setup/up.sql create mode 100644 migrations/2023-11-10-193109_crear_posts/down.sql create mode 100644 migrations/2023-11-10-193109_crear_posts/up.sql create mode 100644 src/bin/escribir_post.rs create mode 100644 src/bin/mostrar_posts.rs create mode 100644 src/bin/publicar_posts.rs create mode 100644 src/lib.rs create mode 100644 src/modelos.rs create mode 100644 src/schema.rs diff --git a/.env b/.env new file mode 100644 index 0000000..001152a --- /dev/null +++ b/.env @@ -0,0 +1 @@ +DATABASE_URL=postgres://blog@192.168.1.11/blogging \ No newline at end of file diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..4fffb2f --- /dev/null +++ b/.gitignore @@ -0,0 +1,2 @@ +/target +/Cargo.lock diff --git a/Cargo.toml b/Cargo.toml new file mode 100644 index 0000000..1d5d87e --- /dev/null +++ b/Cargo.toml @@ -0,0 +1,10 @@ +[package] +name = "rust_diesel_blogs" +version = "0.1.0" +edition = "2021" + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] +diesel = {version = "2.1.3", features = ["postgres"]} +dotenvy = "0.15.7" diff --git a/diesel.toml b/diesel.toml new file mode 100644 index 0000000..c028f4a --- /dev/null +++ b/diesel.toml @@ -0,0 +1,9 @@ +# For documentation on how to configure this file, +# see https://diesel.rs/guides/configuring-diesel-cli + +[print_schema] +file = "src/schema.rs" +custom_type_derives = ["diesel::query_builder::QueryId"] + +[migrations_directory] +dir = "migrations" diff --git a/migrations/.keep b/migrations/.keep new file mode 100644 index 0000000..e69de29 diff --git a/migrations/00000000000000_diesel_initial_setup/down.sql b/migrations/00000000000000_diesel_initial_setup/down.sql new file mode 100644 index 0000000..a9f5260 --- /dev/null +++ b/migrations/00000000000000_diesel_initial_setup/down.sql @@ -0,0 +1,6 @@ +-- This file was automatically created by Diesel to setup helper functions +-- and other internal bookkeeping. This file is safe to edit, any future +-- changes will be added to existing projects as new migrations. + +DROP FUNCTION IF EXISTS diesel_manage_updated_at(_tbl regclass); +DROP FUNCTION IF EXISTS diesel_set_updated_at(); diff --git a/migrations/00000000000000_diesel_initial_setup/up.sql b/migrations/00000000000000_diesel_initial_setup/up.sql new file mode 100644 index 0000000..d68895b --- /dev/null +++ b/migrations/00000000000000_diesel_initial_setup/up.sql @@ -0,0 +1,36 @@ +-- This file was automatically created by Diesel to setup helper functions +-- and other internal bookkeeping. This file is safe to edit, any future +-- changes will be added to existing projects as new migrations. + + + + +-- Sets up a trigger for the given table to automatically set a column called +-- `updated_at` whenever the row is modified (unless `updated_at` was included +-- in the modified columns) +-- +-- # Example +-- +-- ```sql +-- CREATE TABLE users (id SERIAL PRIMARY KEY, updated_at TIMESTAMP NOT NULL DEFAULT NOW()); +-- +-- SELECT diesel_manage_updated_at('users'); +-- ``` +CREATE OR REPLACE FUNCTION diesel_manage_updated_at(_tbl regclass) RETURNS VOID AS $$ +BEGIN + EXECUTE format('CREATE TRIGGER set_updated_at BEFORE UPDATE ON %s + FOR EACH ROW EXECUTE PROCEDURE diesel_set_updated_at()', _tbl); +END; +$$ LANGUAGE plpgsql; + +CREATE OR REPLACE FUNCTION diesel_set_updated_at() RETURNS trigger AS $$ +BEGIN + IF ( + NEW IS DISTINCT FROM OLD AND + NEW.updated_at IS NOT DISTINCT FROM OLD.updated_at + ) THEN + NEW.updated_at := current_timestamp; + END IF; + RETURN NEW; +END; +$$ LANGUAGE plpgsql; diff --git a/migrations/2023-11-10-193109_crear_posts/down.sql b/migrations/2023-11-10-193109_crear_posts/down.sql new file mode 100644 index 0000000..e00da65 --- /dev/null +++ b/migrations/2023-11-10-193109_crear_posts/down.sql @@ -0,0 +1,2 @@ +-- This file should undo anything in `up.sql` +DROP TABLE posts \ No newline at end of file diff --git a/migrations/2023-11-10-193109_crear_posts/up.sql b/migrations/2023-11-10-193109_crear_posts/up.sql new file mode 100644 index 0000000..8636ca1 --- /dev/null +++ b/migrations/2023-11-10-193109_crear_posts/up.sql @@ -0,0 +1,7 @@ +-- Your SQL goes here +CREATE TABLE posts ( + id SERIAL PRIMARY KEY, + title VARCHAR NOT NULL, + body TEXT NOT NULL, + published BOOLEAN NOT NULL DEFAULT FALSE +) \ No newline at end of file diff --git a/src/bin/escribir_post.rs b/src/bin/escribir_post.rs new file mode 100644 index 0000000..1238510 --- /dev/null +++ b/src/bin/escribir_post.rs @@ -0,0 +1,28 @@ +use std::io::{stdin, Read}; + + +use rust_diesel_blogs::*; + +fn main() { + let connection = &mut establecer_coneccion(); + + let mut title = String::new(); + let mut body = String::new(); + + println!("Cual es el titulo de su post: "); + stdin().read_line(&mut title); + let title = title.trim_end(); + + println!("Ingrese el cuerpo de {}, aprete {} para terminar de escribir", title, EOF); + stdin().read_to_string(&mut body); + + let post = crear_post(connection, title, &body); + println!("Grabado post con id: {}", post.id); + +} + +#[cfg(not(windows))] +const EOF: &str = "CTRL+D"; + +#[cfg(windows)] +const EOF: &str = "CTRL+Z"; \ No newline at end of file diff --git a/src/bin/mostrar_posts.rs b/src/bin/mostrar_posts.rs new file mode 100644 index 0000000..3358fa6 --- /dev/null +++ b/src/bin/mostrar_posts.rs @@ -0,0 +1,22 @@ +use self::modelos::*; +use diesel::{prelude::*, connection}; +use rust_diesel_blogs::*; + +fn main() { + use self::schema::posts::dsl::*; + + let connection = &mut establecer_coneccion(); + let resultado = posts + .filter(published.eq(true)) + .limit(10) + .select(Post::as_select()) + .load(connection) + .expect("Error cargando posts"); + + println!("Mostrando {} posts", resultado.len()); + for post in resultado { + println!("{}", post.title); + println!("- - - - - -",); + println!("{}", post.body); + } +} diff --git a/src/bin/publicar_posts.rs b/src/bin/publicar_posts.rs new file mode 100644 index 0000000..9f105ea --- /dev/null +++ b/src/bin/publicar_posts.rs @@ -0,0 +1,23 @@ +use self::modelos::Post; +use rust_diesel_blogs::*; +use diesel::{prelude::*, connection}; +use std::env::args; + +fn main() { + use self::schema::posts::dsl::{posts, published}; + + let id = args() + .nth(1) + .expect("publicar requiere un id") + .parse::() + .expect("ID invalida"); + + let connection = &mut establecer_coneccion(); + + let post = diesel::update(posts.find(id)) + .set(published.eq(true)) + .returning(Post::as_returning()) + .get_results(connection) + .unwrap(); + println!("Publicado post {}", post.get(0).unwrap().title); + } \ No newline at end of file diff --git a/src/lib.rs b/src/lib.rs new file mode 100644 index 0000000..a4ba4cb --- /dev/null +++ b/src/lib.rs @@ -0,0 +1,31 @@ +pub mod modelos; +pub mod schema; + +use std::env; +use diesel::{PgConnection, Connection, RunQueryDsl, SelectableHelper}; +use dotenvy::dotenv; + +use crate::modelos::{NuevoPost, Post}; + +pub fn establecer_coneccion() -> PgConnection { + dotenv().ok(); + + let database_url = env::var("DATABASE_URL") + .expect("La DATABASE_URL tiene que esta definida"); + + PgConnection::establish(&database_url) + .unwrap_or_else(|_| panic!("Error conectando a {}", database_url)) + +} + +pub fn crear_post(conn: &mut PgConnection, title: &str, body: &str) -> Post { + use crate::schema::posts; + + let records = NuevoPost { title, body }; + + diesel::insert_into(posts::table) + .values(records) + .returning(Post::as_returning()) + .get_result(conn) + .expect("Fallo la carga") +} \ No newline at end of file diff --git a/src/modelos.rs b/src/modelos.rs new file mode 100644 index 0000000..a24c5c4 --- /dev/null +++ b/src/modelos.rs @@ -0,0 +1,20 @@ +use diesel::{prelude::{Queryable, Insertable}, Selectable}; + +use crate::schema::posts; + +#[derive(Queryable, Selectable)] +#[diesel(table_name = crate::schema::posts)] +#[diesel(check_for_backend(diesel::pg::Pg))] +pub struct Post { + pub id: i32, + pub title: String, + pub body: String, + pub published: bool, +} + +#[derive(Insertable)] +#[diesel(table_name = posts)] +pub struct NuevoPost<'a> { + pub title: &'a str, + pub body: &'a str, +} \ No newline at end of file diff --git a/src/schema.rs b/src/schema.rs new file mode 100644 index 0000000..e769c99 --- /dev/null +++ b/src/schema.rs @@ -0,0 +1,10 @@ +// @generated automatically by Diesel CLI. + +diesel::table! { + posts (id) { + id -> Int4, + title -> Varchar, + body -> Text, + published -> Bool, + } +}