Passing a map as a value to insert into Cassandra - go

I'm trying to insert a map value into my Cassandra database. I'm using Go to write my client. Currently its throwing the error "can not marshal string into map(varchar, varchar)". I understand what the error is, but I can't resolve it. Here is the code that I've written.
if err := session.Query("INSERT INTO emergency_records
(mapColumn)
VALUES (?)",
"{'key' : 'value'}").Exec();
err != nil {
log.Fatal(err)
}
What I don't get is that I've written one query as a whole unbroken string and it works fine without throwing this error. Yet breaking it down with the question mark it throws the error. I know this is something simple that I'm just overlooking and couldn't find in the documentation, but any help would be great thanks.

I haven't used Go casandra client before but I guess passing map as a map instead of string should work:
mapValue := map[string]string{"key": "value"}
if err := session.Query("INSERT INTO emergency_records (mapColumn) VALUES (?)", mapValue).Exec(); err != nil {
log.Fatal(err)
}

Related

What is privatekey in oracle objectstorage?

c, clerr := objectstorage.NewObjectStorageClientWithConfigurationProvider(common.NewRawConfigurationProvider(
"ocid1.tenancy.oc1..aaaaaaa5jo3pz1alm1o45rzx1ucaab4njxbwaqqbc7ld3l6biayjaert5la",
"ocid1.user.oc1..aaaaaaaauax5bo2gg3az46h53467u57ue86rk9h2wax8w7zzamxgwvsi34ja",
"ap-seoul-1",
"98:bc:6b:13:c1:64:ds:8b:9c:15:11:d2:8d:e5:92:db",
))
I'm trying to use oracle object storage, I checked the official manual, but there is something I don't understand. As above, I need the privateKey, and pricateKeyPassphrase arguments, but I don't know where to get them. Is there a detailed explanation or example?
What i want, is to upload a file to storage.
Where can I go to the page in the oracle console to get the keys I need? please give me some advice
config, err := common.ConfigurationProviderFromFile("./config", "")
if err != nil {
t.Error(err.Error())
}
c, err := objectstorage.NewObjectStorageClientWithConfigurationProvider(config)
if err != nil {
t.Error(err.Error())
}
https://cloud.oracle.com/identity/domains/my-profile/api-keys
I generated a key on this page, put it in my project, and with the above code I was able to get started without any problems.

How to handle postgres query error with pgx driver in golang?

I read this official guide about error handling
i applied it
err := db.connection.QueryRow("INSERT INTO articles(uri) VALUES ($1)", article.URI).Scan()
if err != nil {
var pgErr *pgconn.PgError
if errors.As(err, &pgErr) {
fmt.Println(pgErr.Message) // => syntax error at end of input
fmt.Println(pgErr.Code) // => 42601
}
}
Code doesn't work, my app doens't print anything. But postgres log has ERROR: duplicate key value violates unique constraint "articles_uri_key"
Ok, i can use standart golang method:
err := db.connection.QueryRow("INSERT INTO articles(uri) VALUES ($1)", article.URI).Scan()
if err != nil {
fmt.Println(err)
}
One problem, it prints no rows in result set when no errors in postgres log.
I tried replace
if err != nil with if err != errors.New("no rows in result set"),
it still prints no rows in result set
Use pgx.ErrNoRows
if err != pgx.ErrNoRows {
fmt.Println(err)
}
Please modify your question and make it appropriate.
Duplicate key value is a valid error. If you want to remove the error either you should avoid duplicate entry or remove unique constraint from it.
Using pgx with database/sql, pgx is simply acting as driver.The sql.ErrNoRows error is being returned from the database/sql library. pgx.ErrNoRows is only returned when calling a pgx function directly. As database/sql will bubble up some errors from the driver.
sqlStatement := `
INSERT INTO articles (uri)
VALUES ($1)
RETURNING id`
id := 0
//make sure what type of data you want to scan you should pass it inside scan()
err = db.QueryRow(sqlStatement, article.URI).Scan(&id)
if err != nil {
if err == sql.ErrNoRows { //pgx.ErrNoRows
// there were no rows, but otherwise no error occurred
} else {
log.Fatal(err)
}
}
fmt.Println("New record ID is:", id)
For better understanding or for multiple rows please refer this link : How to get row value(s) back after db insert?
I know it's old question, but I just found the solution
do not use
var pgErr *pgconn.PgError
try to use
var pgErr pgx.PgError
instead

