How do i pass a variable for the query in a get Manager call? - perl

I am trying to make a simple Rose DB call:
$id = xyz;
$name = "company";
DataB::testTable::Manager->get_testTable( query =>[ id => $id, name => $name ] );
in it possible to not have the whole query written every time, and declare it like a string variable such that i can just call
DataB::testTable::Manager->get_testTable( query =>[ $query ] );
where $query = qq { id => $id , name => $name };
Please Help

By what I understood from your question, I am giving this answer.
Try this one.
my $myquery = {query =>{ id=>$id, name=>$name }} ;
TGI::testTable::Manager->get_testTable($myquery);
Hope, this gives some idea to you.
Edit for "Hash with Array reference":
my $myquery = [ id=>$id, name=>$name ] ;
TGI::testTable::Manager->get_testTable(query => $myquery);
check out this : How to pass a a string variable as "query" for get Manager call?

Well actually i figured out how to do that . Its not that complicated. Only thing is RoseDB objects expect an array reference for a query. So something like this works :
my #query = ( id => $id, name => $name );
testDB::testTable::Manager->get_testTable( query => \#query );
Just thought would answer it myself, incase someonelse is looking for a solution to this

Related

How to add multiple custom fields to a wp_query in a shortcode?

In a shortcode I can limit wp_query results by custom field values.
Example:
[my-shortcode meta_key=my-custom-field meta_value=100,200 meta_compare='IN']
And obviously it's possible to use multiple custom fields in a wp_query like WP_Query#Custom_Field_Parameters
But how can I use multiple custom fields in my shortcode? At the moment I do pass all the shortcode parameters with $atts.
On of a few different solutions might be to use a JSON encoded format for the meta values. Note that this isn't exactly user-friendly, but certainly would accomplish what you want.
You would of course need to generate the json encoded values first and ensure they are in the proper format. One way of doing that is just using PHP's built in functions:
// Set up your array of values, then json_encode them with PHP
$values = array(
array('key' => 'my_key',
'value' => 'my_value',
'operator' => 'IN'
),
array('key' => 'other_key',
'value' => 'other_value',
)
);
echo json_encode($values);
// outputs: [{"key":"my_key","value":"my_value","operator":"IN"},{"key":"other_key","value":"other_value"}]
Example usage in the shortcode:
[my-shortcode meta='[{"key":"my_key","value":"my_value","operator":"IN"},{"key":"other_key","value":"other_value"}]']
Which then you would parse out in your shortcode function, something like so:
function my_shortcode($atts ) {
$meta = $atts['meta'];
// decode it "quietly" so no errors thrown
$meta = #json_decode( $meta );
// check if $meta set in case it wasn't set or json encoded proper
if ( $meta && is_array( $meta ) ) {
foreach($meta AS $m) {
$key = $m->key;
$value = $m->value;
$op = ( ! empty($m->operator) ) ? $m->operator : '';
// put key, value, op into your meta query here....
}
}
}
Alternate Method
Another method would be to cause your shortcode to accept an arbitrary number of them, with matching numerical indexes, like so:
[my-shortcode meta-key1="my_key" meta-value1="my_value" meta-op1="IN
meta-key2="other_key" meta-value2="other_value"]
Then, in your shortcode function, "watch" for these values and glue them up yourself:
function my_shortcode( $atts ) {
foreach( $atts AS $name => $value ) {
if ( stripos($name, 'meta-key') === 0 ) {
$id = str_ireplace('meta-key', '', $name);
$key = $value;
$value = (isset($atts['meta-value' . $id])) ? $atts['meta-value' . $id] : '';
$op = (isset($atts['meta-op' . $id])) ? $atts['meta-op' . $id] : '';
// use $key, $value, and $op as needed in your meta query
}
}
}

DBIx::Class update Inflate column with function

I tried to emulate this SQL in DBIx::Class against the update_or_new function.
UPDATE user SET lastseen = GREATEST( lastseen, ?::timestamp ) WHERE userid = ?
It gives an error on inflate column saying it is unable to invoke is_infinity on undef .
$schema->resultset('user')->update_or_new( {
userid => 'peter',
lastseen => \[ 'GREATEST( lastseen, ?::timestamp )', DateTime->from_epoch(epoch => 1234) ]
} );
I guess this is because the InflateColumn::DataTime does not expect a function there. Is there any clean workaround for this issue?
This is a bug in DBIx::Class ( addressed here: https://github.com/dbsrgits/dbix-class/pull/44 ) and the fix is merged. It should be fine on the next release.
That said, if you're using DBIx::Class <= 0.08270...
You're using update_or_new, but the function only makes sense if the row exists already:
GREATEST( lastseen, ?::timestamp ) lastseen is undefined if the row doesn't exist yet.
I read through the source+docs a bunch and cannot find a way to sidestep the InflateColumn code and still have bind values. You can pass in literal SQL with a scalar ref ( \'NOW()' ) but not an array ref.
Your best bet would be to use the ResultSet's update method instead, which does not 'process/deflate any of the values passed in. This is unlike the corresponding "update" in DBIx::Class::Row.'
my $dtf = $schema->storage->datetime_parser; #https://metacpan.org/pod/DBIx::Class::Storage::DBI#datetime_parser
my $user_rs = $schema->resultset('User')->search({ userid => 'peter' });
my $dt = DateTime->from_epoch(epoch => 1234);
#select count(*) where userid = 'peter';
if( $user_rs->count ) {
$user_rs->update(
lastseen => \[ 'GREATEST( lastseen, ? )', $dtf->format_datetime($dt) ]
);
} else {
$user_rs->create({ lastseen => $dt });
}

Incorrect `update statement` using IN operator with Zend

I have a function which is wanted to execute a statement like below:
UPDATE coupon_users SET status = status | '1' WHERE id IN ('3','4')
And in coupon_users model, I wrote a method like below do to:
/**
* #param array $ids #array(3,4)
* #param array $status #1
*/
public function updateStatus(array $ids, $status)
{
$result = $this->_db->query(
"UPDATE {$this->_name} SET status = status | ? WHERE id IN (?)",
array(
$status,
$ids
)
)->execute();
return $result;
}
But the query is always:
UPDATE coupon_users SET status = status | '1' WHERE id IN ('Array')
I don't know what am I wrong here, please help me, many thanks.
According to the PDO documentation (Zend_Db uses PDO as its DB access backend):
You cannot bind multiple values to a single named parameter in, for
example, the IN() clause of an SQL statement.
So, you'll probably need to prepare a bit further your query, so that it contains as many markers as elements in the array. A possible solution could be the following:
// Compose the query
$queryToExecute = "UPDATE {$this->_name} SET status = status | ? WHERE id IN (";
$questionMarks = array();
for ($id in $ids) {
$questionMarks[] = '?';
}
$queryToExecute .= implode(',', $questionMarks);
$queryToExecute .= ')';
// $queryToExecute should have the format "UPDATE ... WHERE id IN (?,?,?,...?)"
// Execute it
$result = $this->_db->query(
$queryToExecute,
array($status, $ids)
)->execute();
Hope that helps,
try:
public function updateStatus(array $ids, $status)
{
$result = $this->_db->query(
"UPDATE {$this->_name} SET status = ? WHERE id IN (?)",
array(
$status,
implode(',',$ids)
)
)->execute();
return $result;
}
Update:
Have you tried?:
$this->_db->update($this->_name, array('status'=>$status), array('id IN (?)'=>$ids));
I haven't tested it, it also depends on what $this->_db is an instance of
http://framework.zend.com/manual/en/zend.db.adapter.html#zend.db.adapter.write.update
Try this..
public function updateStatus(array $ids, $status)
{
$inarray= implode(',',$ids);
$result = $this->_db->query(
"UPDATE {$this->_name} SET status = status | ? WHERE id IN (?)",
array(
$status,
$inarray
)
)->execute();
return $result;
}
Its working fine for me.
$existingImagesIds = array(1, 2, 3, 7);
$where = $pImgModel->getAdapter()->quoteInto("id in (?) ", $existingImagesIds);
$pImgModel->update(array('status' => '0'), $where);

fql_query returns "Array" instead of name

I am trying to create a simple fb app that retrieves the name of the user using fql_query.
Code :
require_once 'facebook.php';
$appapikey = 'xxxx';
$appsecret = 'xxxx';
$facebook = new Facebook($appapikey, $appsecret) ;
$user_id = $facebook->require_login();
$q = "SELECT name FROM user WHERE uid='$user_id'";
$name = $facebook->api_client->fql_query($q);
echo "Name : $name[0][name]";
Output:
Name : Array[name]
Can you tell me what's going wrong here?
Thanks!
Mistake is in this line:
echo "Name : $name[0][name]";
you are including $name[0][name] in quotes, this should be
echo "Name : {$name[0][name]}";
or
echo "Name : ".$name[0][name];
An FQL query always returns an array, even if there is only one item in the result. Think of the result as rows in a normal SQL query.
Any time that I use arrays or database/API calls in PHP I print_r($array_name) to see what was returned. So this:
$name = $facebook->api_client->fql_query("SELECT name FROM user WHERE uid=$user_id");
print_r($name);
Should return this:
Array
(
[0] => Array
(
[name] => First Last
)
)
Another thing, I never put tick marks around values/variables in FQL.
$q = "SELECT name FROM user WHERE uid=$user_id";
$name = $facebook->api_client->fql_query($q);
But when you print the value you should put single quotes around the reference to the named index (in this case, 'name') and you should not wrap it all in double quotes:
echo "Name : " . $name[0]['name'];

How can I create a hash of hashes from an array of hashes in Perl?

I have an array of hashes, all with the same set of keys, e.g.:
my $aoa= [
{NAME=>'Dave', AGE=>12, SEX=>'M', ID=>123456, NATIONALITY=>'Swedish'},
{NAME=>'Susan', AGE=>36, SEX=>'F', ID=>543210, NATIONALITY=>'Swedish'},
{NAME=>'Bart', AGE=>120, SEX=>'M', ID=>987654, NATIONALITY=>'British'},
]
I would like to write a subroutine that will convert this into a hash of hashes using a given key hierarchy:
my $key_hierarchy_a = ['SEX', 'NATIONALITY'];
aoh_to_hoh ($aoa, $key_hierarchy_a) = #_;
...
}
will return
{M=>
{Swedish=>{{NAME=>'Dave', AGE=>12, ID=>123456}},
British=>{{NAME=>'Bart', AGE=>120, ID=>987654}}},
F=>
{Swedish=>{{NAME=>'Susan', AGE=>36, ID=>543210}}
}
Note this not only creates the correct key hierarchy but also remove the now redundant keys.
I'm getting stuck at the point where I need to create the new, most inner hash in its correct hierarchical location.
The problem is I don't know the "depth" (i.e. the number of keys). If I has a constant number, I could do something like:
%h{$inner_hash{$PRIMARY_KEY}}{$inner_hash{$SECONDARY_KEY}}{...} = filter_copy($inner_hash,[$PRIMARY_KEY,$SECONDARY_KEY])
so perhaps I can write a loop that will add one level at a time, remove that key from the hash, than add the remaining hash to the "current" location, but it's a bit cumbersome and also I'm not sure how to keep a 'location' in a hash of hashes...
use Data::Dumper;
my $aoa= [
{NAME=>'Dave', AGE=>12, SEX=>'M', ID=>123456, NATIONALITY=>'Swedish'},
{NAME=>'Susan', AGE=>36, SEX=>'F', ID=>543210, NATIONALITY=>'Swedish'},
{NAME=>'Bart', AGE=>120, SEX=>'M', ID=>987654, NATIONALITY=>'British'},
];
sub aoh_to_hoh {
my ($aoa, $key_hierarchy_a) = #_;
my $result = {};
my $last_key = $key_hierarchy_a->[-1];
foreach my $orig_element (#$aoa) {
my $cur = $result;
# song and dance to clone an element
my %element = %$orig_element;
foreach my $key (#$key_hierarchy_a) {
my $value = delete $element{$key};
if ($key eq $last_key) {
$cur->{$value} ||= [];
push #{$cur->{$value}}, \%element;
} else {
$cur->{$value} ||= {};
$cur = $cur->{$value};
}
}
}
return $result;
}
my $key_hierarchy_a = ['SEX', 'NATIONALITY'];
print Dumper(aoh_to_hoh($aoa, $key_hierarchy_a));
As per #FM's comment, you really want an extra array level in there.
The output:
$VAR1 = {
'F' => {
'Swedish' => [
{
'ID' => 543210,
'NAME' => 'Susan',
'AGE' => 36
}
]
},
'M' => {
'British' => [
{
'ID' => 987654,
'NAME' => 'Bart',
'AGE' => 120
}
],
'Swedish' => [
{
'ID' => 123456,
'NAME' => 'Dave',
'AGE' => 12
}
]
}
};
EDIT: Oh, BTW - if anyone knows how to elegantly clone contents of a reference, please teach. Thanks!
EDIT EDIT: #FM helped. All better now :D
As you've experienced, writing code to create hash structures of arbitrary depth is a bit tricky. And the code to access such structures is equally tricky. Which makes one wonder: Do you really want to do this?
A simpler approach might be to put the original information in a database. As long as the keys you care about are indexed, the DB engine will be able to retrieve rows of interest very quickly: Give me all persons where SEX = female and NATIONALITY = Swedish. Now that sounds promising!
You might also find this loosely related question of interest.