Пример #1
0
// GetAgeModelData does the search and modifies the results struct pointer
// Not placed in the above function to allow this to be called by stand along apps like ocdBulk
func GetAgeModelData(db *sqlx.DB, sqlstring string, results **[]AgeModel) {
	db.MapperFunc(strings.ToUpper)
	err := db.Select(*results, sqlstring)
	if err != nil {
		log.Printf(`Error v2 with: %s`, err)
	}
}
Пример #2
0
func InsertAnswer(db *sqlx.DB, userId int, questionId int, message string) (*Answer, error) {
	a := Answer{}
	a.AuthorId = userId
	a.QuestionId = questionId
	a.Message = message
	var err error

	if err = ValidateAnswer(a); err != nil {
		return nil, err
	}

	qry := sq.Insert("answers").
		Columns("author_id", "question_id", "message").
		Values(a.AuthorId, a.QuestionId, a.Message).
		Suffix("RETURNING *").
		PlaceholderFormat(sq.Dollar)

	sql, params, err := qry.ToSql()
	if err != nil {
		return nil, err
	}

	err = db.Get(&a, sql, params...)
	dbErr := dbError(err)
	if dbErr != nil {
		return nil, dbErr
	} else {
		return &a, nil
	}
}
Пример #3
0
// @Title putJob
// @Description modify an existing jobentry
// @Accept  application/json
// @Param   id              path    int     true        "The row id"
// @Param                 Body body     Job   true "Job object that should be added to the table"
// @Success 200 {object}    output_format.ApiWrapper
// @Resource /api/2.0
// @Router /api/2.0/job/{id}  [put]
func putJob(id int, payload []byte, db *sqlx.DB) (interface{}, error) {
	var v Job
	err := json.Unmarshal(payload, &v)
	v.Id = int64(id) // overwrite the id in the payload
	if err != nil {
		log.Println(err)
		return nil, err
	}
	v.LastUpdated = time.Now()
	sqlString := "UPDATE job SET "
	sqlString += "job_agent = :job_agent"
	sqlString += ",object_type = :object_type"
	sqlString += ",object_name = :object_name"
	sqlString += ",keyword = :keyword"
	sqlString += ",parameters = :parameters"
	sqlString += ",asset_url = :asset_url"
	sqlString += ",asset_type = :asset_type"
	sqlString += ",status = :status"
	sqlString += ",start_time = :start_time"
	sqlString += ",entered_time = :entered_time"
	sqlString += ",tm_user = :tm_user"
	sqlString += ",last_updated = :last_updated"
	sqlString += ",deliveryservice = :deliveryservice"
	sqlString += " WHERE id=:id"
	result, err := db.NamedExec(sqlString, v)
	if err != nil {
		log.Println(err)
		return nil, err
	}
	return result, err
}
Пример #4
0
// UpdateNode updates the given Node.
func UpdateNode(db *sqlx.DB, n models.Node) error {
	if n.RXDelay > 15 {
		return errors.New("max value of RXDelay is 15")
	}

	res, err := db.Exec(`
		update node set
			app_eui = $2,
			app_key = $3,
			used_dev_nonces = $4,
			rx_delay = $5,
			rx1_dr_offset = $6,
			channel_list_id = $7
		where dev_eui = $1`,
		n.DevEUI[:],
		n.AppEUI[:],
		n.AppKey[:],
		n.UsedDevNonces,
		n.RXDelay,
		n.RX1DROffset,
		n.ChannelListID,
	)
	if err != nil {
		return fmt.Errorf("update node %s error: %s", n.DevEUI, err)
	}
	ra, err := res.RowsAffected()
	if err != nil {
		return err
	}
	if ra == 0 {
		return fmt.Errorf("node %s does not exist", n.DevEUI)
	}
	log.WithField("dev_eui", n.DevEUI).Info("node updated")
	return nil
}
Пример #5
0
func connectMySQL() {
	var db *sqlx.DB
	c, err := dockertest.ConnectToMySQL(15, time.Second, func(url string) bool {
		var err error
		db, err = sqlx.Open("mysql", url)
		if err != nil {
			log.Printf("Got error in mysql connector: %s", err)
			return false
		}
		return db.Ping() == nil
	})

	if err != nil {
		log.Fatalf("Could not connect to database: %s", err)
	}

	containers = append(containers, c)
	s := NewSQLManager(db, nil)

	if err = s.CreateSchemas(); err != nil {
		log.Fatalf("Could not create mysql schema: %v", err)
	}

	managers["mysql"] = s
}
Пример #6
0
// @Title postStatsSummary
// @Description enter a new stats_summary
// @Accept  application/json
// @Param                 Body body     StatsSummary   true "StatsSummary object that should be added to the table"
// @Success 200 {object}    output_format.ApiWrapper
// @Resource /api/2.0
// @Router /api/2.0/stats_summary [post]
func postStatsSummary(payload []byte, db *sqlx.DB) (interface{}, error) {
	var v StatsSummary
	err := json.Unmarshal(payload, &v)
	if err != nil {
		log.Println(err)
	}
	sqlString := "INSERT INTO stats_summary("
	sqlString += "cdn_name"
	sqlString += ",deliveryservice_name"
	sqlString += ",stat_name"
	sqlString += ",stat_value"
	sqlString += ",summary_time"
	sqlString += ",stat_date"
	sqlString += ") VALUES ("
	sqlString += ":cdn_name"
	sqlString += ",:deliveryservice_name"
	sqlString += ",:stat_name"
	sqlString += ",:stat_value"
	sqlString += ",:summary_time"
	sqlString += ",:stat_date"
	sqlString += ")"
	result, err := db.NamedExec(sqlString, v)
	if err != nil {
		log.Println(err)
		return nil, err
	}
	return result, err
}
Пример #7
0
// @Title postFederationUsers
// @Description enter a new federation_users
// @Accept  application/json
// @Param                 Body body     FederationUsers   true "FederationUsers object that should be added to the table"
// @Success 200 {object}    output_format.ApiWrapper
// @Resource /api/2.0
// @Router /api/2.0/federation_users [post]
func postFederationUser(payload []byte, db *sqlx.DB) (interface{}, error) {
	var v FederationUsers
	err := json.Unmarshal(payload, &v)
	if err != nil {
		log.Println(err)
		return nil, err
	}
	sqlString := "INSERT INTO federation_users("
	sqlString += "federation_id"
	sqlString += ",username"
	sqlString += ",role"
	sqlString += ",created_at"
	sqlString += ") VALUES ("
	sqlString += ":federation_id"
	sqlString += ",:username"
	sqlString += ",:role"
	sqlString += ",:created_at"
	sqlString += ")"
	result, err := db.NamedExec(sqlString, v)
	if err != nil {
		log.Println(err)
		return nil, err
	}
	return result, err
}
Пример #8
0
func QueryQuestions(db *sqlx.DB, authorId int, query string, offset int) ([]Question, error) {
	qs := []Question{}
	qry := sq.Select("*").From("questions")

	if authorId != 0 {
		qry = qry.Where("author_id = ?", authorId)
	}
	if query != "" {
		word := fmt.Sprint("%", query, "%")
		qry = qry.Where("(title LIKE ? OR question LIKE ?)", word, word)
	}
	if offset > 0 {
		qry = qry.Offset(uint64(offset))
	}

	qry = qry.OrderBy("created_at DESC")
	qry = qry.PlaceholderFormat(sq.Dollar)
	sql, params, err := qry.ToSql()

	if err != nil {
		return qs, err
	} else {
		err := db.Select(&qs, sql, params...)
		dbErr := dbError(err)
		return qs, dbErr
	}
}
Пример #9
0
// @Title putDeliveryservice
// @Description modify an existing deliveryserviceentry
// @Accept  application/json
// @Param   id              path    int     true        "The row id"
// @Param                 Body body     Deliveryservice   true "Deliveryservice object that should be added to the table"
// @Success 200 {object}    output_format.ApiWrapper
// @Resource /api/2.0
// @Router /api/2.0/deliveryservice/{id}  [put]
func putDeliveryservice(id int, payload []byte, db *sqlx.DB) (interface{}, error) {
	var v Deliveryservice
	err := json.Unmarshal(payload, &v)
	v.Id = int64(id) // overwrite the id in the payload
	if err != nil {
		log.Println(err)
		return nil, err
	}
	v.LastUpdated = time.Now()
	sqlString := "UPDATE deliveryservice SET "
	sqlString += "xml_id = :xml_id"
	sqlString += ",active = :active"
	sqlString += ",dscp = :dscp"
	sqlString += ",signed = :signed"
	sqlString += ",qstring_ignore = :qstring_ignore"
	sqlString += ",geo_limit = :geo_limit"
	sqlString += ",http_bypass_fqdn = :http_bypass_fqdn"
	sqlString += ",dns_bypass_ip = :dns_bypass_ip"
	sqlString += ",dns_bypass_ip6 = :dns_bypass_ip6"
	sqlString += ",dns_bypass_ttl = :dns_bypass_ttl"
	sqlString += ",org_server_fqdn = :org_server_fqdn"
	sqlString += ",type = :type"
	sqlString += ",profile = :profile"
	sqlString += ",cdn = :cdn"
	sqlString += ",ccr_dns_ttl = :ccr_dns_ttl"
	sqlString += ",global_max_mbps = :global_max_mbps"
	sqlString += ",global_max_tps = :global_max_tps"
	sqlString += ",long_desc = :long_desc"
	sqlString += ",long_desc_1 = :long_desc_1"
	sqlString += ",long_desc_2 = :long_desc_2"
	sqlString += ",max_dns_answers = :max_dns_answers"
	sqlString += ",info_url = :info_url"
	sqlString += ",miss_lat = :miss_lat"
	sqlString += ",miss_long = :miss_long"
	sqlString += ",check_path = :check_path"
	sqlString += ",last_updated = :last_updated"
	sqlString += ",protocol = :protocol"
	sqlString += ",ssl_key_version = :ssl_key_version"
	sqlString += ",ipv6_routing_enabled = :ipv6_routing_enabled"
	sqlString += ",range_request_handling = :range_request_handling"
	sqlString += ",edge_header_rewrite = :edge_header_rewrite"
	sqlString += ",origin_shield = :origin_shield"
	sqlString += ",mid_header_rewrite = :mid_header_rewrite"
	sqlString += ",regex_remap = :regex_remap"
	sqlString += ",cacheurl = :cacheurl"
	sqlString += ",remap_text = :remap_text"
	sqlString += ",multi_site_origin = :multi_site_origin"
	sqlString += ",display_name = :display_name"
	sqlString += ",tr_response_headers = :tr_response_headers"
	sqlString += ",initial_dispersion = :initial_dispersion"
	sqlString += ",dns_bypass_cname = :dns_bypass_cname"
	sqlString += ",tr_request_headers = :tr_request_headers"
	sqlString += " WHERE id=:id"
	result, err := db.NamedExec(sqlString, v)
	if err != nil {
		log.Println(err)
		return nil, err
	}
	return result, err
}
Пример #10
0
func contentServersSection(cdnName string, ccrDomain string, db *sqlx.DB) (map[string]ContentServer, error) {
	csQuery := "select * from content_servers where cdn='" + cdnName + "'"
	cServers := []CrContentServer{}
	err := db.Select(&cServers, csQuery)
	if err != nil {
		log.Println(err)
		err = fmt.Errorf("contentServersSection error selecting content_servers: %v", err)
		return nil, err
	}
	dsServerQuery := "select * from cr_deliveryservice_server"
	dsServers := []CrDeliveryserviceServer{}
	err = db.Select(&dsServers, dsServerQuery)
	if err != nil {
		log.Println("ERROR: >> ", err)
		err = fmt.Errorf("contentServersSection error selecting cr_deliveryservice_server: %v", err)
		return nil, err
	}
	dsMap := make(map[string]ContentServerDsMap)
	for _, row := range dsServers {
		if dsMap[row.ServerName] == nil {
			dsMap[row.ServerName] = make(ContentServerDsMap)
		}
		// if dsMap[row.ServerName][row.Name] == nil {
		// 	dsMap[row.ServerName][row.Name] = make(ContentServerDomainList, 0, 10)
		// }
		pattern := row.Pattern
		if strings.HasSuffix(pattern, "\\..*") {
			pattern = strings.Replace(pattern, ".*\\.", "", 1)
			pattern = strings.Replace(pattern, "\\..*", "", 1)
			if strings.HasPrefix(row.DsType, "HTTP") {
				pattern = row.ServerName + "." + pattern + "." + ccrDomain
			} else {
				pattern = "edge." + pattern + "." + ccrDomain
			}
		}
		dsMap[row.ServerName][row.Name] = append(dsMap[row.ServerName][row.Name], pattern)
	}

	retMap := make(map[string]ContentServer)
	for _, row := range cServers {
		hCount, _ := strconv.Atoi(row.HashCount)
		hCount = hCount * 1000 // TODO JvD
		retMap[row.HostName] = ContentServer{
			Fqdn:             row.Fqdn,
			HashCount:        hCount,
			HashID:           row.HostName,
			InterfaceName:    row.InterfaceName,
			IP:               row.Ip,
			IP6:              row.Ip6,
			LocationID:       row.CacheGroup,
			Port:             row.Port,
			Profile:          row.Profile,
			Status:           row.Status,
			Type:             row.Status,
			DeliveryServices: dsMap[row.HostName],
		}
	}

	return retMap, nil
}
Пример #11
0
func newRepository(db *sqlx.DB) (*repository, error) {
	r := repository{db: db}

	stmts := map[string]**sqlx.NamedStmt{
		findMood:       &r.findMood,
		setMood:        &r.setMood,
		deleteMood:     &r.deleteMood,
		insertConvo:    &r.insertConvo,
		getConvo:       &r.getConvo,
		deleteConvo:    &r.deleteConvo,
		findConvoLines: &r.findConvoLines,
		insertLine:     &r.insertLine,
		getLine:        &r.getLine,
		deleteLine:     &r.deleteLine,

		fmt.Sprintf(listConvos, ">", "ASC"):  &r.listConvosAsc,
		fmt.Sprintf(listConvos, "<", "DESC"): &r.listConvosDesc,
		fmt.Sprintf(listMoods, ">", "ASC"):   &r.listMoodsAsc,
		fmt.Sprintf(listMoods, "<", "DESC"):  &r.listMoodsDesc,
	}

	for sqlStr, stmt := range stmts {
		prepped, err := db.PrepareNamed(sqlStr)
		*stmt = prepped
		if err != nil {
			return nil, errors.Annotatef(err, "preparing statement %s", sqlStr)
		}
		r.closers = append(r.closers, prepped)
	}

	return &r, nil
}
Пример #12
0
func validateMasterPassword(db *sqlx.DB) {
	c := dbConfig{}

	db.Get(&c, "SELECT `key`, `value` FROM `config` WHERE `key` = 'teststring'")

	if c.Key == "" {
		panic("Could not read the teststring from the config table. Your database is broken.")
	}

	// not yet initialized, so store the ciphertext
	if len(c.Value) == 0 {
		ciphertext, err := Encrypt([]byte(TestString))
		if err != nil {
			panic(err)
		}

		_, err = db.Exec("UPDATE `config` SET `value` = ? WHERE `key` = ?", ciphertext, c.Key)
		if err != nil {
			panic("Could not write initial password marker: " + err.Error())
		}
	} else {
		plaintext, err := Decrypt(c.Value)
		if err != nil {
			panic("The configured password is not usable for the configured database.")
		}

		// this should never happen: a wrong password should always yield an error in Decrypt()
		if TestString != string(plaintext) {
			panic("The configured password is not usable for the configured database.")
		}
	}
}
Пример #13
0
// savePeopleContext records contextual information about people being
// discussed, enabling Abot to replace things like "him", "her", or "they" with
// the names the pronouns represent.
func savePeopleContext(db *sqlx.DB, in *dt.Msg) error {
	if len(in.StructuredInput.People) == 0 {
		return nil
	}
	byt, err := json.Marshal(in.StructuredInput.People)
	if err != nil {
		return err
	}
	if in.User.ID > 0 {
		q := `INSERT INTO states (key, value, userid, pluginname)
		      VALUES ($1, $2, $3, '')
		      ON CONFLICT (userid, pluginname, key)
		      DO UPDATE SET value=$2`
		_, err = db.Exec(q, keyContextPeople, byt, in.User.ID)
	} else {
		q := `INSERT INTO states
		      (key, value, flexid, flexidtype, pluginname)
		      VALUES ($1, $2, $3, $4, '')
		      ON CONFLICT (flexid, flexidtype, pluginname, key)
		      DO UPDATE SET value=$2`
		_, err = db.Exec(q, keyContextPeople, byt, in.User.FlexID,
			in.User.FlexIDType)
	}
	if err != nil {
		return err
	}
	return nil
}
Пример #14
0
// addTimeContext adds a time context to a Message if the word "then" is found.
func addTimeContext(db *sqlx.DB, in *dt.Msg) error {
	var addContext bool
	for _, stem := range in.Stems {
		if stem == "then" {
			addContext = true
			break
		}
	}
	if !addContext {
		return nil
	}
	var byt []byte
	var err error
	if in.User.ID > 0 {
		q := `SELECT value FROM states WHERE userid=$1 AND key=$2`
		err = db.Get(&byt, q, in.User.ID, keyContextTime)
	} else {
		q := `SELECT value FROM states
		      WHERE flexid=$1 AND flexidtype=$2 AND key=$3`
		err = db.Get(&byt, q, in.User.FlexID, in.User.FlexIDType,
			keyContextTime)
	}
	if err == sql.ErrNoRows {
		return nil
	}
	if err != nil {
		return err
	}
	var times []time.Time
	if err = json.Unmarshal(byt, &times); err != nil {
		return err
	}
	in.StructuredInput.Times = times
	return nil
}
Пример #15
0
// @Title putToExtension
// @Description modify an existing to_extensionentry
// @Accept  application/json
// @Param   id              path    int     true        "The row id"
// @Param                 Body body     ToExtension   true "ToExtension object that should be added to the table"
// @Success 200 {object}    output_format.ApiWrapper
// @Resource /api/2.0
// @Router /api/2.0/to_extension/{id}  [put]
func putToExtension(id int, payload []byte, db *sqlx.DB) (interface{}, error) {
	var v ToExtension
	err := json.Unmarshal(payload, &v)
	v.Id = int64(id) // overwrite the id in the payload
	if err != nil {
		log.Println(err)
		return nil, err
	}
	v.LastUpdated = time.Now()
	sqlString := "UPDATE to_extension SET "
	sqlString += "name = :name"
	sqlString += ",version = :version"
	sqlString += ",info_url = :info_url"
	sqlString += ",script_file = :script_file"
	sqlString += ",isactive = :isactive"
	sqlString += ",additional_config_json = :additional_config_json"
	sqlString += ",description = :description"
	sqlString += ",servercheck_short_name = :servercheck_short_name"
	sqlString += ",servercheck_column_name = :servercheck_column_name"
	sqlString += ",type = :type"
	sqlString += ",last_updated = :last_updated"
	sqlString += " WHERE id=:id"
	result, err := db.NamedExec(sqlString, v)
	if err != nil {
		log.Println(err)
		return nil, err
	}
	return result, err
}
Пример #16
0
func GetHero() ([]modal.Modal, error) {
	var db *sqlx.DB
	var err error
	var heroes []modal.Modal

	if db, err = sqlx.Open("mysql", user+":"+password+"@/Dota?parseTime=true"); err != nil {
		return heroes, err
	}
	defer db.Close()

	rows, err := db.Queryx("select * from Hero")
	if err != nil {
		return heroes, err
	}

	for rows.Next() {
		var hero modal.Hero

		err = rows.StructScan(&hero)
		if err != nil {
			return heroes, err
		}

		heroes = append(heroes, hero)
	}
	return heroes, nil
}
Пример #17
0
// @Title putExtensions
// @Description modify an existing extensionsentry
// @Accept  application/json
// @Param   id              path    int     true        "The row id"
// @Param                 Body body     Extensions   true "Extensions object that should be added to the table"
// @Success 200 {object}    output_format.ApiWrapper
// @Resource /api/2.0
// @Router /api/2.0/extensions/{id}  [put]
func putExtension(name string, payload []byte, db *sqlx.DB) (interface{}, error) {
	var arg Extensions
	err := json.Unmarshal(payload, &arg)
	arg.Name = name
	if err != nil {
		log.Println(err)
		return nil, err
	}
	sqlString := "UPDATE extensions SET "
	sqlString += "name = :name"
	sqlString += ",short_name = :short_name"
	sqlString += ",description = :description"
	sqlString += ",version = :version"
	sqlString += ",info_url = :info_url"
	sqlString += ",script_file = :script_file"
	sqlString += ",active = :active"
	sqlString += ",additional_config_json = :additional_config_json"
	sqlString += ",type = :type"
	sqlString += ",created_at = :created_at"
	sqlString += " WHERE name=:name"
	result, err := db.NamedExec(sqlString, arg)
	if err != nil {
		log.Println(err)
		return nil, err
	}
	return result, err
}
Пример #18
0
// @Title putStaticdnsentries
// @Description modify an existing staticdnsentriesentry
// @Accept  application/json
// @Param   id              path    int     true        "The row id"
// @Param                 Body body     Staticdnsentries   true "Staticdnsentries object that should be added to the table"
// @Success 200 {object}    output_format.ApiWrapper
// @Resource /api/2.0
// @Router /api/2.0/staticdnsentries/{id}  [put]
func putStaticdnsentry(id int64, payload []byte, db *sqlx.DB) (interface{}, error) {
	var arg Staticdnsentries
	err := json.Unmarshal(payload, &arg)
	arg.Id = id
	if err != nil {
		log.Println(err)
		return nil, err
	}
	sqlString := "UPDATE staticdnsentries SET "
	sqlString += "name = :name"
	sqlString += ",type = :type"
	sqlString += ",class = :class"
	sqlString += ",ttl = :ttl"
	sqlString += ",rdata = :rdata"
	sqlString += ",deliveryservice = :deliveryservice"
	sqlString += ",cachegroup = :cachegroup"
	sqlString += ",created_at = :created_at"
	sqlString += " WHERE id=:id"
	result, err := db.NamedExec(sqlString, arg)
	if err != nil {
		log.Println(err)
		return nil, err
	}
	return result, err
}
Пример #19
0
func search(db *sqlx.DB, query string) ([]person, error) {
	people := []person{}
	tokens := strings.Split(query, " ")
	cryptoTokens := []string{}

	for _, token := range tokens {
		token = strings.TrimSpace(strings.ToLower(token))
		crypted := fmt.Sprintf("%x", sha256.Sum256([]byte(token)))
		cryptoTokens = append(cryptoTokens, crypted)
	}

	q, args, err := sqlx.In(`SELECT DISTINCT p.id, p.name
                                 FROM people p 
                                 JOIN hashes_people hp ON hp.person_id = p.id
                                 JOIN hashes h ON h.id = hp.hash_id AND h.hash IN (?)
                             GROUP BY p.name`, cryptoTokens)

	if err != nil {
		return people, err
	}

	err = db.Select(&people, q, args...)

	if err != nil {
		return people, err
	}

	return people, err
}
Пример #20
0
// @Title postStaticdnsentries
// @Description enter a new staticdnsentries
// @Accept  application/json
// @Param                 Body body     Staticdnsentries   true "Staticdnsentries object that should be added to the table"
// @Success 200 {object}    output_format.ApiWrapper
// @Resource /api/2.0
// @Router /api/2.0/staticdnsentries [post]
func postStaticdnsentry(payload []byte, db *sqlx.DB) (interface{}, error) {
	var v Staticdnsentries
	err := json.Unmarshal(payload, &v)
	if err != nil {
		log.Println(err)
		return nil, err
	}
	sqlString := "INSERT INTO staticdnsentries("
	sqlString += "name"
	sqlString += ",type"
	sqlString += ",class"
	sqlString += ",ttl"
	sqlString += ",rdata"
	sqlString += ",deliveryservice"
	sqlString += ",cachegroup"
	sqlString += ",created_at"
	sqlString += ") VALUES ("
	sqlString += ":name"
	sqlString += ",:type"
	sqlString += ",:class"
	sqlString += ",:ttl"
	sqlString += ",:rdata"
	sqlString += ",:deliveryservice"
	sqlString += ",:cachegroup"
	sqlString += ",:created_at"
	sqlString += ")"
	result, err := db.NamedExec(sqlString, v)
	if err != nil {
		log.Println(err)
		return nil, err
	}
	return result, err
}
Пример #21
0
// CreateNode creates the given Node.
func CreateNode(db *sqlx.DB, n models.Node) error {
	if n.RXDelay > 15 {
		return errors.New("max value of RXDelay is 15")
	}

	_, err := db.Exec(`
		insert into node (
			dev_eui,
			app_eui,
			app_key,
			rx_delay,
			rx1_dr_offset,
			channel_list_id
		)
		values ($1, $2, $3, $4, $5, $6)`,
		n.DevEUI[:],
		n.AppEUI[:],
		n.AppKey[:],
		n.RXDelay,
		n.RX1DROffset,
		n.ChannelListID,
	)
	if err != nil {
		return fmt.Errorf("create node %s error: %s", n.DevEUI, err)
	}
	log.WithField("dev_eui", n.DevEUI).Info("node created")
	return nil
}
Пример #22
0
func POST_application(rw http.ResponseWriter, r *http.Request, identity *data.Identity,
	render render.Render, db *sqlx.DB) {
	var (
		tx      = db.MustBegin()
		success bool
	)

	defer func() {
		if success {
			tx.Commit()
		} else {
			tx.Rollback()
		}
	}()

	err := r.ParseForm()
	if err != nil {
		panic(err)
	}

	err = data.CreateApplication(tx, &data.Application{
		OwnerId:     identity.Id,
		Name:        r.PostForm.Get("application[name]"),
		RedirectURI: r.PostForm.Get("application[redirect_uri]"),
	})
	if err != nil {
		panic(err)
	}

	success = true
	http.Redirect(rw, r, "/", http.StatusFound)
}
Пример #23
0
func GET_profile(rw http.ResponseWriter, r *http.Request, identity *data.Identity,
	render render.Render, db *sqlx.DB) {
	var (
		tx      = db.MustBegin()
		success bool
		page    struct {
			Accounts          []*data.Account
			OwnedApplications []*data.Application
		}
	)

	defer func() {
		if success {
			tx.Commit()
		} else {
			tx.Rollback()
		}
	}()

	accounts, err := data.GetAccountsWithIdentityId(tx, identity.Id)
	if err != nil {
		panic(err)
	}

	owned_applications, err := data.GetApplicationsOwnedByIdentity(tx, identity.Id)
	if err != nil {
		panic(err)
	}

	page.Accounts = accounts
	page.OwnedApplications = owned_applications
	render.HTML(200, "profile", &page)
}
Пример #24
0
// Update a message as needing training.
func (m *Msg) Update(db *sqlx.DB) error {
	q := `UPDATE messages SET needstraining=$1 WHERE id=$2`
	if _, err := db.Exec(q, m.NeedsTraining, m.ID); err != nil {
		return err
	}
	return nil
}
Пример #25
0
// @Title postLog
// @Description enter a new log
// @Accept  application/json
// @Param                 Body body     Log   true "Log object that should be added to the table"
// @Success 200 {object}    output_format.ApiWrapper
// @Resource /api/2.0
// @Router /api/2.0/log [post]
func postLog(payload []byte, db *sqlx.DB) (interface{}, error) {
	var v Log
	err := json.Unmarshal(payload, &v)
	if err != nil {
		log.Println(err)
		return nil, err
	}
	sqlString := "INSERT INTO log("
	sqlString += "level"
	sqlString += ",message"
	sqlString += ",username"
	sqlString += ",ticketnum"
	sqlString += ",created_at"
	sqlString += ") VALUES ("
	sqlString += ":level"
	sqlString += ",:message"
	sqlString += ",:username"
	sqlString += ",:ticketnum"
	sqlString += ",:created_at"
	sqlString += ")"
	result, err := db.NamedExec(sqlString, v)
	if err != nil {
		log.Println(err)
		return nil, err
	}
	return result, err
}
func fetchConnections(db *sqlx.DB) (map[string]interface{}, error) {
	rows, err := db.Query(`
		select count(*), waiting from pg_stat_activity group by waiting
	`)
	if err != nil {
		logger.Errorf("Failed to select pg_stat_activity. %s", err)
		return nil, err
	}

	var totalActive, totalWaiting float64
	for rows.Next() {
		var count float64
		var waiting string
		if err := rows.Scan(&count, &waiting); err != nil {
			logger.Warningf("Failed to scan %s", err)
			continue
		}
		if waiting != "" {
			totalActive += count
		} else {
			totalWaiting += count
		}
	}

	return map[string]interface{}{
		"active":  totalActive,
		"waiting": totalWaiting,
	}, nil
}
Пример #27
0
// @Title postUsers
// @Description enter a new users
// @Accept  application/json
// @Param                 Body body     Users   true "Users object that should be added to the table"
// @Success 200 {object}    output_format.ApiWrapper
// @Resource /api/2.0
// @Router /api/2.0/users [post]
func postUser(payload []byte, db *sqlx.DB) (interface{}, error) {
	var v Users
	err := json.Unmarshal(payload, &v)
	if err != nil {
		log.Println(err)
		return nil, err
	}
	sqlString := "INSERT INTO users("
	sqlString += "username"
	sqlString += ",role"
	sqlString += ",email"
	sqlString += ",full_name"
	sqlString += ",ssh_pub_key"
	sqlString += ",local_password"
	sqlString += ",created_at"
	sqlString += ") VALUES ("
	sqlString += ":username"
	sqlString += ",:role"
	sqlString += ",:email"
	sqlString += ",:full_name"
	sqlString += ",:ssh_pub_key"
	sqlString += ",:local_password"
	sqlString += ",:created_at"
	sqlString += ")"
	result, err := db.NamedExec(sqlString, v)
	if err != nil {
		log.Println(err)
		return nil, err
	}
	return result, err
}
Пример #28
0
func KillThreads(db *sqlx.DB) {
	var ids []int
	db.Select(&ids, "SELECT Id FROM information_schema.PROCESSLIST WHERE Command != 'binlog dump' AND User != 'system user' AND Id != CONNECTION_ID()")
	for _, id := range ids {
		db.Exec("KILL ?", id)
	}
}
Пример #29
0
func GetLeague() ([]modal.Modal, error) {
	var db *sqlx.DB
	var err error
	var leagues []modal.Modal

	if db, err = sqlx.Open("mysql", user+":"+password+"@/Dota?parseTime=true"); err != nil {
		return leagues, err
	}
	defer db.Close()

	// find league where deleted is 0000-00-00 00:00:00
	rows, err := db.Queryx("select * from League where deleted = ?", deletedTime)
	if err != nil {
		return leagues, err
	}

	for rows.Next() {
		var league modal.League

		err = rows.StructScan(&league)
		if err != nil {
			return leagues, err
		}

		leagues = append(leagues, league)
	}
	return leagues, nil
}
Пример #30
-7
func getSingleFact(db *sqlx.DB, fact string) (*factoid, error) {
	var f factoid
	var tmpCreated int64
	var tmpAccessed int64
	err := db.QueryRow(`select
			id,
			fact,
			tidbit,
			verb,
			owner,
			created,
			accessed,
			count
		from factoid
		where fact like ?
		order by random() limit 1;`,
		fact).Scan(
		&f.id,
		&f.Fact,
		&f.Tidbit,
		&f.Verb,
		&f.Owner,
		&tmpCreated,
		&tmpAccessed,
		&f.Count,
	)
	f.created = time.Unix(tmpCreated, 0)
	f.accessed = time.Unix(tmpAccessed, 0)
	return &f, err
}