Getting Database Rows out of a Package? (I'm probably dumb, but can't find an answer)

Hello all,

Code here: https://github.com/nasquam/taskmaster/blob/master/model/taskpull.go

I have a package I’ve created that I’m calling from my page controller. That package reads from the database and I can write all the data I have out to the screen.

I thought the best way to move that data from my package back into my controller would be to create a group of structs, each struct being 1 row from my query something like:

type RequestResults []RequestResult

I don’t know if I’m not thinking about this properly or if there’s something I’m missing.

package model

import (
	"fmt"
)

//RequestResults Exported
type RequestResult struct {
	id          int
	assignedto  string
	requester   string
	requestname string
	company     string
	priority    string
	status      string
}

//RequestResults are a map of structs
type RequestResults []RequestResult

//PullTasks will print out all the records in the database
func PullTasks() somethingHereToReturn someType  {

	fmt.Println("Start pull tasks")

	//result := RequestResults{}

	rows, QueryErr := db.Query(`SELECT id, assignedto, requester, requestname, company, priority, status FROM golang.tasks WHERE owner =$1 AND active =$2`, "Steven Aiello", "y")
	if QueryErr != nil {
		fmt.Println(QueryErr)
	}
	defer rows.Close()

	i := 0

	for rows.Next() {
		var id int
		var assignedto string
		var requester string
		var requestname string
		var company string
		var priority string
		var status string

		err := rows.Scan(&id, &assignedto, &requester, &requestname, &company, &priority, &status)
		if err != nil {
			fmt.Println(err)
			panic(err)
		}

		RequestResultRow := RequestResult{
			id:          id,
			assignedto:  assignedto,
			requester:   requester,
			requestname: requestname,
			company:     company,
			priority:    priority,
			status:      status,
		}
		//RequestResults = RequestResultRow
		fmt.Println(i, RequestResultRow.id, RequestResultRow.assignedto, RequestResultRow.requester,
			RequestResultRow.requestname, RequestResultRow.company, RequestResultRow.priority, RequestResultRow.status)

		i++
	}

}

Where am I going wrong?

Thank you kindly

I thought the best way to move that data from my package back into my controller would be to create a group of structs, each struct being 1 row from my query

This is what I do. One thing your implementation missed is that the fields for RequestResult need to be exported to be accessed from another package:

type RequestResult struct {
	Id          int
	AssignedTo  string
	Requester   string
	RequestName string
	Company     string
	Priority    string
	Status      string
}

Getting PullTasks into shape took a few more changes:

  • return the slice of results and the errors
  • reformatted the Query and Scan arguments for better reading
  • scan directly into a RequestResult
  • build the slice of RequestResults
func PullTasks() ([]RequestResult, error) {
	fmt.Println("Start pull tasks")

	rows, err := db.Query(`
		SELECT
			id,
			assignedto,
			requester,
			requestname,
			company,
			priority,
			status
		FROM
			golang.tasks
		WHERE
			owner = $1 AND active = $2`,
		"Steven Aiello", "y")
	if err != nil {
		return nil, err
	}
	defer rows.Close()

	var results []RequestResult
	for rows.Next() {
		var result RequestResult
		err = rows.Scan(
			&result.Id,
			&result.AssignedTo,
			&result.Requester,
			&result.RequestName,
			&result.Company,
			&result.Priority,
			&result.Status)
		if err != nil {
			return nil, err
		}

		results = append(results, result)
	}

	return results, nil
}
1 Like

Ok so my line of thinking was right, I just didn’t know how to write the code.

This line here:

var results []RequestResult

I want to make sure I understand it. Is this creating an array of object type RequestResult? In the tutorial video I watched it stated you almost always use slices, but you need to use the “make” command. Is var results []RequestResult simply short hand?

Thank you!

1 Like

Here is the Go Blog entry on slices which is very informative: https://blog.golang.org/go-slices-usage-and-internals , most of which discusses how to make slices of a known size. If you don’t know how big your slice is going to be you can always grow it with the append function.

From the blog, a bit further down, "Since the zero value of a slice (nil) acts like a zero-length slice, you can declare a slice variable and then append to it in a loop: "

// Filter returns a new slice holding only
// the elements of s that satisfy f()
func Filter(s []int, fn func(int) bool) []int {
    var p []int // == nil
    for _, v := range s {
        if fn(v) {
            p = append(p, v)
        }
    }
    return p
}
1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.