• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Golang sql.NullInt64类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Golang中database/sql.NullInt64的典型用法代码示例。如果您正苦于以下问题:Golang NullInt64类的具体用法?Golang NullInt64怎么用?Golang NullInt64使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



在下文中一共展示了NullInt64类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Golang代码示例。

示例1: TestIntOrNull

func TestIntOrNull(t *testing.T) {
	var nullInt sql.NullInt64
	var value driver.Value
	var err error

	// When the integer is zero
	nullInt = IntOrNull(0)

	// nullInt.Valid should be false
	assert.False(t, nullInt.Valid)

	// nullInt.Value() should return nil
	value, err = nullInt.Value()
	assert.Nil(t, err)
	assert.Nil(t, value)

	// When the integer is greater than zero
	nullInt = IntOrNull(1)

	// nullInt.Valid should be true
	assert.True(t, nullInt.Valid)

	// nullInt.Value() should return the integer
	value, err = nullInt.Value()
	assert.Nil(t, err)
	assert.Equal(t, int64(1), value)
}
开发者ID:kunalshah,项目名称:go-oauth2-server,代码行数:27,代码来源:util_test.go


示例2: TestPositiveIntOrNull

func TestPositiveIntOrNull(t *testing.T) {
	var (
		nullInt sql.NullInt64
		value   driver.Value
		err     error
	)

	// When the number is negative
	nullInt = PositiveIntOrNull(-1)

	// nullInt.Valid should be false
	assert.False(t, nullInt.Valid)

	// nullInt.Value() should return nil
	value, err = nullInt.Value()
	assert.Nil(t, err)
	assert.Nil(t, value)

	// When the number is greater than zero
	nullInt = PositiveIntOrNull(1)

	// nullInt.Valid should be true
	assert.True(t, nullInt.Valid)

	// nullInt.Value() should return the integer
	value, err = nullInt.Value()
	assert.Nil(t, err)
	assert.Equal(t, int64(1), value)
}
开发者ID:chenhougen,项目名称:go-oauth2-server,代码行数:29,代码来源:util_test.go


示例3: listAllConnections

func (database Database) listAllConnections() (res DbUsersWithConnections) {
	res = make(DbUsersWithConnections)

	rows, err := database.db.Query(`
		-- Left join because we want users without connections as well
		SELECT u1.id, u1.username, u2.id, u2.username FROM 
			user AS u1 LEFT JOIN connection ON u1.id = connection.fromUser
			LEFT JOIN user AS u2 ON u2.id = connection.toUser
			ORDER BY u1.id
			`)
	checkErr(err)
	defer rows.Close()
	for rows.Next() {
		var fromUser User
		var toUsername sql.NullString
		var toId sql.NullInt64
		err := rows.Scan(&fromUser.Id, &fromUser.Username, &toId, &toUsername)
		checkErr(err)

		if toId.Valid {
			// this user has at least one connection, unpack the nullable values
			toIdValue, _ := toId.Value()
			toUsernameValue, _ := toUsername.Value()
			res[fromUser] = append(res[fromUser], User{toIdValue.(int64), toUsernameValue.(string)})
		} else {
			// this user doesn't have any connections
			res[fromUser] = []User{}
		}
	}
	return res
}
开发者ID:rutchkiwi,项目名称:go-rest-api,代码行数:31,代码来源:db.go


示例4: AllAgents

func AllAgents(db *sql.DB, simid []byte, proto string) (ags []AgentInfo, err error) {
	s := `SELECT AgentId,Kind,Spec,Prototype,ParentId,EnterTime,ExitTime,Lifetime FROM
				Agents
			WHERE Agents.SimId = ?`

	var rows *sql.Rows
	if proto != "" {
		s += ` AND Agents.Prototype = ?`
		rows, err = db.Query(s, simid, proto)
	} else {
		rows, err = db.Query(s, simid)
	}
	if err != nil {
		return nil, err
	}

	for rows.Next() {
		ai := AgentInfo{}
		var exit sql.NullInt64
		if err := rows.Scan(&ai.Id, &ai.Kind, &ai.Impl, &ai.Proto, &ai.Parent, &ai.Enter, &exit, &ai.Lifetime); err != nil {
			return nil, err
		}
		if !exit.Valid {
			exit.Int64 = -1
		}
		ai.Exit = int(exit.Int64)
		ags = append(ags, ai)
	}
	if err := rows.Err(); err != nil {
		return nil, err
	}
	return ags, nil
}
开发者ID:katyhuff,项目名称:cyan,代码行数:33,代码来源:query.go


