Can I increase an existing field in MySQL by one using gorm? Without using raw SQL - mysql

If I use the raw SQL, it would be "UPDATE table_name SET field1 = field1 + 1 WHERE id = an_id_val";
How can I achieve the same thing with func chain calls like db.Update() or db.Save() etc.
Thanks in advance.

You could use a sql expression
DB.Model(&your_model).UpdateColumn("field1 ", gorm.Expr("field1 + ?", 1))
http://gorm.io/docs/update.html

Related

Mysql) when i using user-defined variable , SQL explain use type "ALL"

When i using user-defined variable , i want to use 'index' like 'ref..';
for example,
SET #company_code = "A002";
select *
from product_in_out
where company_code = #company_code
and product_date = "2022-04-13"
and out_type = "Q"
;
above result like this,
[enter image description here][1]
for using SQL index, i've tested that variable to plain text like "A002".
at that time, SQL use index like 'ref'
select *
from product_in_out
where company_code = "A002"
and product_date = "2022-04-13"
and out_type = "Q"
;
if so, is there any good way to use valiable for using mysql Index?!?!
As a workaround, add this composite index:
INDEX(out_type, product_date, company_code)
(I assume product_date is of datatype DATE.)

Laravel update based on other value

How can I translate this to be used within the laravel query builder ?
MYSQL
update mytable
set val = val +1
where id = 1
In laravel
$res = DB::table('mytable')
->update(['val' => ?]);
Thanks
Try:
DB::table('mytable')->where('id',1)->increment('val');
the increment method accept as second parameter the amount to sum, if you need to do val = val + 2 you can use ->increment('val', 2).
See this as reference: https://laravel.com/api/5.3/Illuminate/Database/Eloquent/Builder.html#method_increment
In cases where you're doing a more complicated calculation than an increment, you can also do something like this:
DB::table('mytable')->where('id',1)->update(['val' => DB::raw('val * 3')]);
Be careful with DB::raw - it's not going to escape user input for you.

SQLAlchemy MySQL IF Statement

I'm in the middle of converting an old legacy PHP system to Flask + SQLAlchemy and was wondering how I would construct the following:
I have a model:
class Invoice(db.Model):
paidtodate = db.Column(DECIMAL(10,2))
fullinvoiceamount = db.Column(DECIMAL(10,2))
invoiceamount = db.Column(DECIMAL(10,2))
invoicetype = db.Column(db.String(10))
acis_cost = db.Column(DECIMAL(10,2))
The query I need to run is:
SELECT COUNT(*) AS the_count, sum(if(paidtodate>0,paidtodate,if(invoicetype='CPCN' or invoicetype='CPON' or invoicetype='CBCN' or invoicetype='CBON' or invoicetype='CPUB' or invoicetype='CPGU' or invoicetype='CPSO',invoiceamount,
fullinvoiceamount))) AS amount,
SUM(acis_cost) AS cost, (SUM(if(paidtodate>0,paidtodate,invoiceamount))-SUM(acis_cost)) AS profit FROM tblclientinvoices
Is there an SQLAlchemyish way to construct this query? - I've tried googling for Mysql IF statments with SQlAlchemy but drew blanks.
Many thanks!
Use func(documentation) to generate SQL function expression:
qry = select([
func.count().label("the_count"),
func.sum(func.IF(
Invoice.paidtodate>0,
Invoice.paidtodate,
# #note: I prefer using IN instead of multiple OR statements
func.IF(Invoice.invoicetype.in_(
("CPCN", "CPON", "CBCN", "CBON", "CPUB", "CPGU", "CPSO",)
),
Invoice.invoiceamount,
Invoice.fullinvoiceamount)
)
).label("amount"),
func.sum(Invoice.acis_cost).label("Cost"),
(func.sum(func.IF(
Invoice.paidtodate>0,
Invoice.paidtodate,
Invoice.invoiceamount
))
- func.sum(Invoice.acis_cost)
).label("Profit"),
],
)
rows = session.query(qry).all()
for row in rows:
print row

