building a dynamic query using where clause automatically changing numeric value to string type in SphinxQL query builder - laravel 5.4 - where-clause

$result is an array
$sphinx_ranked = SphinxQL::create($conn)->select('*')->from('jobs')->where('id', 'IN', $result)->execute();
after executing I got error
[1064] index jobs: unsupported filter type '(filter-type-6)' on #id [ SELECT * FROM jobs WHERE id IN ('57', '59')]
If I try this
SELECT * FROM jobs WHERE id IN (57,59);
Then this works. But I want dynamic values to be passed.
Any Help would be appreciated.

Sphinx require more accurate approach to control types of variables. Try next:
$sphinx_ranked = SphinxQL::create($conn)
->select('*')
->from('jobs')
->where('id', 'IN', array_map('intval', $result)) // <- int[] instead of string[]
->execute();

Related

Modify select identifiers in Sql Query using calcite

I want to modify a SQL query using Calcite. For example
SELECT values FROM data to
SELECT values as v FROM data
I could access SqlNode of select identifier using SqlVisiter implementation.
public Object visit(SqlCall sqlCall) {
SqlNodeList selectList = ((SqlSelect) sqlCall).getSelectList();
for (SqlNode sqlNode : selectList) {
System.out.println(sqlNode.toString());
}
Now what should I do to update SqlNode?
The SqlNode objects in the select list will be instances of SqlIdentifier in this case. So you'll have to cast sqlNode to a SqlIdentifier and then you can call .setName(0, "NEW_NAME"). After this, you call unparse on the original root node to get the new query back.

How to write database/SQL query in Yii2, with and without a model

I have a table with multiple column and I want to return a column name using another column name as search criteria. How do I achieve this in yii2?
Below is sample code, normal sql should be:
$name = SELECT type_name FROM ProductTable WHERE type_id = 1;
echo $name;
This should return the value of the column type_name where the value of the column type_id equals 1. I tried this, but it doesn't work
$type_name = ProductTable::find()->where(['type_id' =>$model->type_id]);
$type_name = Product::find(['type_name'])->where(['type_id' =>$model->type_id]);
I also tried this, but I guess it was wrong
I hope my question is clear enough and any help will he appreciated
and u could also use createCommand!
$name = \Yii::$app->getDb()->createCommand("SELECT type_name FROM ProductTable WHERE type_id=:typeId", ['typeId'=>$model->type_id])->queryAll();
For a general introduction to Yii2's ActiveRecord, see the guide: http://www.yiiframework.com/doc-2.0/guide-db-active-record.html
If you want the complete row and have a model, you're just missing a one():
Product::find()->where(['type_id' =>$model->type_id])->one();
If you do have a Model defined and just want a single value, try:
Product::find()->select('type_name')->where(['type_id' =>$model->type_id])->scalar();
Which basically generates an ActiveQuery via the model, and changes it to return only the first column in the first row of matched results.
If you do NOT have a model, you could also generate a normal query without ActiveRecord usage (http://www.yiiframework.com/doc-2.0/yii-db-query.html)
$name = (new Query())->select('type_name')
->from('ProductTable')
->where(['type_id' =>$model->type_id])
->scalar();
I assume you generated ProductTable by using Gii module.
Also, if type_id column is a primary key:
$product = ProductTable::findOne($model->type_id);
if($product !== null) { $product->typeName /*... read value ...*/}
or to get all records
$products = ProductTable::findAll($model->type_id); //match all records.
for any other column use the following syntax instead:
$product = ProductTable::findOne(['type_id' => $model->type_id]);
Use following code to get type_name
$PTable=ProductTable::find()->select('type_name')->where(['type_id' =>$model->type_id])->one();
echo $PTable->type_name;

Yii2 bind param to the raw sql statement for the IN field

When I'm using bindParam in the Yii2:
$arr = [1,3];
$str = implode(' ,', $arr);
Yii::$app->db->createCommand('DELETE FROM article_tag WHERE article_id=:id AND tag_id IN (:str)')
->bindValue(':id', $this->id)
->bindValue(':str', $str)
->execute();
if I bind str to the IN field , the raw sql seems to becomes
SQLSTATE[22007]: Invalid datetime format: 1292 Truncated incorrect DOUBLE value: '1 ,3'
The SQL being executed was: DELETE FROM article_tag WHERE article_id=13 AND tag_id IN ('1 ,3')
and it tells me the incorrect double value here. I guess it's because it adds single quotes to the sql . How could I deal with this ??
The code can be refactored to:
Yii::$app
->db
->createCommand()
->delete('article_tag', ['article_id' => $this->id, 'tag_id' => $arr])
->execute();
Use framework features, writing raw SQL is needed for more complex queries.
See this question to understand how params are automatically binded.
Here you can see how to specify condition to where statement.
For most cases it's better to create ActiveRecord and use ActiveQuery for building queries.

Nhibernate and like statement on XML field

I have a wrapped fluent nhibernate framework that I'm reusing and have no control over the actual mapping.
In my entity object I have a property mapped as string to an XML column in sql.
Hence when I run a query like:
var myResult = (from myTable in DataManager.Session.Query<Table>()
where myTable.thatXmlFieldWhichIsMappedAsString.Contains(AnXmlSnippet))
select myTable).FirstOrDefault();
It is trying to use the LIKE operator in SQL which is invalid on that column type.
How can I get around this without having to select all the rows and converting to List first?
In case, that we do not need .Query() (LINQ), and we can use Criteria query or QueryOver, we can use conversion:
// the projection of the column with xml
// casted to nvarchar
var projection = Projections
.Cast(NHibernateUtil.StringClob
, Projections.Property("thatXmlFieldWhichIsMappedAsString"));
// criteria filtering with LIKE
var criteria = Restrictions.Like(projection, "searched xml");
// query and result
var query = session.QueryOver<MyEntity>()
.Where(criteria)
;
var result = query
.SingleOrDefault<MyEntity>()
;
From my experience this could lead to conversion into small nvarchar(255) - sql server... Then we can do it like this:
var projection = Projections
.SqlProjection("CAST(thatXmlFieldWhichIsMappedAsString as nvarchar(max)) AS str"
, new string[]{}
, new NHibernate.Type.IType[]{}
);

Translating SQL query to Doctrine2 DQL

I'm trying to translate this (My)SQL to DQL
SELECT content, created, AVG(rating)
FROM point
GROUP BY DAY(created)
ORDER BY created ASC
And I'm stuck at GROUP BY part, apparently DAY/WEEK/MONTH isn't recognized as valid "function".
[Semantical Error] line 0, col 80 near '(p.created) ORDER': Error: Cannot group by undefined identification variable.
$this->createQueryBuilder('p')
->select('p')
->groupBy('DAY(p.created)')
->orderBy('p.created', 'ASC')
Q: Is it possible to create this kind of query with query builder, or should I use native query?
It is not possible to use custom DAY/WEEK/MONTH user functions in GROUP BY queries in Doctrine 2.1.?, only SELECT queries are supported (not sure for 2.2.? branch), so I ended up using native query, and everything works fine.
Quick overview of the code:
// creating doctrines result set mapping obj.
$rsm = new Doctrine\ORM\Query\ResultSetMapping();
// mapping results to the message entity
$rsm->addEntityResult('Omglol\AppBundle\Entity\Message', 'm');
$rsm->addFieldResult('m', 'id', 'id');
$rsm->addFieldResult('m', 'content', 'content');
$rsm->addFieldResult('m', 'rating', 'rating');
$rsm->addFieldResult('m', 'created', 'created');
$sql = "SELECT id, content, AVG(rating) as rating, created
FROM message
WHERE domain_id = ?
GROUP BY WEEK(created)";
$query = $this->_em->createNativeQuery($sql, $rsm);
$query->setParameter(1, $domainId);
$query->getResult();
There is the same topic in :
Link to google group