How to convert gorm.DB query to its string representation - go

Let's say I have a gorm.DB object in Go, and I want to extract and assert the query I've built to see it was built correctly.
How can I compare the "string" representation of the query to this object ?

Make sure your gorm is up to date.
Using ToSQL
example:
sql := DB.ToSQL(func(tx *gorm.DB) *gorm.DB {
return tx.Model(&User{}).Where("id = ?", 100).Limit(10).Order("age desc").Find(&[]User{})
})
sql //=> SELECT * FROM "users" WHERE id = 100 AND "users"."deleted_at" IS NULL ORDER BY age desc LIMIT 10
Using DryRun Mode
example:
stmt := db.Session(&Session{DryRun: true}).First(&user, 1).Statement
stmt.SQL.String() //=> SELECT * FROM `users` WHERE `id` = $1 ORDER BY `id`
stmt.Vars //=> []interface{}{1}
Using Debug
example:
db.Debug().Where("name = ?", "jinzhu").First(&User{})

Maybe you can try to use Debug() to print raw sql built by gorm to stdout.
db.Debug().Where("name = ?", "jinzhu").First(&User{})
FYI https://gorm.io/docs/logger.html#Debug

Related

How to use SQL raw query in Laravel

SQL table:
SELECT id,
account_name,
parent_id
FROM
(SELECT id,
account_name,
parent_id,
CASE
WHEN id = 1 THEN #idlist := CONCAT(id)
WHEN FIND_IN_SET(parent_id, #idlist) THEN #idlist := CONCAT(#idlist, ',', id)
END AS checkId
FROM chart_of_account
ORDER BY id ASC) AS T
WHERE checkId IS NOT NULL
When I run this query in MySQL it works fine and the result is fetched perfectly, but when I run it in Laravel like this:
$accountId = DB::select('SELECT id,account_name,parent_id FROM
(SELECT id,account_name,parent_id,
CASE WHEN id = '.$account_id.' THEN #idlist := CONCAT(id)
WHEN FIND_IN_SET(parent_id,#idlist) THEN #idlist := CONCAT(#idlist,', ',id)
END as checkId
FROM chart_of_account
ORDER BY id ASC) as T
WHERE checkId IS NOT NULL');
it gives an error.
Argument 1 passed to Illuminate\\Database\\Connection::prepareBindings() must be of the type array, string given,
Try this:
$query = 'YOUR_QUERY_THE_BIG_ONE:)';
$result = DB::select($query,[]);
dd($result);
Optionally, you can use ? sign in your query wherever you are using user inputs to prevent mySQL injection issue and then provide their value in second parameter array of select function. One example would be:
$inputUserEmail = $request->input('email');
$query = 'SELECT * FROM users WHERE email=?';
$result = DB::select($query,[$inputUserEmail]);
dd($result);
I hope it gives you an idea

DB Query Commands are producing strange sql queries

I have my model as:
type Report struct {
ID int `json:"id,omitempty" gorm:"primary_key"`
Title *string `json:"title" gorm:"not null"`
}
I have initialized variable report as var report Report I have successfully auto migrated this model as database table and have populated database as sql INSERT using GORM's db.Create(&report).
The problem I am facing is while trying query commands. Every query commands supported by GORM such as db.Find(&report) , db.First(&report, 1) is resulting to queries such as folows:
SELECT * FROM "reports" WHERE "reports"."deleted_at" IS NULL AND ((id = $1))
SELECT * FROM "reports" WHERE "reports"."deleted_at" IS NULL AND ((id = $1))
SELECT * FROM reports WHERE (reports.deleted_at IS NULL) AND ((id = $1))
SELECT * FROM reports WHERE (reports.deleted_at IS NULL) AND ((id = $1))
SELECT 0 done
I am unable to query database. I am using GORM with cockroach db. This works fine when using GO pq driver and raw sql commands.
The deleted_at column is a part of GORM's base gorm.Model struct and its soft delete feature. Are you using gorm.Model somewhere that we can't see in this example? This isn't supposed to happen unless you either define a field named DeletedAt or embed a gorm.Model in your model struct.
Since the model has the field deleted_at, gorm is using the soft delete ability automatically. You can use Unscoped
db.Unscoped().Find(&reports)
Which is the same as running the raw query
db.Raw("SELECT * FROM reports").Scan(&reports)

How to run a query string as SQL in laravel

I have a query in a variable and I want to run it :
$sql = "select id,
title,
parent_id
from (select * from categories
order by parent_cat_id, id) base,
(select #pv := '$category_id') tmp
where find_in_set(parent_cat_id, #pv) > 0
and #pv := concat(#pv, ',', id)";
How can run it as a query ?
I was able to run the query using the DB::select function:
$categories = DB::select($sql);
dd($categories);

How to apply the results of a method to a SQL query? [duplicate]

I'm trying to check if a specific ID exists in a table named "Products" in my sqlite database.
def existsCheck( db, id )
temp = db.execute( "select exists(
select 1
from Products
where promoID = ?
) ", [id] )
end
that's my current code but that returns an array which means I have to deal with conversion before I can use it as a boolean. Any ideas how I can change it so that it returns an int with the value 1?
There is no need to use a subquery:
def existsCheck( db, id )
db.execute( "select 1
from Products
where promoID = ?",
[id] ).length > 0
end
This returns a boolean result.
Change it to:
def existsCheck( db, id )
temp = db.execute( "select 1 where exists(
select 1
from Products
where promoID = ?
) ", [id] ).any?
end
SQL query returns 1 when condition is met or empty result set if it's not. Whole function returns boolean depending on result set.

How to query dataset table on primary key of smallInt using linq C#

Let say I have the following sql table. Customer_id column is a primary key with smallint.
And I am trying to create a linq query, where I want to get all data for customer with id, let say 1.
How to do this.
Already done and not working:
1.
var query = from row in dt.AsEnumerable()
where row.Field<Int32>("customer_id") == Convert.ToInt32(2)
select row;
2.
var query = from row in dt.AsEnumerable()
where row.Field<Int16>("customer_id") == Convert.ToInt16(2)
select row
debug for example 1,2
Syntax error
Exceptions
Why don't you use this:
DataRow needle = hayStack.Tables["Customer"].Rows.Find(2);
Your method should be rewritten as something like this:
private DataRow GetCustomerDetails(Int16 customer_id)
{
return _dt.Tables["Customer"].Rows.Find(customer_id);
}
The calling method would have to check for null beeing returned from the method, since an invalid customer_id would cause Find() tu return null.
Try using short type instead of Int32.

Resources