passing an Array as a Parameter to be used in a SQL Query using the "IN" Command

Good Afternoon to All,
I have a question concerning on SQL Queries. is it possible to use an array as a parameter to a query using the "IN" command?
for example,
int x = {2,3,4,5}
UPDATE 'table_name' set 'field' = data WHERE field_ID IN (x)
the reason I am asking this is to avoid an iterative SQL Statement when I have to update data in a database.
I also thought of using a for each statement in for the UPDATE Query but I don't know if it will affect the performance of the query if it will slow down the system if ever 100+ records are updated.
I am using VB.Net btw.
My Database is MySQL Workbench.
I have gotten the answer. I just simply need to convert each elements to a String then concatenate it with a "," for each element. so the parameter that i will pass will be a string.
ANSWER:
int x = {2,3,4,5}
will become
string x = "2,3,4,5"
My Query string will become "UPDATE tablename SET field=value WHERE ID IN("&x&")"
Thank you to all who helped.
If you have the query in a variable (not a stored procedure) and you don't have a huge amount of ids, you could built your own IN. I haven't tested the speed of this approach.
This code won't compile, it's just to give you an idea.
query = "SELECT * FROM table WHERE col IN ("
For t = 0 TO x.Length-1
If t > 0 Then query &= ","
query &= "#var" & t
Next
query &= ")"
...
For t = 0 TO x.Length-1
cmd.Parameters.Add("#var" & t, SqlDbType.Int).Value = x(t)
Next
i am not familiar with mySQL, but when dealing with MSSQL, I normally have a split function in DB so that I can use it to split concatenated integer values as a table, at VB side, something like:
Dim myIds = {1, 2, 3, 4}
Dim sql = <sql>
SELECT m.* FROM dbo.tblMyData m
INNER JOIN dbo.fncSplitIntegerValues(#Ids, ',') t ON t.id = m.Id
</sql>.Value
Using con As New SqlConnection("My connection string..."),
cmd As New SqlCommand(sql, con)
cmd.Parameters.Add("#Ids", SqlDbType.VarChar).Value =
myIds.Select(Function(m) m.ToString).Aggregate(Function(m, n) m & "," & n)
con.Open()
Dim rdr = cmd.ExecuteReader(CommandBehavior.CloseConnection)
While rdr.Read()
Console.WriteLine(rdr.GetValue(0))
' do something else...
End While
End Using
dbo.fncSplitIntegerValues is a db function to split concatenated integer varchar into integer Id with given separator.
it's important not to use plain sql, instead, use sql parameters.
Note: above sample is not tested...

Advanced Search in Linq to SQL possible?

Without the use of "LIKE" in Dynamic Linq it virtually renders it useless to me when trying to create an advanced search query.
How have any of you overcome this Advanced Search problem when using Linq to SQL?
I'd need to search the following field types and they all could be null as well:
List item
varchar (column LIKE '%' + myText + '%')
text (column LIKE '%' + myText + '%')
DateTime (column >= myDate - if the "myDate" is not null of course)
integer (column = myInt - if "myInt" is not null of course)
boolean
I also can't just use ExecuteQuery because then I don't get a true "entity" and all of it's relations/associations.
I just don't see how I can do this with Linq to SQL. I'm currently without Stored Procs so I'd rather not have one stored proc just for this if I can figure this out with Linq.
To make LIKE Statements, you can use the Contains method:
string myText = "test";
var query = dc.Table.Where(r=>r.Column.Contains(myText));
This will generate this kind of SQL Statement:
SELECT [t0].[Column], ... [t0].[ColumnN]
FROM [Table] AS [t0]
WHERE [t0].[Column] LIKE #p0
And the #p0 parameter will have "%test%" as value.
For the Date and int comparison if I understand correctly what do you want, you could do this:
DateTime? myDate = new DateTime(2009, 3, 15);
var query = dc.Table.Where(r=> r.DateColumn > myDate || myDate == null );
So, if myDate is null, the condition DateColumn > myDate wont be evaluated.