Skip to content

Commit

Permalink
Add ping method to Conn
Browse files Browse the repository at this point in the history
- Documented the connection state and ping functionality in README.md

- Added `Ping` method to check connection status with error handling
  • Loading branch information
Srlion committed Oct 7, 2024
1 parent b09500b commit bfa8852
Show file tree
Hide file tree
Showing 2 changed files with 62 additions and 3 deletions.
25 changes: 25 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -389,6 +389,31 @@ if err then
end
```

Also calls `on_disconnected` with an error if one occurs.

#### `State`

Returns the current connection state.

> **Note:** Do **NOT** use numbers directly to check the state of the connection. Always use the provided constants. The numeric values of these constants may change in future versions, and using them directly could break your code.
```lua
local state = conn:State() -- compare it to goobie_mysql.STATES.*
```

#### `Ping`

Pings the database to check the connection status.

> **Note:** It's generally not recommended to use this method to check if a connection is alive, as it may not be reliable. For more information, refer to [this article](https://www.percona.com/blog/checking-for-a-live-database-connection-considered-harmful/).
```lua
local success, err = conn:Ping()
if not success then
print("Error during ping:", err.message)
end
```

#### `Execute`

Executes a query without fetching data.
Expand Down
40 changes: 37 additions & 3 deletions src/conn/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,9 @@ pub const METHODS: &[LuaReg] = lua_regs![
"Disconnect" => start_disconnect,
"DisconnectSync" => start_disconnect_sync,

"State" => get_state,
"Ping" => ping,

"Execute" => execute,
"FetchOne" => fetch_one,
"Fetch" => fetch,
Expand All @@ -43,8 +46,6 @@ pub const METHODS: &[LuaReg] = lua_regs![
"IsDisconnected" => is_disconnected,
"IsError" => is_error,

"State" => get_state,

"__tostring" => __tostring,
"__gc" => __gc,
];
Expand Down Expand Up @@ -119,7 +120,9 @@ impl Conn {
let mut inner_conn = self.inner.lock().await.take();

if let Some(conn) = inner_conn.take() {
let _ = conn.close().await; // let's gracefully close the connection if there is any
// let's gracefully close the connection if there is any
// if it fails, we will still try to connect. we just try to close it
let _ = conn.close().await;
}

self.set_state(State::Connecting);
Expand Down Expand Up @@ -170,6 +173,19 @@ impl Conn {
fn set_state(&self, state: State) {
self.state.store(state, Ordering::Release);
}

#[inline]
async fn ping(&self) -> Result<()> {
let mut inner_conn = self.inner.lock().await;
let inner_conn = match inner_conn.as_mut() {
Some(conn) => conn,
None => bail!("connection is not established"),
};

inner_conn.ping().await?;

Ok(())
}
}

impl std::fmt::Display for Conn {
Expand Down Expand Up @@ -347,6 +363,24 @@ fn get_state(l: lua::State) -> Result<i32> {
Ok(1)
}

#[lua_function]
fn ping(l: lua::State) -> Result<i32> {
let conn = Conn::extract_userdata(l)?;

let res = wait_async(l, async move { conn.ping().await });
match res {
Ok(_) => {
l.push_bool(true);
Ok(1)
}
Err(e) => {
l.push_bool(false);
handle_error(l, e);
Ok(2)
}
}
}

#[lua_function]
fn __tostring(l: lua::State) -> Result<i32> {
let conn = Conn::extract_userdata(l)?;
Expand Down

0 comments on commit bfa8852

Please sign in to comment.