How to add multiple sql_query binds at once? - postgresql

I am using diesel crate to comunicate with a PostgreSQL database.
I have a use case where i want to get data from table preferences into struct Preferences.
I want the output from databse to be filterd by tow fields in the table, to have a specific value in column org_id and to be in group of values in column team_id which i store their values in unknown length array, so i can't do
sql_query(raw_sql).bind::<>().execute()
because i don't know the number of
bind::<>()
then I tried to use collect_binds
but it didn't work, itried to do the following
let mut filter = "".to_string();
let mut params:Vec<i64> = vec![];
let mut c =1;
let org_id = 10;
filter.push_str("(org_id=$1 AND team_id IN (");
params.push(org_id);
for team_id in get_needed_teams_id(){
c = c +1;
filter.push_str(&*format!("${}", c));
params.push(team_id );
}
filter.push_str("))");
let raw_sql = format!("SELECT * FROM preferences WHERE {} ORDER BY user_id ASC, team_id ASC", filter);
let preferences:Vec<Preferences> = vec![];
let sql_res = sql_query(raw_sql).collect_binds(&mut param, &preferences);
Error returned :
error[E0284]: type annotations needed: cannot satisfy `<_ as Backend>::BindCollector == Vec<i64>`
--> src\db\preference_db.rs:146:38
|
146 | let sql_res = sql_query(raw_sql).collect_binds(&mut params, &preferences);
| ^^^^^^^^^^^^^ cannot satisfy `<_ as Backend>::BindCollector == Vec<i64>`

There is currently no way in diesel to bind multiple parameters at once in a loop. collect_binds is entirely unconnected to this and exported by the QueryFragment trait. It can be used by the database connection implementation to receive a list of bind parameters for a given query, not to construct a query.

Related

DELTA TABLES - The specified properties do not match the existing properties

I'm using a set of user properties on DataBricks Delta Tables for metadata management. The problem is when I need to change one of those properties I'm getting the 'FAILED Error: The specified properties do not match the existing properties at /mnt/silver/...' error message.
Databricks documentation only states that an Exception will be raised and I didn't find any argument to force it to accept the new values.
Is it possible to just update table Properties?
Any Suggestions?
Sample Code:
query = f'''
CREATE TABLE if not exists {tableMetadataDBName}.{tableMetadataTableName}
(
... my columns ...
-- COMMON COLUMNS
,Hash string
,sourceFilename STRING
,HashWithFileDate string
,Surrogate_Key STRING
,SessionId STRING
,SessionRunDate TIMESTAMP
,Year INT GENERATED ALWAYS AS ( YEAR(fileDate))
,Month INT GENERATED ALWAYS AS ( MONTH(fileDate))
,fileDate DATE
)
USING DELTA
COMMENT '{tableDocumentationURL}'
LOCATION "{savePath}/parquet"
OPTIONS( "compression"="snappy")
PARTITIONED BY (Year, Month, fileDate )
TBLPROPERTIES ("DataStage"="{txtDataStage.upper()}"
,"Environment"="{txtEnvironment}"
,"source"="{tableMetadataSource}"
,"CreationDate" = "{tableMetadataCreationDate}"
,"CreatedBy" = "{tableMetadataCreatedBy}"
,"Project" = "{tableMetadataProject}"
,"AssociatedReports" = "{tableMetadataAssociatedReports}"
,"UpstreamDependencies" = "{tableMetadataUpstreamDependencies}"
,"DownstreamDependencies" = "{tableMetadataDownstreamDependencies}"
,"Source" = "{tableMetadataSource}"
,"PopulationFrequency" = "{tableMetadataPopulationFrequency}"
,"BusinessSubject" = "{tableMetadataBusinessSubject}"
,"JiraProject" = "{tableMetadataJiraProject}"
,"DevOpsProject" = "{tableMetadataDevOpsProject}"
,"DevOpsRepository" = "{tableMetadataDevOpsRepository}"
,"URL" = "{tableMetadataURL}") '''
spark.sql(query)
Yes, it's possible to change just properties - you need to use "ALTER TABLE [table_name] SET TBLPROPERTIES ..." for that:
query = f"""ALTER TABLE {table_name} SET TBLPROPERTIES (
'CreatedBy' = '{tableMetadataCreatedBy}
,'Project' = '{tableMetadataProject}'
....
)"""
spark.sql(query)

query error: no field 'face' found in schema

