Пример #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
}
Пример #2
0
func (this *db) GetHostsByProxy(proxy string) []*Host {
	var (
		rows *sql.Rows
		err  error
	)
	if len(proxy) == 0 {
		rows, err = this.Conn.Query("select h.id, h.server_id, h.uuid, h.ip, h.status, h.last_check, p.ip from host_host as h " +
			"left join system_proxy as p on h.proxy_id = p.id where p.ip is NULL")
	} else {
		rows, err = this.Conn.Query("select h.id, h.server_id, h.uuid, h.ip, h.status, h.last_check, p.ip from host_host as h "+
			"left join system_proxy as p on h.proxy_id = p.id where p.ip=?", proxy)
	}
	if err != nil {
		return nil
	}
	defer rows.Close()
	hosts := []*Host{}
	for rows.Next() {
		host := &Host{}
		var proxy sql.NullString
		var assestid sql.NullInt64
		if err := rows.Scan(&host.ID, &assestid, &host.UUID, &host.Ip, &host.Status, &host.last_check, &proxy); err != nil {
			continue
		}
		host.Proxy = proxy.String
		if assestid.Valid {
			host.AssestId = int(assestid.Int64)
		}
		hosts = append(hosts, host)
	}
	return hosts
}
Пример #3
0
func (persister *Persister) GetServiceAgentList(cond string) ([]ServiceAgent, error) {
	var rows *sql.Rows
	var err error
	if cond == "" {
		rows, err = persister.Db.Query("SELECT service_host,docker_host,docker_port,is_active,perf_factor,ping_interval_secs,last_ping,exec_command,exec_args,portbinding_min,portbinding_max,portbindings FROM serviceagents")
	} else {
		rows, err = persister.Db.Query("SELECT service_host,docker_host,docker_port,is_active,perf_factor,ping_interval_secs,last_ping,exec_command,exec_args,portbinding_min,portbinding_max,portbindings FROM serviceagents where " + cond)
	}
	if err != nil {
		return nil, err
	}
	defer rows.Close()

	var serviceagents []ServiceAgent
	i := 0
	for rows.Next() {
		serviceagent := ServiceAgent{}
		var timevalue interface{}
		rows.Scan(&serviceagent.ServiceHost, &serviceagent.DockerHost, &serviceagent.DockerPort, &serviceagent.IsActive, &serviceagent.PerfFactor, &serviceagent.KeepAlive, &timevalue, &serviceagent.ExecCommand, &serviceagent.ExecArgs, &serviceagent.Portbind_min, &serviceagent.Portbind_max, &serviceagent.Portbindings)
		switch timevalue.(type) {
		case string:
			serviceagent.LastPing, err = time.Parse("2006-01-02 15:04:05 ", timevalue.(string))
		case time.Time:
			serviceagent.LastPing = timevalue.(time.Time)
		}

		if err != nil {
			log.Println("error reading row ", err)
		}
		serviceagents = append(serviceagents, serviceagent)
		i = i + 1
	}
	return serviceagents, nil
}
Пример #4
0
//	sql_ := fmt.Sprintf(`SELECT "Json" %s where `+p.wheresql, p.getFrom())
//	var rows *sql.Rows
//	if rows, p.Err = p._query(sql_, p.whereargs...); p.NotErr() {
//		defer rows.Close()
//		for rows.Next() {
//			var v []byte
//			rows.Scan(&v)
//			obj := reflect.New(p.model.Type).Interface()
//			json.Unmarshal(v, obj)
//			slicev = reflect.Append(slicev, reflect.ValueOf(obj).Elem())
//		}
//		resultv.Elem().Set(slicev.Slice(0, slicev.Len()))
//	}
//	return p
//}
func (p *Scope) PageJson(lst T, page, perPage int) (pager db.Paging) {
	p.checkModel(lst)
	pf := filter.NewPageFilter(page, perPage)
	p.Limit(pf.Skip(), perPage)
	pager.Total = p.Count(lst)
	//	log.Println(pager.Total)
	resultv := reflect.ValueOf(lst)
	if resultv.Kind() != reflect.Ptr || resultv.Elem().Kind() != reflect.Slice {
		panic("out argument must be a slice address")
	}
	slicev := resultv.Elem()
	wsa := p.buildWhere()
	pas := p.buildPage()
	sql_ := fmt.Sprintf(`SELECT "Json" %s `+wsa.Sql+" "+pas.Sql, p.getFrom())
	var rows *sql.Rows
	if rows, p.Err = p._query(sql_, wsa.Args...); p.NotErr() {
		defer rows.Close()
		for rows.Next() {
			var v []byte
			rows.Scan(&v)
			obj := reflect.New(p.model.Type).Interface()
			json.Unmarshal(v, obj)
			slicev = reflect.Append(slicev, reflect.ValueOf(obj).Elem())
		}
		resultv.Elem().Set(slicev.Slice(0, slicev.Len()))
	}
	pager.Items = lst
	//	log.Println(lst)
	return
}
Пример #5
0
func (gkDbCon *GkDbConDef) getMaxChatId() (int32, *gkerr.GkErrDef) {
	var stmt *sql.Stmt
	var maxId int32 = 0
	var err error

	stmt, err = gkDbCon.sqlDb.Prepare("select max(id) from chat_archives")
	if err != nil {
		return 0, gkerr.GenGkErr("sql.Prepare"+getDatabaseErrorMessage(err), err, ERROR_ID_PREPARE)
	}

	defer stmt.Close()

	var rows *sql.Rows

	rows, err = stmt.Query()
	if err != nil {
		return 0, gkerr.GenGkErr("stmt.Query"+getDatabaseErrorMessage(err), err, ERROR_ID_QUERY)
	}

	defer rows.Close()

	if rows.Next() {
		err = rows.Scan(&maxId)
		if err != nil {
			return 0, gkerr.GenGkErr("rows.Scan"+getDatabaseErrorMessage(err), err, ERROR_ID_ROWS_SCAN)
		}
	}

	return maxId, nil
}
Пример #6
0
func (m *mysql) AuditLog(from, to, limit, offset int64, reverse bool) ([]*proto.ChangeLog, error) {
	var r *sql.Rows
	var err error

	if from == 0 && to == 0 {
		q := "readLog"
		if reverse {
			q += "Desc"
		}
		r, err = st[q].Query(limit, offset)
	} else {
		q := "readBetween"
		if reverse {
			q += "Desc"
		}
		r, err = st[q].Query(from, to, limit, offset)
	}

	if err != nil {
		return nil, err
	}
	defer r.Close()

	var logs []*proto.ChangeLog

	for r.Next() {
		var id int

		log := &proto.ChangeLog{
			Change: &proto.Change{
				ChangeSet: &proto2.ChangeSet{},
			},
		}
		if err := r.Scan(
			&id,
			&log.Action,
			&log.Change.Id,
			&log.Change.Path,
			&log.Change.Author,
			&log.Change.Comment,
			&log.Change.Timestamp,
			&log.Change.ChangeSet.Timestamp,
			&log.Change.ChangeSet.Checksum,
			&log.Change.ChangeSet.Data,
			&log.Change.ChangeSet.Source,
		); err != nil {
			if err == sql.ErrNoRows {
				return nil, errors.New("not found")
			}
			return nil, err
		}
		logs = append(logs, log)

	}
	if r.Err() != nil {
		return nil, err
	}

	return logs, nil
}
Пример #7
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
}
Пример #8
0
func sqlToMaps(ctx *Ctx, sqlString string, sqlParams ...interface{}) (ret []map[string]interface{}, err error) {
	ret = []map[string]interface{}{}
	var rows *sql.Rows
	rows, err = ctx.db.Query(sqlString, sqlParams...)
	defer rows.Close()
	if err != nil {
		return
	}
	columns, err := rows.Columns()
	if err != nil {
		return
	}
	count := len(columns)
	values := make([]interface{}, count)
	valuePtrs := make([]interface{}, count)
	for i := 0; i < count; i++ {
		valuePtrs[i] = &values[i]
	}
	for rows.Next() {
		retRow := map[string]interface{}{}
		rows.Scan(valuePtrs...)
		for i, col := range columns {
			val := values[i]
			switch val.(type) {
			case []uint8:
				retRow[col] = string(val.([]uint8))
			default:
				retRow[col] = val
			}
		}
		ret = append(ret, retRow)
	}
	return
}
Пример #9
0
func (db *StatsDB) streamBuckets(result *sql.Rows, out chan Bucket) {
	var err error
	defer result.Close()
LOOP:
	for result.Next() && result.Err() == nil {
		var bucket Bucket
		var info string
		bucket.Info = make(map[string]interface{})
		err = result.Scan(&bucket.Id, &bucket.ServerTime, &bucket.Bucket, &info)
		if err != nil {
			printf("error scanning database: %v", err)
			break LOOP
		}
		dec := json.NewDecoder(bytes.NewBufferString(info))
		err = dec.Decode(&bucket.Info)
		if err != nil {
			printf("error decoding info from record: %v", err)
			break LOOP
		}
		select {
		case out <- bucket:
		case <-time.After(time.Second * 10):
			break LOOP
		}
	}
	close(out)
}
Пример #10
0
func Test_Query(t *testing.T) {
	conn, err := sql.Open("mysql", TestConnParam)
	utest.IsNilNow(t, err)
	defer conn.Close()

	var res *sql.Rows

	res, err = conn.Query("SELECT * FROM test ORDER BY id ASC")
	utest.IsNilNow(t, err)
	defer res.Close()

	i := 0
	for res.Next() {
		var (
			id    int64
			value string
		)

		err := res.Scan(&id, &value)
		utest.IsNilNow(t, err)

		utest.Equal(t, id, int64(i))
		utest.Equal(t, value, strconv.Itoa(i))
		i++
	}

	utest.Equal(t, i, 10)
}
Пример #11
0
// LastK returns the k most recent command lines in history
func (d Database) LastK(qp conf.QueryParams) ([]byte, error) {
	var rows *sql.Rows
	var err error
	switch qp.Unique {
	case true:
		rows, err = d.Query(`SELECT * FROM
                                      (SELECT rowid, * FROM history
                                         WHERE user LIKE ? AND host LIKE ? AND command LIKE ? ESCAPE '\'
                                         GROUP BY command
                                         ORDER BY datetime DESC LIMIT ?)
                                      ORDER BY datetime ASC`,
			qp.User, qp.Host, qp.Command, qp.Kappa)
	default:
		rows, err = d.Query(`SELECT * FROM
                                      (SELECT rowid, * FROM history
                                         WHERE user LIKE ? AND host LIKE ? AND command LIKE ? ESCAPE '\'
                                         ORDER BY datetime DESC LIMIT ?)
                                   ORDER BY datetime ASC`,
			qp.User, qp.Host, qp.Command, qp.Kappa)
	}
	if err != nil {
		return []byte{}, err
	}
	defer rows.Close()

	res := result.New(qp.Format)
	for rows.Next() {
		var user, host, command string
		var t time.Time
		var row int
		rows.Scan(&row, &user, &host, &command, &t)
		res.AddRow(row, user, host, command, t)
	}
	return res.Formatted(), nil
}
Пример #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
}
Пример #13
0
func (self *PostgresDatabase) GetThreadReplies(rootpost string, start, limit int) (repls []string) {
	var rows *sql.Rows
	var err error
	if limit > 0 {
		rows, err = self.conn.Query("SELECT message_id FROM ArticlePosts WHERE message_id IN ( SELECT message_id FROM ArticlesPosts WHERE ref_id = $1 ORDER BY time_posted DESC LIMIT $2 ) ORDER BY time_posted ASC", rootpost, limit)
	} else {
		rows, err = self.conn.Query("SELECT message_id FROM ArticlePosts WHERE message_id IN ( SELECT message_id FROM ArticlePosts WHERE ref_id = $1 ) ORDER BY time_posted ASC", rootpost)
	}
	offset := start
	if err == nil {
		for rows.Next() {
			// TODO: this is a hack, optimize queries plz
			if offset > 0 {
				offset--
				continue
			}
			var msgid string
			rows.Scan(&msgid)
			repls = append(repls, msgid)
		}
		rows.Close()
	} else {
		log.Println("failed to get thread replies", rootpost, err)
	}
	return
}
Пример #14
0
func dataCompletenessTagProto(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, tag, typeID from data.completeness_tag
				JOIN mtr.tag USING (tagpk)
				JOIN data.site USING (sitepk)
				JOIN data.completeness_type USING (typepk)
				ORDER BY tag ASC`); err != nil {
		return weft.InternalServerError(err)
	}
	defer rows.Close()

	var ts mtrpb.DataCompletenessTagResult

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

		if err = rows.Scan(&t.SiteID, &t.Tag, &t.TypeID); 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
}
Пример #15
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
}
Пример #16
0
func Test_Query(t *testing.T) {
	conn, err := sql.Open("mysql", TestConnParam)
	unitest.NotError(t, err)
	defer conn.Close()

	var res *sql.Rows

	res, err = conn.Query("SELECT * FROM test ORDER BY id ASC")
	unitest.NotError(t, err)
	defer res.Close()

	i := 0
	for res.Next() {
		var (
			id    int64
			value string
		)

		err := res.Scan(&id, &value)
		unitest.NotError(t, err)

		unitest.Pass(t, id == int64(i))
		unitest.Pass(t, value == strconv.Itoa(i))
		i++
	}

	unitest.Pass(t, i == 10)
}
Пример #17
0
func sqlToStringsMaps(ctx *Ctx, sqlString string, sqlParams ...interface{}) (ret []map[string]string, err error) {
	ret = []map[string]string{}
	var rows *sql.Rows
	rows, err = ctx.db.Query(sqlString, sqlParams...)
	defer rows.Close()
	if err != nil {
		return
	}
	columns, err := rows.Columns()
	if err != nil {
		return
	}
	count := len(columns)
	values := make([]sql.NullString, count) // Без NullString невозможно определить, когда NULL
	valuePtrs := make([]interface{}, count)
	for i := 0; i < count; i++ {
		valuePtrs[i] = &values[i]
	}
	for rows.Next() {
		retRow := map[string]string{}
		rows.Scan(valuePtrs...)
		for i, col := range columns {
			retRow[col] = values[i].String
		}
		ret = append(ret, retRow)
	}
	return
}
Пример #18
0
func (db *StatsDB) streamRows(result *sql.Rows, out chan Stats) {
	var err error
	defer result.Close()
LOOP:
	for result.Next() && result.Err() == nil {
		var stat Stats
		var info string
		stat.Info = make(map[string]string)
		err = result.Scan(&stat.Id, &stat.System, &stat.SubSystem, &stat.Message, &stat.Context, &stat.ServerTime, &stat.ClientTime, &stat.Error, &info)
		if err != nil {
			printf("error scanning database: %v", err)
			break
		}
		dec := json.NewDecoder(bytes.NewBufferString(info))
		err = dec.Decode(&stat.Info)
		if err != nil {
			printf("error decoding info from record: %v", err)
			break
		}
		select {
		case out <- stat:
		case <-time.After(time.Second * 10):
			break LOOP
		}
	}
	close(out)
}
Пример #19
0
// Query all expired uploads - uploads thus not having any records which are currently active
func (tx *Transaction) QueryExpiredUploads() (result []string, 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"
			GROUP BY "u"."id"
			HAVING MAX("u"."expiration") < NOW()`)
		if err != nil {
			return
		}

		defer rows.Close()

		for rows.Next() {
			var id string

			err = rows.Scan(&id)
			if err != nil {
				return
			}

			result = append(result, id)
		}

		return
	})

	return
}
Пример #20
0
func (tca *TCA) getCertificateSets(enrollmentID string) ([]*TCertSet, error) {
	var sets = []*TCertSet{}
	var err error

	var rows *sql.Rows
	rows, err = tca.retrieveCertificateSets(enrollmentID)
	if err != nil {
		return nil, err
	}
	defer rows.Close()

	var enrollID string
	var timestamp int64
	var nonce []byte
	var kdfKey []byte

	for rows.Next() {
		if err = rows.Scan(&enrollID, &timestamp, &nonce, &kdfKey); err != nil {
			return nil, err
		}
		sets = append(sets, &TCertSet{Ts: timestamp, EnrollmentID: enrollID, Key: kdfKey})
	}
	if err = rows.Err(); err != nil {
		return nil, err
	}

	return sets, nil
}
Пример #21
0
// getCardsWithWhereQuery returns all of the cards that match a certain WHERE query.
func getCardsWithWhereQuery(query string, params ...interface{}) []Card {
	var cards []Card
	var err error

	sqlQ := "select cardbody, cardtype, cardblanks, classic, id, createdon, rating, raters, approved, createdby from %s " + query
	var rows *sql.Rows
	if len(params) == 0 {
		rows = database.GetByQuery(sqlQ)
	} else {
		rows = database.GetByQuery(sqlQ, params...)
	}
	defer rows.Close()

	var card Card
	for rows.Next() {
		err = rows.Scan(&card.CardBody, &card.CardType,
			&card.CardBlanks, &card.Classic, &card.ID,
			&card.CreatedOn, &card.Rating, &card.Raters,
			&card.Approved, &card.CreatedBy)
		if err != nil {
			log.Fatal(err)
		}

		cards = append(cards, card)
	}

	err = rows.Err()
	if err != nil {
		log.Fatal(err)
	}

	return cards
}
Пример #22
0
func (c *Connection) getSchemaColumns(schema string, table string) ([]*SchemaColumn, error) {
	var rows *sql.Rows
	var err error
	if rows, err = c.ctrDB.Query(`
		SELECT
			COLUMN_NAME, COLLATION_NAME, CHARACTER_SET_NAME,
			COLUMN_COMMENT, COLUMN_TYPE, COLUMN_KEY
		FROM
			COLUMNS
		WHERE
			TABLE_SCHEMA = ? AND TABLE_NAME = ?`, schema, table); err != nil {
		return nil, err
	}

	defer rows.Close()

	var cols []*SchemaColumn
	for rows.Next() {
		col := &SchemaColumn{}
		if err = rows.Scan(&col.COLUMN_NAME, &col.COLLATION_NAME, &col.CHARACTER_SET_NAME, &col.COLUMN_COMMENT,
			&col.COLUMN_TYPE, &col.COLUMN_KEY); err != nil {
			return nil, err
		}

		cols = append(cols, col)
	}

	if err = rows.Err(); err != nil {
		return nil, err
	}

	return cols, nil
}
Пример #23
0
func (gkDbCon *GkDbConDef) getNextChatArchivesId() (int32, *gkerr.GkErrDef) {
	var stmt *sql.Stmt
	var err error

	stmt, err = gkDbCon.sqlDb.Prepare("select nextval('chat_archives_seq')")
	if err != nil {
		return 0, gkerr.GenGkErr("sql.Prepare"+getDatabaseErrorMessage(err), err, ERROR_ID_PREPARE)
	}

	defer stmt.Close()

	var rows *sql.Rows

	rows, err = stmt.Query()
	if err != nil {
		return 0, gkerr.GenGkErr("stmt.Query"+getDatabaseErrorMessage(err), err, ERROR_ID_QUERY)
	}

	defer rows.Close()

	var id int32

	if rows.Next() {
		err = rows.Scan(&id)
		if err != nil {
			return 0, gkerr.GenGkErr("rows.Scan"+getDatabaseErrorMessage(err), err, ERROR_ID_ROWS_SCAN)
		}
	} else {
		return 0, gkerr.GenGkErr("select users", nil, ERROR_ID_NO_ROWS_FOUND)
	}

	return id, nil
}
Пример #24
0
func ConvertData(columns []string, size int64, rows *sql.Rows) []interface{} {
	row := make([]interface{}, len(columns))
	values := make([]interface{}, len(columns))
	answer := make([]interface{}, size)

	for i, _ := range row {
		row[i] = &values[i]
	}

	j := 0
	for rows.Next() {
		rows.Scan(row...)
		record := make(map[string]interface{}, len(values))
		for i, col := range values {
			if col != nil {
				//fmt.Printf("\n%s: type= %s\n", columns[i], reflect.TypeOf(col))
				switch col.(type) {
				case bool:
					record[columns[i]] = col.(bool)
					break
				case int:
					record[columns[i]] = col.(int)
					break
				case int64:
					record[columns[i]] = int(col.(int64))
					break
				case float64:
					record[columns[i]] = col.(float64)
					break
				case string:
					record[columns[i]] = col.(string)
					break
				// case []byte:
				//     record[columns[i]] = string(col.([]byte))
				//     break
				case []int8:
					record[columns[i]] = col.([]string)
					break
				case time.Time:
					record[columns[i]] = col
					break
				case []uint8:
					data := strings.Split(strings.Trim(string(col.([]uint8)), "{}"), ",")
					if len(data) == 1 {
						record[columns[i]] = data[0]
					} else {
						record[columns[i]] = data
					}
					break
				default:
					utils.HandleErr("ConvertData: ", errors.New("Unexpected type."), nil)
				}
			}
			answer[j] = record
		}
		j++
	}
	rows.Close()
	return answer
}
Пример #25
0
func (p *Scope) AllJson(lst T) *Scope {
	p.checkModel(lst)
	p.Select(p.orm.mapper("Json"))
	p.From(p.model.Name)
	resultv := reflect.ValueOf(lst)
	if resultv.Kind() != reflect.Ptr || resultv.Elem().Kind() != reflect.Slice {
		panic("out argument must be a slice address")
	}
	slicev := resultv.Elem()

	sa := p.builder.SqlSelect()

	var rows *sql.Rows
	if rows, p.Err = p._query2(sa); p.NotErr() {
		defer rows.Close()
		for rows.Next() {
			var v []byte
			rows.Scan(&v)
			obj := reflect.New(p.model.Type).Interface()
			json.Unmarshal(v, obj)
			slicev = reflect.Append(slicev, reflect.ValueOf(obj).Elem())
		}
		resultv.Elem().Set(slicev.Slice(0, slicev.Len()))
	}
	return p
}
Пример #26
0
Файл: app.go Проект: GeoNet/mtr
// write a protobuf to b of all applicationid's in app.application
func appIdProto(r *http.Request, h http.Header, b *bytes.Buffer) *weft.Result {
	var err error
	var rows *sql.Rows

	if rows, err = dbR.Query(`SELECT applicationid FROM app.application ORDER BY applicationid ASC`); err != nil {
		return weft.InternalServerError(err)
	}
	defer rows.Close()

	var ar mtrpb.AppIDSummaryResult

	for rows.Next() {
		var ai mtrpb.AppIDSummary

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

		ar.Result = append(ar.Result, &ai)
	}

	var by []byte

	if by, err = proto.Marshal(&ar); err != nil {
		return weft.InternalServerError(err)
	}

	b.Write(by)

	return &weft.StatusOK
}
Пример #27
0
func scanCards(rows *sql.Rows, r router) ([]Card, error) {
	cards := []Card{}

	defer rows.Close()

	for rows.Next() {
		var blob []byte
		var card Card

		if err := rows.Scan(&blob); err != nil {
			return cards, err
		}

		err := json.Unmarshal(blob, &card)

		if err != nil {
			return cards, err
		}

		cards = append(cards, card)
	}
	if err := rows.Err(); err != nil {
		return cards, err
	}
	for i, _ := range cards {
		cards[i].Fill(r)
	}
	return cards, nil
}
Пример #28
0
// ListSecrets returns an iterator function that walks through all secrets in the database.
// The iterator takes an integer argument, which is the maximum number of results to return per iteration.
// If a key name is specified, the results are limited to secrets shared with that key.
func (p *DB) ListSecrets(key *string) func(int) ([]secrets.Secret, error) {
	pos := 0

	return func(n int) (res []secrets.Secret, err error) {
		if err := p.refresh(); err != nil {
			return nil, err
		}

		var rows *sql.Rows

		if key != nil {
			rows, err = p.conn.Table("secrets").Select(
				"secrets.id, secrets.name, secrets.message, secrets.nonce, secrets.pubkey, secrets.key_id").Joins(
				"left join keys on secrets.key_id = keys.id").Where(
				"keys.name = ?", *key).Order("id asc").Limit(n).Offset(pos).Rows()
		} else {
			rows, err = p.conn.Table("secrets").Select("id, name, message, nonce, pubkey, key_id").Order("id asc").Limit(n).Offset(pos).Rows()
		}

		for rows.Next() {
			out := new(secrets.Secret)
			err = rows.Scan(&out.ID, &out.Name, &out.Message, &out.Nonce, &out.Pubkey, &out.KeyID)
			if err != nil {
				return
			}
			res = append(res, *out)
		}
		err = rows.Close()
		pos += len(res)
		return
	}
}
Пример #29
0
func populateTechSupports(rows *sql.Rows, ch chan []TechSupport) {
	var t TechSupport
	var ts []TechSupport
	for rows.Next() {
		err := rows.Scan(
			&t.ID,
			&t.VehicleMake,
			&t.VehicleModel,
			&t.VehicleYear,
			&t.PurchaseDate,
			&t.PurchasedFrom,
			&t.DealerName,
			&t.ProductCode,
			&t.DateCode,
			&t.Issue,
			&t.Contact.ID,
			&t.BrandID,
		)
		if err != nil {
			ch <- ts
		}
		ts = append(ts, t)
	}
	defer rows.Close()
	ch <- ts
	return
}
Пример #30
0
func NewMsgRepository(db *sql.DB) *MsgRepository {
	mr := &MsgRepository{}
	mr.db = db
	mr.urIDs = make(map[types.ID]types.ID, 10240)
	gsql.MustExec(mr.db, `create table if not exists read_msgs(
	user_id bigint primary key,
	msg_id bigint not null default 0
	)`)

	for i := 0; i < userMsgTableCount; i++ {
		mr.CreateUserMsgTable(types.ID(i))
	}

	for i := 0; i < groupMsgTableCount; i++ {
		mr.CreateGroupMsgTable(types.ID(i))
	}

	var rows *sql.Rows
	rows, err := mr.db.Query("select user_id, msg_id from read_msgs")
	if err != nil {
		log.Panic(err)
	}
	defer rows.Close()
	var uid, msgID types.ID
	for rows.Next() {
		err = rows.Scan(&uid, &msgID)
		if err != nil {
			panic(err)
		}
		mr.urIDs[uid] = msgID
	}
	return mr
}