Laravel Migration: Combine multiple values in a new colum - sql

i'm trying to make a migration using Laravel. The idea is to get the values of columns 'code' and 'id' in different tables, and merge them into a column 'name' with '-' separators.
So in part it is a SQL problem.
Currently i'm trying something like this.
First migration to create the new column 'name'
public function up()
{
Schema::table('work_order', function (Blueprint $table) {
$table->string('name')->nullable();
});
}
(works just fine)
And second migration to populate the new column with values
class AlterColumnNameWorkOrder extends Migration
{
public function up()
{
$company_code = DB::statement("SELECT code FROM company");
$campaign_code = DB::statement("SELECT code FROM campaign");
$work_order_number = DB::statement("SELECT id FROM work_order");
DB::statement("UPDATE work_order SET name = $company_code + '-' + $campaign_code + '-' + $work_order_number");
}
and i'm getting this error
SQLSTATE[22P02]: Invalid text representation: 7 ERROR: invalid input syntax for integer: "-"
LINE 1: UPDATE work_order SET name = 1 + '-' + 1 + '-' + 1
I'm thinking that i'm not getting the values but the index instead.
UPDATE: I solved the problem by replacing + for ||. But now in column 'name' all my values are "1-1-1". The values are not being represented. What am i missing?
UPDATE2: I noticed that i was defining an unnecessary variable $work_order_number. As it belongs to the same table to be updated. So I removed it and put the field "id" directly in the statement.
DB::statement("UPDATE work_order SET name = $company_code || '-' || $campaign_code || '-' || id");
Now the third value is shown correctly. And this reduces my problem to getting values from another table into an column.

First of all, you shouldn't use migrations to populate the database. Read the documentation about seeds.
Also, i think your select query is wrong. Isn't you missing a where clause?
Run php artisan migrate to migrate your database, then create a new seed, and add this to the run method:
$company_code = DB::table('company')->select('code')->where('id', some_id)->first()->code;
$campaing_code = DB::table('campaing')->select('code')->where('id', some_id)->first()->code;
$work_order_number = DB::table('work_number')->select('id')->where('id', some_id)->first()->id;
$sql = "UPDATE work_order SET name = concat('{$company_code}', '-', '{$campaign_code}', '-', '{$work_order_number}');
DB::statement(DB::raw($sql));
Now, just run php artisan db:seed --class=YourSeedClassName and it should work.

Related

Newly created column not registering in Case statement - 'Object not found'

I am combining a group of columns to create the specs per each line item. I then will compare these specs to the specs from an excel sheet that have an ID with them. So in the end the ID will be associated with the correct items in the database. To do this, I create a new column called SpecKey and then write a Case statement to compare. Below is some simplified code to show what I am doing. Is there a reason why I cannot use SpecKey in the case statement? And is there a workaround or better way to do this?
When I swap SpecKey with an already existing column in the database, the code compiles. But using the newly created column, SpecKey, seems to be the problem. Here is the error I receive in DBeaver: 'SQL Error [42501]: UCAExc:::5.0.1 user lacks privilege or object not found: FULL.SPECKEY'
SQL Code:
SELECT Flat_Size + '|' + Finish_Size + '|' + STD_PK + '|' + STD_PK_QUANTITY as SpecKey,
CASE WHEN FULL.SpecKey IS '4x8|4x4|Each|1' THEN '12345ID'
ELSE NULL
END AS TemplateID
FROM `Table`

How to make new database keywords in Katalon Studio and use them

How to make custom scripts and use them?
I already made a database connection script and I'm using it in Test Case but now I don't want to use select statements.
I made an SQLHandler where I connect to DB and I want to make another to perform select action.
The script I provided I use in my test case and want to hide it from test case and use something like my SQLHandler:
SQLHandler sql = new SQLHandler()
List<GroovyRowResult> res = sql.getSelectResults('SELECT COUNT(*) as calls FROM test WHERE canc IS NOT NULL AND cncat IS NULL')
int countFromDb = res.get(0).get('Calls')
println("No. of rows in Database is(are):" + res.get(0))
I think you can create custom keyword and hide the select statement there. An example of custom keyword looks like:
class sample {
#Keyword
def getResource() {
SQLHandler sql = new SQLHandler()
List<GroovyRowResult> res = sql.getSelectResults('SELECT COUNT(*) as calls FROM test WHERE canc IS NOT NULL AND cncat IS NULL')
int countFromDb = res.get(0).get('Calls')
println("No. of rows in Database is(are):" + res.get(0))
return res.get(0))
}
More information could be found at https://docs.katalon.com/katalon-studio/videos/custom_keywords_and_method_call_statements.html

"<ID>" Error with a multiple line query SQL in Google App Script using AS statement

Multiple line query SQL in Google App script works perfectly like this (I'm querying Big query here) :
var request = {
query:
'SELECT SUM(amount)' +
'FROM mybigquerytable;'
};
However when I'm adding an AS statement like this :
var request = {
query:
'SELECT SUM(amount) AS foo' +
'FROM mybigquerytable;'
};
It doesn't work. I have the following error :
Encountered " <ID> "mybigquerytable "" at line 0, column 0. Was expecting: <EOF> (line 14, file "myscriptnamehere")
I don't understand why...
Thanks.
Add space after foo
var request = {
query:
'SELECT SUM(amount) AS foo ' +
'FROM mybigquerytable;'
};
you can see difference by trying both versions in BigQuery UI:
SELECT SUM(amount)FROM mybigquerytable;
and
SELECT SUM(amount) AS fooFROM mybigquerytable;
Above are equivalent to those in your question and as you will see second will not be able to run

Pyodbc and Access with query parameter that contains a period

I recently found a bug with some Access SQL queries that I can't seem to track down. I have a fairly straightforward SQL query that I use to retrieve data from an access database that's "managed" in an older application (ie the data is already in the database and I have no real control over what's in there).
import pyodbc
MDB = '******.MDB'
DRV = '{Microsoft Access Driver (*.mdb)}'
PWD = ''
con = pyodbc.connect('DRIVER={};DBQ={};PWD={}'.format(DRV, MDB, PWD))
sql = ('SELECT Estim.PartNo, Estim.Descrip, Estim.CustCode, Estim.User_Text1, Estim.Revision, ' +
'Estim.Comments, Routing.PartNo AS RPartNo, Routing.StepNo, Routing.WorkCntr, Routing.VendCode, ' +
'Routing.Descrip AS StepDescrip, Routing.SetupTime, Routing.CycleTime, ' +
'Routing.WorkOrVend, ' +
'Materials.PartNo as MatPartNo, Materials.SubPartNo, Materials.Qty, ' +
'Materials.Unit, Materials.TotalQty, Materials.ItemNo, Materials.Vendor ' +
'FROM (( Estim ' +
'INNER JOIN Routing ON Estim.PartNo = Routing.PartNo ) ' +
'INNER JOIN Materials ON Estim.PartNo = Materials.PartNo )')
if 'PartNo' in kwargs:
key = kwargs['PartNo']
sql = sql + 'WHERE Estim.PartNo=?'
cursor = con.cursor().execute(sql, key)
# use this for debuging only
num = 0
for row in cursor.fetchall():
num += 1
return num
This works fine for all PartNo except when PartNo contains a decimal point. Curiously, when PartNo contains a decimal point AND a hyphen, I get the appropriate record(s).
kwargs['PartNo'] = "100.100-2" # returns 1 record
kwargs['PartNo'] = "200.100" # returns 0 records
Both PartNos exist when viewed in the other application, so I know there should be records returned for both queries.
My first thought was to ensure kwargs['PartNo'] is a string key = str(kwargs['PartNo']) with no change.
I also tried to places quotes around the 'PartNo' value with no success. key = '\'' + kwargs['PartNo'] + '\''
Finally, I tried to escape the . with no success (I realize this would break most queries, but I'm just trying to track down the issue with a single period) key = str(kwargs['partNo']).replace('.', '"."')
I know using query parameters should handle all the escaping for me, but at this point, I'm just trying to figure out what's going on. Any thoughts on this?
So the issue isn't with the query parameters - everything works as it should. The problem is with the SQL statement. I incorrectly assumed - and never checked - that there was a record in the Materials table that matched PartNo.
INNER JOIN Materials ON Estim.PartNo = Materials.PartNo
will only return a record if PartNo is found in both tables, which in this particular case it is not.
Changing it to
LEFT OUTER JOIN Materials ON Estim.PartNo = Materials.PartNo
produces the expected results. See this for info on JOINS. https://msdn.microsoft.com/en-us/library/bb243855(v=office.12).aspx
As for print (repr(key)) - flask handles the kwarg type upstream properly
api.add_resource(PartAPI, '/api/v1.0/part/<string:PartNo>'
so when I ran this in the browser, I got the "full length" strings. When run in the cmd line using python -c ....... I was not handling the argument type properly as Gord pointed out, so it was truncating the trailing zeros. I didn't think the flask portion was relevant, so I never added that in the original question.

Multiple parameter values

I have a problem with BIRT when I try to pass multiple values from report parameter.
I'm using BIRT 2.6.2 and eclipse.
I'm trying to put multiple values from cascading parameter group last parameter "JDSuser". The parameter is allowed to have multiple values and I'm using list box.
In order to be able to do that I'm writing my sql query with where-in statement where I replace text with javascript. Otherwise BIRT sql can't get multiple values from report parameter.
My sql query is
select jamacomment.createdDate, jamacomment.scopeId,
jamacomment.commentText, jamacomment.documentId,
jamacomment.highlightQuote, jamacomment.organizationId,
jamacomment.userId,
organization.id, organization.name,
userbase.id, userbase.firstName, userbase.lastName,
userbase.organization, userbase.userName,
document.id, document.name, document.description,
user_role.userId, user_role.roleId,
role.id, role.name
from jamacomment jamacomment left join
userbase on userbase.id=jamacomment.userId
left join organization on
organization.id=jamacomment.organizationId
left join document on
document.id=jamacomment.documentId
left join user_role on
user_role.userId=userbase.id
right join role on
role.id=user_role.roleId
where jamacomment.scopeId=11
and role.name in ( 'sample grupa' )
and userbase.userName in ( 'sample' )
and my javascript code for that dataset on beforeOpen state is:
if( params["JDSuser"].value[0] != "(All Users)" ){
this.queryText=this.queryText.replaceAll('sample grupa', params["JDSgroup"]);
var users = params["JDSuser"];
//var userquery = "'";
var userquery = userquery + users.join("', '");
//userquery = userquery + "'";
this.queryText=this.queryText.replaceAll('sample', userquery);
}
I tryed many different quote variations, with this one I get no error messages, but if I choose 1 value, I get no data from database, but if I choose at least 2 values, I get the last chosen value data.
If I uncomment one of those additional quote script lines, then I get syntax error like this:
The following items have errors:
Table (id = 597):
+ An exception occurred during processing. Please see the following message for details: Failed to prepare the query execution for the
data set: Organization Cannot get the result set metadata.
org.eclipse.birt.report.data.oda.jdbc.JDBCException: SQL statement does not return a ResultSet object. SQL error #1:You have an error in
your SQL syntax; check the manual that corresponds to your MySQL
server version for the right syntax to use near 'rudolfs.sviklis',
'sample' )' at line 25 ;
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to
your MySQL server version for the right syntax to use near
'rudolfs.sviklis', 'sample' )' at line 25
Also, I should tell you that i'm doing this by looking from working example. Everything is the same, the previous code resulted to the same syntax error, I changed it to this script which does the same.
The example is available here:
http://developer.actuate.com/community/forum/index.php?/files/file/593-default-value-all-with-multi-select-parsmeter/
If someone could give me at least a clue to what I should do that would be great.
You should always use the value property of a parameter, i.e.:
var users = params["JDSuser"].value;
It is not necessary to surround "userquery" with quotes because these quotes are already put in the SQL query arround 'sample'. Furthermore there is a mistake because userquery is not yet defined at line:
var userquery = userquery + users.join("', '");
This might introduce a string such "null" in your query. Therefore remove all references to userquery variable, just use this expression at the end:
this.queryText=this.queryText.replaceAll('sample', users.join("','"));
Notice i removed the blank space in the join expression. Finally once it works finely, you probably need to make your report input more robust by testing if the value is null:
if( params["JDSuser"].value!=null && params["JDSuser"].value[0] != "(All Users)" ){
//Do stuff...
}