示例5: createLoginLog

func createLoginLog(succeeded bool, remoteAddr, login string, user *User) error {
	succ := 0
	if succeeded {
		succ = 1
	}

	var userId sql.NullInt64
	if user != nil {
		userId.Int64 = int64(user.ID)
		userId.Valid = true

		mu.Lock()
		if succeeded {
			resetUserFailCount(user.ID)
			resetIpFailCount(remoteAddr)
		} else {
			incrUserFailCount(user.ID)
			incrIpFailCount(remoteAddr)
		}
		mu.Unlock()
	}

	_, err := db.Exec(
		"INSERT INTO login_log (`created_at`, `user_id`, `login`, `ip`, `succeeded`) "+
			"VALUES (?,?,?,?,?)",
		time.Now(), userId, login, remoteAddr, succ,
	)

	return err
}
开发者ID:walf443,项目名称:isucon4,代码行数:30,代码来源:db.go


示例6: addPublicAccess

func addPublicAccess(app *app, houseID, html string) error {
	// Parse title of page
	title := titleReg.FindStringSubmatch(html)[1]
	if !validTitle(title) {
		// <title/> was invalid, so look for an <h1/>
		header := headerReg.FindStringSubmatch(html)[1]
		if validTitle(header) {
			// <h1/> was valid, so use that instead of <title/>
			title = header
		}
	}
	title = strings.TrimSpace(title)

	// Get thumbnail
	data := url.Values{}
	data.Set("url", fmt.Sprintf("%s/%s.html", app.cfg.HostName, houseID))

	u, err := url.ParseRequestURI("https://peeper.html.house")
	u.Path = "/"
	urlStr := fmt.Sprintf("%v", u)

	client := &http.Client{}
	r, err := http.NewRequest("POST", urlStr, bytes.NewBufferString(data.Encode()))
	if err != nil {
		fmt.Printf("Error creating request: %v", err)
	}
	r.Header.Add("Content-Type", "application/x-www-form-urlencoded")
	r.Header.Add("Content-Length", strconv.Itoa(len(data.Encode())))

	var thumbURL string
	resp, err := client.Do(r)
	if err != nil {
		fmt.Printf("Error requesting thumbnail: %v", err)
		return impart.HTTPError{http.StatusInternalServerError, "Couldn't generate thumbnail"}
	} else {
		defer resp.Body.Close()
		body, _ := ioutil.ReadAll(resp.Body)
		if resp.StatusCode == http.StatusOK {
			thumbURL = string(body)
		}
	}

	// Add to public houses table
	approved := sql.NullInt64{Valid: false}
	if app.cfg.AutoApprove {
		approved.Int64 = 1
		approved.Valid = true
	}
	_, err = app.db.Exec("INSERT INTO publichouses (house_id, title, thumb_url, added, updated, approved) VALUES (?, ?, ?, NOW(), NOW(), ?) ON DUPLICATE KEY UPDATE title = ?, updated = NOW()", houseID, title, thumbURL, approved, title)
	if err != nil {
		return err
	}

	// Tweet about it
	tweet(app, houseID, title)

	return nil
}
开发者ID:writeas,项目名称:htmlhouse,代码行数:58,代码来源:construction.go


示例7: tonullint64

func tonullint64(d *int64) sql.NullInt64 {
	var n sql.NullInt64
	n.Valid = (d != nil)
	if !n.Valid {
		return n
	}
	n.Int64 = *d
	return n
}
开发者ID:ArchieT,项目名称:3manchess,代码行数:9,代码来源:bits.go


示例8: tonullint8

