orchard Job Queue - Publish operation with-in a queued job gives exception - orchardcms-1.9

I have a service method Import() which creates a new content item and publishes it. If I call this method from my Controller/Action or any Handler, it works fine. But if I try to create job queue for this method, the job is created and the Import() method is called, but in fails on contentManager.Publish(item) with the following exception, on class DefaultContentManager.cs:
An exception of type 'NHibernate.Exceptions.GenericADOException' occurred in NHibernate.dll but was not handled in user code
Additional information: could not execute query
[ SELECT this_.Id as Id1_2_, this_.Number as Number1_2_, this_.Published as Published1_2_, this_.Latest as Latest1_2_, this_.Data as Data1_2_, this_.ContentItemRecord_id as ContentI6_1_2_, contentite1_.Id as Id0_0_, contentite1_.Data as Data0_0_, contentite1_.ContentType_id as ContentT3_0_0_, contenttyp4_.Id as Id2_1_, contenttyp4_.Name as Name2_1_ FROM Orchard_Framework_ContentItemVersionRecord this_ inner join Orchard_Framework_ContentItemRecord contentite1_ on this_.ContentItemRecord_id=contentite1_.Id left outer join Orchard_Framework_ContentTypeRecord contenttyp4_ on contentite1_.ContentType_id=contenttyp4_.Id WHERE contentite1_.Id = #p0 and this_.Published = #p1 ]
Name:cp0 - Value:1 Name:cp1 - Value:True
[SQL: SELECT this_.Id as Id1_2_, this_.Number as Number1_2_, this_.Published as Published1_2_, this_.Latest as Latest1_2_, this_.Data as Data1_2_, this_.ContentItemRecord_id as ContentI6_1_2_, contentite1_.Id as Id0_0_, contentite1_.Data as Data0_0_, contentite1_.ContentType_id as ContentT3_0_0_, contenttyp4_.Id as Id2_1_, contenttyp4_.Name as Name2_1_ FROM Orchard_Framework_ContentItemVersionRecord this_ inner join Orchard_Framework_ContentItemRecord contentite1_ on this_.ContentItemRecord_id=contentite1_.Id left outer join Orchard_Framework_ContentTypeRecord contenttyp4_ on contentite1_.ContentType_id=contenttyp4_.Id WHERE contentite1_.Id = #p0 and this_.Published = #p1]
My Import() method looks like this:
public void Import(string id)
{
...
var item = contentManager.New("MyType");
contentManager.Create(item, VersionOptions.Draft);
...
contentManager.Publish(item);
}
This exception occurs on the following statement:
return contentItemVersionCriteria.List<ContentItemVersionRecord>()

Related

Sometimes postgres does not return records when queried remotely from JDBC Client

public static ArrayList<String[]> getDailyRecords () throws ClassNotFoundException {
ArrayList<String[]> list=new ArrayList<String[]> ();
String[] header = {"City", "Location", "Asset", "Number of Alerts", "Time spent in alerts", "Last seen temparature", "Limit"};
list.add (header);
String myDriver = "org.postgresql.Driver";
Class.forName (myDriver);
try( Connection conn = DriverManager.getConnection( ApplicationSettings.DATABASE_URL, ApplicationSettings.DATABASE_USER, ApplicationSettings.DATABASE_PASSWORD);
Statement st = conn.createStatement ();) {
conn.setAutoCommit (true);
ResultSet rs=null;
st.setFetchSize (200);
String dailyQuery="select * from sch.reports();";
rs= st.executeQuery (dailyQuery);
while (rs.next ()) {
String[] ar = new String[7];
ar[0] = rs.getString ("location");
ar[1] = rs.getString ("sublocation");
ar[2] = rs.getString ("zone");
ar[3] = rs.getString ("total_count");
ar[4] = rs.getString ("period");
String temp = rs.getString ("temparature");
ar[5] = temp;
list.add (ar);
}
conn.close ();
st.close ();
rs.close ();
}catch(Exception e){
e.printStackTrace ();
}catch(Error e){
e.printStackTrace ();
}
finally {
if(list.size ()==1){
System.out.println ("NO records found");
}else{
System.out.println ("Foudn some records");
}
return list;
}
I have a sql function, which does return records when queried locally from postgres clients. I invoke this function at scheduled timings from a java application. This worked fine for few months. But all of sudden, st.executeQuery() returning empty result set occasionally. Like 4 out of 10 attempts of executeQuery() in a day return empty resultset.
Things I have tried out:
Made sure query returns some records always. It should return 60 records.
Captured Errors,Exceptions. There were no errors seen.
Made sure JDBC connection is closed.
Debugged Postgres JDBC driver classes. Found that in cases when resultset is empty, data was not received from postgres data stream.
can size of data in tables influence query response?
Any help is kindly appreciated!
Update: SQL function definition added.
DECLARE
exception_error_code text;
exception_message text;
exception_detail text;
exception_hint text;
exception_context text;
BEGIN
RETURN QUERY
select l.name as location,sl.name as sublocation,z.name as zone,al.lim as lim,count(al.id) total_count,sum(al.timestamp_to-al.timestamp_from) period,t2.temperature temparature
from
map.location l
left join
map.sub_location sl
on l.id=sl.location_id
left join
map.zone z
on sl.id=z.sub_location_id
left join
map.subzone sz
on z.id=sz.zone_id
inner join
(select *,(info::json -> 'breach_type')::text as lim from alr.live where date(timestamp_from)= date(now() + INTERVAL '5 hours 30 minutes')) al
on sz.id= al.sub_zone_id
left join
(select subzone_id,max(nd_timestamp) as nd_timestamp from tel.temperature_sh group by subzone_id) t1
on al.sub_zone_id=t1.subzone_id
left join
tel.temperature_sh t2
on t1.subzone_id=t2.subzone_id
and t1.nd_timestamp=t2.nd_timestamp
group by l.name ,sl.name,z.name,t2.temperature , al.lim
order by l.name ,sl.name,z.name;
-- if something "breaks" do the following
EXCEPTION WHEN others THEN
get stacked diagnostics
exception_error_code = RETURNED_SQLSTATE
,exception_message = MESSAGE_TEXT
,exception_detail = PG_EXCEPTION_DETAIL
,exception_hint = PG_EXCEPTION_HINT
,exception_context = PG_EXCEPTION_CONTEXT
;
-- log exception for debugging
PERFORM public.insert_db_exception(
exception_error_code
,exception_message
,exception_detail
,exception_hint
,exception_context
);
END;

Eclipselink ScrollableCursor fails on second next() call

I am trying to use ScrollableCursor for loading all users of the system to memory.
I have a code like this:
Query findUsersQuery
= entityManager.createNamedQuery(UserEntity.QUERY_ALL_USERS, UserEntity.class);
findUsersQuery.setHint(QueryHints.SCROLLABLE_CURSOR, Boolean.TRUE);
findUsersQuery.setHint(QueryHints.CURSOR_PAGE_SIZE, bulkSize);
findUsersQuery.setMaxResults(maxInitialCacheSize);
ScrollableCursor scrollableCursor = (ScrollableCursor) findUsersQuery.getSingleResult();
int leftSize = scrollableCursor.size();
while (scrollableCursor.hasNext()) {
int nextSize = leftSize > bulkSize ? bulkSize : leftSize;
List subscriberPrefs = scrollableCursor.next(nextSize);
leftSize -= nextSize;
//... Result list processing
}
The query is: SELECT s FROM UserEntity u order by u.userId
Size of result table is 100, when scrollableCursor.next(nextSize); called, i get following exception:
org.eclipse.persistence.exceptions.DatabaseException
Internal Exception: java.sql.SQLRecoverableException: Closed Resultset
Error Code: 17010
at org.eclipse.persistence.exceptions.DatabaseException.sqlException(DatabaseException.java:324)
at org.eclipse.persistence.internal.databaseaccess.DatabaseAccessor.cursorRetrieveNextRow(DatabaseAccessor.java:447)[215:org.eclipse.persistence.core:2.4.1.v20121003-ad44345]
at org.eclipse.persistence.queries.ScrollableCursor.retrieveNextObject(ScrollableCursor.java:563)[215:org.eclipse.persistence.core:2.4.1.v20121003-ad44345]
at org.eclipse.persistence.queries.ScrollableCursor.loadNext(ScrollableCursor.java:411)[215:org.eclipse.persistence.core:2.4.1.v20121003-ad44345]
at org.eclipse.persistence.queries.ScrollableCursor.next(ScrollableCursor.java:437)[215:org.eclipse.persistence.core:2.4.1.v20121003-ad44345]
at org.eclipse.persistence.queries.ScrollableCursor.next(ScrollableCursor.java:459)[215:org.eclipse.persistence.core:2.4.1.v20121003-ad44345]
While calling next(10) the first row loaded normally and the exceptions occurs on second row. I don't have an idea why. Can anybody say how i can avoid this error?

Call stored procedure in EF 6 Repository Pattern without output parameters

I'm working with Repository Pattern and EF6. What I need to do is to call a SP that delete records for mapping table that have nothing in common within the repository I'm calling the SP.
I've tried with
this.dbSet.SqlQuery("exec mySP #Param1, #Param2", param1, param2);
but this returns all the records from the DB of the current repository I'm in. It's like I've wrote "SELECT * FROM Group" (if I'm in GroupRepository).
My SP returns nothing since it's deleting some records and I already wasted 2 days of searching how to call the SP. I can give additional info if needed.
Can anybody help?
Finally I manage to execute my stored procedure, which was accepting a List<int> and an Id. The code looks like this:
SQL SERVER:
CREATE TYPE [dbo].[IntListType] AS TABLE
(
[Item] INT
);
GO
CREATE PROCEDURE [removeEventUsersFromEvents]
(
#EventIds [dbo].[IntListType] READONLY,
#UserId INT
)
AS
BEGIN
BEGIN Tran T1
DECLARE #query NVARCHAR(MAX)
SET NOCOUNT ON;
SET #query = 'DELETE FROM [EventUser]
WHERE [EventID] IN (SELECT Item from #EventIds) AND [UserID] = #UserId';
EXECUTE sp_executesql #query,
N'#EventIds [dbo].[IntListType] READONLY, #UserId INT',
#EventIds,
#UserId;
COMMIT Tran T1
END;
C#:
List<int> eventIdsToBeDeleted = this.dbSet...(geting some Ids from the db);
DataTable dt = new DataTable("IntListType");
dt.Columns.Add("Item", typeof(Int32));
eventIdsToBeDeleted.ForEach(id => dt.Rows.Add(id));
var eventIds = new SqlParameter("EventIds", SqlDbType.Structured);
eventIds.TypeName = "dbo.IntListType";
eventIds.Value = dt;
foreach (var user in usersToBeDeletedFromEvents)
{
var userId = new SqlParameter("UserId", SqlDbType.Int);
userId.Value = user.UserID;
this.Context.Database.SqlQuery(typeof(List<int>),
"EXEC removeCalendarEventUsersFromSpecificGroupAndEvents
#CalendarEventIds,
#UserProfileDetailId",
eventIds,
userId);
}
This will eventually return an empty List<int>.

JPA criteria: count from multiselect query

I want to implement a table component with pagination. The result in the table is retrieved by a multiselect-query like this:
SELECT DISTINCT t0.userId,
t0.userName,
t1.rolleName
FROM userTable t0
LEFT OUTER JOIN roleTable t1 ON t0.userId = t1.fkUser
WHERE(t0.userType = 'normalUser' AND t1.roleType = 'loginRole')
This result I can get via a multiselect-query.
Now for the pagination I have to retrieve the total rowcount at first.
Is there anybody who can define a criteriaquery for one of this sql? I failed because a subquery does not support multiselects and I do not know how to get this distinct into a count statement.
SELECT COUNT(*) FROM
(
SELECT DISTINCT t0.userId,
t0.userName,
t1.rolleName
FROM userTable t0
LEFT OUTER JOIN roleTable t1 ON t0.userId = t1.fkUser
WHERE(t0.userType = 'normalUser' AND t1.roleType = 'loginRole')
)
or
SELECT COUNT(DISTINCT t0.userId || t0.userName || t1.rolleName)
FROM userTable t0
LEFT OUTER JOIN roleTable t1 ON t0.userId = t1.fkUser
WHERE(t0.userType = 'normalUser' AND t1.roleType = 'loginRole')
Thanks in advance!
Btw. I am using OpenJpa on a WebSphere AppServer
The following is not tested but should work:
CriteriaBuilder builder = em.getCriteriaBuilder();
CriteriaQuery<Long> query = builder.createQuery(Long.class);
Root<User> t0 = query.from(User.class);
Join<User, Role> t1 = t0.join("roles", JoinType.LEFT);
query.select(builder.concat(t0.get(User_.userId), builder.concat(t0.get(User_.userName), t1.get(Role_.rolleName))).distinct(true);
query.where(cb.equal(t0.get("userType"), "normalUser"), cb.equal(t1.get("roleType"), "loginRole"));
TypedQuery<Long> tq = em.createQuery(query);
Due to known issue https://jira.spring.io/browse/DATAJPA-1532 Multiselect does not work with repo.findall method. I handled this by autowiring entity manager to service class.
#Autowired
EntityManager entityManager;
public List<?> getResults() throws ParseException
{
//ModelSpecification modelSpecification = new ModelSpecification();
CriteriaQuery<DAO> query = modelSpecification.getSpecQuery();
TypedQuery<DAO> typedQuery = entityManager.createQuery(query);
List<?> resultList = typedQuery.getResultList();
//List<DAO> allData = entityManager.createQuery(query).getResultList();
return resultList;
}
You can find working code here https://github.com/bsridharpatnaik/CriteriaMultiselectGroupBy

Extending Zend_Db

I apologize if my title is a bit misleading and it turns out that it's some other class under Zend_Db.
I use the following method of extracting data from a MSSQL:
// $_config contains information about how to connect to my MSSQL server
$config = new Zend_Config($_config);
$db = Zend_Db::factory($config->database);
$sql = "SELECT * FROM table1";
print_r($db->fetchAll($sql));
So far no problem and everything runs smooth :).
Now I need to run some more complex queries with multiple rowsets:
$sql2 = <<<EOD
DECLARE #test INT
SET #test = 42
SELECT * FROM table1 WHERE col1 = #test
SELECT col2 FROM table2 UNION
SELECT col3 FROM table2
SELECT * FROM table3
EOD;
print_r($db->fetchAll($sql2));
I hope you get the idea.
Using $db->fetchAll($sql2); will result in
Fatal error: Uncaught exception
'Zend_Db_Statement_Exception' with
message 'SQLSTATE[HY000]: General
error: 10038 Attempt to initiate a new
SQL Server operation with results
pending. [10038] (severity 7)
[(null)]' in
\Sacp026a\sebamweb$\prod\includes\Zend\Db\Statement\Pdo.php:234
The following function will return all the correct rowsets:
function sqlquery_multiple($zdb, $sql) {
$stmt = $zdb->query($sql);
$rowsets = array();
do {
if ($stmt->columnCount() > 0) {
$rowsets[] = $stmt->fetchAll(PDO::FETCH_ASSOC);
}
} while ($stmt->nextRowset());
return $rowsets;
}
print_r(sqlquery_multiple($db, $sql2));
Now my big question is:
How do I extend Zend_Db, so I can implement and use the function above as $db->fetchMulti($sql2); instead of sqlquery_multiple($db, $sql2)?
Thanks in advance :)
NB: It's worth mentioning that I'm using the ODBC-patch in order to be able to fetch multiple rowsets in the first place.