Golang – How to create helper mysql to generate uuid / uuid_short without create new connection? Here's the code

huangapple go评论84阅读模式
英文:

Golang - How to create helper mysql to generate uuid / uuid_short without create new connection? Here's the code

问题

我正在尝试生成UUID_SHORT()作为ID。我不想使用触发器,而是先获取UUID_SHORT(),然后将其插入作为ID。但是,我对如何创建GetUUID()函数作为辅助函数感到困惑。

根据下面的代码,它总是在生成UUID_SHORT()之前设置新连接,这意味着将会有很多连接只是为了生成UUID_SHORT()。

如何在不创建新连接的情况下创建func GetUUID()

以下是代码:

package database

import (
	"database/sql"
	"fmt"
	"log"
	"os"
	"time"

	_ "github.com/go-sql-driver/mysql"
)

type connection struct {
	sqlDB *sql.DB
}

func NewMysqlConnection(databaseConnection *sql.DB) *connection {
	return &connection{databaseConnection}
}

func SetupMysqlDatabaseConnection() (db *sql.DB) {
	var (
		driver   = os.Getenv("DB_DRIVERNAME")
		username = os.Getenv("DB_USERNAME")
		password = os.Getenv("DB_PASSWORD")
		host     = os.Getenv("DB_HOST")
		port     = os.Getenv("DB_PORT")
		name     = os.Getenv("DB_NAME")
	)

	connection := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?parseTime=true", username, password, host, port, name)

	db, err := sql.Open(driver, connection)

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

	db.SetMaxOpenConns(100)
	db.SetMaxIdleConns(100)
	db.SetConnMaxLifetime(100 * time.Millisecond)

	return
}

func (c *connection) GenerateUUID() (uuid uint64, err error) {
	uuid = 0

	queryGetUUID := c.sqlDB.QueryRow(`SELECT UUID_SHORT()`)

	err = queryGetUUID.Scan(
		&uuid,
	)

	return
}

func GetUUID() (uuid uint64, err error) {
	mysql := SetupMysqlDatabaseConnection()
	db := NewMysqlConnection(mysql)

	uuid, err = db.GenerateUUID()

	return
}

请注意,我只翻译了代码部分,其他内容不包括在内。

英文:

I'm trying to generate UUID_SHORT() to be an ID. Instead of using trigger, I get the UUID_SHORT() first and then insert as an ID. But, I'm confusing of how to create GetUUID() function as helper.

As my code bellow, it always setup new connection before generate the UUID_SHORT() which means there will be so many connection just to generate UUID_SHORT()

How to create func GetUUID() without creating new connection?

Here's the code:

package database
import (
"database/sql"
"fmt"
"log"
"os"
"time"
_ "github.com/go-sql-driver/mysql"
)
type conncetion struct {
sqlDB *sql.DB
}
func NewMysqlConnection(databaseConnection *sql.DB) *conncetion {
return &conncetion{databaseConnection}
}
func SetupMysqlDatabaseConnection() (db *sql.DB) {
var (
driver   = os.Getenv("DB_DRIVERNAME")
username = os.Getenv("DB_USERNAME")
password = os.Getenv("DB_PASSWORD")
host     = os.Getenv("DB_HOST")
port     = os.Getenv("DB_PORT")
name     = os.Getenv("DB_NAME")
)
connection := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?parseTime=true", username, password, host, port, name)
db, err := sql.Open(driver, connection)
if err != nil {
log.Fatal(err)
}
db.SetMaxOpenConns(100)
db.SetMaxIdleConns(100)
db.SetConnMaxLifetime(100 * time.Millisecond)
return
}
func (c *conncetion) GenerateUUID() (uuid uint64, err error) {
uuid = 0
queryGetUUID := c.sqlDB.QueryRow(`SELECT UUID_SHORT()`)
err = queryGetUUID.Scan(
&uuid,
)
return
}
func GetUUID() (uuid uint64, err error) {
mysql := SetupMysqlDatabaseConnection()
db := NewMysqlConnection(mysql)
uuid, err = db.GenerateUUID()
return
}

答案1

得分: 0

