Switch over to new format + clean up matches

This commit is contained in:
Steven Fackler 2013-09-03 20:07:10 -07:00
parent 7990809251
commit 9891f597bc
2 changed files with 44 additions and 43 deletions

View File

@ -43,9 +43,20 @@ macro_rules! match_read_message(
) )
) )
macro_rules! match_read_message_or_fail(
($conn:expr, { $($($p:pat)|+ => $e:expr),+ }) => (
match_read_message!($conn, {
$(
$($p)|+ => $e
),+ ,
resp => fail2!("Bad response: {}", resp.to_str())
})
)
)
fn handle_notice_response(fields: ~[(u8, ~str)]) { fn handle_notice_response(fields: ~[(u8, ~str)]) {
let err = PostgresDbError::new(fields); let err = PostgresDbError::new(fields);
info!("%s: %s", err.severity, err.message); info2!("{}: {}", err.severity, err.message);
} }
#[deriving(ToStr)] #[deriving(ToStr)]
@ -123,7 +134,7 @@ impl PostgresConnection {
pub fn connect(url: &str) -> PostgresConnection { pub fn connect(url: &str) -> PostgresConnection {
match PostgresConnection::try_connect(url) { match PostgresConnection::try_connect(url) {
Ok(conn) => conn, Ok(conn) => conn,
Err(err) => fail!("Failed to connect: %s", err.to_str()) Err(err) => fail2!("Failed to connect: {}", err.to_str())
} }
} }
@ -176,12 +187,11 @@ impl PostgresConnection {
} }
loop { loop {
match_read_message!(conn, { match_read_message_or_fail!(conn, {
ParameterStatus { parameter, value } => ParameterStatus { parameter, value } =>
info!("Parameter %s = %s", parameter, value), info!("Parameter %s = %s", parameter, value),
BackendKeyData {_} => (), BackendKeyData {_} => (),
ReadyForQuery {_} => break, ReadyForQuery {_} => break
resp => fail!("Bad response: %?", resp.to_str())
}) })
} }
@ -211,7 +221,7 @@ impl PostgresConnection {
} }
fn handle_auth(&self, user: UserInfo) -> Option<PostgresConnectError> { fn handle_auth(&self, user: UserInfo) -> Option<PostgresConnectError> {
match_read_message!(self, { match_read_message_or_fail!(self, {
AuthenticationOk => return None, AuthenticationOk => return None,
AuthenticationCleartextPassword => { AuthenticationCleartextPassword => {
let pass = match user.pass { let pass = match user.pass {
@ -237,23 +247,21 @@ impl PostgresConnection {
self.write_message(&PasswordMessage { self.write_message(&PasswordMessage {
password: output.as_slice() password: output.as_slice()
}); });
}, }
resp => fail!("Bad response: %?", resp.to_str())
}) })
match_read_message!(self, { match_read_message_or_fail!(self, {
AuthenticationOk => None, AuthenticationOk => None,
ErrorResponse { fields } => ErrorResponse { fields } =>
Some(DbError(PostgresDbError::new(fields))), Some(DbError(PostgresDbError::new(fields)))
resp => fail!("Bad response: %?", resp.to_str())
}) })
} }
pub fn prepare<'a>(&'a self, query: &str) -> PostgresStatement<'a> { pub fn prepare<'a>(&'a self, query: &str) -> PostgresStatement<'a> {
match self.try_prepare(query) { match self.try_prepare(query) {
Ok(stmt) => stmt, Ok(stmt) => stmt,
Err(err) => fail!("Error preparing \"%s\": %s", query, Err(err) => fail2!("Error preparing \"{}\": {}", query,
err.to_str()) err.to_str())
} }
} }
@ -276,24 +284,21 @@ impl PostgresConnection {
}, },
&Sync]); &Sync]);
match_read_message!(self, { match_read_message_or_fail!(self, {
ParseComplete => (), ParseComplete => (),
ErrorResponse { fields } => { ErrorResponse { fields } => {
self.wait_for_ready(); self.wait_for_ready();
return Err(PostgresDbError::new(fields)); return Err(PostgresDbError::new(fields));
}, }
resp => fail!("Bad response: %?", resp.to_str())
}) })
let param_types = match_read_message!(self, { let param_types = match_read_message_or_fail!(self, {
ParameterDescription { types } => types, ParameterDescription { types } => types
resp => fail!("Bad response: %?", resp.to_str())
}); });
let result_desc = match_read_message!(self, { let result_desc = match_read_message_or_fail!(self, {
RowDescription { descriptions } => descriptions, RowDescription { descriptions } => descriptions,
NoData => ~[], NoData => ~[]
resp => fail!("Bad response: %?", resp.to_str())
}); });
self.wait_for_ready(); self.wait_for_ready();
@ -328,7 +333,7 @@ impl PostgresConnection {
pub fn update(&self, query: &str, params: &[&ToSql]) -> uint { pub fn update(&self, query: &str, params: &[&ToSql]) -> uint {
match self.try_update(query, params) { match self.try_update(query, params) {
Ok(res) => res, Ok(res) => res,
Err(err) => fail!("Error running update: %s", err.to_str()) Err(err) => fail2!("Error running update: {}", err.to_str())
} }
} }
@ -346,16 +351,15 @@ impl PostgresConnection {
match_read_message!(self, { match_read_message!(self, {
ReadyForQuery {_} => break, ReadyForQuery {_} => break,
ErrorResponse { fields } => ErrorResponse { fields } =>
fail!("Error: %s", PostgresDbError::new(fields).to_str()), fail2!("Error: {}", PostgresDbError::new(fields).to_str()),
_ => () _ => ()
}) })
} }
} }
fn wait_for_ready(&self) { fn wait_for_ready(&self) {
match_read_message!(self, { match_read_message_or_fail!(self, {
ReadyForQuery {_} => (), ReadyForQuery {_} => ()
resp => fail!("Bad response: %?", resp.to_str())
}) })
} }
} }
@ -461,20 +465,19 @@ impl<'self> PostgresStatement<'self> {
}, },
&Sync]); &Sync]);
match_read_message!(self.conn, { match_read_message_or_fail!(self.conn, {
BindComplete => None, BindComplete => None,
ErrorResponse { fields } => { ErrorResponse { fields } => {
self.conn.wait_for_ready(); self.conn.wait_for_ready();
Some(PostgresDbError::new(fields)) Some(PostgresDbError::new(fields))
}, }
resp => fail!("Bad response: %?", resp.to_str())
}) })
} }
pub fn update(&self, params: &[&ToSql]) -> uint { pub fn update(&self, params: &[&ToSql]) -> uint {
match self.try_update(params) { match self.try_update(params) {
Ok(count) => count, Ok(count) => count,
Err(err) => fail!("Error running update: %s", err.to_str()) Err(err) => fail2!("Error running update: {}", err.to_str())
} }
} }
@ -489,7 +492,7 @@ impl<'self> PostgresStatement<'self> {
let num; let num;
loop { loop {
match_read_message!(self.conn, { match_read_message_or_fail!(self.conn, {
CommandComplete { tag } => { CommandComplete { tag } => {
let s = tag.split_iter(' ').last().unwrap(); let s = tag.split_iter(' ').last().unwrap();
num = match FromStr::from_str(s) { num = match FromStr::from_str(s) {
@ -507,8 +510,7 @@ impl<'self> PostgresStatement<'self> {
ErrorResponse { fields } => { ErrorResponse { fields } => {
self.conn.wait_for_ready(); self.conn.wait_for_ready();
return Err(PostgresDbError::new(fields)); return Err(PostgresDbError::new(fields));
}, }
resp => fail!("Bad response: %?", resp.to_str())
}) })
} }
self.conn.wait_for_ready(); self.conn.wait_for_ready();
@ -520,7 +522,7 @@ impl<'self> PostgresStatement<'self> {
-> PostgresResult<'self> { -> PostgresResult<'self> {
match self.try_query(params) { match self.try_query(params) {
Ok(result) => result, Ok(result) => result,
Err(err) => fail!("Error running query: %s", err.to_str()) Err(err) => fail2!("Error running query: {}", err.to_str())
} }
} }
@ -535,13 +537,12 @@ impl<'self> PostgresStatement<'self> {
let mut data = ~[]; let mut data = ~[];
loop { loop {
match_read_message!(self.conn, { match_read_message_or_fail!(self.conn, {
EmptyQueryResponse | EmptyQueryResponse |
CommandComplete {_} => { CommandComplete {_} => {
break; break;
}, },
DataRow { row } => data.push(row), DataRow { row } => data.push(row)
resp => fail!("Bad response: %?", resp.to_str())
}) })
} }
self.conn.wait_for_ready(); self.conn.wait_for_ready();
@ -618,7 +619,7 @@ impl<'self> RowIndex for &'self str {
fn idx(&self, stmt: &PostgresStatement) -> uint { fn idx(&self, stmt: &PostgresStatement) -> uint {
match stmt.find_col_named(*self) { match stmt.find_col_named(*self) {
Some(idx) => idx, Some(idx) => idx,
None => fail!("No column with name %s", *self) None => fail2!("No column with name {}", *self)
} }
} }
} }

View File

@ -120,7 +120,7 @@ pub trait WriteMessage {
impl<W: Writer> WriteMessage for W { impl<W: Writer> WriteMessage for W {
fn write_message(&mut self, message: &FrontendMessage) { fn write_message(&mut self, message: &FrontendMessage) {
debug!("Writing message %?", message); debug2!("Writing message {:?}", message);
let mut buf = MemWriter::new(); let mut buf = MemWriter::new();
let mut ident = None; let mut ident = None;
@ -268,10 +268,10 @@ impl<R: Reader> ReadMessage for R {
't' => read_parameter_description(&mut buf), 't' => read_parameter_description(&mut buf),
'T' => read_row_description(&mut buf), 'T' => read_row_description(&mut buf),
'Z' => ReadyForQuery { state: buf.read_u8_() }, 'Z' => ReadyForQuery { state: buf.read_u8_() },
ident => fail!("Unknown message identifier `%c`", ident) ident => fail2!("Unknown message identifier `{}`", ident)
}; };
assert!(buf.eof()); assert!(buf.eof());
debug!("Read message %?", ret); debug2!("Read message {:?}", ret);
ret ret
} }
} }
@ -310,7 +310,7 @@ fn read_auth_message(buf: &mut MemReader) -> BackendMessage {
0 => AuthenticationOk, 0 => AuthenticationOk,
3 => AuthenticationCleartextPassword, 3 => AuthenticationCleartextPassword,
5 => AuthenticationMD5Password { salt: buf.read_bytes(4) }, 5 => AuthenticationMD5Password { salt: buf.read_bytes(4) },
val => fail!("Unknown Authentication identifier `%?`", val) val => fail2!("Unknown Authentication identifier `{}`", val)
} }
} }