func tonullint8(d *int8) sql.NullInt64 {
	var n sql.NullInt64
	n.Valid = (d != nil)
	if n.Valid {
		return n
	}
	n.Int64 = int64(*d)
	return n
}
开发者ID:ArchieT,项目名称:3manchess,代码行数:9,代码来源:bits.go


示例9: writeMessage

func (w writer) writeMessage() error {
	start := time.Now()
	defer w.stats.recordWrite(start)
	channel := fmt.Sprintf("room-%d", rand.Int31n(int32(w.numChannels)))
	message := start.String()

	// TODO(bdarnell): retry only on certain errors.
	for {
		txn, err := w.db.Begin()
		if err != nil {
			continue
		}

		// TODO(bdarnell): make this a subquery when subqueries are supported on insert.
		row := txn.QueryRow(`select max(msg_id) from fakerealtime.messages where channel=$1`, channel)
		var maxMsgID sql.NullInt64
		if err := row.Scan(&maxMsgID); err != nil {
			_ = txn.Rollback()
			continue
		}
		if !maxMsgID.Valid {
			maxMsgID.Int64 = 0
		}
		newMsgID := maxMsgID.Int64 + 1

		row = txn.QueryRow(`select max(update_id) from fakerealtime.updates`, channel)
		var maxUpdateID sql.NullInt64
		if err := row.Scan(&maxUpdateID); err != nil {
			_ = txn.Rollback()
			continue
		}
		if !maxUpdateID.Valid {
			maxUpdateID.Int64 = 0
		}
		newUpdateID := maxUpdateID.Int64 + 1

		if _, err := txn.Exec(`insert into fakerealtime.messages (channel, msg_id, message) values ($1, $2, $3)`,
			channel, newMsgID, message); err != nil {
			_ = txn.Rollback()
			continue
		}

		if _, err := txn.Exec(`insert into fakerealtime.updates (update_id, channel, msg_id) values ($1, $2, $3)`,
			newUpdateID, channel, newMsgID); err != nil {
			_ = txn.Rollback()
			continue
		}

		if err := txn.Commit(); err == nil {
			return nil
		}
	}
}
开发者ID:BramGruneir,项目名称:examples-go,代码行数:53,代码来源:main.go


示例10: checkIntForNull

func checkIntForNull(eventInt string, event *sql.NullInt64) {
	var err error

	if eventInt == "" {
		event.Valid = false
	} else {
		event.Int64, err = strconv.ParseInt(eventInt, 10, 64)
		if err != nil {
			event.Valid = false
			return
		}

		event.Valid = true
	}
}
开发者ID:Qlean,项目名称:silvia,代码行数:15,代码来源:postgres.go


示例11: preparePutTweet

func preparePutTweet(db *sql.DB) func(*twitter.Tweet) {
	putTweetStmt, err := db.Prepare(putTweetSql)
	if err != nil {
		panic(err)
	}

	return func(t *twitter.Tweet) {
		var retweetedStatusId sql.NullInt64
		if t.RetweetedStatus != nil {
			retweetedStatusId.Int64 = t.RetweetedStatus.Id
			retweetedStatusId.Valid = true
		}

		putTweetStmt.Exec(t.Id, t.Text, t.CreatedAt.Time, t.InReplyToStatusId, t.InReplyToUserId, retweetedStatusId, t.Source, t.User.Id)
	}
}
开发者ID:jcla1,项目名称:tweet_collector,代码行数:16,代码来源:tweet_collector.go


示例12: createLoginLog

func createLoginLog(succeeded bool, remoteAddr, login string, user *User) error {
	succ := 0
	if succeeded {
		succ = 1
	}

	var userId sql.NullInt64
	if user != nil {
		userId.Int64 = int64(user.ID)
		userId.Valid = true
	}

	_, err := prepareInsertLog.Exec(time.Now(), userId, login, remoteAddr, succ)

	return err
}
开发者ID:matsuu,项目名称:ansible-isucon-pass,代码行数:16,代码来源:db.go


示例13: Scan

