I have a Golang User struct with PasswordHash of type *[]byte
type User struct {
ID UserID `json:"id,omitempty" db:"u_user_id"`
PasswordHash *[]byte `json:"-" db:"u_password_hash"`
CreatedAt *time.Time `json:"-" db:"u_created_at"`
}
When i try to insert data as shown below
user := &User{
ID: id,
PasswordHash: &hashedPassword,
}
var result *model.User
rows, err := db.NamedQuery(createUserQuery, user)
if err != nil {
panic(err)
}
i get an Operational error:
panic: Operational error: 42000!Conversion of string '$2a$10$sODoBKGZtXzQziSDzFGJKuxZ0cSiNN38ZqD4YtmoLsWOa7K0bVXWW' to blob failed
is it that i have a wrong database type because my MonetDb type for the password column is blob
Can you open a bug report at https://github.com/MonetDB/MonetDB-Go with a specific reproducible example? I was not able to reproduce the problem.
Related
I am fetching some data from MYSQL database.. Using query data is getting correclty (eg 10 rows)
I want to bind into a list of model for displaying.
But panic error displaying
type UserDetails []UserDetail
type UserDetail struct {
id string `json:"id" boil:",bind"`
ScreenName string `json:"screenName" boil:",bind" `
}
func (m *mysqlStore) GetUsersDetails(ctx context.Context) () {
var userDetails []*models.UserDetail
err := queries.Raw(`
SELECT
user.id,
user.screen_name
FROM user
group by user.id
`).Bind(ctx, m.db, &userDetails)
if err != nil {
fmt.Println(err)
}
fmt.Println(userDetails)
}
here using the MYSQLQuery i am getting the correct data. I want to display that in a list of arrary eg:
[
{"id":"1",
"screenName":"test"},
{"id":"2",
"screenName":"test"}
]
what is the issue in my go code?
I got the Answer
In this case struct must be
type UserDetail struct {
id string `json:"id"`
ScreenName string `json:"screenName"`
}
and
var userDetails []models.UserDetail
Cassandra table and UDT
CREATE TYPE IF NOT EXISTS phone_type(
code TEXT,
phone TEXT,
);
CREATE TABLE IF NOT EXISTS user_by_phone(
user_id UUID,
phone FROZEN<phone_type>,
password TEXT,
PRIMARY KEY (phone)
);
golang struct
type PhoneType struct {
Code string `json:"code"`
Phone string `json:"phone"`
}
phone := PhoneType{
Code: "+1",
Phone: "7777777777",
}
gqcql query
err := Session.Query("SELECT user_id, password FROM user_by_phone WHERE phone=?;", phone).Scan(
&user.UserID,
&user.Password,
)
With this code it returns not found eventhough have a record in cassandra table.
How to query by UDT using gocql?
Try defining your struct like this (use cql instead of json in your struct definition)
type PhoneType struct {
Code string `cql:"code"`
Phone string `cql:"phone"`
}
phone := PhoneType{
Code: "+1",
Phone: "7777777777",
}
as per the example here:
https://github.com/gocql/gocql/blob/master/udt_test.go
This then worked for me:
var id gocql.UUID
var password string
iter := session.Query("SELECT user_id, password FROM user_by_phone WHERE phone=?;", phone).Iter()
for iter.Scan(&id, &password) {
fmt.Println("Phone Record:", id, password)
}
if err := iter.Close(); err != nil {
log.Fatal(err)
}
I am learning golang with gqlgen and gorm as orm, I am creating an app using with 2 models user and messages where the user has a list of messages,
and the messages have sender and recipient.
I have made them like the following
type User struct {
ID string `json:"id" gorm:"primary_key;type:uuid;default:uuid_generate_v4()"`
Username string `json:"username"`
Email string `json:"email"`
FirstName string `json:"firstName"`
LastName string `json:"lastName"`
Messages []*Message `json:"messages"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
DeletedAt *time.Time `json:"deleted_at" sql:"index"`
}
type Message struct {
ID string `json:"id" gorm:"primary_key;type:serial"`
Title string `json:"title"`
Body string `json:"body"`
DueDate time.Time `json:"dueDate"`
IsViewed bool `json:"isViewed" gorm:"default:false"`
SenderID string `json:"senderId" gorm:"type:uuid"`
Sender *User `json:"sender" gorm:"foreignkey:SenderID"`
RecipientID string `json:"recipientId" gorm:"type:uuid"`
Recipient *User `json:"recipient" gorm:"foreignkey:RecipientID"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
DeletedAt *time.Time `json:"deleted_at" sql:"index"`
}
when I retrieve the messages data using Preload
var messages []*models.Message
err := db.
Preload("Sender").
Preload("Recipient").
Find(&messages).Error
if err != nil {
return nil, err
}
return messages, err
it works perfectly but my problem is when trying to retrieve the user with the messages preloaded.
var users []*models.User
err := db.
Preload("Messages").
Find(&users).Error
if err != nil {
return nil, err
}
return users, err
this one gives me the following error can't preload field Messages for models.User
I know I might design my schema wrong if there's a better way to organize it I would appreciate it so much, thanks in advance.
I think you should separate messages in User to SentMessages and ReceivedMessages. Then you can specify foreign keys in User like that:
SentMessages []*Message `gorm:"foreignkey:SenderID" json:"sentMessages"`
ReceivedMessages []*Message `gorm:"foreignkey:RecipientID" json:"receivedMessages"`
then use it as the following:
var users []*models.User
err := db.
Preload("SentMessages").
Preload("ReceivedMessages").
Find(&users).Error
if err != nil {
return nil, err
}
return users, err
that should work as you want
I think you've to take a closer look on how the association are made(actually create from the official gorm package) like (&Model{}).Create(target).Association("Column").Append(&related_instance)
So when you'll retry it using Preload everything gone be Ok. And BTW it work with your current design. Hope it helps.
Getting an error while inserting a slice into Redis database using redix.v3. What's redis command to insert a slice? SET or HMSET?
My code:
type Domain struct {
ID string `json:"ID,omitempty"`
ParentID string `json:"parentID,omitempty"`
ParentType string `json:"parentType,omitempty"`
Owner string `json:"owner,omitempty"`
PATEnabled string `json:"PATEnabled,omitempty"`
Name string `json:"name,omitempty"`
}
for _, domain := range domains {
if err := client.Do(radix.FlatCmd(nil, "HMSET", domain.ID, domain)); err != nil {
log.Println(err)
}
Error message:
could not marshal value of type Domain
I'm trying to write an API that will do different things with the data depending on its purpose.
API results - The API should expose certain fields to the user
Validation - Validation should handle different schemas e.g. login form doesn't require Name, but register does
Database - The database should save everything, including password etc. - if I try using the same struct for the API and DB with json:"-" or un-exporting the field the database save also ignores the field
Some sample code is below with a couple of comments in capitals to show where I ideally need to type cast to change the data. As they are different structs, they cannot be type cast, so I get an error. How can I fix this?
Alternatively, what is a better way of doing different things with the data without having lots of similar structs?
// IDValidation for uuids
type IDValidation struct {
ID string `json:"id" validate:"required,uuid"`
}
// RegisterValidation for register form
type RegisterValidation struct {
Name string `json:"name" validate:"required"`
Email string `json:"email" validate:"required,email"`
Password string `json:"password" validate:"required,min=8"`
}
// UserModel to save in DB
type UserModel struct {
ID string `json:"id,omitempty"`
Name string `json:"name"`
Email string `json:"email"`
Password string `json:"password,omitempty"`
Active bool `json:"active,omitempty"`
CreatedAt int64 `json:"created_at,omitempty"`
UpdatedAt int64 `json:"updated_at,omitempty"`
jwt.StandardClaims
}
// UserAPI data to display to user
type UserAPI struct {
ID string `json:"id,omitempty"`
Name string `json:"name"`
Email string `json:"email"`
Active bool `json:"active,omitempty"`
}
// register a user
func register(c echo.Context) error {
u := new(UserModel)
if err := c.Bind(u); err != nil {
return err
}
// NEED TO CAST TO RegisterValidation HERE?
if err := c.Validate(u); err != nil {
return err
}
token, err := u.Register()
if err != nil {
return err
}
return c.JSON(http.StatusOK, lib.JSON{"token": token})
}
// retrieve a user
func retrieve(c echo.Context) error {
u := IDValidation{
ID: c.Param("id"),
}
if err := c.Validate(u); err != nil {
return echo.NewHTTPError(http.StatusBadRequest, err.Error())
}
// NEED TO CAST USER TO UserAPI?
user, err := userModel.GetByID(u.ID)
if err != nil {
return err
}
return c.JSON(200, lib.JSON{"message": "User found", "user": user})
}