Error: Sequence contains more than one element - linq-to-sql

I am getting the following error on production server. It works well on localhost.
Error: Sequence contains more than one element

That is an InvalidOperationException thrown by the Single method.
This method is supposed to return only one element, and your query is returning more than one, you have to check the criteria you use on your query.
It will also throw an exception if it doesn't find an element. You can use SingleOrDefault() method to return null (or default value, i.e. 0 for int) if there are no records.
If you are expecting multiple elements but just one the first one, you can use First instead of Single or FirstOrDefault.

Related

Laravel SQL is not performing as expected. No syntax error

Can any Laravel developers help me understand why the following SQL statement is not working. I don't get any errors, it simply doesn't do what it should:
DB::table('devices')
->leftJoin('hotel_device','hotel_device.device_id','devices.id')
->where("hotel_device.device_id","IS","NULL")
->delete();
This should remove all device ids where the leftJoin link returns as NULL (ie. where this device id is not being used in the "hotel_device" table).
If I run it as raw SQL directly in the database it works correctly. Note the "IS" condition rather than "=" condition, as I am refering to a NULL value. (using "=" didn't find any matching rows)
thanks.
You should use the whereNull method to compare to null rather than trying to filter it using the regular where method.
DB::table('devices')
->leftJoin('hotel_device','hotel_device.device_id','devices.id')
->whereNull("hotel_device.device_id")
->delete();

Delphi: Cannot perform this operation on an open dataset

When I tried to use FireDAC FDQuery with MySQL database I got the following error:
Cannot perform this operation on an open dataset.
query.Open(....my connection string to MySQL....);
try
query.ExecSql;
finally
query.Close;
I filled the FDQuery by double-clicking on the icon on the form. I also
connected to the database to test it. It gave back the results correctly.
I would like to use it from code, but it doesn't work, so
I debugged it. I always get to the breakpoint: query.Close;
You can't call Open and ExecSQL on the same SQL, because they do different things.
Use Open when the query will return a result set, which means for a SELECT. Use ExecSQL when the query does not return a result set, which means for an INSERT, DELETE or UPDATE.
I can't tell you which one applies to your situation, because you failed to include your SQL in your post.
I don't know about FireDAC specifically, but in general with these kind of database components, for queries not returning a result set, thus suitable for ExecSQL, you would want to use ExecSQL on the Connection object, in this case TFDConnection. (Which would presumably be the Connection object that your FDQuery object is connected to.)
http://docwiki.embarcadero.com/RADStudio/Rio/en/Executing_Commands_(FireDAC)
Apparently there is an ExecSQL method on TFDCustomQuery, but I'm not sure why you would use that, and as you discovered, it doesn't work if the query is already in use.

IllegalStateException while trying create NativeQuery with EntityManager

I have been getting this annoying exception while trying to create a native query with my entity manager. The full error message is:
java.lang.IllegalStateException: During synchronization a new object was found through a relationship that was not marked cascade PERSIST: com.model.OneToManyEntity2#61f3b3b.
at org.eclipse.persistence.internal.sessions.RepeatableWriteUnitOfWork.discoverUnregisteredNewObjects(RepeatableWriteUnitOfWork.java:313)
at org.eclipse.persistence.internal.sessions.UnitOfWorkImpl.calculateChanges(UnitOfWorkImpl.java:723)
at org.eclipse.persistence.internal.sessions.RepeatableWriteUnitOfWork.writeChanges(RepeatableWriteUnitOfWork.java:441)
at org.eclipse.persistence.internal.jpa.EntityManagerImpl.flush(EntityManagerImpl.java:874)
at org.eclipse.persistence.internal.jpa.QueryImpl.performPreQueryFlush(QueryImpl.java:967)
at org.eclipse.persistence.internal.jpa.QueryImpl.executeReadQuery(QueryImpl.java:207)
at org.eclipse.persistence.internal.jpa.QueryImpl.getSingleResult(QueryImpl.java:521)
at org.eclipse.persistence.internal.jpa.EJBQueryImpl.getSingleResult(EJBQueryImpl.java:400)
The actual code that triggers the error is:
Query query;
query = entityManager.createNativeQuery(
"SELECT MAX(CAST(SUBSTRING_INDEX(RecordID,'-',-1) as Decimal)) FROM `QueriedEntityTable`");
String recordID = (query.getSingleResult() == null ?
null :
query.getSingleResult()
.toString());
This is being executed with an EntityTransaction in the doTransaction part. The part that is getting me with this though is that this is the first code to be executed within the doTransaction method, simplified below to:
updateOneToManyEntity1();
updateOneToManyEntity2();
entityManager.merge(parentEntity);
The entity it has a problem with "OneToManyEntity1" isn't even the table I'm trying to create the query on. I'm not doing any persist or merge up until this point either, so I'm also not sure what is supposedly causing it to be out of sync. The only database work that's being done up until this code is executed is just pulling in data, not changing anything. The foreign keys are properly set up in the database.
I'm able to get rid of this error by doing as it says and marking these relationships as Cascade.PERSIST, but then I get a MySQLContrainstraViolationException on the query.getSingleResult() line. My logs show that its doing some INSERT queries right before this, so it looks like its reaching the EntityManager.merge part of my doTransaction method, but the error and call stack point to a completely different part of the code.
Using EclipseLink (2.6.1), Glassfish 4, and MySQL. The entitymanager is using RESOURCE_LOCAL with all the necessary classes listed under the persistence-unit tag and exclude-unlisted-classes is set to false.
Edit: So some more info as I'm trying to work through this. If I put a breakpoint at the beginning of the transaction and then execute entityManager.clear() through IntelliJ's "Evaluate Expression" tool, everything works fine at least the first time through. Without it, I get an error as it tries to insert empty objects into the table.
Edit #2: I converted the nativeQuery part into using the Criteria API and this let me actually make it through my code so I could find where it was unintentionally adding in a null object to my entity list. I'm still just confused as to why the entity manager is caching these errors or something to the point that creating a native query is breaking because its still trying to insert bad data. Is this something I'd need to call EntityManager.clear() before doing each time? Or am I supposed to call this when there is an error in the doTransaction method?
So after reworking the code and setting this aside, I stumbled on at least part of the answer to my question. My issue was caused by the object being persisted prior to the transaction starting. So when I was entering my transaction, it first tried to insert/update data from my entity objects and threw an error since I hadn't set the values of most of the non-null columns. I believe this is the reason I was getting the cascade errors and I'm positive this is the source of the random insert queries I saw being fired off at the beginning of my transaction. Hope this helps someone else avoid a lot of trouble.

erlang - exception error: no function clause matching

I've created a concatenate/1 function, which should concatenate a list of lists and atoms:
concatenate(L)->
concatenate(L,[]).
concatenate([],R)->
reverse(R);
concatenate([H|T],R) when is_atom(H) ->
concatenate(T,[H|R]);
concatenate([[]|L],R)->
concatenate(L,R);
concatenate([[H|T]|L],R)->
concatenate([T|L],[H|R]).
However I get the error:
15> ml:concatenate([[1,2],4,[3,4,5],[5,6]]).
** exception error: no function clause matching
ml:concatenate([4,[3,4,5],[5,6]],[2,1]) (ml.erl, line 27)
which I believe should match, because of the second concatenate/2 clause.
May I ask, what am I doing wrong here?
Following the reasoning in Viacheslav Kovalev's answer, given that I want to handle atoms and numbers here, I have come up with the following solution:
concatenate([],R)->
R;
concatenate([H|T],R) when not(is_list(H)) ->
reverse(concatenate(T,[H|R]));
concatenate([[]|L],R)->
concatenate(L,R);
concatenate([[H|T]|L],R)->
concatenate([T|L],[H|R]).
In the second clause you are using when is_atom(H) guard, which fails to match clause (because H in this case is number). Change it to when is_number(H).

SSIS Error Logging (Data Flow Compoment Derived Column)

What the best way to check the column (in DerivedColum component) is NULL.
If NULL => log error
else continue with data flow.
Regards
Place conditional split transformation before or after derived column transformation to remove rows with NULLs.
OR:
Create a Dummy variable with value -1.
In the derived column use something like ISNULL(myCol) ? (DT_I4)SQRT(#[User::Dummy]) : myCol
Configure error output to redirect row on error.
Connect error output to a flat-file destination.
Note:
SQRT(-1) in the step 2 raises error.
Make sure that type-cast in step 2 matches myCol type; I have used DT_I4.
This might help you partially.
Flowing the derived column control into a condional split control. To flow only non-nulls create a condition
!(ISNULL(COLUMN_NAME))
Then connect the conditional split back to your standard flow. This will flow the correct instances as your require.
The thing I can't quite figure out is the logging of this error. Maybe try creating a second condition:
(ISNULL(COLUMN_NAME))
And flow that into some dataflow task that will cause an error to be raised, not really elegant though. Or you could try flowing into another derived column that uses values in the row to form an output to some log file.