From 9294c0ee57a366a345fc0b8b1215b2a65b08fdfa Mon Sep 17 00:00:00 2001 From: Jack Christensen Date: Fri, 7 Jun 2013 14:23:46 -0500 Subject: [PATCH] Add SelectRow --- connection.go | 13 +++++++++++++ connection_test.go | 29 +++++++++++++++++++++++++++++ 2 files changed, 42 insertions(+) diff --git a/connection.go b/connection.go index 93c35a53..5b9b2dd8 100644 --- a/connection.go +++ b/connection.go @@ -145,6 +145,19 @@ func (c *Connection) SelectRows(sql string) (rows []map[string]string, err error return } +// Null values are not included in row. However, because maps return the 0 value +// for missing values this flattens nulls to empty string. If the caller needs to +// distinguish between a real empty string and a null it can use the comma ok +// pattern when accessing the map +func (c *Connection) SelectRow(sql string) (row map[string]string, err error) { + onDataRow := func(r *DataRowReader) error { + row = c.rxDataRow(r) + return nil + } + err = c.SelectFunc(sql, onDataRow) + return +} + func (c *Connection) sendSimpleQuery(sql string) (err error) { bufSize := 5 + len(sql) + 1 // message identifier (1), message size (4), null string terminator (1) buf := c.getBuf(bufSize) diff --git a/connection_test.go b/connection_test.go index 95e4db23..bf5c4b8e 100644 --- a/connection_test.go +++ b/connection_test.go @@ -172,3 +172,32 @@ func TestSelectRows(t *testing.T) { t.Error("Null value shouldn't have been present in map") } } + +func TestSelectRow(t *testing.T) { + conn := getSharedConnection() + + row, err := conn.SelectRow("select 'Jack' as name, null as position") + if err != nil { + t.Fatal("Query failed") + } + + if row["name"] != "Jack" { + t.Error("Received incorrect name") + } + + value, presence := row["position"] + if value != "" { + t.Error("Should have received empty string for null") + } + if presence != false { + t.Error("Null value shouldn't have been present in map") + } + + row, err = conn.SelectRow("select 'Jack' as name where 1=2") + if row != nil { + t.Error("No matching row should have returned nil") + } + if err != nil { + t.Fatal("Query failed") + } +}