Giter Club home page Giter Club logo

rustorm's Introduction

Build Status

rustorm

Rustorm

Financial Contributors on Open Collective Latest Version Build Status MIT licensed

Rustorm is an SQL-centered ORM with focus on ease of use on conversion of database types to their appropriate rust type.

Selecting records

use rustorm::{
    DbError,
    FromDao,
    Pool,
    ToColumnNames,
    ToTableName,
};

#[derive(Debug, FromDao, ToColumnNames, ToTableName)]
struct Actor {
    actor_id: i32,
    first_name: String,
}

#[cfg(any(feature="with-postgres", feature = "with-sqlite"))]
fn main() {
    let mut pool = Pool::new();
    #[cfg(feature = "with-sqlite")]
    let db_url = "sqlite://sakila.db";
    #[cfg(feature = "with-postgres")]
    let db_url = "postgres://postgres:p0stgr3s@localhost/sakila";
    let em = pool.em(db_url).unwrap();
    let sql = "SELECT * FROM actor LIMIT 10";
    let actors: Result<Vec<Actor>, DbError> =
        em.execute_sql_with_return(sql, &[]);
    println!("Actor: {:#?}", actors);
    let actors = actors.unwrap();
    assert_eq!(actors.len(), 10);
    for actor in actors {
        println!("actor: {:?}", actor);
    }
}
#[cfg(feature="with-mysql")]
fn main() {
   println!("see examples for mysql usage, mysql has a little difference in the api");
}

Inserting and displaying the inserted records

use chrono::{
    offset::Utc,
    DateTime,
    NaiveDate,
};
use rustorm::{
    DbError,
    FromDao,
    Pool,
    TableName,
    ToColumnNames,
    ToDao,
    ToTableName,
};


#[cfg(any(feature="with-postgres", feature = "with-sqlite"))]
fn main() {
    mod for_insert {
        use super::*;
        #[derive(Debug, PartialEq, ToDao, ToColumnNames, ToTableName)]
        pub struct Actor {
            pub first_name: String,
            pub last_name: String,
        }
    }

    mod for_retrieve {
        use super::*;
        #[derive(Debug, FromDao, ToColumnNames, ToTableName)]
        pub struct Actor {
            pub actor_id: i32,
            pub first_name: String,
            pub last_name: String,
            pub last_update: DateTime<Utc>,
        }
    }

    let mut pool = Pool::new();
    #[cfg(feature = "with-sqlite")]
    let db_url = "sqlite://sakila.db";
    #[cfg(feature = "with-postgres")]
    let db_url = "postgres://postgres:p0stgr3s@localhost/sakila";
    let em = pool.em(db_url).unwrap();
    let tom_cruise = for_insert::Actor {
        first_name: "TOM".into(),
        last_name: "CRUISE".to_string(),
    };
    let tom_hanks = for_insert::Actor {
        first_name: "TOM".into(),
        last_name: "HANKS".to_string(),
    };

    let actors: Result<Vec<for_retrieve::Actor>, DbError> =
        em.insert(&[&tom_cruise, &tom_hanks]);
    println!("Actor: {:#?}", actors);
    assert!(actors.is_ok());
    let actors = actors.unwrap();
    let today = Utc::now().date();
    assert_eq!(tom_cruise.first_name, actors[0].first_name);
    assert_eq!(tom_cruise.last_name, actors[0].last_name);
    assert_eq!(today, actors[0].last_update.date());

    assert_eq!(tom_hanks.first_name, actors[1].first_name);
    assert_eq!(tom_hanks.last_name, actors[1].last_name);
    assert_eq!(today, actors[1].last_update.date());
}
#[cfg(feature="with-mysql")]
fn main() {
   println!("see examples for mysql usage, mysql has a little difference in the api");
}

Rustorm is wholly used by diwata

License: MIT

Contributors

Code Contributors

This project exists thanks to all the people who contribute. [Contribute].

Financial Contributors

Become a financial contributor and help us sustain our community. [Contribute]

Individuals

Organizations

Support this project with your organization. Your logo will show up here with a link to your website. [Contribute]

rustorm's People

Contributors

alu avatar edmellum avatar ivanceras avatar miketang84 avatar monkeywithacupcake avatar mstuehn avatar traviscross avatar zimond avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

rustorm's Issues

Derive macros aren't usable unless rustorm_dao is added as a separate dependency.

rustorm version: 0.17
rust version: 1.45.2

Attempting to use any of the derive macros provided by rustorm (ToDao, FromDao, ToTableName, ToColumnNames) will fail to compile with the following error message: error[E0433]: failed to resolve: use of undeclared type or module `rustorm_dao`

Adding rustorm_dao = "0.5" as a dependency in Cargo.toml fixes this but since rustorm_dao is already a dependency of rustorm and this is not mentioned anywhere in the readme I am guessing this isn't supposed to be the case? If this is expected, it should probably be mentioned somewhere.

