Reuse code that contains variables in same script bash - linux

I have a small block of code in bash like below
#!/bin/bash
query="select * from table where id = ${row_id}"
row_id=1
echo "$query"
row_id=3
echo "$query"
row_id=4
echo "$query"
expected output is below
select * from table where id = 1
select * from table where id = 3
select * from table where id = 5
But I am getting nothing as output
I know I am referencing variable before assigning it.
The idea here is to use reusable code instead of writing the same code at many places
How can I achieve what I want

You can create a function and call the function at various place by assign variable to it
#!/bin/bash
# create a function with variable and write your command
# here your command is print the query
my_function_name(){
arg1=$1
echo "select * from table where id = ${arg1}"
}
# assign varaible
row_id=1
# print the ourput of function when above variable is assigned
query=$(my_function_name "$row_id")
echo $query
# assign varaible
row_id=2
# print the ourput of function when above variable is assigned
query=$(my_function_name "$row_id")
echo $query
# assign varaible
row_id=3
# print the ourput of function when above variable is assigned
query=$(my_function_name "$row_id")
echo $query

you should be getting
select * from table where id =
select * from table where id =
select * from table where id =
and as you already mentioned the reason is
I know I am referencing variable before assigning it.
One way to implement this
$ for row_id in 1 3 5;
do
echo "select * from table where id = $row_id";
done
select * from table where id = 1
select * from table where id = 3
select * from table where id = 5
UPDATE
Based on the comment
Here if row_id is a random variable I get as part of another query then
how do I get the correct query as my output
which is different from the posted question, better to define a function
$ getquery() { echo "select * from table where id = $1"; }
$ getquery $RANDOM
select * from table where id = 12907

Related

python bigquery script extract childjob information before query execution

following this https://cloud.google.com/bigquery/docs/samples/bigquery-query-script
we can get the child_job information after the query (parentjob) executed
but how do we extract the child_job query before it executed?
parent_job
"""
-- Declare a variable to hold names as an array.
DECLARE top_names ARRAY<STRING>;
-- Build an array of the top 100 names from the year 2017.
SET top_names = (
SELECT ARRAY_AGG(name ORDER BY number DESC LIMIT 100)
FROM `bigquery-public-data.usa_names.usa_1910_2013`
WHERE year = 2000
);
-- Which names appear as words in Shakespeare's plays?
SELECT
name AS shakespeare_name
FROM UNNEST(top_names) AS name
WHERE name IN (
SELECT word
FROM `bigquery-public-data.samples.shakespeare`
);
"""
when this query executed it will create 2 child job:
childjob 1
SELECT STRUCT<ARRAY<STRING>>(( SELECT ARRAY_AGG(name ORDER BY number DESC LIMIT 100) FROM `bigquery-public-data.usa_names.usa_1910_2013` WHERE year = 2000 )).*;
childjob 2
SELECT name AS shakespeare_name FROM UNNEST(top_names) AS name WHERE name IN ( SELECT word FROM `bigquery-public-data.samples.shakespeare` )
is there any way we can extract the child_job query before the parentjob executed?

How to write a query for reordering elements

