i have this flexisearch code:
import de.hybris.platform.core.model.order.*
import de.hybris.platform.core.model.product.*
import de.hybris.platform.jalo.flexiblesearch.FlexibleSearch;
query = """
Select {o:code}, {p:code}, {oe:rrp} from {
OrderEntry as oe
join Order as o on {oe:order}={o:pk}
join Product as p on {oe:product}={p:pk}
}
where {o:code} = ?orderCode
"""
result = FlexibleSearch.getInstance().search(query, [orderCode: "12345555"], [String.class, String.class, String.class], true, true, 0, -1).result
int i = 1;
for (result in result){
out.println(result.get(0) + "--" + result.get(1) + "--" + result.get(2));
i++
}
But I wanted to add multiple order codes to the query so I can fetch orders depending on the code. Something like:
orderCode: "12345555", "1576789", "56768"
What should be my query to achieve my requirement?
Related
Scenario : send post request until a condition meet but maximum 5 times otherwise fail the script
step1: get one data from database
step2: get 2nd data from db based on step one result(if step 2 gives null then start again from step 1 and maximum occurrence can be 5 times)
step3: prepare a soap request and put 1st and 2nd data as input in the request body which we got in step 1 and 2.
Step4: send a soap request and print the response
step5: validate if response.id >5000(if this condition doesn't fulfill repeat the process from step1 to step 5 but again repeat only till 5 times and if still condition doesn't fulfill till 5th time then fail the test case)
Note:- I tried with retry until as well but looks like it keeps sending the step 5 only so it will not change the request body data which we need to change after every run from step 1 to step 5.
Also, I researched a lot and came across many similar questions but couldn't achieve my desired result.
Condition based on response value in karate
Scenario: GetCountriesWithId
* def RandomNumber =
"""
function() {
var count = 1
while (count<=5) {
var RandomNumber = db.readRows("select trunc(dbms_random.value(10000000, 10010000)) min, trunc(dbms_random.value(10200000, 10250000)) max from dual")
karate.log('RandomNumber->',RandomNumber)
var HolderFromDB = db.readRows("SELECT productId, userId from table1 WHERE id between "+RandomNumber[0].MIN+" and "+RandomNumber[0].MAX+" ")
if (HolderFromDB.length >= 1) {
karate.log('condition satisfied, exiting');
return HolderFromDB;
}
count++
}
}
"""
* def HolderFromDB = call RandomNumber
* def productId = HolderFromDB.productId
* def userId = HolderFromDB.userId
* def javaclass = Java.type('epos.positionmanagement.service.test.GetSpendingLimitRequestTest')
* def map = {deviceTypeId: 2, entityId: '#(defaultEntity)', ppr_id: '#(productId)', userId: '#(userId)' }
* def createGetSpendingLimitRequest = javaclass.getPayload(map)
Then print 'Request body--->', createGetSpendingLimitRequest
Given request createGetSpendingLimitRequest
When soap action 'Request'
Then status 500
Then print '\n', response
* def revisionId = get response //GetSpendingLimitResponse/spendingLimit/totalAmount*1
* def result = revisionId<=50000 ? karate.call('test1.feature') : {}
I think this test case should not be automated. Because it is not clear and it has a lot of dependent situation. You should take principle for making each test case standalone and independent. Also Test cases should have been good designed so that you can easily develop a code for them. Otherwise even if you have achieved to automate them, they will be most probably flaky tests and you will spend more time to fix them instead of testing them manually. Think twice, think scenarios once more also and decide your next move. Also please take a look this business logic which mentioned in your scenarios once more since it doesn't look so logical.
I have resolved the issue as below:-
Put the steps till post request in another feature file as below:-
#ignore
Feature: Reusable
Background: Maintenance Soap Request
* def DbUtils = Java.type('util.DbUtils')
* def db = new DbUtils(eposEnvironment.database[defaultEntity])
* url eposEnvironment.baseUrl
#Limit-GTC-Straddle #parallel=false
Scenario: Limit-GTC-Straddle
* def derivativeOrderTemp =
"""
function() {
var count = 1
while (count <= 10) {
var selectRandomLetter = db.readRows("select chr(trunc(dbms_random.value(65,74))) firstLetter, chr(trunc(dbms_random.value(80,90))) lastLetter, trunc(dbms_random.value(1, 4)) positionToBuy, to_char(current_date + 364, 'YYYY-MM-DD') expDate from dual")
var symbol1FromDB = db.readRows("select * from (select be_symbool, RTRIM(be_muntsoort) as be_muntsoort, be_code, be_optietype, be_expiratiedatum as be_expiratiedatum2, to_char(to_date(be_expiratiedatum, 'YYYYMMDD'), 'YYYY-MM-DD') as be_expiratiedatum, be_exerciseprijs, brs_naam, be_bv_beurs, round(max (quot_laat) keep (dense_rank last order by quot_datum)+ 1, 0) as limit, (round(max (quot_laat) keep (dense_rank last order by quot_datum)+ 1, 0)*100*-1*" + selectRandomLetter[0].POSITIONTOBUY + ") effAmount, be_volgnummer from beleggingsinstrument join fn_quotes_table on quot_symbool = be_symbool and quot_optietype = be_optietype and quot_expiratiedatum = be_expiratiedatum and quot_exerciseprijs = be_exerciseprijs join beurzen on brs_nummer = be_bv_beurs where be_Symbool in (select be_symbool from beleggingsinstrument where be_bi_nummer = 100 and length(trim(be_symbool)) < 4 and substr(trim(be_symbool),1,1) between '" + selectRandomLetter[0].FIRSTLETTER + "' and '" + selectRandomLetter[0].LASTLETTER + "' and be_geblokkeerd = 0 and be_handelen_toegestaan = 1 and be_referentiesymbool = ' ') and be_optietype = 'CALL' and be_handelen_toegestaan = 1 and be_expiratiedatum > to_char(sysdate, 'yyyymmdd') group by be_symbool, be_muntsoort, be_code, be_optietype, be_expiratiedatum, be_exerciseprijs, be_bv_beurs, quot_laat, brs_naam, quot_laat, quot_datum, be_volgnummer ) where rownum = 1")
karate.log('Symbol1FromDB-->', symbol1FromDB)
if (symbol1FromDB.length >= 1) {
karate.log('condition satisfied, exiting from first conditionalGoto1 loop counter');
var indirectCosts1FromDB = db.readRows("select icf_cfcu_id, cfcu_description, decode(icf_amount, null, 0, icf_amount) icf_amount, decode(icf_currency, null, 'NULL', icf_currency) icf_currency, decode(icf_percentage, null, 0, icf_percentage) icf_percentage from EPP_OWNER.INDIRECT_COSTS_PER_FUND join epp_owner.calculationrules on cfcu_id = icf_cfcu_id where icf_be_id = " + symbol1FromDB[0].BE_VOLGNUMMER + " and (icf_import_date_till > to_char(sysdate, 'yy-mm-dd') or icf_search_date_till is null) and icf_ex_ante_ex_post_ind = 'A' and icf_cfcu_id in (67)")
karate.log('indirectCosts1FromDB-->', indirectCosts1FromDB)
var symbol2FromDB = db.readRows("select * from (select be_symbool, RTRIM(be_muntsoort) as be_muntsoort, be_code, be_optietype, to_char(to_date(be_expiratiedatum, 'YYYYMMDD'), 'YYYY-MM-DD') as be_expiratiedatum, be_exerciseprijs, brs_naam, be_bv_beurs, round(max (quot_laat) keep (dense_rank last order by quot_datum)+ 1, 0) as limit, (round(max (quot_laat) keep (dense_rank last order by quot_datum)+ 1, 0)*100*-1*" + selectRandomLetter[0].POSITIONTOBUY + ") effAmount, be_volgnummer from beleggingsinstrument join fn_quotes_table on quot_symbool = be_symbool and quot_optietype = be_optietype and quot_expiratiedatum = be_expiratiedatum and quot_exerciseprijs = be_exerciseprijs join beurzen on brs_nummer = be_bv_beurs where be_Symbool = '" + symbol1FromDB[0].BE_SYMBOOL + "' and be_optietype = 'PUT' and be_handelen_toegestaan = 1 and be_expiratiedatum = '" + symbol1FromDB[0].BE_EXPIRATIEDATUM2 + "' group by be_symbool, be_muntsoort, be_code, be_optietype, be_expiratiedatum, be_exerciseprijs, be_bv_beurs, quot_laat, brs_naam, quot_laat, quot_datum, be_volgnummer ) where rownum = 1")
karate.log('Symbol2FromDB-->', symbol2FromDB)
var indirectCosts2FromDB = db.readRows("select icf_cfcu_id, cfcu_description, decode(icf_amount, null, 0, icf_amount) icf_amount, decode(icf_currency, null, 'NULL', icf_currency) icf_currency, decode(icf_percentage, null, 0, icf_percentage) icf_percentage from EPP_OWNER.INDIRECT_COSTS_PER_FUND join epp_owner.calculationrules on cfcu_id = icf_cfcu_id where icf_be_id = " + symbol2FromDB[0].BE_VOLGNUMMER + " and (icf_import_date_till > to_char(sysdate, 'yy-mm-dd') or icf_search_date_till is null) and icf_ex_ante_ex_post_ind = 'A' and icf_cfcu_id in (67)")
karate.log('indirectCosts2FromDB-->', indirectCosts2FromDB)
var selectRandomNumber = db.readRows("select trunc(dbms_random.value(10020000, 10050000)) min, trunc(dbms_random.value(11000000, 11500000)) max from dual")
karate.log('selectRandomNumber-->', selectRandomNumber)
var holderFromDB = db.readRows("SELECT * from (select ap_relatienr, ap_rekeningnr, hpp_holdernummer, ppr_id from aktuele_posities ap join epp_owner.rekeningen_per_product on rpp_relatienummer = ap.ap_relatienr and rpp_rekening_nummer = ap.ap_rekeningnr and rpp_rekeningsoort = ap.ap_rekening_soort join epp_owner.holders_per_product on hpp_relatienummer = rpp_relatienummer and hpp_product = rpp_productnummer and hpp_product_volgnr = rpp_volgnr_per_product and hpp_type_holder = 1 join rekeningen on re_rekening = rpp_rekening_nummer and re_nummer = rpp_relatienummer and re_rekening_status = 2 join epp_owner.wwwusers on wus_holder = hpp_holdernummer and wus_userblocked = 0 join producten_per_relatie on ppr_relatienummer = rpp_relatienummer and ppr_productnummer = rpp_productnummer and ppr_volgnr_per_product = rpp_volgnr_per_product JOIN on_line_dossier onld ON onld.onld_relatienummer = hpp_relatienummer and onld_productnummer = rpp_productnummer join kennis_per_client a on rpp_relatienummer = ke_clientnr where rpp_productnummer = 100 and rpp_volgnr_per_product = 1 and ap.ap_rekening_soort = 1000 and ap_saldo_positie > 7000 AND ap.ap_relatienr between " + selectRandomNumber[0].MIN + " and " + selectRandomNumber[0].MAX + " and onld.onld_klasse = 16 and onld.onld_ontvangstdatum <> '00000000' and onld.onld_vervaldatum = '00000000' and ((ke_kennis_niv = 'V' or ke_ervaring = 'V') and ke_mifcat_id = 25) and not exists (select 1 from kennis_per_client b where (ke_kennis_niv = 'O' or ke_ervaring = 'O') and a.ke_clientnr = b.ke_clientnr) and rpp_relatienummer in (select cl_nummer from clienten where cl_nummer between " + selectRandomNumber[0].MIN + " and " + selectRandomNumber[0].MAX + " and cl_geb_datum < to_char(add_months(sysdate, -216), 'YYYYMMDD')) and not exists (select 1 from profiel_toevoeging_verwijderen where ptv_relatie = ap.ap_relatienr) and not exists (select 1 from rekeninghouders_details where UPPER(eor_compliancecode) like 'INSIDER%' and eor_partij_id = hpp_holdernummer) ) where rownum = 1")
karate.log('holderFromDB-->', holderFromDB)
while (count <= 10) {
if (holderFromDB.length >= 1) {
karate.log('condition satisfied, exiting from conditionalGoto2');
productId = holderFromDB[0].get('PPR_ID')
userId = holderFromDB[0].get('HPP_HOLDERNUMMER')
return {
productId,
userId
};
}
count++;
if (count >= 9) {
karate.fail('Count exceeded more than 10 times and conditionalgoto2 loop counter failed')
}
}
count++;
if (count >= 9) {
karate.fail('Count exceeded more than 10 times and conditionalgoto1 loop counter failed')
}
}
}
}
"""
* def derivativeTemp = call derivativeOrderTemp
* def productId = derivativeTemp.productId
* print 'Product Id is-->',productId
* def userId = derivativeTemp.userId
* print 'User Id is-->',userId
################GetSpendingLimit###########################
* def javaclass = Java.type('epos.positionmanagement.service.test.GetSpendingLimitRequestTest')
* def map = {deviceTypeId: 2, entityId: '#(defaultEntity)', ppr_id: '#(productId)', userId: '#(userId)' }
* def createGetSpendingLimitRequest = javaclass.getPayload(map)
Then print 'Request body--->', createGetSpendingLimitRequest
Given request createGetSpendingLimitRequest
When soap action 'Request'
Then print '\n', response
And then call this feature file from other test case feature file as below :-
#Ordering
Feature: CreateCombinationDerivativeOrderTemp
Background: Ordering Soap Request
* url eposEnvironment.baseUrl
#parallel=true
Scenario: Limit-GTC-Straddle
* call read('reusable.feature#Limit-GTC-Straddle')
* def revisionId = get response //GetSpendingLimitResponse/spendingLimit/totalAmount*1
# * eval for(var i=0; i<=10; i++) (revisionId<3000 && i<10 ? karate.call('request1.feature') : karate.fail('Condition did not fulfill in 10 occurrence hence failing the test case'))
* def condionalgoto3 =
"""
function() {
for (var i = 0; i <= 10; i++) {
if (revisionId < 3000) {
karate.call('request1.feature')
if (i >= 9) {
karate.fail('Count exceeded more than 10 times and conditionalgoto3 loop counter failed')
}
}
}
}
"""
* call condionalgoto3
Note :- These java classes I am using to create a payload xml which was requirement of the project and these java classes are nothing but the actual services which I have added as pom dependency in my project which directly gives me the payload xml request and I just create a map and fill the value in the request body so these java classes are mandatory to use.And also these db queries are being used to fetch the actual customer details from a database to prepare the request body so there is nothing which I can ignore or improve in this test case but yes in some queries they are using some random values to fetch some customer data that I can definitely use some Java/Js/Karate.range() but apart from that I really dont think I can improve anything here.
We use a google script to get data from a SQL database into a spreadsheet. There is a time-driven trigger for the function.
Every time I run the function, there is a time out.
Exception: The query has timed out
When I run the function a second time, it usually works fine. Does anybody has a solution for that?
The address and password of the Database is not shown here.
function onOpen() {
var spreadsheet = SpreadsheetApp.getActive();
var menuItems = [
{name: 'JTL Import', functionName: 'readData'}
];
spreadsheet.addMenu('JTL-Import', menuItems);
}
// Replace the variables in this block with real values.
var address = 'XXXX'; //ex. '10.1.1.1:1433'
var user = 'TAXDOO';
var userPwd = 'XXX';
var db = 'eazybusiness';
var dbUrl = 'jdbc:sqlserver://' + address + ';databaseName=' + db;
function StockUnitsSold30days() {
var conn = Jdbc.getConnection(dbUrl, user, userPwd);
var stmt = conn.createStatement();
var results = stmt.executeQuery("SELECT a.cArtNr SKU, aaI18n.cwertvarchar [Cut_ID], CONVERT(FLOAT, ISNULL(wmsLager.fbestand, 0)) [Stock_WMS], CONVERT(FLOAT, ISNULL(StreckenLager.fbestand, 0)) [Stock_Streckenlager], CONVERT(FLOAT, ISNULL(fba.fanzahlfba, 0)) [Stock_FBA], CONVERT(FLOAT, ISNULL(PendingLager.fbestand, 0)) [Stock_Pending], CONVERT(FLOAT, ISNULL(WmsAusgang.Anzahl, 0)) [Units_WMS_Outgoing], CONVERT(FLOAT, ISNULL(fbaAusgang.SumAnzahl, 0)) [Units_FBA_Outgoing],CONVERT(FLOAT, ISNULL(MengeAufWarenEingang.fAnzahlAktuell,0)) [Stock_Wareneingangsplatz] FROM dbo.tartikel a INNER JOIN dbo.tartikelattribut aa ON aa.kartikel = a.kartikel INNER JOIN dbo.tartikelattributsprache aaI18n ON aaI18n.kartikelattribut = aa.kartikelattribut AND aaI18n.ksprache = 0 INNER JOIN dbo.tattributsprache attributI18n ON attributI18n.kattribut = aa.kattribut AND attributI18n.ksprache = 0 AND attributI18n.cname = 'CutDesign_ID' LEFT OUTER JOIN dbo.vlagerbestandfba fba ON a.kArtikel = fba.kartikel LEFT OUTER JOIN dbo.vlagerbestandprolageralle wmsLager ON wmsLAger.kartikel = a.kArtikel AND wmsLager.kwarenlager = 4 LEFT OUTER JOIN dbo.vlagerbestandprolageralle StreckenLager ON StreckenLager.kartikel = a.kArtikel AND Streckenlager.kwarenlager = 5 LEFT OUTER JOIN dbo.vlagerbestandprolageralle PendingLager ON PendingLager.kartikel = a.kArtikel AND PendingLager.kwarenlager = 7 LEFT OUTER JOIN (SELECT a.kArtikel, SUM(wla.fAnzahl) Anzahl FROM dbo.tBestellung b JOIN dbo.tbestellpos bp ON bp.tBestellung_kBestellung = b.kBestellung JOIN dbo.trechnung r ON r.tBestellung_kBestellung = b.kBestellung JOIN dbo.tLieferschein l ON l.kBestellung = b.kBestellung JOIN dbo.tLieferscheinPos lp ON lp.kBestellPos = bp.kBestellPos JOIN dbo.tWarenLagerAusgang wla ON wla.kLieferscheinPos = lp.kLieferscheinPos JOIN dbo.tArtikel a ON bp.tArtikel_kArtikel = a.kArtikel WHERE DATEDIFF(dd, b.derstellt, GETDATE()) <= 30 GROUP BY a.kArtikel ) AS WmsAusgang ON WmsAusgang.kArtikel = a.kArtikel LEFT OUTER JOIN (SELECT map.kArtikel, SUM(abp.nQuantityPurchased) SumAnzahl FROM dbo.pf_amazon_bestellung ab JOIN dbo.pf_amazon_bestellungpos abp ON abp.kAmazonBestellung = ab.kAmazonBestellung JOIN dbo.tBestellung b ON b.cInetBestellNr = ab.cOrderId JOIN dbo.trechnung r ON r.tBestellung_kBestellung = b.kBestellung JOIN dbo.pf_amazon_angebot_mapping map ON map.cSellerSKU = abp.cArtNr WHERE nFBA = 1 AND cOrderStatus = 'Shipped' AND DATEDIFF(dd, b.derstellt, GETDATE()) <= 30 GROUP BY map.kArtikel) FbaAusgang ON FbaAusgang.kArtikel = a.kArtikel LEFT OUTER JOIN (SELECT DISTINCT ta.kArtikel, twle.fAnzahlAktuell FROM dbo.tArtikel ta JOIN dbo.tWarenLagerEingang twle ON twle.kArtikel = ta.kArtikel JOIN dbo.tWarenlagerPlatz twlp ON twle.kWarenLagerPlatz = twlp.kWarenLagerPlatz WHERE twlp.cName = 'Wareneingangsplatz') MengeAufWarenEingang ON MengeAufWarenEingang.kArtikel = a.kArtikel");
var metaData=results.getMetaData();
var numCols = metaData.getColumnCount();
var spreadsheet = SpreadsheetApp.getActive();
var sheet = spreadsheet.getSheetByName("Test");
//you can use the following line to get the active sheet
//var sheet = SpreadsheetApp.getActiveSheet();
sheet.clearContents();
var arr=[];
for (var col = 0; col < numCols; col++) {
arr.push(metaData.getColumnName(col + 1));
}
sheet.appendRow(arr);
while (results.next()) {
arr=[];
for (var col = 0; col < numCols; col++) {
arr.push(results.getString(col + 1));
}
sheet.appendRow(arr);
}
results.close();
stmt.close();
sheet.autoResizeColumns(1, numCols+1);
}```
Runs slow first time and then fast right after can be a sign of a poorly optimized query.
If there' a table scan, the data might be loaded into cache the first time. It's in cache the second time.
That's a lot of JOINS and a big query. I would recommend a stored procedure if it's an option. The query plan might indicate missing indexes. It should also show the most expensive operations.
If 30 days is is a small fraction of the data and derstellt has an index, then compare the column directly to a date. Wrapping a DATEDIFF around the column prevents effective use of the index on that column.
DECLARE #TodayMinus29DaysMidnight datetime = CAST(GETDATE() - 29 as date)
SELECT...
WHERE b.derstellt < #TodayMinus29DaysMidnight
I would also verify the derived table with the DISINCT. Would a GROUP BY be better?
I'm in Powershell v4.0. I have a dropdown on my UI that I am filling with data from my database. I call a function that grabs the data like so:
$ConfigDynamicContractID.ItemsSource = (GetDynamicContracts).DefaultView
On the backend it looks like this:
function GetDynamicContracts{
$ContractQuery = "select con.ContractNumber as Name, c.ContractID from foo..campaign c inner join foo..campaigntemplate ct on c.campaignid = ct.campaignid
inner join foo..template t on ct.templateid = t.templateid inner join bar..contracts con on con.ContractID = c.ContractID
where c.ProductType = 'INTRO' and t.FileName = 'Intro Dynamic Template' and c.DeleteFlag = 0"
$ContractResult = ExecuteSelect "Bar" $ContractQuery
return , $ContractResult
}
This code works fine. I was then told that the tables referenced above can't talk to each other so I have to do individual calls to each and filter in powershell. So here is my code for that:
function GetDynamicContracts{
$CampaignQuery = "Select c.* From foo..Campaign c join foo..CampaignTemplate ct on c.CampaignID = ct.CampaignID
join foo..Template t on ct.TemplateID = t.TemplateID
Where c.ProductType = 'INTRO' and t.FileName = 'Intro Dynamic Template' and c.DeleteFlag = 0"
$CampaignResults = ExecuteSelect "foo" $CampaignQuery
$ContractIDs = New-Object System.Collections.ArrayList
foreach($row in $CampaignResults.Rows){
$ContractIDs.Add($row.ContractID)
}
$ContractIDs = $ContractIDs -join ","
$PHQuery = "Select ContractID, ContractNumber as Name From Contracts Where ContractID in ($ContractIDs)"
$PHResults = ExecuteSelect "Bar" $PHQuery
#Log $MyInvocation.MyCommand $PSBoundParameters
return ,$PHResults
}
This code for some reason does not work when returning a single row. But if I break this function call into two separate, then it works. See below:
function GetDynamicContracts{
$ContractIDs = GetDynamicCampaign
$ContractIDs = $ContractIDs[1]
$PHQuery = "Select ContractID, ContractNumber as Name From Contracts Where ContractID in ($ContractIDs)"
$PHResults = ExecuteSelect "PhytelMaster" $PHQuery
Log $MyInvocation.MyCommand $PSBoundParameters
return ,$PHResults
}
function GetDynamicCampaign{
$CampaignQuery = "Select c.* From Campaign..Campaign c join Campaign..CampaignTemplate ct on c.CampaignID = ct.CampaignID
join Campaign..Template t on ct.TemplateID = t.TemplateID
Where c.ProductType = 'INTRO' and t.FileName = 'Intro Dynamic Template' and c.DeleteFlag = 0"
$CampaignResults = ExecuteSelect "Campaign" $CampaignQuery
$ContractIDs = New-Object System.Collections.ArrayList
foreach($row in $CampaignResults.Rows){
$ContractIDs.Add($row.ContractID)
}
$ContractIDs = $ContractIDs -join ","
return $ContractIDs
}
It seems that making two execute selects in a single function causes the ',' to fail to do what it does when returning the data. Can anyone explain why?? Thanks ahead of time and since I have a workaround there is no rush.
As #TheMadTechnician and #wOxxOm point out ArrayList spams the indexes into the return and return, returns everything that gets spammed in the function. So when I expected $PHResults I also got the ArrayList spam. I could use something other than the ArrayList or I also found that if I wrap my function code in $null = #{ 'Code' } and then return the variable I want, all I get is that variable. It's ugly but it works.
I have a very simple db that has two tables, one to store a user's auth (username and pw) and one to store preferences. Currently when my app initializes, it checks for settings first and then auth. But I want to grab it all at once. The way the app is designed, there is only ever 1 record in either table, so I don't use WHERE clauses in my queries.
The problem is, when I do queries separately, they give different results than if I join them.
Consider this scenario: a user logs in, sets some settings and then logs out. In may app this causes the auth table to be cleared but the settings remain intact.
Sign-out query (just clears auth table)
db.transaction(function(tx) {
tx.executeSql('DELETE FROM userdata');
}, errorDB);
However this outputs "0 rows found":
db.transaction(function(tx) {
tx.executeSql('SELECT USERDATA.*, PREFS.* FROM USERDATA, PREFS', [], function (tx, results) {
var len = results.rows.length;
console.log(len + " rows found.");
for (var i=0; i<len; i++){
console.log("Row = " + i + " ID = " + results.rows.item(i).id + " Data = " + results.rows.item(i));
}
}, errorDB);
}, errorDB);
Whereas this outputs a row:
db.transaction(function(tx) {
tx.executeSql('SELECT * FROM PREFS', [], function (tx, results) {
var len = results.rows.length;
console.log(len + " rows found.");
for (var i=0; i<len; i++){
console.log("Row = " + i + " ID = " + results.rows.item(i).id + " Data = " + results.rows.item(i));
}
}, errorDB);
}, errorDB);
Even if there is no auth shouldn't the join query find the prefs data? What's going on here?
When you list two tables A and B in the FROM clause, you get a cross join, which returns A×B records.
So if one table is empty, the result will be empty, too.
To ensure that you have a record even for an empty table, add another record with UNION ALL, then use LIMIT 1 return the first record.
For example,
SELECT Name, PW FROM UserData
UNION ALL
SELECT NULL, NULL
LIMIT 1
will return either a single record with the name/password, or a single record with two NULL values.
To join that with the other table, use a subquery:
SELECT *
FROM (SELECT Name, PW FROM UserData
UNION ALL
SELECT NULL, NULL
LIMIT 1),
Prefs
I got the error: ORA-00933: SQL command not properly ended when run the follow linq query at LinqPad V4.42.14(AnyCPU), database is Oracle 11g.
If I replace
where coof.CoofCode == tod.PatTrnsplntFail.CoofCode && coof.OrgCode == prod.OrgCode
to
where coof.CoofCode == tod.PatTrnsplntFail.CoofCode
it works, but I can not remove that factor.
Any body can help me out will be great appreciate.
void Main()
{
var q = (from pat in Pats
from patr in pat.PatRegisters
from prod in patr.PatRegisterOrgDets
from tod in prod.TransplantOrgDets
select new {
PatId = pat.PatID,
FullName = pat.FirstName + ", " + pat.LastName,
RegisterDate = patr.RegDate.ToString("yyyy-MMM-dd"),
TransplantDate = tod.Transplant.TransplantDate.ToString("yyyy-MMM-dd"),
OrganSpec = tod.OrgSpec.Descrip,
IsTransplantedFailed = tod.PatTrnsplntFail.TodID == 0 ? false: true,
TransplantedFailReason = from coof in CausesOfOrgFail
where coof.CoofCode == tod.PatTrnsplntFail.CoofCode && coof.OrgCode == prod.OrgCode
select coof.Descrip
}).Distinct().OrderBy(o => o.PatId);
q.Dump(true);
}
I found a work around way to avoid the issue, but acturally I do not think this is a good way, I fell the LinqPad Oracle Driver has internal bugs cause that issue. Joeseph if you could read this, please give your suggestion. So use the follow linq query instead:
void Main()
{
var q1 = (from pat in Pats
from patr in pat.PatRegisters
from prod in patr.PatRegisterOrgDets
from tod in prod.TransplantOrgDets
where tod.PatTrnsplntFail.TodID == null
select new {
PatId = pat.PatID,
FullName = pat.FirstName + ", " + pat.LastName,
RegisterDate = patr.RegDate.ToString("yyyy-MMM-dd"),
TransplantDate = tod.Transplant.TransplantDate.ToString("yyyy-MMM-dd"),
OrganSpec = tod.OrgSpec.Descrip,
IsTransplantedFailed = false,
CausesOfOrgFailReason = ""
}).Distinct().OrderBy(o => o.PatId);
var q2 = (from pat in Pats
from patr in pat.PatRegisters
from prod in patr.PatRegisterOrgDets
from tod in prod.TransplantOrgDets
from coof in CausesOfOrgFail where coof.CoofCode == tod.PatTrnsplntFail.CoofCode && coof.OrgCode == prod.OrgCode
where tod.PatTrnsplntFail.TodID != null
select new {
PatId = pat.PatID,
FullName = pat.FirstName + ", " + pat.LastName,
RegisterDate = patr.RegDate.ToString("yyyy-MMM-dd"),
TransplantDate = tod.Transplant.TransplantDate.ToString("yyyy-MMM-dd"),
OrganSpec = tod.OrgSpec.Descrip,
IsTransplantedFailed = true,
CausesOfOrgFailReason = coof.Descrip
}).Distinct().OrderBy(o => o.PatId);
q1.ToList().Union(q2.ToList()).OrderBy(o => o.PatId).Dump(true);
}