Skip to content

Commit

Permalink
Update xsql QueryFirst()
Browse files Browse the repository at this point in the history
  • Loading branch information
onanying committed Jun 7, 2024
1 parent 9999534 commit 6a20447
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 7 deletions.
13 changes: 12 additions & 1 deletion src/xsql/db.go
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,7 @@ func (t *DB) Begin() (*Tx, error) {
}, nil
}

func (t *DB) Query(query string, args ...interface{}) ([]Row, error) {
func (t *DB) Query(query string, args ...interface{}) ([]*Row, error) {
f, err := t.query.Fetch(query, args, t.Options)
if err != nil {
return nil, err
Expand All @@ -87,6 +87,17 @@ func (t *DB) Query(query string, args ...interface{}) ([]Row, error) {
return r, nil
}

func (t *DB) QueryFirst(query string, args ...interface{}) (*Row, error) {
rows, err := t.Query(query, args...)
if err != nil {
return nil, err
}
if len(rows) == 0 {
return nil, sql.ErrNoRows
}
return rows[0], nil
}

func (t *DB) Find(i interface{}, query string, args ...interface{}) error {
query = t.tableComplete(i, query)
f, err := t.query.Fetch(query, args, t.Options)
Expand Down
11 changes: 5 additions & 6 deletions src/xsql/fetcher.go
Original file line number Diff line number Diff line change
Expand Up @@ -32,8 +32,7 @@ func (t *Fetcher) First(i interface{}) error {
if len(rows) == 0 {
return sql.ErrNoRows
}
row := rows[0]
if err := t.foreach(&row, rootValue, rootType); err != nil {
if err := t.foreach(rows[0], rootValue, rootType); err != nil {
return err
}

Expand All @@ -58,7 +57,7 @@ func (t *Fetcher) Find(i interface{}) error {
if itemValue.Kind() == reflect.Ptr {
itemValue = itemValue.Elem()
}
if err := t.foreach(&rows[r], itemValue, itemValue.Type()); err != nil {
if err := t.foreach(rows[r], itemValue, itemValue.Type()); err != nil {
return err
}
root.Set(reflect.Append(root, itemValue))
Expand All @@ -67,7 +66,7 @@ func (t *Fetcher) Find(i interface{}) error {
return nil
}

func (t *Fetcher) Rows() ([]Row, error) {
func (t *Fetcher) Rows() ([]*Row, error) {
columns, err := t.r.Columns()
if err != nil {
return nil, err
Expand All @@ -85,7 +84,7 @@ func (t *Fetcher) Rows() ([]Row, error) {
}

// Fetch rows
var rows []Row
var rows []*Row

for t.r.Next() {
err = t.r.Scan(scanArgs...)
Expand All @@ -101,7 +100,7 @@ func (t *Fetcher) Rows() ([]Row, error) {
}
}

rows = append(rows, Row{
rows = append(rows, &Row{
v: rowMap,
options: t.options,
})
Expand Down

0 comments on commit 6a20447

Please sign in to comment.