initial commit

This commit is contained in:
2023-11-10 17:25:16 -03:00
commit fb030ce429
15 changed files with 207 additions and 0 deletions

1
.env Normal file
View File

@@ -0,0 +1 @@
DATABASE_URL=postgres://blog@192.168.1.11/blogging

2
.gitignore vendored Normal file
View File

@@ -0,0 +1,2 @@
/target
/Cargo.lock

10
Cargo.toml Normal file
View File

@@ -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"

9
diesel.toml Normal file
View File

@@ -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"

0
migrations/.keep Normal file
View File

View File

@@ -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();

View File

@@ -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;

View File

@@ -0,0 +1,2 @@
-- This file should undo anything in `up.sql`
DROP TABLE posts

View File

@@ -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
)

28
src/bin/escribir_post.rs Normal file
View File

@@ -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";

22
src/bin/mostrar_posts.rs Normal file
View File

@@ -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);
}
}

23
src/bin/publicar_posts.rs Normal file
View File

@@ -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::<i32>()
.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);
}

31
src/lib.rs Normal file
View File

@@ -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")
}

20
src/modelos.rs Normal file
View File

@@ -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,
}

10
src/schema.rs Normal file
View File

@@ -0,0 +1,10 @@
// @generated automatically by Diesel CLI.
diesel::table! {
posts (id) {
id -> Int4,
title -> Varchar,
body -> Text,
published -> Bool,
}
}