Get a single item from the query Firestore

I'm trying to get a single document from the Firestore Firebase using Golang. I know that it is easy if you have an id, you can write something like this:
database.Collection("profiles").Doc(userId).Get(ctx)
In my case I need to find a specific document using a Where condition, and this is where I get stuck. So far I was able to come up only with the following:
database.Collection("users").Where("name", "==", "Mark").Limit(1).Documents(ctx).GetAll()
And it is obviously not the best solution since I am looking only for one (basically the first) document which follows the condition and using GetAll() seems really weird. What would be the best approach?
The application can call Next and Stop to get a single document:
func getOne(ctx context.Context, q firestore.Query) (*firestore.DocumentSnapshot, error) {
it := q.Limit(1).Documents(ctx)
defer it.Stop()
snap, err := it.Next()
if err == iterator.Done {
err = fmt.Errorf("no matching documents")
}
return snap, err
}

Running SQL queries in Tarantool from Go are silent (no errors)

I try to run SQL queries from a Golang application using the official Tarantool client. The only way I know how to do it is by using conn.Eval like below. But I don't receive any errors. I can drop non existing tables, insert rows with duplicate keys. I will never find out that something went wrong.
resp, err := conn.Eval("box.execute([[TRUNCATE TABLE not_exists;]])", []interface{}{})
// err is always nil
// resp.Error is always empty
Can you point out the way to get errors or the right way to run SQL queries.
thanks for the question!
I have talked to the team and we have two options for you. Here is the first one:
resp, err := conn.Eval("return box.execute([[TRUNCATE TABLE \"not_exists\";]])", []interface{}{})
if len(resp.Tuples()) > 1 {
fmt.Println("Error", resp.Tuples()[1])
}else{
fmt.Println("Result", resp.Tuples()[0])
}
And here is the second one:
r, err := tnt.Eval("local data, err = box.execute(...) return data or box.error(err)", []interface{}{
`TRUNCATE table "not_exists";`,
})
if err != nil {
log.Fatalln(err)
}
I hope that helps! And if it doesn't - let me know and we will look into this one more time.

Json issue in getting date in golang dropbox library

I'm writing a little program using the dropbox api to learn go. I'm using the client library here: https://github.com/stacktic/dropbox.
I'm able to upload and download a file so I know my api keys and what not are working correctly. Using the Metadata method I can get the metadata for a file. However, when I try to use the UnmarshalJSON method to get a human readable date from the ClientMtime item in the entry struct, I get "unexpected end of JSON input". Any ideas on what's the issue?
The code I'm using is as follows:
func main() {
db := dropbox.NewDropbox()
db.SetAppInfo("Blah", "blah")
db.SetAccessToken("Token")
list,err := db.Metadata("/app_folder/test.jpg", true, false, "", "", 1)
if err != nil {
log.Fatal(err)
}
var date []byte
err = list.ClientMtime.UnmarshalJSON(date)
if err != nil {
log.Fatal(err)
}
fmt.Printf("%v", date)
}
Thanks!
You want:
date, err := list.ClientMtime.MarshalJSON()
UnmarshalJson goes the other way; []byte -> DBTime
That's why it's an end of input error, the []byte is empty.
Optionally, ClientMTime is a time. Time which has String() and Format() methods.
You can access all the time formatting features by converting it.
See: https://github.com/stacktic/dropbox/blob/master/dropbox.go#L158

Resources