How execute SQL

@ivanceras
Hi.

I want to execute SQL that does not need return value like below.

UPDATE user set name = ? where id = ?

I looked for match to the objective, but i can't found it.
What should I use?

Option with custom types

@ivanceras Hi! Thank you for merging my PR :D. But i got new problem :(.

We have defined several custom type such as Id(i64).

It can be used as query parameter if we defined impl rustorm::ToValue for Id.

impl rustorm::ToValue for Id {
    fn to_value(&self) -> rustorm::Value {
        rustorm::Value::Bigint(self.0)
    }
}

#[derive(Debug, FromDao)]
struct R {}

let _: Vec<R> = em
    .execute_sql_with_return("SELECT id FROM table id = ?", &[&Id(99)])
    .unwrap();

It can be used as result type if we defined impl From<&rustorm::Value> for Id.

impl From<&rustorm::Value> for Id {
    fn from(v: &rustorm::Value) -> Id {
        match v {
            rustorm::Value::Bigint(v) => Id(*v),
            _ => panic!("unable to convert"),
        }
    }
}

#[derive(Debug, FromDao)]
struct R {
    e: Id,
}

let _: Vec<R> = em
    .execute_sql_with_return("SELECT id FROM table", &[])
    .unwrap();

But we can't be used if it wrapted by Option because From and ToValue are external trait, and Option is external type.

The newtype pattern such as Id(i64) is general in Rust so I think it ’s worth making it available.
I think need new trait such as FromValue for instead of From.
But it's will makes broken changes.

What do you think the idea?

support for int/bigint arrays

I was trying to use this but ran into issues with some of my columns having int and bigint arrays, tried to also hack around it by implementing FromValue myself but ran into more issues with Array::Int being only 32bits.

Why so many println statments?

Its really annoying that a library has so many println statements and the log level info is too much just for executing sql statements.

Problem to adopt it.

Hi, rustorm_dao, and rustorm_codegen should update to latest on crates.io, so we can do development using rustorm.

Compiling bug

mike@DESKTOP-IU99086:~/sappworks/rustorm$ cargo build
   Compiling rustorm v0.10.7 (/home/mike/sappworks/rustorm)
error[E0599]: no method named `safe_name` found for type `dao::TableName` in the current scope
  --> src/table.rs:29:19
   |
29 |         self.name.safe_name()
   |                   ^^^^^^^^^

error[E0599]: no method named `safe_complete_name` found for type `dao::TableName` in the current scope
  --> src/table.rs:33:19
   |
33 |         self.name.safe_complete_name()
   |                   ^^^^^^^^^^^^^^^^^^
   |
   = help: did you mean `complete_name`?

error: aborting due to 2 previous errors

For more information about this error, try `rustc --explain E0599`.
error: Could not compile `rustorm`.

To learn more, run the command again with --verbose.
mike@DESKTOP-IU99086:~/sappworks/rustorm$ rustc -V
rustc 1.30.0-nightly (63d51e89a 2018-09-28)


Problem in Option<Enum>

Hi.

We want to use enum as query result and parameter so we implemented traits to enum.
But it does not work when contain in Option because From<Value> for Option<Enum> does not implemented .
As you know we cannot implement the trait because Value and Option are outside crate both.
I make Opt<Option<T>> and avoid it, are there more happy solution?

Example.

use rustorm::codegen::{ToColumnNames, ToDao, ToTableName};

#[derive(Debug)]
enum ExampleEnum {
    A,
    B,
}

impl rustorm::ToValue for ExampleEnum {
    fn to_value(&self) -> rustorm::Value {
        self.into()
    }
}

impl From<&ExampleEnum> for rustorm::Value {
    fn from(from: &ExampleEnum) -> rustorm::Value {
        match from {
            ExampleEnum::A => "a",
            ExampleEnum::B => "b",
        }
        .into()
    }
}

impl From<&rustorm::Value> for ExampleEnum {
    fn from(value: &rustorm::Value) -> Self {
        match value {
            rustorm::Value::Text(value) => match value.as_str() {
                "a" => ExampleEnum::A,
                "b" => ExampleEnum::B,
                _ => panic!("unkonwn value"),
            },
            _ => panic!("unspported type"),
        }
    }
}

// OK!
#[derive(Debug, ToDao, ToColumnNames, ToTableName)]
struct ExampleStruct {
    value: ExampleEnum,
}

// NG...
#[derive(Debug, ToDao, ToColumnNames, ToTableName)]
struct ExampleOptionStruct {
    value: Option<ExampleEnum>,
}

implement std Error for error types

This could help errors from this crate work better with general error handling crates.

Currently the most suitable solution would be using the thiserror crate. Or, we could manulay implement std::error::Error for all the errors exported from rustorm.

Which is your fav? I can make a PR based on the choice.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.