Esempio n. 1
2
func readAll(t *testing.T, rows *sql.Rows) resultSlice {
	defer rows.Close()

	cols, err := rows.Columns()
	if err != nil {
		t.Fatal(err)
	}

	colStrs := make([]*string, len(cols))
	for i := range cols {
		colStrs[i] = &cols[i]
	}

	results := resultSlice{colStrs}

	for rows.Next() {
		strs := make([]*string, len(cols))
		vals := make([]interface{}, len(cols))
		for i := range vals {
			vals[i] = &strs[i]
		}
		if err := rows.Scan(vals...); err != nil {
			t.Fatal(err)
		}
		results = append(results, strs)
	}

	if err := rows.Err(); err != nil {
		t.Fatal(err)
	}

	return results
}
Esempio n. 2
0
/*
ScanAll accepts a pointer to a slice of a type and fills it with repeated calls to Scan.

ScanAll only works if you're trying to extract a single object from each row
of the query results. Additionally, it closes the passed sql.Rows object. ScanAll
effectively replaces this code

  // old code
  defer rows.Close()
  objs := []Object{}
  for rows.Next() {
	  var obj Object
	  Scan(rows, &obj)
	  objs = append(objs, obj)
  }

With simply

  // new code
  objs := []Object{}
  ScanAll(rows, &objs)
*/
func ScanAll(rows *sql.Rows, slicePtr interface{}) error {
	defer rows.Close()

	sliceVal := reflect.ValueOf(slicePtr).Elem()

	if sliceVal.Kind() != reflect.Slice {
		return fmt.Errorf("Argument to crud.ScanAll is not a slice")
	}

	elemType := sliceVal.Type().Elem()

	if elemType.Kind() != reflect.Struct {
		return fmt.Errorf("Argument to crud.ScanAll must be a slice of structs")
	}

	for rows.Next() {
		newVal := reflect.New(elemType)

		if er := Scan(rows, newVal.Interface()); er != nil {
			return er
		}

		sliceVal.Set(reflect.Append(sliceVal, newVal.Elem()))
	}

	return nil
}
Esempio n. 3
0
func scanItemComment(comment *data.ItemComment, rows *sql.Rows) error {
	var updateTimeString string

	err := rows.Scan(
		&comment.ID,
		&comment.ItemID,
		&comment.Author,
		&comment.Body,
		&updateTimeString,
	)

	if err != nil {
		return err
	}

	updateTime, err := time.Parse("2006-01-02 15:04:05", updateTimeString) // this assumes UTC as timezone

	if err != nil {
		log.Println("ItemComment scanner failed to parse time. " + updateTimeString)
		return err
	}

	comment.UpdateTime = updateTime

	return nil
}
Esempio n. 4
0
func scanUser(user *data.User, rows *sql.Rows) error {
	var createTimeString string

	err := rows.Scan(
		&user.Username,
		&user.Password,
		&user.Salt,
		&user.Role,
		&user.TrustLevel,
		&createTimeString,
	)

	if err != nil {
		return err
	}

	createTime, err := time.Parse("2006-01-02 15:04:05", createTimeString) // this assumes UTC as timezone

	if err != nil {
		log.Println("User scanner failed to parse time.")
		return err
	}

	user.CreateTime = createTime

	return nil
}
Esempio n. 5
0
File: main.go Progetto: pzduniak/db
/*
	Copies *sql.Rows into the slice of maps or structs given by the pointer dst.
*/
func (self *T) FetchRow(dst interface{}, rows *sql.Rows) error {

	dstv := reflect.ValueOf(dst)

	if dstv.IsNil() || dstv.Kind() != reflect.Ptr {
		return db.ErrExpectingPointer
	}

	itemv := dstv.Elem()

	columns, err := getRowColumns(rows)

	if err != nil {
		return err
	}

	next := rows.Next()

	if next == false {
		return db.ErrNoMoreRows
	}

	item, err := self.fetchResult(itemv.Type(), rows, columns)

	if err != nil {
		return err
	}

	itemv.Set(reflect.Indirect(item))

	return nil
}
func sexDomain(dom string) (sexAnswer bool, err error) {
	var stmt *sql.Stmt

	stmt, err = db.Prepare(`SELECT dom FROM domains WHERE dom = $1 AND sex = true LIMIT 1`)

	if err != nil {
		fmt.Printf("db.Prepare error: %v\n", err)
		return false, err
	}

	var rows *sql.Rows

	rows, err = stmt.Query(dom)
	if err != nil {
		fmt.Printf("stmt.Query error: %v\n", err)
		return false, err
	}

	defer stmt.Close()
	if rows.Next() {
		var domain string

		err = rows.Scan(&domain)
		if err != nil {
			fmt.Printf("rows.Scan error: %v\n", err)
			return false, err
		}
		if configuration.Debug == "Yes" {
			fmt.Println("domain => \"" + domain + "\"")
		}
		return true, err
	}

	return false, nil
}
Esempio n. 7
0
func bmPreparedQuery(b *testing.B) {
	stmt, err := db.Prepare("SELECT number, str FROM test")
	if err != nil {
		panic(err)
	}

	var num int64
	var str string
	var i int64
	var rows *sql.Rows
	for rep := 0; rep < 10000; rep++ {
		rows, err = stmt.Query()
		if err != nil {
			panic(err)
		}

		i = 0
		for rows.Next() {
			rows.Scan(&num, &str)
			if num != i {
				panic(fmt.Sprintf("Result didn't match: %d!=%d", num, i))
			}
			i++
		}

		if i != 100 {
			panic(fmt.Sprintf("Rows count doesn't match: %d!=100", i))
		}
	}

	stmt.Close()
}
Esempio n. 8
0
File: scan.go Progetto: rjp/crud
func (scan *Scan) One(rows *sql.Rows) error {
	for rows.Next() {
		return scan.Scan(rows, meta.DirectValueOf(scan.To))
	}

	return errors.New("No matching rows found.")
}
Esempio n. 9
0
func setTimer(rows *sql.Rows) (*Timer, error) {
	var finishedAt pq.NullTime
	var createdAt pq.NullTime

	timer := Timer{}

	err := rows.Scan(&timer.ID, &timer.User, &timer.Name, &createdAt, &finishedAt)
	if err != nil {
		return nil, err
	}

	val, err := createdAt.Value()
	if err != nil {
		return nil, err
	}

	if val != nil {
		timer.CreatedAt = &createdAt.Time
	}

	val, err = finishedAt.Value()
	if err != nil {
		return nil, err
	}

	if val != nil {
		timer.FinishedAt = &finishedAt.Time
	}

	return &timer, nil
}
Esempio n. 10
0
// Scan values from the database
func scan(cols []string, rows *sql.Rows) map[string]interface{} {

	var rtn = map[string]interface{}{}

	// Create scanner array
	var values []interface{}
	var generic = reflect.TypeOf(values).Elem()
	for i := 0; i < len(cols); i++ {
		values = append(values, reflect.New(generic).Interface())
	}

	// Scan!
	var err = rows.Scan(values...)
	if err != nil {
		n.Log("Driver failed to scan values: %s", err.Error())
		return nil
	}

	// Convert into native types
	for i := 0; i < len(cols); i++ {
		var raw_value = *(values[i].(*interface{}))
		var raw_type = reflect.TypeOf(raw_value)
		switch {
		case raw_type == reflect.TypeOf(int64(0)):
			rtn[cols[i]] = raw_value.(int64)
		}
	}

	return rtn
}
Esempio n. 11
0
//List ...
func (vs VictualService) List() []Victual {
	db, err := sql.Open("postgres", "host=localhost port=5432 user=pober dbname=pober sslmode=disable")
	checkErr(err)
	defer db.Close()

	var rows *sql.Rows
	rows, err = db.Query("SELECT id, description, brand, source, energyCal, energyJoule, fat, saturatedFat, carbohydrates, sugars, protein, salt, fiber, barCode, weightVolumeRatio FROM dc.victual")
	checkErr(err)

	victuals := []Victual{}

	for rows.Next() {
		var victual Victual
		err = rows.Scan(&victual.ID,
			&victual.Description,
			&victual.Brand,
			&victual.Source,
			&victual.EnergyCal,
			&victual.EnergyJoule,
			&victual.Fat,
			&victual.SaturatedFat,
			&victual.Carbohydrates,
			&victual.Sugars,
			&victual.Protein,
			&victual.Salt,
			&victual.Fiber,
			&victual.BarCode,
			&victual.WeightVolumeRatio)
		checkErr(err)
		victuals = append(victuals, victual)
	}
	return victuals
}
Esempio n. 12
0
func findNotesByUser(user *User, query string) []*Note {
	var err error
	var rows *sql.Rows

	if len(query) == 0 {
		rows, err = db.Query("SELECT * FROM notes WHERE user_id=?", user.ID)
	} else {
		queryFmt := fmt.Sprintf("%%%s%%", query)
		rows, err = db.Query(
			"SELECT * FROM notes WHERE user_id=? AND (body LIKE ? OR title LIKE ?)",
			user.ID,
			queryFmt,
			queryFmt)
	}

	if err != nil {
		checkErr(err, "findNotesByUser")
	} else {
		defer rows.Close()
	}

	var notes []*Note
	for rows.Next() {
		notes = append(notes, noteFromDbRows(rows))
	}
	return notes
}
Esempio n. 13
0
func getCallRoutes(lastNHours int, failedOnly bool) (callRoutes []*callRoute, err error) {
	var rows *sql.Rows
	callRouteSQL := `
      SELECT * FROM (
        SELECT c.app, c.route, COUNT(c.*) AS count, ROUND(AVG(extract(epoch from (c."end" - c.start))*1000000))::bigint AS avg_duration
        FROM "` + appmon.DBSchema + `".call c
        WHERE current_timestamp - c.start < ($1::int * interval '1 hour')
          AND c."end" IS NOT NULL
          AND ((NOT $2) OR (http_status_code < 200 OR http_status_code >= 400))
        GROUP BY app, route
      ) q ORDER BY count DESC
`
	rows, err = appmon.DB.Query(callRouteSQL, lastNHours, failedOnly)
	if err != nil {
		return nil, err
	}
	for rows.Next() {
		cr := new(callRoute)
		err = rows.Scan(&cr.App, &cr.Route, &cr.Count, &cr.AvgDuration)
		if err != nil {
			return
		}
		callRoutes = append(callRoutes, cr)
	}
	return
}
Esempio n. 14
0
func bindComponent(name string, rs *sql.Rows, ctype componentType, manager *Manager) (*Component, error) {
	var id int64
	cols, err := rs.Columns()
	if err != nil {
		return nil, err
	}
	ifaces := make([]interface{}, len(cols))
	ifaceptrs := make([]interface{}, len(cols))
	for i := 0; i < len(ifaces); i++ {
		ifaceptrs[i] = &ifaces[i]
	}
	err = rs.Scan(ifaceptrs...)
	if err != nil {
		return nil, err
	}
	cv := reflect.New(ctype.typ).Elem()
	for i, field := range cols {
		if field == "entity_id" {
			id = ifaces[i].(int64)
			continue
		}
		f := cv.FieldByName(field)
		if !f.IsValid() {
			return nil, fmt.Errorf("Field %s is invalid for %s", field, name)
		}
		iv := reflect.ValueOf(ifaces[i])
		switch iv.Kind() {
		case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
			f.SetInt(iv.Int())
		default:
			f.Set(iv)
		}
	}
	return &Component{entity: id, name: name, isNew: false, manager: manager, data: cv.Addr().Interface()}, nil
}
Esempio n. 15
0
func (d DAO) Select(key interface{}, result interface{}) error {
	if d.conn == nil {
		return errors.New("no connection to mysql!")
	}

	var err error
	var rows *sql.Rows
	sql := fmt.Sprintf("select * from %s where id = %d", d.table, key)
	rows, err = d.conn.Query(sql)
	if err != nil {
		fmt.Println(err)
		return err
	}

	t := reflect.ValueOf(result)
	e := t.Elem()

	e = e.Slice(0, e.Len())
	i := 0
	for rows.Next() && i < e.Len() {
		j := 0
		s := make([]interface{}, 0, 10)
		for j < e.Index(i).NumField() {
			s = append(s, e.Index(i).Field(j).Addr().Interface())
			j++
			//fmt.Println(j)
		}
		err = rows.Scan(s...)
		i++
	}

	return err
}
Esempio n. 16
0
func validate_result_of_sp(dbt *DBTest, rows *sql.Rows) {

	// final OK packet , indicate last INSERT effected rows
	// https://dev.mysql.com/doc/internals/en/multi-resultset.html
	if res, ok := rows.Sibling(); false == ok {
		dbt.Fatal("there should be a last ok packet.")
	} else if nil == res {
		dbt.Fatal("last packet of CALL should return a Result.")
	} else {
		if affcted, err := res.RowsAffected(); nil != err {
			dbt.Fatal("should not return err when RowsAffected")
		} else if 1 != affcted {
			dbt.Fatal("Last INSERT STMT in SP should affected one row. ")
		}

		if insertId, err := res.LastInsertId(); nil != err {
			dbt.Fatal("should not return err when LastInsertId")
		} else if 0 != insertId {
			dbt.Fatalf("Last INSERT STMT in SP should not return LAST_INSERT_ID:%d ", insertId)
		}
		if true == rows.Next() {
			dbt.Fatal("last packet has no rows, but just affected rows and last insert id")
		}
	}

}
Esempio n. 17
0
//Parse an executed query
func (dbw *Sqlite3) Parse(rows *sql.Rows) (results Results, err error) {
	// here im not sure what im getting from the db as it can be anything from the results
	//therefore i wish i can just put everything in a bucket, and think later.
	tc, tn := dbw.TotalCount(rows)
	// multiFields := make([]interface{}, tc)
	multiFieldsPtrs := make([]interface{}, tc)
	for i := 0; i < tc; i++ {
		var multiFields interface{}
		multiFieldsPtrs[i] = &multiFields
	}

	headers := make(map[string]interface{})
	headers["fields"] = tn
	results = append(results, headers)
	for rows.Next() {
		err = rows.Scan(multiFieldsPtrs...)
		checkErrors(err)
		tempMap := make(map[string]interface{})
		for idx, label := range tn {
			row := *(multiFieldsPtrs[idx].(*interface{}))
			// if sizeOf(row) < 1 {
			// 	skip = true
			// 	break
			// }
			tempMap[label] = row
		}
		results = append(results, tempMap)
	}
	return
}
Esempio n. 18
0
File: models.go Progetto: moshee/gas
// Query multiple rows into a slice.
func querySlice(model *model, slice interface{}, rows *sql.Rows) error {
	// var slice *[]T
	// sliceVal := *slice
	var (
		sliceVal = reflect.ValueOf(slice).Elem()
		foundCap = 0
		err      error
	)
	// first, populate the existing allocated elements in the slice. If it's an
	// empty slice, this loop will effectively be skipped.
	for i := 0; i < sliceVal.Len() && rows.Next(); i++ {
		if foundCap, err = model.scan(sliceVal.Index(i), rows, foundCap); err != nil {
			return err
		}
	}

	// now start scanning into new values and append to the slice. If we're
	// already done, this loop will effectively be skipped.
	// var sliceElemType type = T
	sliceElemType := sliceVal.Type().Elem()
	for rows.Next() {
		val := reflect.New(sliceElemType)
		if _, err := model.scan(val, rows, foundCap); err != nil {
			return err
		}
		sliceVal.Set(reflect.Append(sliceVal, val.Elem()))
	}

	return nil
}
Esempio n. 19
0
File: scan.go Progetto: rjp/crud
func (scan *Scan) ScanToStruct(rows *sql.Rows, record reflect.Value) error {
	columns, err := rows.Columns()
	if err != nil {
		return err
	}

	values := make([]interface{}, len(columns))

	for i, column := range columns {
		var field reflect.Value

		fieldName := scan.SQLColumnDict[column]

		if scan.ToPointers {
			field = record.Elem().FieldByName(fieldName)
		} else {
			field = record.FieldByName(fieldName)
		}

		if field.IsValid() {
			values[i] = field.Addr().Interface()
		} else {
			values[i] = &values[i]
		}
	}

	return rows.Scan(values...)
}
Esempio n. 20
0
func populateApplicationGuides(rows *sql.Rows, ch chan []ApplicationGuide) {
	var ag ApplicationGuide
	var ags []ApplicationGuide
	var catID *int
	var icon []byte
	var catName *string
	for rows.Next() {
		err := rows.Scan(
			&ag.ID,
			&ag.Url,
			&ag.Website.ID,
			&ag.FileType,
			&catID,
			&icon,
			&catName,
		)
		if err != nil {
			ch <- ags
		}
		if catID != nil {
			ag.Category.CategoryID = *catID
		}
		if catName != nil {
			ag.Category.Title = *catName
		}
		if icon != nil {
			ag.Icon = string(icon[:])
		}
		ags = append(ags, ag)
	}
	ch <- ags
	return
}
Esempio n. 21
0
func MItemSelectByID(db *sql.DB, itemID int) (*MItem, error) {
	q := `
select
	item_id
	,image_id
	,type
	,name
	,detail
	,param
from
	m_item
where
	item_id = $1
`
	var rows *sql.Rows
	var err error
	rows, err = db.Query(q, itemID)
	if err != nil {
		return nil, err
	}

	for rows.Next() {
		var mItem MItem
		if err := rows.Scan(&mItem.ItemID, &mItem.ImageID, &mItem.ItemType, &mItem.Name, &mItem.Detail, &mItem.Param); err != nil {
			fmt.Println(err)
		}
		return &mItem, nil
	}

	return nil, errors.New("not found")
}
Esempio n. 22
0
// 根据父节点地区码获取该节点下的地区列表
func FindRegionByParentCode(parentCode string) (regions []*Region, err error) {
	db := GetMySQL()
	defer db.Close()

	regions = []*Region{}

	var rows *sql.Rows

	if parentCode == "" { //根节点的情况
		rows, err = db.Query("SELECT code,name FROM region WHERE parent_code is null")
	} else {
		rows, err = db.Query("SELECT code,name FROM region WHERE parent_code = ?", parentCode)
	}

	if err != nil {
		Log.Error(err.Error())
		return regions, err
	}

	for rows.Next() {
		region := new(Region)
		err := rows.Scan(&region.Code, &region.Name)
		if err != nil {
			Log.Warn(err.Error())
			return regions, err
		}
		regions = append(regions, region)
	}

	return regions, nil
}
Esempio n. 23
0
func fieldModelProto(r *http.Request, h http.Header, b *bytes.Buffer) *weft.Result {
	var err error
	var rows *sql.Rows

	if rows, err = dbR.Query(`SELECT modelID
		FROM
		field.model`); err != nil {
		return weft.InternalServerError(err)
	}

	var fmr mtrpb.FieldModelResult

	for rows.Next() {
		var t mtrpb.FieldModel

		if err = rows.Scan(&t.ModelID); err != nil {
			return weft.InternalServerError(err)
		}

		fmr.Result = append(fmr.Result, &t)
	}

	var by []byte
	if by, err = proto.Marshal(&fmr); err != nil {
		return weft.InternalServerError(err)
	}

	b.Write(by)

	return &weft.StatusOK
}
Esempio n. 24
0
// 用于FindAll中,具体model在遍历rows时调用(提取的公共代码)
func (this *Dao) Scan(rows *sql.Rows, colNum int, colFieldMap map[string]interface{}, selectCol ...string) error {
	scanInterface := make([]interface{}, 0, colNum)
	for _, column := range selectCol {
		scanInterface = append(scanInterface, colFieldMap[column])
	}
	return rows.Scan(scanInterface...)
}
Esempio n. 25
0
func GetResultsTwo(rows *sql.Rows) [][]string {
	var (
		results [][]string
		//result  [][]string
		id      string
		types   string
		title   string
		message string
		i       int
	)
	results = make([][]string, 1)
	i = 0
	for rows.Next() {
		err := rows.Scan(&id, &types, &title, &message)
		if err != nil {
			//fmt.Println(err)
		}
		messages := []string{id, types, title, message}
		fmt.Println(messages)
		for index, element := range messages {
			results[i][index] = element
		}
		i++
	}
	return results
}
Esempio n. 26
0
// Query if given upload is expired - an upload thus not having any records which are currently active
func (tx *Transaction) QueryExpiredUpload(id string) (result bool, err error) {
	err = tx.do(func(tx *sql.Tx) (err error) {
		var rows *sql.Rows

		rows, err = tx.Query(`
      SELECT 
        "u"."id" AS "id"
      FROM "uploads" AS "u"
      WHERE "u"."id" = $1
      GROUP BY "u"."id"
      HAVING MAX("u"."expiration") < NOW()`,
			id)
		if err != nil {
			return
		}

		defer rows.Close()

		if rows.Next() {
			result = true
		}

		return
	})

	return
}
Esempio n. 27
0
func scanUserDirection(direction *data.UserDirection, rows *sql.Rows) error {
	var updateTimeString string

	err := rows.Scan(
		&direction.Username,
		&direction.LockUsername,
		&direction.Command,
		&direction.Heading,
		&direction.Lat,
		&direction.Lng,
		&updateTimeString,
	)

	if err != nil {
		return err
	}

	updateTime, err := time.Parse("2006-01-02 15:04:05", updateTimeString) // this assumes UTC as timezone

	if err != nil {
		log.Println("UserDirection scanner failed to parse time.")
		return err
	}

	direction.UpdateTime = updateTime

	return nil
}
Esempio n. 28
0
func dataSiteProto(r *http.Request, h http.Header, b *bytes.Buffer) *weft.Result {
	var err error
	var rows *sql.Rows

	if rows, err = dbR.Query(`SELECT siteID, latitude, longitude FROM data.site`); err != nil {
		return weft.InternalServerError(err)
	}

	var ts mtrpb.DataSiteResult

	for rows.Next() {
		var t mtrpb.DataSite

		if err = rows.Scan(&t.SiteID, &t.Latitude, &t.Longitude); err != nil {
			return weft.InternalServerError(err)
		}

		ts.Result = append(ts.Result, &t)
	}

	var by []byte
	if by, err = proto.Marshal(&ts); err != nil {
		return weft.InternalServerError(err)
	}

	b.Write(by)

	return &weft.StatusOK
}
Esempio n. 29
0
func Scan2Struct(rows *sql.Rows, stru interface{}) error {
	beanVal := reflect.ValueOf(stru)
	if beanVal.Kind() != reflect.Ptr {
		return errors.New("Scan2Bean bean not a pointer")
	}
	beanVal = beanVal.Elem()

	cols, err := rows.Columns()
	if err != nil {
		return err
	}

	dest := make([]interface{}, len(cols))
	for i, col := range cols {
		fldName := convertColName2FldName(col)
		fldVal := beanVal.FieldByName(fldName)
		if fldVal.Kind() != reflect.Struct && fldVal.Kind() != reflect.Ptr {
			dest[i] = fldVal.Addr().Interface()
		} else if fldVal.Type().String() == "time.Time" {
			dest[i] = &ReflectScanner{Value: &fldVal}
			//			dest[i] = &TypeTestScanner{}
		} else {
			panic(fmt.Sprintf("Scan2Bean %v %v not support", fldName, fldVal.Type().String()))
		}
	}

	return rows.Scan(dest...)
}
Esempio n. 30
0
func scanRqEntry(rows *sql.Rows) (rq_entry *RunQueueEntry, err error) {
	rq_entry = new(RunQueueEntry)
	err = rows.Scan(
		&rq_entry.Id,
		&rq_entry.ClassName,
		&rq_entry.timetable_id,
		&rq_entry.generation_id,
		&rq_entry.hostname,
		&rq_entry.hostname_idx,
		&rq_entry.JobData,
		&rq_entry.method,
		&rq_entry.RunStatus,
		&rq_entry.created,
		&rq_entry.waiting_ts,
		&rq_entry.should_init_ts,
		&rq_entry.init_attempts,
		&rq_entry.init_ts,
		&rq_entry.running_ts,
		&rq_entry.max_finished_ts,
		&rq_entry.finished_ts,
		&rq_entry.stopped_employee_id,
		&rq_entry.token,
		&rq_entry.retry_attempt,
		&rq_entry.settings_id)
	return
}