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

Delete feature - Issue #16 #36

Merged
merged 4 commits into from
Nov 21, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 35 additions & 0 deletions migrations.toml
Original file line number Diff line number Diff line change
@@ -1 +1,36 @@
# This file is auto-generated by Turbosql.
# It is used to create and apply automatic schema migrations.
# It should be checked into source control.
# Modifying it by hand may be dangerous; see the docs.

migrations_append_only = [
"CREATE TABLE person (rowid INTEGER PRIMARY KEY) STRICT",
"ALTER TABLE person ADD COLUMN name TEXT",
"ALTER TABLE person ADD COLUMN age INTEGER",
"ALTER TABLE person ADD COLUMN image_jpg BLOB",
]
output_generated_schema_for_your_information_do_not_edit = """
CREATE TABLE _turbosql_migrations (
rowid INTEGER PRIMARY KEY,
migration TEXT NOT NULL
) STRICT
CREATE TABLE person (
rowid INTEGER PRIMARY KEY,
name TEXT,
age INTEGER,
image_jpg BLOB
) STRICT
"""

[output_generated_tables_do_not_edit.person]
name = "person"

[[output_generated_tables_do_not_edit.person.columns]]
name = "rowid"
rust_type = "Option < i64 >"
sql_type = "INTEGER PRIMARY KEY"

[[output_generated_tables_do_not_edit.person.columns]]
name = "name"
rust_type = "Option < String >"
sql_type = "TEXT"
33 changes: 33 additions & 0 deletions turbosql-impl/src/delete.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
use quote::quote_spanned;

use crate::Table;

pub(super) fn delete(table: &Table) -> proc_macro2::TokenStream {
let sql = makesql_delete(table);
super::validate_sql_or_abort(&sql);
let columns = table.columns.iter().filter(|c| c.name == "rowid").map(|c| {
let ident = &c.ident;
if c.sql_type == "TEXT" && c.rust_type != "Option < String >" {
quote_spanned!(c.span => &::turbosql::serde_json::to_string(&self.#ident)? as &dyn ::turbosql::ToSql)
} else {
quote_spanned!(c.span => &self.#ident as &dyn ::turbosql::ToSql)
}
})
.collect::<Vec<_>>();


quote_spanned! { table.span =>
fn delete(&self) -> Result<usize, ::turbosql::Error> {
assert!(self.rowid.is_some());
::turbosql::__TURBOSQL_DB.with(|db| {
let db = db.borrow_mut();
let mut stmt = db.prepare_cached(#sql)?;
Ok(stmt.execute(&[#( #columns ),*] as &[&dyn ::turbosql::ToSql])?)
})
}
}
}

fn makesql_delete(table: &Table) -> String {
format!("DELETE FROM {} WHERE rowid = ?", table.name)
}
3 changes: 3 additions & 0 deletions turbosql-impl/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ const MIGRATIONS_FILENAME: &str = "test.migrations.toml";

mod insert;
mod update;
mod delete;

#[derive(Debug, Clone)]
struct Table {
Expand Down Expand Up @@ -724,6 +725,7 @@ pub fn turbosql_derive_macro(input: proc_macro::TokenStream) -> proc_macro::Toke

let fn_insert = insert::insert(&table);
let fn_update = update::update(&table);
let fn_delete = delete::delete(&table);

// output tokenstream

Expand All @@ -732,6 +734,7 @@ pub fn turbosql_derive_macro(input: proc_macro::TokenStream) -> proc_macro::Toke
impl ::turbosql::Turbosql for #table {
#fn_insert
#fn_update
#fn_delete
}
}
.into()
Expand Down
1 change: 1 addition & 0 deletions turbosql/src/lib_inner.rs
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ pub trait Turbosql {
/// Updates this existing row in the database, based on `rowid`, which must be `Some`. All fields are overwritten in the database. On success, returns the number of rows updated, which should be 1.
fn update(&self) -> Result<usize, Error>;
fn update_batch<T: AsRef<Self>>(rows: &[T]) -> Result<(), Error>;
fn delete(&self) -> Result<usize, Error>;
}

#[derive(thiserror::Error, Debug)]
Expand Down
7 changes: 7 additions & 0 deletions turbosql/tests/integration_test.rs
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,13 @@ fn integration_test() {
select!(Vec<String> "field_string FROM personintegrationtest").unwrap(),
vec!["Bob", "Bob"]
);
let mut r = PersonIntegrationTest {
..Default::default()
};
let id = r.insert().unwrap();
r.rowid = Some(id);
r.delete().unwrap();
assert!(select!(PersonIntegrationTest "WHERE rowid = ?", id).is_err());
execute!("DELETE FROM personintegrationtest WHERE rowid = 2").unwrap();
assert_eq!(select!(i64 "SELECT 1").unwrap(), 1);
assert_eq!(select!(bool "SELECT 1 > ? AS val", 0).unwrap(), true);
Expand Down