i have bigint column named as face in mysql. and this is my sphinx.conf
source src1
{
type = mysql
sql_host = localhost
sql_user = root
sql_pass = pass
sql_db = nums
sql_port = 3306 # optional, default is 3306
sql_query = SELECT id,id AS id_attr,tel,name,sex,face from tel
sql_attr_uint = id_attr
sql_attr_bigint = face
}
index num
{
rt_attr_bigint = face
rt_field = face
source = src1
path = C:/sphinx/bin/data/numaralar
}
i can make search by name and tel but not with face.
Fatal error: Uncaught exception 'Foolz\SphinxQL\Exception\DatabaseException' with message '[1064] index nums: query error: no field 'face' found in schema [ SELECT * FROM nums WHERE MATCH('(#face 123456)') LIMIT 0, 10 OPTION max_matches = 5000;SHOW META]' in ..
why may it be?
You are trying to use the value as an field. The # fulltext operator (and indeed the whole of MATCH() full text query, operates on fields ONLY.
You've instead defined face as an atribute. Attributes don't work in full-text queries.
Can
Make face a field instead (remove the sql_attr_bigint) or make it both an attribute and field. (to do that, would have to duplicate it like you've duplicated the id, one for field, one for attribute. or use sql_field_string, but that makes a string attribute)
or
Use filter by the attribute instead. Dont really know how to do that in Foolz. But the SphinxQL query would be something like
SELECT * FROM nums WHERE `face` = 123456 LIMIT 0, 10

How to do a select statement query with comma separator?

I need to do a simple query, Select Statement
I want to search in Table all record with value "ValueA, ValueB".
If I use this code, not work well:
String255 valueToFilter;
valueToFilter = 'ValueA, ValueB';
select count (RecId) from MyTable
where MyTable.Field like valueToFilter ;
But not working, I need to keep all record with value "ValueA" or "ValueB", if in the file there is value like : "ValueA, ValueC" I want to get too.
I don't know the number of values (valueToFilter).
Thanks!
From my point of view the easiest way to accomplish this is to split your filter string:
String255 valueToFilterA = 'ValueA';
String255 valueToFilterB = 'ValueB';
;
select count (RecId) from MyTable
where MyTable.Field like valueToFilterA
|| MyTable.Field like valueToFilterB;
If you don't know the number of values you should use query object to add ranges dynamically:
Query query = new Query();
QueryRun queryRun;
QueryBuildDataSource qbds;
QueryBuildRange queryRange;
container conValues;
;
qbds = query.addDataSource(tableNum(MyTable));
for (i = 1; i <= conlen(conValues); i++)
{
queryRange = qbds.addRange(fieldNum(MyTable, Field));
queryRange.value(SysQuery::valueLike(conPeek(conValues, i)));
}
queryRun = new QueryRun(query);
info(strFmt("Records count %1", SysQuery::countTotal(queryRun)));

Selecting parent records by filtering multiple fields of collection of links

I have been trying to figure out this for a couple of days know but I can't come up with a query that gives me the correct results. The essence of the task is that I am trying to retrieve all the nodes of a graph that have children with attributes that satisfy multiple constraints. The issue I have is that a node may have multiple linked nodes and when I try to apply criteria to restrict which nodes must be returned by the query the criteria need to be imposed against sets of nodes instead of individual nodes.
Let me explain the problem in more detail through an example. Here is a sample schema of companies and locations. Each company can have multiple locations.
create class company extends V;
create property company.name STRING;
create class location extends V;
create property location.name STRING;
create property location.type INTEGER;
create property location.inactive STRING;
Let me now create a couple of records to illustrate the problem I have.
create vertex company set name = 'Company1';
create vertex location set name = 'Location1', type = 5;
create vertex location set name = 'Location2', type = 7;
create edge from (select from company where name = 'Company1') to (select from location where name in ['Location1', 'Location2']);
create vertex company set name = 'Company2';
create vertex location set name = 'Location3', type = 6;
create vertex location set name = 'Location4', type = 5, inactive = 'Y';
create edge from (select from company where name = 'Company2') to (select from location where name in ['Location3','Location4']);
I want to retrieve all companies that either don't have a location of type 5 or have a location of type 5 that is inactive (inactive = 'Y'). The query that I tried initially is shown below. It doesn't work because the $loc.type is evaluated against a collection of values instead of a individual record so the is null is not applied against the individual field 'inactive' of each location record but against the collection of values of the field 'inactive' for each parent record. I tried sub-queries, the set function, append and so on but I can't get it to work.
select from company let loc = out() where $loc.type not contains 5 or ($loc.type contains 5 and $loc.type is null)
You can try with this query:
select expand($c)
let $a = ( select expand(out) from E where out.#class = "company" and in.#class="location" and in.type = 5 and in.inactive = "Y" ),
$b = ( select from company where 5 not in out("E").type ),
$c = unionAll($a,$b)
UPDATE
I have created this graph
You can use this query
select expand($f)
let $a = ( select from E where out.#class = "company" and in.#class="location" ),
$b = ( select expand(out) from $a where in.type = 5 and in.inactive = "Y"),
$c = ( select expand(out) from $a where in.type = 5 and in.inactive is null),
$d = difference($b,$c),
$e = ( select from company where 5 not in out("E").type ),
$f = unionAll($d,$e)
Hope it helps.
Try this query:
select expand($d) from company
let $a=(select from company where out().type <> 5 and name contains $parent.current.name),
$b=(select from company where out().type contains 5 and name=$parent.current.name),
$c=(select from company where out().inactive contains "Y" and name=$parent.current.name),
$d=unionall($a,intersect($b,$c))
Hope it helps,
Regards,
Michela

How to join the tables in linq to sql?

Table1 :
userid name address
1 venkat srinagr
2 venkatesh sainagar
Table2:
id userid lat lon
1 1 14.000 15.000
2 2 14.3526 15.3698
by passing "venkat" as parameter then need to pull all matching records and his userid,name,lat,lon.
in above table1 "venkat" contains in both rows then need to pull 2 records.how to get userid,name,lat,lon for all matching rows..
for sigle record i am able to get.but there are multiple rows how to get please tell me....
var result = from p in cxt.Table2
where p.Table1.Name.Contains(name)
select new
{
p.Users.User_Id,p.Users.Name,p.Latitude,p.Longitude
};
Im sure someone will say this is not the most effective way but this is how i would do it.
string InputString = "venkat";
var tab =(from a in db.tablea
from b in db.tableb
where a.userid == b.userid && a.name == InputString
select new
{
UserID = a.userid,
Username = a.name,
Latitude = b.lat,
Longditude = b.lon
}).FirstOrDefault();
FirstOrDefault() is only if you want to force only one output or null,
if you want a collection of some sort, then just remove it.