pgx is not returning rows after I do an insert - go

Im just doing an insert using the following code, and while i can see the data in the database, pgx is not returning any rows.
rows, err := db.Query(context.Background(), `
INSERT INTO
reservation (room_id, user_id)
VALUES
($1, $2)
`, roomId, userId)
I tried using QueryRow too but same thing, no rows are returned. Can anyone tell me where Im going wrong?

Related

Using Where condition with Upsert Query in Gorm GoLang

I am trying to use where condition using upsert query in Gorm GoLang but the upsert query is not getting formed correctly. It is just updating the values without where condition.
Here is my code -
onConflict := clause.OnConflict{
Where: clause.Where{Exprs: []clause.Expression{clause.Lte{Column: "timestamp", Value: time.Now()}}},
DoUpdates: clause.AssignmentColumns([]string{"first_name", "last_name", "timestamp", "updated_at"}),
}
insert := gormSQLDB.Clauses(onConflict).Create(&Users)
The mysql query formed from above code is -
INSERT INTO `users` (`first_name`,`last_name`,`timestamp`,`updated_at`,`id`) VALUES ('Ram','Kumar','2022-05-03 03:59:16','2022-06-07 14:45:22.631','5befa85e-e642-11ec-89a5-acde48001122') ON DUPLICATE KEY UPDATE `first_name`=VALUES(`first_name`),`last_name`=VALUES(`last_name`),`timestamp`=VALUES(`timestamp`),`updated_at`=VALUES(`updated_at`)
My requirement is to update the row on the basis of same id field with where condition as timestamp should be lower than current timestamp. But the where clause is not working. Can anybody tell me what is wrong in my code?

Checking the row existence before insertion using Cassandra within a Go application

I am using gocql with my Go application and trying to solve the issue described below.
CREATE TABLE IF NOT EXISTS website.users (
id uuid,
email_address text,
first_name text,
last_name text,
created_at timestamp,
PRIMARY KEY (email_address)
);
This query is going to override matching record which is Cassandra's expected behaviour.
INSERT INTO users (id, email_address, first_name, last_name, created_at)
VALUES (?, ?, ?, ?, ?)
In order to prevent overriding the existing record we can use IF NOT EXISTS at the end of the query.
INSERT INTO users (id, email_address, first_name, last_name, created_at)
VALUES (?, ?, ?, ?, ?)
IF NOT EXISTS
However, there is no way for me to know if the query affected any rows in DB or not. Somehow I need to return something like "Record exists" message back to caller but it is currently not possible. If there was something specific with session.Query(...).Exec() it would be useful but there isn't as far as I know.
I was thinking to SELECT by email_address before proceeding with INSERT if there was no matching record but as you can guess this is not feasible because by the time I INSERTed a new record after SELECT, some other operation could have INSERTed a new record with same email address.
How do we handle such scenario?
The solution is to use ScanCAS and the test case example from the library is here.
NOTE:
Order of the fields in ScanCAS() should match cqlsh> DESCRIBE keyspace.users; output for the CREATE TABLE ... block.
If you don't care about the scanned fields, prefer MapScanCAS instead.
func (r Repository) Insert(ctx context.Context, user User) error {
var (
emailAddressCAS, firstNameCAS, idCAS, lastNameCAS string
createdAtCAS time.Time
)
query := `
INSERT INTO users (email_address, created_at, first_name, id, last_name)
VALUES (?, ?, ?, ?, ?) IF NOT EXISTS
`
applied, err := r.session.Query(
query,
user.EmailAddress,
user.CreatedAt,
user.FirstName,
user.LastName,
user.CreateAt,
).
WithContext(ctx).
ScanCAS(&emailAddressCAS, &createdAtCAS, &firstNameCAS, &idCAS, &lastNameCAS)
if err != nil {
return err
}
if !applied {
// Check CAS vars here if you want.
return // your custom error implying a duplication
}
return nil
}
If you're using INSERT with IF NOT EXISTS, then in contrast to "normal" inserts that doesn't return anything, such query returns a single row result consisting of:
field with name [applied], and true value - if there was no record before, and new row was inserted
field with name [applied], and false value + all columns of existing row.
So you just need to get result of your insert query, and analyze it. See documentation for more details.

Return last inserted ID/SERIAL values with CockroachDB

How do I get the last ID/SERIAL value inserted into a table? Is there a CockroachDB function similar to SQL Server’s SCOPE_IDENTITY()?
There’s no function in CockroachDB for returning last inserted values. But you can use the RETURNING clause of the INSERT statement.
For example, this is how you’d use RETURNING to return an auto-generated SERIAL value:
CREATE TABLE users (id SERIAL, name STRING);
INSERT INTO users (name) VALUES ('mike') RETURNING id;

Inserting data from table (SELECT) with REF - Oracle Database

I'm trying to insert all data from Pacient table to Pacient_OR table (Object-Relational). Is there a simple way to do that (one script), if Pacient table has column with Pojistovna_ID (foreign key) and in Pacient_OR table there is REF to the Pojistovna_OR. Both Pojistovna and Pojistovna_OR are populated with the same data, but one is relational, second is based on object type.
I tried this (and more ofc):
INSERT INTO pacient_or
(pacient_or.id,
pacient_or.jmeno,
pacient_or.prijmeni,
pacient_or.datum_narozeni,
pacient_or.rodne_cislo,
pacient_or.telefon,
pacient_or.krevni_skupina,
pacient_or.rodinna_anamneza,
pacient_or.adresa,
pacient_or.pojistovna)
SELECT pacient.id,
pacient.jmeno,
pacient.prijmeni,
pacient.datum_narozeni,
pacient.rodne_cislo,
pacient.telefon,
pacient.krevni_skupina,
pacient.rodinna_anamneza,
Adresa_typ(pacient.ulice, pacient.mesto, pacient.psc),
(SELECT Ref(poj)
FROM pacient pac,
pojistovna_or poj
WHERE pac.pojistovna_id = poj.id)
FROM pacient;
This code throws error:
single-row subquery returns more than one row
Do not use pacient pac in the subquery. Link it to the pacient in your main from-clause. And even better do not use a subquery for this.

Sybase JDBC get generated keys

In Postgres, I can write
INSERT .. RETURNING *
To retrieve all values that had been generated during the insert. In Oracle, HSQLDB, I can use
String[] columnNames = ...
PreparedStatement stmt = connection.prepareStatement(sql, columnNames);
// ...
stmt.execute();
stmt.getGeneratedKeys();
To retrieve all values that had been generated. MySQL is a bit limited and only returns columns that are set to AUTO_INCREMENT. But how can this be done with Sybase SQL Anywhere? The JDBC driver does not implement these methods, and there is no INSERT .. RETURNING clause, as in Postgres. Is there way to do it, other than maybe running
SELECT ##identity
immediately after the insert?
My current implementation executes three consecutive SQL statements:
-- insert the data first
INSERT INTO .. VALUES (..)
-- get the generated identity value immediately afterwards
SELECT ##identity
-- get the remaining values from the record (possibly generated by a trigger)
SELECT * FROM .. WHERE ID = :previous_identity
The third statement can be omitted, if only the ID column is requested

Resources