I'm working on a code that will have a list of items in a specific order and I'd like to reorder them at will. The setup isn't really that important, but to summarize it, it's a node server with MSSQL database.
For the sake of the demonstration lets say we're discussing forum categories that show in a specific order.
Id | OrderNumber | Name
------------------------
1 | 1 | Rules
2 | 3 | Off-topic
5 | 2 | General
8 | 4 | Global
I've already handled the front end that will allow me to reorder them as I like and the problem is what should happen when I press the save button on the database.
Ideally I'd like to send a JavaScript object containing item IDs in the right order to the API endpoint on the server that will execute a stored procedure. Something like:
Data = {
IDs:"5,2,8,1"
}
Is there a way that I can program a that stored procedure that it's only parameter is the list of Ids but that it can go through that list and do something I can only describe as the following pseudo code:
var Order = 1;
foreach ID in Data.IDs
UPDATE Categories SET OrderNum = Order WHERE Id = ID
Order = Order + 1
My biggest problem is that I'm not very experienced with advanced SQL commands, but that's the only part I need help with, I handled everything else already. Thank you for your help.
Example
Declare #IDs varchar(max) = '5,2,8,1'
Update A
set OrderNumber=B.RetSeq
From YourTable A
Join (
Select RetSeq = row_number() over (order by (select null))
,RetVal = B.n.value('(./text())[1]', 'int')
From ( values (cast('<x>' + replace(#IDs,',','</x><x>')+'</x>' as xml) )) A(xmldata)
Cross Apply xmldata.nodes('x') B(n)
) B on A.ID=B.RetVal
Updated Table
Id OrderNumber Name
1 4 Rules
2 2 Off-topic
5 1 General
8 3 Global

Kohana 3 ORM compares 2 columns in where clause

I need to generate query like that :
SELECT * FROM `table1` WHERE `date1` < `date2`
I can't find how to compare 2 columns in kohana ORM. Here date2 is considered as text.
$foo = ORM::factory('model1')->where('date1','<','date2');
How can I write this line ?
Thanks!
More info:
I use this for the moment:
$query = DB::query(Database::SELECT, "SELECT id FROM table1 WHERE `date1` < `date2`");
$result = $query->execute();
$foo = array();
foreach ($result as $r) {
$foo[] = ORM::factory("model1", $r['id']);
}
If you don't want Kohana to modify the string, as it would with the 3rd argument in the DB where function, you can use the DB::expr() function which will leave what you pass unmodified. So with your example, you could use
$foo = ORM::factory('model1')->where('date1','<',DB::expr('date2'));

How can I access array index in Kohana

I am getting the result set in an array. Now I am trying to access the id that is the first index of the array but getting an error. Please let me know how to access the indexes of array.
$email_template = DB::query(Database::SELECT,"select * from mail_settings where id = " .$email['id'])->execute();
When you just run the execute method on a query, you get back a Database_MySQL_Result object.
To return an array instead, use the as_array method like so:
$email_template = DB::query(Database::SELECT,
"select * from mail_settings where id = " .$email['id'])
->execute()->as_array();
Now you will be able to access the resultset as an array.
If all you want/need is the first or current row from the query, you can use the current method which you can read more about in the Kohana_Database_MySQL_Result class:
$email_template = DB::query(Database::SELECT,
"select * from mail_settings where id = " .$email['id'])
->execute()->current();
You are getting a Database_MySQL_Result object, not an array.
This will be correct.
$email_template = DB::query(Database::SELECT,
"select * from mail_settings where id = " .$email['id'])
->execute()->current();

Searching phpbb's 'topic_title' via MYSQL php, but exact match doesn't work

$sql = sprintf( "SELECT topic_title
FROM `phpbb_topics`
WHERE `topic_title` LIKE '%%%s%%' LIMIT 20"
, mysql_real_escape_string('match this title')
);
Which I run this query in phpMyAdmin the results are: (correct)
match this title
match this title 002
But when I run that same MYSQL query in PHP I get: (incorrect)
match this title 002
I have also tried MATCH AGAINST with the same result with both php and phpMyAdmin:
$sql = "SELECT topic_title
FROM phpbb_topics
WHERE MATCH (topic_title)
AGAINST('match this title' IN BOOLEAN MODE)";
The whole block of code im using to search with:
mysql_connect("localhost", "user", "pass") or die(mysql_error());
mysql_select_db("phpbb") or die(mysql_error());
$query = "match this title";
$query = "SELECT topic_title
FROM phpbb_topics
WHERE MATCH (topic_title)
AGAINST('$query' IN BOOLEAN MODE)";
// Doesn't work (these 2 both give the same result "match this title 002" and no the "match this title")
// $query = "SELECT * FROM `phpbb_topics`
// WHERE `topic_title`
// LIKE '%$query%'
// LIMIT 0, 30 "; // Doesn't work
$result = mysql_query($query) or die(mysql_error());
$row = mysql_fetch_array($result) or die(mysql_error());
while($row = mysql_fetch_array($result)){
$topic_title = $row['topic_title'];
echo "$topic_title";
}
Any idea as to what i'm doing wrong?
I'v been searching all over the place and have found next to no help :(
The problem is that after you execute your query you fetch the first row, do nothing with it, enter the loop by fetching the second row and start printing results..
If you remove the first $row = mysql_fetch_array($result), (directly after $result = mysql_query($query) or die(mysql_error());) you should be fine.
Another comment; If you echo a variable you don't have to put any qoutes around it. And in the way you're doing it now, you won't get a newline between the results so you might want to change that line to echo $topic_title . "<br>";

Resources