Skip to content

Commit

Permalink
Remove "on_error" for queries
Browse files Browse the repository at this point in the history
Rename "on_done" to "callback", receives two arguments, first is an error table, second is the result
  • Loading branch information
Srlion committed Oct 9, 2024
1 parent dbc7cec commit 892343f
Show file tree
Hide file tree
Showing 2 changed files with 63 additions and 67 deletions.
50 changes: 28 additions & 22 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -122,28 +122,31 @@ Executes a query without returning any data (e.g., `INSERT`, `UPDATE`).
```lua
conn:Execute("INSERT INTO users (name, age) VALUES (?, ?)", {
params = {"John Doe", 30},
on_done = function(result)
print("Affected Rows:", result.affected_rows)
print("Insert ID:", result.insert_id)
end,
on_error = function(err)
print("Error:", err.message)
callback = function(err, res)
if err then
print("Error:", err.message)
return
end

print("Affected Rows:", res.affected_rows)
print("Insert ID:", res.insert_id)
end,
})
```

**Synchronous execution:**

```lua
local err, result = conn:Execute("UPDATE users SET age = age + 1 WHERE id = ?", {
local err, res = conn:Execute("UPDATE users SET age = age + 1 WHERE id = ?", {
params = {1},
sync = true,
})
if err then
print("Error:", err.message)
-- Handle error
else
print("Rows affected:", result.affected_rows)
print("Rows affected:", res.affected_rows)
print("Insert ID:", res.insert_id)
end
```

Expand All @@ -158,14 +161,16 @@ Fetches multiple rows from a `SELECT` query.
```lua
conn:Fetch("SELECT * FROM users WHERE age > ?", {
params = {20},
on_done = function(rows)
callback = function(err, rows)
if err then
print("Error:", err.message)
return
end

for _, row in ipairs(rows) do
print("User:", row.name, "Age:", row.age)
end
end,
on_error = function(err)
print("Error:", err.message)
end,
end
})
```

Expand Down Expand Up @@ -194,16 +199,18 @@ Fetches a single row from a `SELECT` query.
```lua
conn:FetchOne("SELECT * FROM users WHERE id = ?", {
params = {1},
on_done = function(row)
callback = function(err, row)
if err then
print("Error:", err.message)
return
end

if row then
print("User:", row.name, "Age:", row.age)
else
print("No user found.")
end
end,
on_error = function(err)
print("Error:", err.message)
end,
end
})
```

Expand Down Expand Up @@ -297,7 +304,7 @@ I use it to test async queries in a synchronous environment, to verify that they
```lua
local is_done = false
conn:Execute("SELECT 1", {
on_done = function()
callback = function()
is_done = true
},
})
Expand Down Expand Up @@ -328,14 +335,13 @@ The following options can be used with `Execute`, `Fetch`, and `FetchOne` method
| `sync` | `boolean` | If `true`, runs the query synchronously. Defaults to `false`. |
| `raw` | `boolean` | If `true`, executes the query as a raw SQL string without using prepared statements. Defaults to `false`. Useful for executing multiple statements. |
| `params` | `table` | Parameters for parameterized queries. Ignored if `raw = true`. |
| `on_done` | `function` | Callback function called upon successful completion of the query. |
| `on_error` | `function` | Callback function called when an error occurs during the query execution. |
| `callback` | `function` | Callback function invoked when the process is complete. |

**Notes:**

- When using `raw = true`, you can execute multiple statements in a single query.
- Be cautious with raw queries to avoid SQL injection attacks. Only use raw queries when necessary.
- Refer to the [Error Table](#error-table) for the structure of error objects passed to `on_error`.
- Refer to the [Error Table](#error-table) for the structure of error objects passed to `callback`.

### Connection Methods

Expand Down
80 changes: 35 additions & 45 deletions src/query/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,8 +20,7 @@ pub struct Query {
pub query: String,
pub r#type: QueryType,
pub params: Params,
pub on_done: i32,
pub on_error: i32,
pub callback: i32,
pub sync: bool,
pub raw: bool,
}
Expand All @@ -34,8 +33,7 @@ impl Query {
sync: true,
raw: false,
params: Vec::new(),
on_error: LUA_NOREF,
on_done: LUA_NOREF,
callback: LUA_NOREF,
}
}

Expand Down Expand Up @@ -104,12 +102,8 @@ impl Query {
}

fn parse_on_fns(&mut self, l: lua::State, arg_n: i32) -> Result<()> {
if l.get_field_type_or_nil(arg_n, c"on_done", LUA_TFUNCTION)? {
self.on_done = l.reference();
}

if l.get_field_type_or_nil(arg_n, c"on_error", LUA_TFUNCTION)? {
self.on_error = l.reference();
if l.get_field_type_or_nil(arg_n, c"callback", LUA_TFUNCTION)? {
self.callback = l.reference();
}

Ok(())
Expand Down Expand Up @@ -139,48 +133,44 @@ impl Query {
res: Result<QueryResult>,
traceback: Option<&str>,
) -> i32 {
let process = || {
let res = match res {
Ok(QueryResult::Execute(info)) => process_info(l, info),
Ok(QueryResult::Row(row)) => process_row(l, row),
Ok(QueryResult::Rows(rows)) => process_rows(l, &rows),
Err(e) => Err(e),
};

// handle_error pushes the error as a table to the stack
res.map_err(|e| handle_error(l, e))
let res = match res {
Ok(QueryResult::Execute(info)) => process_info(l, info),
Ok(QueryResult::Row(row)) => process_row(l, row),
Ok(QueryResult::Rows(rows)) => process_rows(l, &rows),
Err(e) => Err(e),
};

let (returns_count, err_msg) = match res {
Ok(0) => {
l.push_nil();
(1, None)
}
Ok(n) => {
l.push_nil();
l.insert(-n - 1);
(n + 1, None)
}
Err(e) => {
// handle_error pushes the error as a table to the stack
let err_msg = handle_error(l, e);
(1, Some(err_msg))
}
};

if self.sync {
return match process() {
Ok(rets) => {
if rets == 0 {
l.push_nil();
1
} else {
l.push_nil();
l.insert(-rets - 1);
rets + 1
}
}
Err(_) => 1,
};
return returns_count;
}

match process() {
Ok(rets) => {
l.pcall_ignore_function_ref(self.on_done, rets, 0);
}
Err(msg) => {
let (called_function, _) = l.pcall_ignore_function_ref(self.on_error, 1, 0);
if !called_function {
l.error_no_halt(&msg, traceback);
}
let (called_function, _) = l.pcall_ignore_function_ref(self.callback, returns_count, 0);
// make sure that if there is an error, it doesn't go silent
// can't combine these two if statements because it's not stabliized yet for using "if let" statement :)
if !called_function {
if let Some(err_msg) = err_msg {
l.error_no_halt(&err_msg, traceback);
}
};
}

l.dereference(self.on_done);
l.dereference(self.on_error);
l.dereference(self.callback);

0
}
Expand Down

0 comments on commit 892343f

Please sign in to comment.