Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added insert multiple rows support #8

Merged
merged 9 commits into from
Dec 31, 2024

Conversation

Sanchiz1
Copy link
Contributor

@Sanchiz1 Sanchiz1 commented Dec 28, 2024

  1. Updated inserts Field:

    • Changed the value property to values: Vec<Box<dyn ToSql>>.
  2. Refactored insert Method:

    • Updated the insert method to store values in new property.
  3. Added insert_many Method:

    • Introduced the insert_many method to handle bulk insertion of multiple rows.

@tjardoo
Copy link
Owner

tjardoo commented Dec 29, 2024

Thanks for the PR! Looks good to me.

This setup works if all the fields are of the same type - in the example all the fields are of the type &str. If I add a vector with only a field 'age' for example of the type u32 it also works. But when we have field with different type like - name, email of &str and age of u32 it doesn't work. Do you have any suggestion on how we could cover this?

let rows = vec![
    vec![
        ("name", "Alice"),
        ("email", "[email protected]"),
        ("age", 21),
    ],
    vec![("name", "Bob"), ("email", "[email protected]"), ("age", 22)],
];

let query = Eloquent::query().table("users").insert_many(rows);

assert_eq!(
    query.sql().unwrap(),
    "INSERT INTO users (name, email, age) VALUES ('Alice', '[email protected]' 21), ('Bob', '[email protected]', 22)"
);

@Sanchiz1
Copy link
Contributor Author

Sanchiz1 commented Dec 29, 2024

Hi, thank you for reviewing the PR and for raising this excellent point! To handle fields of mixed types we can update the implementation to use Box for the value type. The throwback will be the need to construct rows using Box::new()

let rows = vec![
        vec![
            ("name", Box::new("Alice") as Box<dyn ToSql>),
            ("email", Box::new("[email protected]") as Box<dyn ToSql>),
            ("age", Box::new(21) as Box<dyn ToSql>),
        ],
        vec![
            ("name", Box::new("Bob") as Box<dyn ToSql>),
            ("email", Box::new("[email protected]") as Box<dyn ToSql>),
            ("age", Box::new(22) as Box<dyn ToSql>),
        ],
    ];

But we can introduce some kind of rows builder for simpler code.

@tjardoo
Copy link
Owner

tjardoo commented Dec 30, 2024

Thanks for adjustments. That works but I don't really like the wrapping in a Box and typing it every time with as Box<dyn ToSql>.

What do you think of this? Feel free to adjust.

let rows = vec![
    eloquent_sql_row! {
        "name" => "Alice",
        "email" => "[email protected]",
        "age" => 21,
        "is_active" => true,
    },
    eloquent_sql_row! {
        "name" => "Bob",
        "email" => "[email protected]",
        "age" => 22,
        "is_active" => false,
    },
];

let query = Eloquent::query().table("users").insert_many(rows);

assert_eq!(
    query.sql().unwrap(),
    "INSERT INTO users (name, email, age, is_active) VALUES ('Alice', '[email protected]', 21, true), ('Bob', '[email protected]', 22, false)"
);

and then in the eloquent_core\src\lib.rs we add this macro.

#[macro_export]
macro_rules! eloquent_sql_row {
    ($($key:expr => $value:expr),* $(,)?) => {
        vec![
            $(($key, Box::new($value) as Box<dyn ToSql>)),*
        ]
    };
}
pub fn insert_many(mut self, rows: Vec<Vec<(&str, Box<dyn ToSql>)>>) -> Self {
    rows.into_iter().for_each(|row| self.add_row(row));

    self
}

fn add_insert(&mut self, column: &str, value: Box<dyn ToSql>) {
    if let Some(insert) = self.inserts.iter_mut().find(|i| i.column == column) {
        insert.values.push(value);
    } else {
        self.inserts.push(Insert {
            column: column.to_string(),
            values: vec![value],
        });
    }
}

fn add_row(&mut self, row: Vec<(&str, Box<dyn ToSql>)>) {
    row.into_iter()
        .for_each(|(column, value)| self.add_insert(column, value));
}

I also did try this using a HashMap that does work but as the hash is different each time the order of the columns to be inserted is too - and that prevented me to get the assertion to work every time.

@tjardoo tjardoo linked an issue Dec 30, 2024 that may be closed by this pull request
@Sanchiz1
Copy link
Contributor Author

Sanchiz1 commented Dec 30, 2024

Great suggestion!

  1. Created macro:
#[macro_export]
macro_rules! eloquent_sql_row {
    ($($key:expr => $value:expr),* $(,)?) => {
        vec![
            $(($key, Box::new($value) as Box<dyn $crate::ToSql>)),*
        ]
    };
}
  1. Updated insert_many method documentation using macro.

@Sanchiz1
Copy link
Contributor Author

Sanchiz1 commented Dec 30, 2024

Created validator that checks for equal number of values per column across inserts, prevents creating query with rows with different values.

Please let me know if you want to adjust something!

@tjardoo
Copy link
Owner

tjardoo commented Dec 31, 2024

Thanks a lot. Nice addition! Will merge it.

@tjardoo tjardoo merged commit 1de0c9c into tjardoo:master Dec 31, 2024
2 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Insert multiple rows support
2 participants