// Scan a value into the Int64, error on nil or unparsable
func (i *Int64) Scan(value interface{}) error {
	tmp := sql.NullInt64{}
	tmp.Scan(value)

	if tmp.Valid == false {
		// TODO: maybe nil should be simply allowed to be empty int64?
		return errors.New("Value should be a int64 and not nil")
	}
	i.Int64 = tmp.Int64

	i.DoInit(func() {
		i.shadow = tmp.Int64
	})

	return nil
}
开发者ID:c2h5oh,项目名称:norm,代码行数:17,代码来源:int64.go


示例14: InsertLine

func (r *repository) InsertLine(userID, convoID string, line *Line) error {
	var publicID string

	var convo convoRec
	err := r.getConvo.Get(&convo, struct{ UserID, PublicID string }{userID, convoID})
	if err != nil {
		return errors.Trace(err)
	}

	for i := 0; i < maxInsertRetries; i++ {
		rv, err := rand.Int(rand.Reader, big.NewInt(math.MaxInt64))
		if err != nil {
			return errors.Trace(err)
		}
		publicID = lineIDPrefix + strconv.FormatUint(rv.Uint64(), 36)

		var moodID sql.NullInt64
		if line.mood.id != 0 {
			moodID.Int64 = int64(line.mood.id)
			moodID.Valid = true
		}

		_, err = r.insertLine.Exec(struct {
			PublicID, Animal, Text, MoodName string
			Think                            bool
			MoodID                           sql.NullInt64
			ConversationID                   int
		}{
			publicID, line.Animal, line.Text, line.MoodName,
			line.Think,
			moodID,
			convo.IntID,
		})
		if err == nil {
			line.ID = publicID
			return nil
		}

		dbErr, ok := err.(*pq.Error)
		if !ok || dbErr.Code != dbErrDupUnique {
			return errors.Trace(err)
		}
	}

	return errors.New("Unable to insert a new, unique line")
}
开发者ID:antifuchs,项目名称:saypi,代码行数:46,代码来源:repository.go


示例15: TestNullTypeInt64

func TestNullTypeInt64(t *testing.T) {
	var userID sql.NullInt64
	userID.Scan(nil)
	b := Eq{"user_id": userID}
	sql, args, err := b.ToSql()

	assert.NoError(t, err)
	assert.Empty(t, args)
	assert.Equal(t, "user_id IS NULL", sql)

	userID.Scan(int64(10))
	b = Eq{"user_id": userID}
	sql, args, err = b.ToSql()

	assert.NoError(t, err)
	assert.Equal(t, []interface{}{int64(10)}, args)
	assert.Equal(t, "user_id = ?", sql)
}
开发者ID:collinglass,项目名称:squirrel,代码行数:18,代码来源:expr_test.go


示例16: Scan

func (s *scanner) Scan(src interface{}) error {
	var err error

	switch s.value.Type().Kind() {
	case reflect.Struct:
		nt := mysql.NullTime{}
		err := nt.Scan(src)
		if err != nil {
			return err
		}
		s.value.Set(reflect.ValueOf(nt.Time))
	case reflect.Bool:
		nb := sql.NullBool{}
		err := nb.Scan(src)
		if err != nil {
			return err
		}
		s.value.SetBool(nb.Bool)
	case reflect.String:
		ns := sql.NullString{}
		err = ns.Scan(src)
		if err != nil {
			return err
		}
		s.value.SetString(ns.String)
	case reflect.Int64:
		ni := sql.NullInt64{}
		err = ni.Scan(src)
		if err != nil {
			return err
		}
		s.value.SetInt(ni.Int64)
	case reflect.Float64:
		ni := sql.NullFloat64{}
		err = ni.Scan(src)
		if err != nil {
			return err
		}
		s.value.SetFloat(ni.Float64)
	}
	return nil
}
开发者ID:hypertornado,项目名称:prago,代码行数:42,代码来源:struct_scanners.go


示例17: createLoginLog