全局变量的使用如何?

英文:

How about global variable ?

package database
import (
"database/sql"
"fmt"
"log"
"os"
"time"
_ "github.com/go-sql-driver/mysql"
)
type conncetion struct {
sqlDB *sql.DB
}
var globalConnection *conncetion
func GetDB() *conncetion {
return globalConnection
}
func NewMysqlConnection(databaseConnection *sql.DB) *conncetion {
return &conncetion{databaseConnection}
}
func SetupMysqlDatabaseConnection() (db *sql.DB) {
var (
driver   = os.Getenv("DB_DRIVERNAME")
username = os.Getenv("DB_USERNAME")
password = os.Getenv("DB_PASSWORD")
host     = os.Getenv("DB_HOST")
port     = os.Getenv("DB_PORT")
name     = os.Getenv("DB_NAME")
)
connection := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?parseTime=true", username, password, host, port, name)
db, err := sql.Open(driver, connection)
if err != nil {
log.Fatal(err)
}
db.SetMaxOpenConns(100)
db.SetMaxIdleConns(100)
db.SetConnMaxLifetime(100 * time.Millisecond)
return
}
func (c *conncetion) GenerateUUID() (uuid uint64, err error) {
uuid = 0
queryGetUUID := c.sqlDB.QueryRow(`SELECT UUID_SHORT()`)
err = queryGetUUID.Scan(
&uuid,
)
return
}
func GetUUID() (uuid uint64, err error) {
// mysql := SetupMysqlDatabaseConnection()
// db := NewMysqlConnection(mysql)
db = GetDB()
uuid, err = db.GenerateUUID()
return
}
// can be written on main.go / server.go
func init() {
globalConnection = NewMysqlConnection(database.SetupMysqlDatabaseConnection())
}

But I don't know it is good or not to open an idle connection and spamming request on 1 connection.

答案2

得分: 0

你正在利用数据库来为你生成UUID,只要你让数据库来做,你就需要一个连接来发送查询。

在这里,你通常有两个选择:

  1. 在插入数据时让数据库动态生成UUID。
  2. 在发送之前在你自己的代码中生成UUID。

在插入时生成ID

这意味着你需要改变操作方式,插入数据的命令应该类似于:

INSERT INTO your_table(id, value)
VALUES (
  UUID_SHORT(), 
  -- 其他值
);

这将在插入时自动生成ID,无需在之前生成。

如果你需要在插入后知道ID,你有几个选项,比如使用LAST_INSERT_ID()或查询刚刚创建的数据。

查看这个问题以获取更多信息。

在代码中生成ID

你可以使用像github.com/google/uuid这样的包。

import "github.com/google/uuid"

func GenerateUUID() (uint32, error) {
  id, err := uuid.NewRandom()
  if err != nil {
    return 0, err
  }
  return id.ID(), nil
}

注意,你也可以获得UUID的字符串表示,或者可以从uint32轻松地转换为uint64

英文:

You're leveraging the database to generated the UUID for you, as long as you're letting the DB do it you'll need a connection to send the query.

You generally have two options here:

  1. let the DB generate the UUID on the fly when inserting your data
  2. generate the UUID in your own code before sending it

Generate ID on insert

This means you need to change the way you operate, your command for inserting data will need to look something like this:

INSERT INTO your_table(id, value)
VALUES (
  UUID_SHORT(), 
  -- other values
);

This will automatically generate the ID for you during the insert, without needing to generate it before.

If you need to know the ID after the insert was performed, you have a few options, like using LAST_INSERT_ID() or querying the data you just created.

See this other question for more info.

Generate ID in code

You can use a package like github.com/google/uuid.

import "github.com/google/uuid"

func GenerateUUID() (uint32, error) {
  id, err := uuid.NewRandom()
  if err != nil {
    return 0, err
  }
  return id.ID(), nil
}

Note that you can also get a string representation for the UUID, or you can cast it to uint64 easily from uint32.

huangapple
  • 本文由 发表于 2022年1月27日 16:57:10
  • 转载请务必保留本文链接:https://go.coder-hub.com/70875730.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定