Пример #1
0
func TestGet(t *testing.T) {

	settings, err := Open("_examples/input/settings.yaml")

	if err != nil {
		t.Errorf("Test failed.")
	}

	test1 := "Hello World!"
	val1 := to.String(settings.Get("test_string"))

	if val1 != test1 {
		t.Errorf("Got %t expecting %t.", val1, test1)
	}

	val2 := int(to.Int64(settings.Get("non_defined_int")))

	if val2 != 0 {
		t.Errorf("Test failed.")
	}

	test3 := "Third"

	val3 := settings.Get("test_map", "element_3", "test_sequence").([]interface{})

	if val3[2] != test3 {
		t.Errorf("Got %t expecting %t.", val3[2], test3)
	}

	test5 := "Hello World!"
	val5 := to.String(settings.Get("test_string"))

	if test5 != val5 {
		t.Errorf("Got %t expecting %t.", test5, val5)
	}

	test6 := 1234
	val6 := int(to.Int64(settings.Get("test_int")))

	if test6 != val6 {
		t.Errorf("Got %t expecting %t.", test6, val6)
	}

	test7 := float64(1.2)
	val7 := to.Float64(settings.Get("test_float"))

	if test7 != val7 {
		t.Errorf("Got %t expecting %t.", test7, val7)
	}

	test8 := true
	val8 := to.Bool(settings.Get("test_bool"))

	if test8 != val8 {
		t.Errorf("Got %t expecting %t.", test8, val8)
	}

}
Пример #2
0
// This test appends some data into the "artist" table.
func TestAppend(t *testing.T) {

	var err error
	var id interface{}

	// Opening database.
	sess, err := db.Open(wrapperName, settings)

	if err != nil {
		t.Fatalf(err.Error())
	}

	// We should close the database when it's no longer in use.
	defer sess.Close()

	// Getting a pointer to the "artist" collection.
	artist, err := sess.Collection("artist")

	if err != nil {
		t.Fatalf(err.Error())
	}

	// Appending a map.
	id, err = artist.Append(map[string]string{
		"name": "Ozzie",
	})

	if to.Int64(id) == 0 {
		t.Fatalf("Expecting an ID.")
	}

	// Appending a struct.
	id, err = artist.Append(struct {
		Name string `field:name`
	}{
		"Flea",
	})

	if to.Int64(id) == 0 {
		t.Fatalf("Expecting an ID.")
	}

	// Appending a struct (using tags to specify the field name).
	id, err = artist.Append(struct {
		ArtistName string `field:"name"`
	}{
		"Slash",
	})

	if to.Int64(id) == 0 {
		t.Fatalf("Expecting an ID.")
	}

}
Пример #3
0
func ActivityJSONHandler(ctx context.Context, rw http.ResponseWriter, r *http.Request) {
	dataRenderer := data.FromContext(ctx)

	page := int(to.Int64(r.FormValue("page")))
	if page <= 0 {
		page = 1
	}

	limit := int(to.Int64(r.FormValue("limit")))
	if limit <= 0 {
		limit = 50
	}

	var cnt int
	if err := models.DB.Model(&models.ListActivity{}).Count(&cnt).Error; err != nil {
		panic(err)
	}

	totalpages := cnt / 50
	if cnt%50 != 0 {
		totalpages++
	}

	if page > totalpages {
		page = totalpages
	}

	var activities []models.ListActivity
	if err := models.DB.Limit(limit).Offset((page - 1) * limit).Order("created_at desc").Find(&activities).Error; err != nil && err != gorm.ErrRecordNotFound {
		panic(err)
	}

	// render a better karma view
	var rendered []*activityJSON
	for _, v := range activities {
		// load the username...
		rendered = append(rendered, &activityJSON{
			ListId:  v.ListID,
			User:    models.FindUserByID(v.UserID).Username,
			Comment: string(bluemonday.UGCPolicy().SanitizeBytes(blackfriday.MarkdownCommon([]byte(v.Activity)))),
			Time:    v.CreatedAt,
			URL:     render.ConvertURL("/b/" + to.String(v.ListID)),
		})
	}

	dataRenderer.Data = map[string]interface{}{
		"totalpages": totalpages,
		"page":       page,
		"activities": rendered,
	}
	dataRenderer.Type = data.DataJSON
}
Пример #4
0
/*
	Returns the number of rows in the current table that match certain conditions.
*/
func (self *Table) Count(terms ...interface{}) (int, error) {
	terms = append(terms, db.Fields{"COUNT(1) AS _total"})

	result, err := self.FindAll(terms...)

	if err == nil {
		return int(to.Int64(result[0]["_total"])), nil
	}

	return 0, err
}
Пример #5
0
func (k *Karma) APIRequest(user *models.User, action string, value string) (interface{}, error) {
	// action == label
	// value == -1/0/+1/etc

	// check if we have the action available
	for _, v := range k.Labels {
		if v.Label != action {
			continue
		}

		// check if we can take action on this label
		votable := k.checkLabel(v)
		if votable&karmaCanVote == 0 {
			return nil, ErrKarmaLabelIsClosed
		}

		if value == KarmaAccept {
			if votable&karmaCanAccept == 0 {
				return nil, ErrKarmaLabelCannotClose
			}
			k.State[v.Label] = KarmaStateAccepted

			return karmaGenericOk, nil
		} else if value == KarmaReject {
			if votable&karmaCanReject == 0 {
				return nil, ErrKarmaLabelCannotClose
			}
			k.State[v.Label] = KarmaStateRejected

			return karmaGenericOk, nil
		}

		vote := to.Int64(value)
		if vote < v.LowValue || vote > v.HighValue {
			return nil, ErrKarmaValueOutOfRange
		}

		// alright, add it in
		labelVotes, ok := k.Votes[v.Label]
		if !ok {
			labelVotes = map[string]int64{}
			k.Votes[v.Label] = labelVotes
		}

		labelVotes[user.Username] = vote

		k.save()

		return karmaGenericOk, nil
	}

	return nil, ErrKarmaLabelNotFound
}
Пример #6
0
func decodeTime(node *xmlx.Node) (t Time) {
	if node == nil {
		return t
	}

	t.Type = TimeType(strings.ToUpper(node.As("*", "type")))

	lowNode := Nget(node, "low")
	if lowNode != nil && !lowNode.HasAttr("*", "nullFlavor") {
		t.Low, _ = ParseHL7Time(lowNode.As("*", "value"))
	}
	highNode := Nget(node, "high")
	if highNode != nil && !highNode.HasAttr("*", "nullFlavor") {
		t.High, _ = ParseHL7Time(highNode.As("*", "value"))
	}

	val := node.As("*", "value")
	if len(val) > 0 {
		t.Value, _ = ParseHL7Time(val)
	} else {
		centerNode := Nget(node, "center")
		if centerNode != nil {
			t.Value, _ = ParseHL7Time(centerNode.As("*", "value"))
		}
	}

	if t.Value.IsZero() && !t.Low.IsZero() && t.High.IsZero() {
		t.Value = t.Low
	}

	period := Nget(node, "period")
	if period != nil {
		value := time.Duration(to.Int64(period.As("*", "value")))
		unit := period.As("*", "unit")
		switch strings.ToLower(unit) {
		case "s":
			t.Period = time.Second * value
		case "min":
			t.Period = time.Minute * value
		case "h":
			t.Period = time.Hour * value
		case "d":
			t.Period = time.Hour * 24 * value
		case "wk":
			t.Period = time.Hour * 24 * 7 * value
		case "mo":
			t.Period = time.Hour * 24 * 30 * value
		}
	}

	return t
}
Пример #7
0
// A generic parser for wowprofessions.com.
func ParseGeneric(s string) [][]Reagent {
	allmatches := itemRe.FindAllStringSubmatch(s, -1)
	var ret [][]Reagent
	//ret := make([][]Reagent, len(allmatches))
	for _, matches := range allmatches {
		// fmt.Println(matches)
		count := int(to.Int64(matches[len(matches)-2]))
		if count == 0 {
			count = 1
		}
		name := strings.Trim(matches[len(matches)-1], " ")

		ret = append(ret, []Reagent{Reagent{name, count}})
	}

	return ret
}
Пример #8
0
// getHandler service returns a request body.
func getHandler(wri http.ResponseWriter, req *http.Request) {
	var err error
	var response getResponse

	if err = req.ParseForm(); err != nil {
		log.Printf("ParseForm: %q", err)
		return
	}

	response.ID = uint(to.Int64(req.Form.Get("id")))

	res := col.Find(response)

	res.Select(
		"id",
		"method",
		"origin",
		"content_type",
		"content_length",
		"status",
		"host",
		"url",
		"scheme",
		"header",
		"request_header",
		"date_start",
		"date_end",
		"time_taken",
	)

	if err = res.One(&response.Response); err != nil {
		log.Printf("res.One: %q", err)
		return
	}

	replyJSON(wri, response)

	return
}
Пример #9
0
// getHandler service returns a request body.
func getHandler(w http.ResponseWriter, r *http.Request) {

	var err error
	if err = r.ParseForm(); err != nil {
		log.Printf("ParseForm: %q", err)
		replyCode(w, http.StatusInternalServerError)
		return
	}

	var response getResponse
	response.ID = uint(to.Int64(r.Form.Get("id")))

	res := storage.Find(response.ID)

	res.Select(
		"id",
		"method",
		"origin",
		"content_type",
		"content_length",
		"status",
		"host",
		"url",
		"scheme",
		"header",
		"request_header",
		"date_start",
		"date_end",
		"time_taken",
	)

	if err = res.One(&response.Response); err != nil {
		log.Printf("res.One: %q", err)
		replyCode(w, http.StatusInternalServerError)
		return
	}

	replyJSON(w, response)
}
Пример #10
0
// Execute runs a luminos server using a settings file.
func (c *runCommand) Execute() (err error) {
	var stat os.FileInfo

	// If no settings file was specified, use the default.
	if *flagSettings == "" {
		*flagSettings = envSettingsFile
	}

	// Attempt to stat the settings file.
	stat, err = os.Stat(*flagSettings)

	// It must not return an error.
	if err != nil {
		return fmt.Errorf("Error while opening %s: %q", *flagSettings, err)
	}

	// We must have a value in stat.
	if stat == nil {
		return fmt.Errorf("Could not load settings file: %s.", *flagSettings)
	}

	// And the file must not be a directory.
	if stat.IsDir() {
		return fmt.Errorf("Could not open %s: it's a directory!", *flagSettings)
	}

	// Now that we're positively sure that we have a valid file, let's try to
	// read settings from it.
	if settings, err = loadSettings(*flagSettings); err != nil {
		return fmt.Errorf("Error while reading settings file %s: %q", *flagSettings, err)
	}

	// Starting settings watcher.
	if err = settingsWatcher(); err == nil {
		watch.Watch(*flagSettings)
	}

	// Reading setttings.
	serverType := to.String(settings.Get("server", "type"))

	domain := envServerDomain
	address := to.String(settings.Get("server", "socket"))

	if address == "" {
		domain = envServerProtocol
		address = fmt.Sprintf("%s:%d", to.String(settings.Get("server", "bind")), to.Int64(settings.Get("server", "port")))
	}

	// Creating a network listener.
	var listener net.Listener

	if listener, err = net.Listen(domain, address); err != nil {
		return fmt.Errorf("Could not create network listener: %q", err)
	}

	// Listener must be closed when the function exits.
	defer listener.Close()

	// Attempt to start a server.
	switch serverType {
	case "fastcgi":
		if err == nil {
			log.Printf("Starting FastCGI server. Listening at %s.\n", address)
			fcgi.Serve(listener, &server{})
		} else {
			return fmt.Errorf("Failed to start FastCGI server: %q", err)
		}
	case "standalone":
		if err == nil {
			log.Printf("Starting HTTP server. Listening at %s.\n", address)
			http.Serve(listener, &server{})
		} else {
			return fmt.Errorf("Failed to start HTTP server: %q", err)
		}
	default:
		return fmt.Errorf("Unknown server type: %s", serverType)
	}

	return nil
}
Пример #11
0
// downloadHandler provides a downloadable document given its ID.
func downloadHandler(wri http.ResponseWriter, req *http.Request) {

	var err error
	var response getResponse

	if err = req.ParseForm(); err != nil {
		log.Printf("ParseForm: %q", err)
		return
	}

	wireFormat := to.Bool(req.Form.Get("wire"))
	direction := req.Form.Get("type")

	response.ID = uint(to.Int64(req.Form.Get("id")))

	res := col.Find(response)

	res.Select(
		"id",
		"url",
		"method",
		"header",
		"request_header",
		"date_end",
		db.Raw{"hex(body) AS body"},
		db.Raw{"hex(request_body) AS request_body"},
	)

	if err = res.One(&response.Response); err != nil {
		log.Printf("res.One: %q", err)
		return
	}

	var u *url.URL

	if u, err = url.Parse(response.URL); err != nil {
		log.Printf("url.Parse: %q", err)
		return
	}

	var body []byte

	basename := path.Base(u.Path)

	switch direction {
	case directionRequest:
		if body, err = hex.DecodeString(string(response.RequestBody)); err != nil {
			log.Printf("url.Parse: %q", err)
			return
		}

		if wireFormat {

			buf := bytes.NewBuffer(nil)

			buf.WriteString(fmt.Sprintf("%s %s HTTP/1.1\r\n", response.Method, u.RequestURI()))

			for k, vv := range response.RequestHeader.Header {
				for _, v := range vv {
					buf.WriteString(fmt.Sprintf("%s: %s\r\n", k, v))
				}
			}

			buf.WriteString("\r\n")

			wri.Header().Set("Content-Disposition", `attachment; filename="`+u.Host+"-"+basename+`.bin"`)

			buf.Write(body)

			http.ServeContent(wri, req, "", response.DateEnd, bytes.NewReader(buf.Bytes()))

		} else {

			wri.Header().Set("Content-Disposition", `attachment; filename="`+basename+`"`)

			http.ServeContent(wri, req, basename, response.DateEnd, bytes.NewReader(body))

		}

	default:
		if body, err = hex.DecodeString(string(response.Body)); err != nil {
			log.Printf("url.Parse: %q", err)
			return
		}

		if wireFormat {

			buf := bytes.NewBuffer(nil)

			for k, vv := range response.Header.Header {
				for _, v := range vv {
					buf.WriteString(fmt.Sprintf("%s: %s\r\n", k, v))
				}
			}

			buf.WriteString("\r\n")

			wri.Header().Set("Content-Disposition", `attachment; filename="`+u.Host+"-"+basename+`.bin"`)

			buf.Write(body)

			http.ServeContent(wri, req, "", response.DateEnd, bytes.NewReader(buf.Bytes()))

		} else {

			wri.Header().Set("Content-Disposition", `attachment; filename="`+basename+`"`)

			http.ServeContent(wri, req, basename, response.DateEnd, bytes.NewReader(body))

		}

	}

	return
}
Пример #12
0
// This test uses and result and tries to fetch items one by one.
func TestResultFetch(t *testing.T) {

	var err error
	var res db.Result

	// Opening database.
	sess, err := db.Open(wrapperName, settings)

	if err != nil {
		t.Fatalf(err.Error())
	}

	// We should close the database when it's no longer in use.
	defer sess.Close()

	artist, err := sess.Collection("artist")

	if err != nil {
		t.Fatalf(err.Error())
	}

	// Testing map
	res = artist.Find()

	row_m := map[string]interface{}{}

	for {
		err = res.Next(&row_m)

		if err == db.ErrNoMoreRows {
			// No more row_ms left.
			break
		}

		if err == nil {
			if to.Int64(row_m["id"]) == 0 {
				t.Fatalf("Expecting a not null ID.")
			}
			if to.String(row_m["name"]) == "" {
				t.Fatalf("Expecting a name.")
			}
		} else {
			t.Fatalf(err.Error())
		}
	}

	res.Close()

	// Testing struct
	row_s := struct {
		Id   uint64
		Name string
	}{}

	res = artist.Find()

	for {
		err = res.Next(&row_s)

		if err == db.ErrNoMoreRows {
			// No more row_s' left.
			break
		}

		if err == nil {
			if row_s.Id == 0 {
				t.Fatalf("Expecting a not null ID.")
			}
			if row_s.Name == "" {
				t.Fatalf("Expecting a name.")
			}
		} else {
			t.Fatalf(err.Error())
		}
	}

	res.Close()

	// Testing tagged struct
	row_t := struct {
		Value1 uint64 `field:"id"`
		Value2 string `field:"name"`
	}{}

	res = artist.Find()

	for {
		err = res.Next(&row_t)

		if err == db.ErrNoMoreRows {
			// No more row_t's left.
			break
		}

		if err == nil {
			if row_t.Value1 == 0 {
				t.Fatalf("Expecting a not null ID.")
			}
			if row_t.Value2 == "" {
				t.Fatalf("Expecting a name.")
			}
		} else {
			t.Fatalf(err.Error())
		}
	}

	res.Close()

	// Testing Result.All() with a slice of maps.
	res = artist.Find()

	all_rows_m := []map[string]interface{}{}
	err = res.All(&all_rows_m)

	if err != nil {
		t.Fatalf(err.Error())
	}

	for _, single_row_m := range all_rows_m {
		if to.Int64(single_row_m["id"]) == 0 {
			t.Fatalf("Expecting a not null ID.")
		}
	}

	// Testing Result.All() with a slice of structs.
	res = artist.Find()

	all_rows_s := []struct {
		Id   uint64
		Name string
	}{}
	err = res.All(&all_rows_s)

	if err != nil {
		t.Fatalf(err.Error())
	}

	for _, single_row_s := range all_rows_s {
		if single_row_s.Id == 0 {
			t.Fatalf("Expecting a not null ID.")
		}
	}

	// Testing Result.All() with a slice of tagged structs.
	res = artist.Find()

	all_rows_t := []struct {
		Value1 uint64 `field:"id"`
		Value2 string `field:"name"`
	}{}
	err = res.All(&all_rows_t)

	if err != nil {
		t.Fatalf(err.Error())
	}

	for _, single_row_t := range all_rows_t {
		if single_row_t.Value1 == 0 {
			t.Fatalf("Expecting a not null ID.")
		}
	}
}
Пример #13
0
// Appends an item (map or struct) into the collection.
func (t *table) Append(item interface{}) (interface{}, error) {

	var pKey []string
	var columns sqlgen.Columns
	var values sqlgen.Values
	var arguments []interface{}
	//var id []interface{}

	cols, vals, err := t.FieldValues(item, toInternal)

	if err != nil {
		return nil, err
	}

	columns = make(sqlgen.Columns, 0, len(cols))
	for i := range cols {
		columns = append(columns, sqlgen.Column{cols[i]})
	}

	arguments = make([]interface{}, 0, len(vals))
	values = make(sqlgen.Values, 0, len(vals))
	for i := range vals {
		switch v := vals[i].(type) {
		case sqlgen.Value:
			// Adding value.
			values = append(values, v)
		default:
			// Adding both value and placeholder.
			values = append(values, sqlPlaceholder)
			arguments = append(arguments, v)
		}
	}

	if pKey, err = t.source.getPrimaryKey(t.tableN(0)); err != nil {
		if err != sql.ErrNoRows {
			// Can't tell primary key.
			return nil, err
		}
	}

	stmt := sqlgen.Statement{
		Type:    sqlgen.SqlInsert,
		Table:   sqlgen.Table{t.tableN(0)},
		Columns: columns,
		Values:  values,
	}

	// No primary keys defined.
	if len(pKey) == 0 {
		var res sql.Result

		if res, err = t.source.doExec(stmt, arguments...); err != nil {
			return nil, err
		}

		// Attempt to use LastInsertId() (probably won't work, but the exec()
		// succeeded, so the error from LastInsertId() is ignored).
		lastID, _ := res.LastInsertId()

		return lastID, nil
	}

	var rows *sql.Rows

	// A primary key was found.
	stmt.Extra = sqlgen.Extra(fmt.Sprintf(`RETURNING "%s"`, strings.Join(pKey, `", "`)))
	if rows, err = t.source.doQuery(stmt, arguments...); err != nil {
		return nil, err
	}

	defer rows.Close()

	var keyMap map[string]interface{}
	err = sqlutil.FetchRow(rows, &keyMap)

	// Does the item satisfy the db.IDSetter interface?
	if setter, ok := item.(db.IDSetter); ok {
		if err := setter.SetID(keyMap); err != nil {
			return nil, err
		}
		return nil, nil
	}

	// The IDSetter interface does not match, we'll be looking for another
	// interface match.
	if len(keyMap) == 1 {

		id := keyMap[pKey[0]]

		// Matches db.Int64IDSetter
		if setter, ok := item.(db.Int64IDSetter); ok {
			if err = setter.SetID(to.Int64(id)); err != nil {
				return nil, err
			}
			return nil, nil
		}

		// Matches db.Uint64IDSetter
		if setter, ok := item.(db.Uint64IDSetter); ok {
			if err = setter.SetID(to.Uint64(id)); err != nil {
				return nil, err
			}
			return nil, nil
		}

		// No interface matched, falling back to old behaviour.
		return to.Int64(id), nil
	}

	// More than one key, no interface matched, let's return a map.
	return keyMap, nil
}
Пример #14
0
func (self *runCommand) Execute() error {

	// Default settings file.
	if *flagSettings == "" {
		*flagSettings = DEFAULT_SETTINGS_FILE
	}

	stat, err := os.Stat(*flagSettings)

	if err != nil {
		return fmt.Errorf("Error while opening %s: %s", *flagSettings, err.Error())
	}

	if stat != nil {

		if stat.IsDir() == true {

			return fmt.Errorf("Could not open %s: it's a directory!", *flagSettings)

		} else {

			settings, err = loadSettings(*flagSettings)

			if err != nil {
				return fmt.Errorf("Error while reading settings file %s: %s", *flagSettings, err.Error())
			}

			err = settingsWatcher()

			if err == nil {
				watch.Watch(*flagSettings)
			}

			serverType := to.String(settings.Get("server", "type"))

			domain := DEFAULT_SERVER_DOMAIN
			address := to.String(settings.Get("server", "socket"))

			if address == "" {
				domain = DEFAULT_SERVER_PROTOCOL
				address = fmt.Sprintf("%s:%d", to.String(settings.Get("server", "bind")), to.Int64(settings.Get("server", "port")))
			}

			listener, err := net.Listen(domain, address)

			if err != nil {
				return err
			}

			defer listener.Close()

			switch serverType {
			case "fastcgi":
				if err == nil {
					log.Printf("Starting FastCGI server. Listening at %s.", address)
					fcgi.Serve(listener, &server{})
				} else {
					return fmt.Errorf("Failed to start FastCGI server: %s", err.Error())
				}
			case "standalone":
				if err == nil {
					log.Printf("Starting HTTP server. Listening at %s.", address)
					http.Serve(listener, &server{})
				} else {
					return fmt.Errorf("Failed to start HTTP server: %s", err.Error())
				}
			default:
				return fmt.Errorf("Unknown server type: %s", serverType)
			}

		}
	} else {
		return fmt.Errorf("Could not load settings file: %s.", *flagSettings)
	}

	return nil
}
Пример #15
0
// ListsAPIHandler shows the collection of lists, with filters, paginated, JSON'ified.
func ListsAPIHandler(ctx context.Context, rw http.ResponseWriter, r *http.Request) {
	dataRenderer := data.FromContext(ctx)
	dataRenderer.Type = data.DataJSON

	platform := r.FormValue("platform")
	channel := r.FormValue("channel")
	status := r.FormValue("status")

	limit := int(to.Int64(r.FormValue("limit")))
	if limit <= 0 {
		limit = 50 // reasonable
	}

	page := int(to.Int64(r.FormValue("page")))
	if page <= 0 {
		page = 1
	}

	baseDB := models.DB.Model(&models.List{})
	if platform != "" {
		baseDB = baseDB.Where("platform = ?", platform)
	}

	if channel != "" {
		baseDB = baseDB.Where("channel = ?", channel)
	}

	if status == models.ListRunning || status == models.ListPending || status == models.ListSuccess || status == models.ListFailed {
		baseDB = baseDB.Where("stage_result = ?", status)
	} else if status != "" {
		panic(ErrBadRequest)
	}

	var cnt int
	if err := baseDB.Count(&cnt).Error; err != nil {
		panic(err)
	}

	totalpages := cnt / limit
	if cnt%limit != 0 {
		totalpages++
	}

	if page > totalpages {
		page = totalpages
	}

	var packages []*models.List
	if err := baseDB.Limit(limit).Offset((page - 1) * limit).Order("updated_at desc").Find(&packages).Error; err != nil && err != gorm.ErrRecordNotFound {
		panic(err)
	}

	dataRenderer.Data = map[string]interface{}{
		"lists": packages,
		"pages": map[string]interface{}{
			"prev":    page - 1,
			"current": page,
			"next":    page + 1,
			"total":   totalpages,
		},
	}
}
Пример #16
0
// Return the market price of an item
func (e *Item) Market() int {
	m := e.Find("market").Text()
	return int(to.Int64(m))
}
Пример #17
0
// Tests datatype conversions.
func TestDataTypes(t *testing.T) {
	var res db.Result
	var items []db.Item

	sess, err := db.Open(wrapperName, settings)

	if err != nil {
		t.Fatalf(err.Error())
	}

	defer sess.Close()

	dataTypes := sess.ExistentCollection("data_types")

	dataTypes.Truncate()

	ids, err := dataTypes.Append(testValues)

	if err != nil {
		t.Fatalf(err.Error())
	}

	found, err := dataTypes.Count(db.Cond{"id": db.Id(ids[0])})

	if err != nil {
		t.Fatalf(err.Error())
	}

	if found == 0 {
		t.Errorf("Expecting an item.")
	}

	// Getting and reinserting (a db.Item).
	item, _ := dataTypes.Find()

	_, err = dataTypes.Append(item)

	if err == nil {
		t.Fatalf("Expecting duplicated-key error.")
	}

	delete(item, "id")

	_, err = dataTypes.Append(item)

	if err != nil {
		t.Fatalf(err.Error())
	}

	// Testing date ranges
	items, err = dataTypes.FindAll(db.Cond{
		"_date": time.Now(),
	})

	if err != nil {
		t.Fatalf(err.Error())
	}

	if len(items) > 0 {
		t.Fatalf("Expecting no results.")
	}

	items, err = dataTypes.FindAll(db.Cond{
		"_date <=": time.Now(),
	})

	if err != nil {
		t.Fatalf(err.Error())
	}

	if len(items) != 2 {
		t.Fatalf("Expecting some results.")
	}

	// Testing struct
	sresults := []testValuesStruct{}

	res, err = dataTypes.Query()

	if err != nil {
		t.Fatalf(err.Error())
	}

	err = res.All(&sresults)

	if err != nil {
		t.Fatalf(err.Error())
	}

	// Testing struct equality
	for _, item := range sresults {
		if reflect.DeepEqual(item, testValues) == false {
			t.Errorf("Struct is different.")
		}
	}

	// Testing maps
	results, _ := dataTypes.FindAll()

	for _, item := range results {

		for key, _ := range item {

			switch key {

			// Signed integers.
			case
				"_int",
				"_int8",
				"_int16",
				"_int32",
				"_int64":
				if to.Int64(item[key]) != testValues.Int64 {
					t.Fatalf("Wrong datatype %v.", key)
				}

			// Unsigned integers.
			case
				"_uint",
				"_uint8",
				"_uint16",
				"_uint32",
				"_uint64":
				if to.Uint64(item[key]) != testValues.Uint64 {
					t.Fatalf("Wrong datatype %v.", key)
				}

			// Floating point.
			case "_float32":
			case "_float64":
				if to.Float64(item[key]) != testValues.Float64 {
					t.Fatalf("Wrong datatype %v.", key)
				}

			// Boolean
			case "_bool":
				if to.Bool(item[key]) != testValues.Bool {
					t.Fatalf("Wrong datatype %v.", key)
				}

			// String
			case "_string":
				if to.String(item[key]) != testValues.String {
					t.Fatalf("Wrong datatype %v.", key)
				}

			// Date
			case "_date":
				if to.Time(item[key]).Equal(testValues.Date) == false {
					t.Fatalf("Wrong datatype %v.", key)
				}
			}
		}
	}

}
Пример #18
0
// pullHandler service serves paginated requests.
func pullHandler(w http.ResponseWriter, r *http.Request) {
	var err error
	var response pullResponse

	if err = r.ParseForm(); err != nil {
		log.Printf("ParseForm: %q", err)
		replyCode(w, http.StatusInternalServerError)
		return
	}

	q := r.Form.Get("q")

	q = cleanPattern.ReplaceAllString(q, " ")
	q = spacesPattern.ReplaceAllString(q, " ")

	response.Page = uint(to.Int64(r.Form.Get("page")))

	if response.Page < 1 {
		response.Page = 1
	}

	// Result set
	res := storage.Find().Select(
		"id",
		"method",
		"origin",
		"status",
		"host",
		"path",
		"scheme",
		"url",
		"content_length",
		"content_type",
		"date_start",
		"time_taken",
	).OrderBy("id").Limit(pageSize).Offset(pageSize * int(response.Page-1))

	if q != "" {
		terms := strings.Split(q, " ")
		conds := db.Or()

		for _, term := range terms {
			conds.Or(
				db.Or(
					db.Raw(`host LIKE '%`+term+`%'`),
					db.Raw(`origin LIKE '%`+term+`%'`),
					db.Raw(`path LIKE '%`+term+`%'`),
					db.Raw(`content_type LIKE '%`+term+`%'`),
					db.Cond{"method": term},
					db.Cond{"scheme": term},
					db.Cond{"status": term},
				),
			)
		}

		res.Where(conds)
	}

	// Pulling information page.
	if err = res.All(&response.Data); err != nil {
		log.Printf("res.All: %q", err)
		replyCode(w, http.StatusInternalServerError)
		return
	}

	// Getting total number of pages.
	if c, err := res.Count(); err == nil {
		response.Pages = uint(math.Ceil(float64(c) / float64(pageSize)))
	}

	replyJSON(w, response)
}
Пример #19
0
// Attempts to append some data into the "artist" table.
func TestAppend(t *testing.T) {
	var err error
	var id interface{}
	var sess db.Database
	var artist db.Collection
	var total uint64

	if sess, err = db.Open(Adapter, settings); err != nil {
		t.Fatal(err)
	}

	defer sess.Close()

	if artist, err = sess.Collection("artist"); err != nil {
		t.Fatal(err)
	}

	// Attempt to append a map.
	itemMap := map[string]string{
		"name": "Ozzie",
	}

	if id, err = artist.Append(itemMap); err != nil {
		t.Fatal(err)
	}

	if to.Int64(id) == 0 {
		t.Fatalf("Expecting an ID.")
	}

	// Attempt to append a struct.
	itemStruct := struct {
		Name string `db:"name"`
	}{
		"Flea",
	}

	if id, err = artist.Append(itemStruct); err != nil {
		t.Fatal(err)
	}

	if to.Int64(id) == 0 {
		t.Fatalf("Expecting an ID.")
	}

	// Attempt to append a tagged struct.
	itemStruct2 := struct {
		ArtistName string `db:"name"`
	}{
		"Slash",
	}

	if id, err = artist.Append(itemStruct2); err != nil {
		t.Fatal(err)
	}

	if to.Int64(id) == 0 {
		t.Fatalf("Expecting an ID.")
	}

	// Attempt to append and update a private key
	itemStruct3 := artistWithInt64Key{
		Name: "Janus",
	}

	if _, err = artist.Append(&itemStruct3); err != nil {
		t.Fatal(err)
	}

	if itemStruct3.id == 0 {
		t.Fatalf("Expecting an ID.")
	}

	// Counting elements, must be exactly 4 elements.
	if total, err = artist.Find().Count(); err != nil {
		t.Fatal(err)
	}

	if total != 4 {
		t.Fatalf("Expecting exactly 4 rows.")
	}

}
Пример #20
0
// pullHandler service serves paginated requests.
func pullHandler(wri http.ResponseWriter, req *http.Request) {
	var err error
	var response pullResponse

	if err = req.ParseForm(); err != nil {
		log.Printf("ParseForm: %q", err)
		return
	}

	q := req.Form.Get("q")

	q = cleanPattern.ReplaceAllString(q, " ")
	q = spacesPattern.ReplaceAllString(q, " ")

	response.Page = uint(to.Int64(req.Form.Get("page")))

	if response.Page < 1 {
		response.Page = 1
	}

	// Result set
	res := col.Find().Select(
		"id",
		"method",
		"origin",
		"status",
		"host",
		"path",
		"scheme",
		"url",
		"content_length",
		"content_type",
		"date_start",
		"time_taken",
	).Sort("id").Limit(pageSize).Skip(pageSize * (response.Page - 1))

	if q != "" {

		terms := strings.Split(q, " ")
		conds := make(db.Or, 0, len(terms))

		for _, term := range terms {
			conds = append(conds, db.Or{
				db.Raw{`host LIKE '%` + term + `%'`},
				db.Raw{`origin LIKE '%` + term + `%'`},
				db.Raw{`path LIKE '%` + term + `%'`},
				db.Raw{`content_type LIKE '%` + term + `%'`},
				db.Cond{"method": term},
				db.Cond{"scheme": term},
				db.Cond{"status": term},
			},
			)
		}

		res.Where(conds...)
	}

	// Pulling information page.
	if err = res.All(&response.Data); err != nil {
		log.Printf("res.All: %q", err)
		return
	}

	// Getting total number of pages.
	if c, err := res.Count(); err == nil {
		response.Pages = uint(math.Ceil(float64(c) / float64(pageSize)))
	}

	replyJSON(wri, response)

	return
}
Пример #21
0
// Attempts to fetch results one by one.
func TestResultFetch(t *testing.T) {
	var err error
	var res db.Result
	var sess db.Database
	var artist db.Collection

	if sess, err = db.Open(Adapter, settings); err != nil {
		t.Fatal(err)
	}

	defer sess.Close()

	if artist, err = sess.Collection("artist"); err != nil {
		t.Fatal(err)
	}

	// Dumping into a map.
	rowMap := map[string]interface{}{}

	res = artist.Find()

	for {
		err = res.Next(&rowMap)

		if err == db.ErrNoMoreRows {
			break
		}

		if err == nil {
			if to.Int64(rowMap["id"]) == 0 {
				t.Fatalf("Expecting a not null ID.")
			}
			if to.String(rowMap["name"]) == "" {
				t.Fatalf("Expecting a name.")
			}
		} else {
			t.Fatal(err)
		}
	}

	res.Close()

	// Dumping into an struct with no tags.
	rowStruct := struct {
		ID   uint64
		Name string
	}{}

	res = artist.Find()

	for {
		err = res.Next(&rowStruct)

		if err == db.ErrNoMoreRows {
			break
		}

		if err == nil {
			if rowStruct.ID == 0 {
				t.Fatalf("Expecting a not null ID.")
			}
			if rowStruct.Name == "" {
				t.Fatalf("Expecting a name.")
			}
		} else {
			t.Fatal(err)
		}
	}

	res.Close()

	// Dumping into a tagged struct.
	rowStruct2 := struct {
		Value1 uint64 `field:"id"`
		Value2 string `field:"name"`
	}{}

	res = artist.Find()

	for {
		err = res.Next(&rowStruct2)

		if err == db.ErrNoMoreRows {
			break
		}

		if err == nil {
			if rowStruct2.Value1 == 0 {
				t.Fatalf("Expecting a not null ID.")
			}
			if rowStruct2.Value2 == "" {
				t.Fatalf("Expecting a name.")
			}
		} else {
			t.Fatal(err)
		}
	}

	res.Close()

	// Dumping into an slice of maps.
	allRowsMap := []map[string]interface{}{}

	res = artist.Find()
	if err = res.All(&allRowsMap); err != nil {
		t.Fatal(err)
	}

	if len(allRowsMap) != 4 {
		t.Fatalf("Expecting 4 items.")
	}

	for _, singleRowMap := range allRowsMap {
		if to.Int64(singleRowMap["id"]) == 0 {
			t.Fatalf("Expecting a not null ID.")
		}
	}

	// Dumping into an slice of structs.

	allRowsStruct := []struct {
		ID   uint64
		Name string
	}{}

	res = artist.Find()
	if err = res.All(&allRowsStruct); err != nil {
		t.Fatal(err)
	}

	if len(allRowsStruct) != 4 {
		t.Fatalf("Expecting 4 items.")
	}

	for _, singleRowStruct := range allRowsStruct {
		if singleRowStruct.ID == 0 {
			t.Fatalf("Expecting a not null ID.")
		}
	}

	// Dumping into an slice of tagged structs.
	allRowsStruct2 := []struct {
		Value1 uint64 `field:"id"`
		Value2 string `field:"name"`
	}{}

	res = artist.Find()

	if err = res.All(&allRowsStruct2); err != nil {
		t.Fatal(err)
	}

	if len(allRowsStruct2) != 4 {
		t.Fatalf("Expecting 4 items.")
	}

	for _, singleRowStruct2 := range allRowsStruct2 {
		if singleRowStruct2.Value1 == 0 {
			t.Fatalf("Expecting a not null ID.")
		}
	}
}
Пример #22
0
// Attempts to append some data into the "artist" table.
func TestAppend(t *testing.T) {
	var err error
	var id interface{}
	var sess db.Database
	var artist db.Collection
	var total uint64

	if sess, err = db.Open(Adapter, settings); err != nil {
		t.Fatal(err)
	}

	defer sess.Close()

	if artist, err = sess.Collection("artist"); err != nil {
		t.Fatal(err)
	}

	// Attempt to append a map.
	item_m := map[string]string{
		"name": "Ozzie",
	}

	if id, err = artist.Append(item_m); err != nil {
		t.Fatal(err)
	}

	if to.Int64(id) == 0 {
		t.Fatalf("Expecting an ID.")
	}

	// Attempt to append a struct.
	item_s := struct {
		Name string `db:"name"`
	}{
		"Flea",
	}

	if id, err = artist.Append(item_s); err != nil {
		t.Fatal(err)
	}

	if to.Int64(id) == 0 {
		t.Fatalf("Expecting an ID.")
	}

	// Append to append a tagged struct.
	item_t := struct {
		ArtistName string `db:"name"`
	}{
		"Slash",
	}

	if id, err = artist.Append(item_t); err != nil {
		t.Fatal(err)
	}

	if to.Int64(id) == 0 {
		t.Fatalf("Expecting an ID.")
	}

	// Counting elements, must be exactly 3 elements.
	if total, err = artist.Find().Count(); err != nil {
		t.Fatal(err)
	}

	if total != 3 {
		t.Fatalf("Expecting exactly 3 rows.")
	}

}