func createLoginLog(succeeded bool, remoteAddr, login string, user *User) error {
	succ := 0
	if succeeded {
		succ = 1
	}

	var userId sql.NullInt64
	if user != nil {
		userId.Int64 = int64(user.ID)
		userId.Valid = true
	}

	_, err := db.Exec(
		"INSERT INTO login_log (`created_at`, `user_id`, `login`, `ip`, `succeeded`) "+
			"VALUES (?,?,?,?,?)",
		time.Now(), userId, login, remoteAddr, succ,
	)

	return err
}
开发者ID:shogo82148,项目名称:isucon4_powawa,代码行数:20,代码来源:db.go


示例18: createLoginLog

func createLoginLog(succeeded bool, remoteAddr, login string, user *User) {
	succ := 0
	if succeeded {
		succ = 1
	}

	now := time.Now()

	var userId sql.NullInt64
	if user != nil {
		userId.Int64 = int64(user.ID)
		userId.Valid = true
	}

	go func() {
		db.Exec(
			"INSERT INTO login_log (`created_at`, `user_id`, `login`, `ip`, `succeeded`) "+
				"VALUES (?,?,?,?,?)",
			now, userId, login, remoteAddr, succ,
		)
	}()

	if user != nil {
		if succeeded {
			UserIdFailures[user.ID] = 0
			IpFailtures[remoteAddr] = 0

			LastLoginHistory[user.ID] = [2]LastLogin{
				{
					Login:     login,
					IP:        remoteAddr,
					CreatedAt: now.Format("2006-01-02 15:04:05"),
				},
				LastLoginHistory[user.ID][0],
			}
		} else {
			UserIdFailures[user.ID]++
			IpFailtures[remoteAddr]++
		}
	}
}
开发者ID:gam0022,项目名称:isucon4-qualifier-practice-2,代码行数:41,代码来源:db.go


示例19: SaveThing

func (w *DatabaseWorld) SaveThing(thing *Thing) (ok bool) {
	tabletext, err := json.Marshal(thing.Table)
	if err != nil {
		log.Println("Error serializing table data for thing", thing.Id, ":", err.Error())
		return false
	}

	var parent sql.NullInt64
	if thing.Parent != 0 {
		parent.Int64 = int64(thing.Parent)
		parent.Valid = true
	}
	var owner sql.NullInt64
	if thing.Owner != 0 && thing.Type.HasOwner() {
		owner.Int64 = int64(thing.Owner)
		owner.Valid = true
	}
	var program sql.NullString
	if thing.Program != nil {
		program.String = thing.Program.Text
		program.Valid = true
	}

	// TODO: save the allow list
	_, err = w.db.Exec("UPDATE thing SET name = $1, parent = $2, owner = $3, adminlist = $4, denylist = $5, tabledata = $6, program = $7 WHERE id = $8",
		thing.Name, parent, owner, thing.AdminList, thing.DenyList,
		types.JsonText(tabletext), program, thing.Id)
	if err != nil {
		log.Println("Error saving a thing", thing.Id, ":", err.Error())
		return false
	}
	return true
}
开发者ID:natmeox,项目名称:mess,代码行数:33,代码来源:world.go


示例20: CreateThing

func (w *DatabaseWorld) CreateThing(name string, tt ThingType, creator *Thing, parent *Thing) (thing *Thing) {
	thing = NewThing()
	thing.Name = name
	thing.Type = tt
	thing.Parent = parent.Id

	var creatorId sql.NullInt64
	if creator != nil && thing.Type.HasOwner() {
		creatorId.Int64 = int64(creator.Id)
		thing.Creator = creator.Id
		thing.Owner = creator.Id
	}

	row := w.db.QueryRow("INSERT INTO thing (name, type, creator, owner, parent) VALUES ($1, $2, $3, $4, $5) RETURNING id, created",
		thing.Name, thing.Type.String(), creatorId, creatorId, thing.Parent)
	err := row.Scan(&thing.Id, &thing.Created)
	if err != nil {
		log.Println("Error creating a thing", name, ":", err.Error())
		return nil
	}

	return
}
开发者ID:natmeox,项目名称:mess,代码行数:23,代码来源:world.go



注:本文中的database/sql.NullInt64类示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Golang sql.NullString类代码示例发布时间:2022-05-24
下一篇:
Golang sql.NullFloat64类代码示例发布时间:2022-05-24
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap