mongodb inserting inspite of a document with a specific name being present - ruby

I have this following piece of code
coll_name = "#{some_name}_#{differentiator}"
coll_object = #database[coll_name]
idExist = coll_object.find({"adSet.name" => NAME}).first()
if idExist.nil?
docId = coll_object.insert(request)
else
docId = idExist["_id"]
end
return docId
differentiator can be the same or different from the Loop that is code is called.So everytime there can be a new collection or same collection.Now if the same collection is recieved then there might be an object with name = NAME. In that case no insert should be carried out.However i have observed that documents with the same NAME are getting inserted.Can anybody helpout on this problem.

The explanation for this behavior could be a race condition: The duplicate is inserted by another thread/process between line 3 and 5 of your application. Two threads try to create the same name at the same time, the database returns for both that the name doesn't exist yet, and when those replies arrived, both insert the document.
To prevent this from happening, create an unique index on the name-field. This will prevent MongoDB from inserting two documents with the same name. When you do this, you could remove the check for existence before inserting. Just try to insert the document, and then call getLastError to find out if it worked. When it didn't, retrieve the existing document with an additional query.

Related

Error : FRM-41337:Cannot populate the list from record group

I have a record group that is using a block item, i.e. where cust_id = :order.cust_id
Sometimes it works, sometimes not.
When I query an existing record, I am able to add a new line and enter the condition code i.e. from the populated record group. But when I enter a new order, the list is empty. I tried to put the code in when-new-record-instance, but I get an error
select profile profile1, profile profile2
from dss.v_unit_conditions
where cust_id = :order.dsp_cust_id
and profile_type = 'UC'
and active = 'Y'
41337 - cannot populate list from record group
If I use that in when-tab-change, then I get the same error.
When you perform query, you acquire :ORDER.DSP_CUST_ID value so Record Group Query fetches something.
On the other hand, when you're entering a new order, I presume that :ORDER.DSP_CUST_ID is empty, query doesn't return anything and raises an error.
It means that :ORDER.DSP_CUST_ID must be known. In order to make the Record Group Query work, consider creating it dynamically, i.e. when :ORDER.DSP_CUST_ID gets its value. As it seems that you're entering it manually, the WHEN-VALIDATE-ITEM might be your choice. Have a look at CREATE_GROUP_FROM_QUERY (and, possibly, POPULATE_GROUP_FROM_QUERY) built-ins. They are described (with examples) in Forms Online Help System.

How to enable/use SNMPv2 RowStatus feature on pysnmp if new row indexes aren't known on table creation?

I'm implementing a NTCIP agent using pysnmp with lots of tables containing SNMPv2 RowStatus columns.
I need to allow clients to create new conceptual rows on existing agent tables, however there is no way to know the indices of such rows before their creation. Consequently, I can't create such RowStatus object instances on pysnmp. Without this instances, the client have no object to issue a SET command in order to add a conceptual row to the table.
Is there any way to handle this on pysnmp? Perhaps a column generic callback mechanism or something similar.
I think I have found the problem on creating new rows.
The original (ASN.1) mib file defines all RowStatus columns as read-write, but pysnmp MibTableColumn createTest method fails if symbol access permission is not read-create. Changing the RowStatus definitions on the MIB source solved the problem.
After doing that I could create new rows, but noticed another issue: a snmp walk on the table caused a timeout. The problem is that pysnmp doesn't know which values to put on new row elements which are not indices and do not have default values defined, so it puts None - which causes a 'Attempted "__hash__" operation on ASN.1 schema object' PyAsn1Error. In order to handle this the client must issue SET commands to every field in the newly created row before getting them OR add default values to column objects (not sure about that, but default values are not populated by mibdump as original ASN.1 mibs never define default values of itens which are not optional, by definition). My code to export columns for my StaticTable class follows (incomplete code, but I think some method and attribute names speak by themselves).
def add_create_test_callback(superclass, create_callback, error_callback=None):
"""Create a class based on superclass that calls callback function when element is changed"""
class VarCCb(superclass):
def createTest(self, name, val, idx, acInfo):
if create_callback and val in [4, 'createAndWait', 5, 'createAndGo']:
superclass.createTest(self, name, val, idx, acInfo)
create_callback(name, val, idx, acInfo)
else:
if error_callback:
error_callback(name, 'optionNotSupported')
raise error.NoCreationError(idx=idx, name=name)
return VarCCb
class StaticTable:
# ....
def config_cols(self):
"""Add callback do RowStatus columns and default values for other columns that are not indices"""
MibTableColumn, = self.mib_builder.importSymbols('SNMPv2-SMI', 'MibTableColumn')
_, column_symbols = self.import_column_symbols()
for index, symbol in enumerate(column_symbols):
if symbol.syntax.__class__.__name__ == 'DcmRowStatus':
# add callback for row creation on all row status columns
MibTableColumnWCb = add_create_test_callback(MibTableColumn, self.create_callback,
self.error_callback)
# setMaxAccess needs to be defined, otherwise symbol is defaulted as readonly
new_col = MibTableColumnWCb(symbol.name, symbol.syntax.clone()).setMaxAccess('readcreate')
named_col = {symbol.label: new_col}
elif index >= self.index_n and self.column_default_values:
new_col = MibTableColumn(symbol.name, symbol.syntax.clone(self.column_default_values[index]))
named_col = {symbol.label: new_col}
else:
new_col = None
named_col = None
if new_col:
self.mib_builder.unexportSymbols(self.mib_name, symbol.label)
self.mib_builder.exportSymbols(self.mib_name, **named_col)
# ...
Not sure if this is the right way to do it, please correct me if I am wrong. Maybe I shouldn't include this here, but it is part of the way to solving the original question and may help others.
Thanks!
I think with SNMP in general you can't remotely create table rows without knowing their indices. Because index is the way how you convey SNMP agent the information where exactly the row shall reside in the table.
In technical terms, to invoke RowStatus object for a column you need to know its index (e.g. row ID).
If I am mistaken, please explain how that would work?
The other case is when you are not creating table row remotely, but just expose the data you already have at your SNMP agent through the SNMP tables mechanism. Then you can take just build the indices off the existing data. That would not require your SNMP manager to know the indices beforehand.
The possible mid-ground approach can be if your SNMP agent exposes some information that SNMP manager can use for building proper indices for the table rows to be created.
All in all, I think the discussion would benefit from some more hints on your situation. ;-)

How to stop Doctrine from returning a primary key for every query

I am kind of annoyed at Doctrine for returning primary keys in each and every query even though I don't want it to. Is there anyway to stop this ? coz I don't really want those damn primary keys along with my doctrine query results.
A query for instance that I have is:
$getAllDatesForUserQuery = $this->createQuery('s')
->select('s.datename')
->where('s.userid = ?',3)
->setHydrationMode(Doctrine::HYDRATE_ARRAY) ;
In this situation, it retrieves all the datenames as it should, but also happily returns the primary key column value. I DON"T WANT IT.
Is it me? or is it Doctrine ?
In a case like this where you want a simple array and only have a single field being selected, the answer is the Single Scalar Hydration mode. Use it like this:
$q = $this->createQuery('s')
->select('s.datename')
->where('s.userid = ?',3)
->setHydrationMode(Doctrine::HYDRATE_SINGLE_SCALAR);
You should find that the query will return a simple one-dimensional array containing only the value(s) you wanted.

Yii ActiveRecord Primary Key retrieval

I have looked around and have not found anything similar to what I am asking.
Short of extending the CActiveRecord class is there a way to query just the primary key values (or any column's values) of a table and have an array of those values returned instead of a collection of activerecord objects?
ie
ModelName::model()->getColumnValues('column_name');
I keep having to get a list of record that match a certain condition and then run through the results to pull out the column values I need. I would like to cut out the last step and just get the values instead of the entire record.
Any ideas?
Using a CDbCommand you can execute a query and fetch the results from one column with the queryColumn method. queryColumn returns the results from the first column.
Example:
$command = Yii::app()->db->createCommand("SELECT column FROM table WHERE ...");
$result = $command->queryColumn();

SQL Server request is very slow when nothing to retrieve?

We are facing a strange performance problem with "SQL Server Express 2005" in a very simple condition.
We have a table with: [timestamp], [id], [value] columns.
and only one primary unique index on [timestamp]+[id].
The table contains around 68.000.000 records.
The request is:
SELECT TOP 1 timestamp FROM table WHERE id=1234 ORDER BY timestamp
If there is at least one record for this id the result is given in few miliseconds.
If there is no record for this id the result is given in at least 30 SECONDS!!!
We tried many other simple similar request, and as soon as we have no corresponding records for the id the processing time is awfully long.
Do you have any explanation and idea to avoid this?
TOP 1 ORDER BY what?
If it finds one record, it must scan the entire table to find more, since you don't have
an index on id.
If you did, but wanted "ORDER BY timestamp", it would still table scan because it doesn't know the id is unique in the timestamp index (even though it might make sense to you because the id is declared unique, say - is it? How if it's not a unique index of its own or as the 1st field in a multicolumn index? - or they both increase monotonically, say - do they?)
If the ID is a unique ID then your ORDER BY isn't needed - and an index on just that field would be enough.

Resources