I had lookup fields (type:int64, Extended from RefRecId) and I had written lookup filtering code for them but I had to convert them into strings ( I had added relations to make them lookup fields) But since they are "String" instead of "reference group" my code doesn't work. How can I filter them when they are 'string'. Here is my code for filtering for reference groups:
[FormControlEventHandler(formControlStr(InventSite, InventSite_MyField), FormControlEventType::Lookup)]
public static void InventSite_MAndEDay_OnLookup(FormControl sender, FormControlEventArgs e)
{
SysReferenceTableLookup tableLookup = SysReferenceTableLookup::newParameters(tableNum(ReferenceTables), sender);
Query query = new Query();
InventSite inventSite;
QueryBuildDataSource qbds = query.addDataSource(tableNum(ReferenceTables));
qbds.addRange(fieldNum(ReferenceTables,ReferenceTablesType )).value(queryValue(ReferenceTablesTypeBaseEnum::MyField));
tableLookup.addLookupField(fieldNum(ReferenceTables, Name ));
tableLookup.addLookupField(fieldNum(ReferenceTables, Description ));
tableLookup.parmQuery(query);
tableLookup.performFormLookup();
Can you please help me with this?
Thanks and regards...
use sysTableLookup instead of SysReferenceTableLookup
Related
I want to write junit for this method returning country List
public List<String> getCountries(String countryCd) {
String sql = "select COUNTRY_NAME from MY_COUNTRY WHERE COUNTRY_CD = :countryCd ";
List<String> countries;
SqlParameterSource parameters = new MapSqlParameterSource().addValue("countryCd", countryCd);
countries = namedParameterJdbcTemplate.query(sql,parameters, (resultSet, rowNum) ->
resultSet.getString("COUNTRY_NAME")));
return countries
}
I tried something like this
Mockito.when(namedParameterJdbcTemplate.queryForObject(queryJobs, parameters, String.class))
MapSqlParameterSource inherits its equals method from Object.
This means that 2 parameter sources are equal only if they reference same instance.
You need to provide an argument matcher to compare this argument and not use equals method. The cleanest way to do it is via Custom Argument Matcher.
Alternatively, you relax the requirements for this argument and use any(MapSqlParameterSource.class) matcher.
try using
Mockito.when(namedParameterJdbcTemplate.queryForObject(any(), any(), any())).thenRetrun(you v
I have clients passing in IDs like this: /v1/path?id=1,2,3
What I have and want
I have a resource class for Dropwizard/Jersey.
I'd like to show up the query-parameter id=1,2,3 as a List parameter in my resource's GET method
// Resource class
public List<Something> getFilteredList(#QueryParam("id") List<String> ids) {
// filter the List<Something> based on a list of ids
}
Right now, the ids list contains 1 string which is "1,2,3".
What I tried
I tried a filter but the query parameters given by Jersey's
ContainerRequestContext.getUriInfo().getQueryParameters()
is immutable.
Questions
I would like to apply a filter and change any comma separated query parameters into multi-valued parameters so that the resource method gets a list instead.
Is there a way to change the existing query parameters using a Jersey filter?
What's a good way to solve this problem?
The best way I can think of is to just create a wrapper class for the list. This makes it easier to take advantage of the specified functionality of Jersey. You can see what I mean at Passing custom type query parameter.
For example
public class IdFilter {
private List<String> ids = new ArrayList<>();
public List<String> getIds() { return ids; }
public static IdFilter valueOf(String param) {
IdFilter filter = new IdFilter();
for (String id: param.split(",") {
filter.getIds().add(id);
}
}
}
getFilteredList(#QueryParam("id") IdFilter ids) {
We don't need to do anything else. Just having the static valueOf is enough for Jersey to know how to parse the query string.
3 ways to solve it:
use the generic context-parameter UriInfo , which is not very expressive
add an explicit custom type that can parse a comma-separated list
stay with #QueryParam List<String> requiring a concatenated query like ?id=1&id=2&id=3 given as URI
I would prefer the second as most-expressive, like answered already by Paul. This way you can concisely pass a single CSV like ?id=1,2,3,3 and also use a Set to ensure unique ID values, e.g. resulting in only [1, 2, 3].
Generic context-param UriInfo
One way would be to use a generic parameter #Context UriInfo to get the list in the method's body:
public List<Something> getFilteredList( #Context UriInfo uriInfo ) {
List<String> idList = uriInfo.getQueryParameters().get("id"); // before was #QueryParam("id")
System.out.println("idList: " + idList);
// filter a given list by ids
var somethingFiltered = getSomethingList().stream()
.filter(s -> idList.contains(s.getId()))
.collect(toList());
return Response.status(Status.OK).entity(somethingFiltered).build();
}
See the tutorial in Java Vogue(2015): QueryParam Annotation In Jersey -
Custom type with static valueOf(String) factory-method
The other way is to design a custom type which can be constructed using a String:
class IdSet {
Set<String> values;
// a factory method, can also be named valueOf
public static IdSet fromString(String commaSeparated) {
return new HashSet( Arrays.asList( commaSeparated.split(",") ) );
}
}
public List<Something> getFilteredList(#QueryParam("id") IdSet ids) {
System.out.println("ids (Set): " + ids.values);
// filter a given list by ids
var somethingFiltered = getSomethingList().stream()
.filter(s -> ids.values.contains(s.getId()))
.collect(toList());
return Response.status(Status.OK).entity(somethingFiltered).build();
}
See Jersey's JavaDocs for #QueryParam:
The type T of the annotated parameter, field or property must either:
Be a primitive type
Have a constructor that accepts a single String argument
Have a static method named valueOf or fromString that accepts a single String argument (see, for example, Integer.valueOf(String))
Have a registered implementation of ParamConverterProvider that returns a ParamConverter instance capable of a "from string" conversion for the type.
Be List<T>, Set<T> or SortedSet<T>, where T satisfies 2, 3 or 4 above. The resulting collection is read-only.
Use a collection interface with multiple key-value pairs
When the calling client uses following URI pattern: /something?id=1&id=2&id=3 then JAX-RS can deserialize them to a single parameter of List<String> id having given multiple elements:
public List<Something> getFilteredList(#QueryParam("id") List<String> ids) {
System.out.println("ids : "+ids);
// filter a given list by ids
var somethingFiltered = getSomethingList().stream()
.filter(s -> ids.contains(s.getId()))
.collect(toList());
return Response.status(Status.OK).entity(somethingFiltered).build();
}
See Mkyong: JAX-RS #QueryParam example where explained the multiple occurrences of orderBy in the GET query:
#QueryParam will convert the query parameter “orderBy=age&orderBy=name” into java.util.List automatically.
See also
Handling Multiple Query Parameters in Jersey
Deserializing List<Map<String, String>> QueryParam in jersey 1
Jersey, #QueryParam List<String>
I am new to .Net field and i wrote a method in c# which takes a string as a parameter from the data base and returns a BusinessContact type which consists entityid, contactid, name, alias.
Here is my code
public BusinessContact GetAccountExecutiveForBroker(string brokerUserName)
{
SqlStatement select = new SqlStatement();
select.Sql = #"select cb.* from custom_brokers cb
join rolodex_contacts rc on cb.aecontactid = rc.contactid and cb.lenderdatabaseid = rc.lenderdatabaseid
where cb.brokerusername = #brokerUserName";
select.AddParameter("brokerusername", brokerUserName);
return db.SelectObject(select, MapContact);
}
I am unable to figure out what unit test cases can be performed on this method. Please help me with this.
You can test input parameter brokerUserName.
if it is empty.
if it is null
if it contains sql injection data (like 'a' or 1=1 --;)
I have a class (ServicesTableModel) which inherits from QSqlRelationalTableModel. In the constructor I have:
ServicesTableModel::ServicesTableModel( QWidget* parent, QSqlDatabase db )
: QSqlRelationalTableModel( parent, db )
{
setTable( "servicios" );
select();
...
}
Now, if I place the line
qDebug() << primaryKey();
where the dots are I get
QSqlRecord( 1 )
" 0:" QSqlField("ser_id", int, required: no, generated: yes)
which makes perfect sense, but after
qDebug() << primaryKey().name();
the answer is
""
so I can't reach the name of the primary key.
The table is sqlite, defined with
CREATE TABLE servicios (ser_id integer primary key, ... )
This matters because I'm trying to generalize the class for objects closely related to the rows in a table, and it seems natural not to have to provide the primary key name to the constructor.
I must surely be doing something wrong, or I don't understand what the name()_ method from QSqlField does.
primaryKey.name() returns the name of the index.
In SQL, an index can be named, and this is independent from the name of the field(s) used for the key.
An index can work on several fields.
Each field name can be retrieved with key.fieldName(i), with 0<i<key.count()
I am trying to get Doctrine2 Entities, ordered by their ID which apparently is a String even though it contains only Numbers.
So what I would like to do is something like this:
SELECT entity1, cast (entity1.id AS integer) AS orderId
FROM Namespace\Bla\MyEntity
ORDER BY orderId
Is there a way to do something like this in Doctrine2?
Or, what would be the best practise to get my Result if i can't change the type of the id (due to customer requirements of course)?
Attention: I am not asking SQL Code, i am asking for a Doctrine2 Solution, preferably in DQL
You should be able to add your own function to implement this feature.
The class would look something like this:
namespace MyProject\Query;
use Doctrine\ORM\Query\AST\Functions\FunctionNode;
use Doctrine\ORM\Query\Lexer;
use Doctrine\ORM\Query\Parser;
use Doctrine\ORM\Query\SqlWalker;
class CastAsInteger extends FunctionNode
{
public $stringPrimary;
public function getSql(SqlWalker $sqlWalker)
{
return 'CAST(' . $this->stringPrimary->dispatch($sqlWalker) . ' AS integer)';
}
public function parse(Parser $parser)
{
$parser->match(Lexer::T_IDENTIFIER);
$parser->match(Lexer::T_OPEN_PARENTHESIS);
$this->stringPrimary = $parser->StringPrimary();
$parser->match(Lexer::T_CLOSE_PARENTHESIS);
}
}
You'll need to register your function:
$config = $em->getConfiguration();
$config->addCustomNumericFunction('INT', CastAsInteger::class);
Then you can use it:
SELECT e, INT(e.id) AS HIDDEN orderId
FROM Namespace\Bla\MyEntity e
ORDER BY orderId
PS: By adding the HIDDEN keyword, the alias orderId won't be in the results (and is only used for ordering).
Based on Jasper N. Brouwer answer, this is a little bit enhanced solution:
<?php
namespace MyProject\Query;
use Doctrine\ORM\Query\AST\Functions\FunctionNode;
use Doctrine\ORM\Query\Lexer;
use Doctrine\ORM\Query\Parser;
use Doctrine\ORM\Query\SqlWalker;
class Cast extends FunctionNode
{
/** #var \Doctrine\ORM\Query\AST\PathExpression */
protected $first;
/** #var string */
protected $second;
/**
* #param SqlWalker $sqlWalker
*
* #return string
*/
public function getSql(SqlWalker $sqlWalker)
{
return sprintf("CAST(%s AS %s)",
$this->first->dispatch($sqlWalker),
$this->second
);
}
/**
* #param Parser $parser
*
* #return void
*/
public function parse(Parser $parser)
{
$parser->match(Lexer::T_IDENTIFIER);
$parser->match(Lexer::T_OPEN_PARENTHESIS);
$this->first = $parser->ArithmeticPrimary();
$parser->match(Lexer::T_AS);
$parser->match(Lexer::T_IDENTIFIER);
$this->second = $parser->getLexer()->token['value'];
$parser->match(Lexer::T_CLOSE_PARENTHESIS);
}
}
Now it should be possible to write DQL like this:
SELECT e, CAST(e.id AS integer) AS HIDDEN orderId FROM Namespace\Bla\MyEntity e ORDER BY orderId
Try this one by with out changing the data type
select (entity1 * 1) as display_value, entity1 as return_value
from Table_Name
order by 1 asc;
Think it's better to use some extra functional in such cases ( without trying "to circumvent" theirs). E.g. an excellent solution adding almost all necessary ( not supported from box ) stuff for Doctrine 2 is DoctrineExtensions by beberlei (github). With it it's possible to use directly CAST-statement like in OP's case:
("Symfony-example") E.g. in your config.xml add lines:
orm:
..
entity_managers:
....
dql:
....
string_functions:
CAST: DoctrineExtensions\Query\Mysql\Cast
Then U can use it like:
SELECT entity1, CAST(entity1.id AS integer) AS orderId
FROM Namespace\Bla\MyEntity
ORDER BY orderId
Not sure if this works, but to access an entity ID you need the IDENTITY() DQL function. Try this:
SELECT entity1 FROM Namespace\Bla\MyEntity ORDER BY IDENTITY(entity1)
I think you want order by entity1. if your entity1 data type is integer then no need to change it into integer or if it is not then you should do it. below is query for you.try this one.
select entity1,cast(entity1 as integer) as order_id from Table_Name order by 1 asc;
I just did something similar in my own code yesterday. I was able to do:
select cast(entity1 as int) as OrderID
from yourtablename
where yourconditions
I had to actually cast mine as money and then int, but if you don't have a decimal, you should not have that issue. You can also try casting as numeric or using convert instead of cast, but cast is better in this situation.
Why do you need entity1 as a column if you already have the same value in OrderID?