Foreign Key violation when inserting nested collections in EF6 (database first) - asp.net

I have a nested collection in a database first project using Identifying Relationships
For example (showing the primary entity keys only):
+--Quotes--+ +------State-----+ +---State Info---+
|ID (int) | -(1-*)-> | Quote_ID (int) | -(1-*)-> | Quote_ID (int) |
+----------+ | State_ID (int) | | State_ID (int) |
+----------------+ | Info_ID (int) |
+----------------+
Note that in the first association, it is a one-to-many association where Quotes.ID --> Quote_ID.
The second association is a one-to-many composite key who's principal keys are Quote_ID/State_ID.
Now, let's say that Quote already exist (as theQuote) and I'm adding a new state:
theQuote.States.add(new State with {.State_ID=5})
And now I'm adding a new state info:
StateObj.StateInfos.add(New StateInfo with {.Info_ID=38})
Now I hook up a SQL profiler and save it:
db.SaveChanges()
What is happening is that I see two inserts:
exec sp_executesql N'INSERT [dbo].[States]([Quote_ID], [State_ID])
VALUES (#0, #1)',#0=153888,#1=5
exec sp_executesql N'INSERT [dbo].[StateInfo]([Quote_ID],[State_ID],[Info_ID])
values (#0, #1, #2)',#0=0,#1=0,#2=38
Note that in the first insert, the child collection, EF understands the relationship and automatically inserts the correct quote_id. However, in the second insert, the grandchild collection, it doesn't properly synch up the association and does not know the proper values. This results in an unfortunate "the Insert statement conflicted with the FOREIGN KEY constraint ..." SQL error.
Now this scenario works just fine if the StateObj already exists and I'm only inserting StateInfo. I need to be able to insert both State and StateInfo.
Seems like a reasonable request of EF6, but for some reason, I cannot get this to work. I've tried changing the StoreGeneratedPattern property of the entity keys to "Identity" but to no avail.
Any thoughts?

I have a reason why this is happening. Apparently, I have an overlapping key.
The table model I presented was not complete. I have an additional association that apparently creates the issue:
+--Quotes--+ +------State-----+ +---State Info---+
|ID (int) | -(1-*)-> | Quote_ID (int) | -(1-*)-> | Quote_ID (int) |
+----------+ | State_ID (int) | | State_ID (int) |
| StateView (nav)| | Info_ID (int) |
+----------------+ +----------------+
^
+-StateView-+ | (1-*)
| ID (int) |----+
+-----------+
The association is with StateView.ID as the primary and State.State_ID as the foreign key. If this relationship is removed, db.savechanges works as expected.
Alternatively, instead of using
theQuote.States.add(new State with {.State_ID=5})
Do this instead:
dim StateViewObj as StateView=db.StateView.Find(5)
theQuote.States.add(new State with {.StateView=StateViewObj})
This seems to work.

Related

Query to check multiple attributes in dynamodb

I am trying to retrieve a list of items based on loggedInUserId. Below is a rough schema I have
{
personId: 1,
accountManagerId: 2,
accountExecId: 3,
successManagerId: 5
}
I want to retrieve all the records if loggedInUserId is any of above mentioned fields. What will be the best way to organize the data?
Thanks for your help
Typically in DynamoDB you denormalize the data, unlike the normalized schema you show. That would look like the following:
pk | sk | data
1 | personId | other info
1 | accountManagerId | other info
2 | personId | other info
4 | successManagerId | other info
Now if you have a loggedInUserId as 1 and you do a Query API call to your table you get all the items that user relates to.
SELECT * FROM mytable WHERE pk= 1
1 | personId | other info
1 | accountManagerId | other info
We you have two options.
One would look something like
PK SK PersonId AccountManagerId AccountExecId SuccessManagerId
<partition value> <sort value> 1 2 3 5
The other would be to just store the whole object in a json string
PK SK UserData
<partition value> <sort value> <user data>
I prefer the second one, but both are valid
Edit:
For querying, if you want to search by the loggedInUserId you can set it as a partition key
PK=LOGGED_IN_USER_ID#1
And a simple Java example for query
var dynamoClient = DynamoDbEnhancedClient.builder().dynamoDbClient(dynamoDbClient).build();
var table = dynamoClient.table("Users", TableSchema.fromClass(Users.class));
table.getItem(Key.builder().partitionValue("1").build());
Its easier to use string partition and sort keys

Update foreign key in Qt QSqlRelationalTableModel

I'm coding in python (PySide2), but the overall concept concerns the Qt Framework.
Here are two tables of mine:
Table "recordings":
| Column | Type |
| -------- | -------------------|
| id | int (primary key) |
| param1 | int |
| param2 | int |
| ... | int |
| paramN | int |
Table "analyzed_recs":
| Column | Type |
| -------- | -------------------|
| id | int (primary key) |
| rec_id | int (foreign key) | <-- Points to recordings.id
| paramN | int |
I need in my program to display param1 and param2 from the former. In Qt I used a QSqlRelationalTable to fulfill this objective:
def _init_db_models(self):
self.analyzed_recs_sql_model = QSqlTableModel(self, self.db)
self.analyzed_recs_sql_model.setTable("analyzed_recs")
rec_id = self.analyzed_recs_sql_model.fieldIndex('rec_id')
self.analyzed_recs_sql_model.setRelation(rec_id, QSqlRelation("recordings", "id", "param1"))
self.analyzed_recs_sql_model.setRelation(rec_id, QSqlRelation("recordings", "id", "param2"))
self.analyzed_recs_sql_model.select()
self.analyzed_data_table.setModel(self.analyzed_recs_sql_model)
This code works fine in displaying the desired fields.
However, when it comes to update a record in analyzed_recs:
record = self.analyzed_recs_sql_model.record()
record.remove(record.indexOf("id"))
record.setValue("rec_id", self.current_rec_id)
record.setValue("param1", self.param1)
record.setValue("param2", param2)
self.analyzed_recs_sql_model.insertRecord(-1, record)
self.analyzed_recs_sql_model.submitAll()
The column rec_id is not set (NULL) into the table (the other params are correctly inserted into the table).
On the contrary, if I avoid using QSqlRelationalTableModel and take QSqlTableModel instead, the insertion is performed correctly (as I expected), but I lose the INNER JOIN display feature.
I was thinking as a work around to create two distinct models, a QSqlRelationalTableModel only for displaying and a QSqlTableModel only for editing the data. However I don't like the extra workload of syncing the two.
I'm sure there is a Qt feature to achieve this, but unfortunately I'm missing it.
Any suggestion?
I've had the same problem using PYQT.
The record object returned by calling record() method has no fields named 'rec_id' because the QSqlRelationalTableModel changes it with the referenced field name 'param1'. We can verify the field names using:
fieldcount = record.count()
for i in range(fieldcount):
logging.info("field %s %s", i, record.fieldName(i))
so we need to add the field before assigning it:
record = self.analyzed_recs_sql_model.record()
record.remove(record.indexOf("id"))
record.append(QSqlField("rec_id"))
record.setValue("rec_id", self.current_rec_id)

Weird behavior in mariadb table with unique key defined (ie, not so unique)

I'm trying to export/import a BD from one system to another but the import fails with the following error:
ERROR 1062 (23000) at line 8232: Duplicate entry '0-3-30168717-com_liferay_product_navigation_product_menu_web_...' for key 'IX_C7057FF7'
That table is defined as such:
CREATE TABLE `PortletPreferences` (
`portletPreferencesId` bigint(20) NOT NULL,
`ownerId` bigint(20) DEFAULT NULL,
`ownerType` int(11) DEFAULT NULL,
`plid` bigint(20) DEFAULT NULL,
`portletId` varchar(200) DEFAULT NULL,
`preferences` longtext DEFAULT NULL,
`mvccVersion` bigint(20) NOT NULL DEFAULT 0,
`companyId` bigint(20) DEFAULT NULL,
PRIMARY KEY (`portletPreferencesId`),
UNIQUE KEY `IX_C7057FF7` (`ownerId`,`ownerType`,`plid`,`portletId`),
In the mysql dump file, I see these two entries:
(31453178,0,3,30168717,'com_liferay_product_navigation_product_menu_web_portlet_ProductMenuPortlet','<portlet-preferences />',0,10132)
(31524539,0,3,30168717,'com_liferay_product_navigation_product_menu_web_portlet_ProductMenuPortlet','<portlet-preferences />',0,10132)
So, yep, there are two entries with the same unique key. How is that possible?!?
Knowing this, I ran the following select statement against the source DB:
select portletPreferencesId, ownerId, ownerType, plid, portletId from PortletPreferences where ownerId = 0 AND ownerType = 3 AND plid = 30168717 AND portletId like 'com_liferay_product_navigation_product_menu_web%';
And it outputs just ONE LINE!
+----------------------+---------+-----------+----------+----------------------------------------------------------------------------+
| portletPreferencesId | ownerId | ownerType | plid | portletId |
+----------------------+---------+-----------+----------+----------------------------------------------------------------------------+
| 31524539 | 0 | 3 | 30168717 | com_liferay_product_navigation_product_menu_web_portlet_ProductMenuPortlet |
+----------------------+---------+-----------+----------+----------------------------------------------------------------------------+
By the portletPreferencesId field, it outputs the second entry in the dump file. So I did one more select for the other row as such:
select portletPreferencesId, ownerId, ownerType, plid, portletId from PortletPreferences where portletPreferencesId = 31453178;
And I get:
+----------------------+---------+-----------+----------+----------------------------------------------------------------------------+
| portletPreferencesId | ownerId | ownerType | plid | portletId |
+----------------------+---------+-----------+----------+----------------------------------------------------------------------------+
| 31453178 | 0 | 3 | 30168717 | com_liferay_product_navigation_product_menu_web_portlet_ProductMenuPortlet |
+----------------------+---------+-----------+----------+----------------------------------------------------------------------------+
My question is, what's going on?!? Why is that entry not output by the first select statement and why is it there in the first place if those fields were supposed to be unique???
I have a bad feeling about the state of the source database :-( Oh, and that's just one. I have multiple duplicate keys like that in that table :-(
Thanks
There are occasional bugs like MDEV-15250 that can cause duplicate entries to occur.
Sometimes you may not see these as parts of the optimizer expect only a single row because of the unique constraint so won't search beyond it. Maybe a query across a range including the entries would be more likely to show it (which is what mysqldump would have done).
If you don't think its related to ALTER TABLE occurring at the same time as insertions (like MDEV-15250), and have a good hunch as the set of operations on the table that may have escaped the unique key enforcement, can you please create a bug report.

Using Indexes results in Update locks cannot be acquired during a READ UNCOMMITTED transaction

After upgrading to mariadb 10.5.11 I ran into a weird problem with the indexes.
Simple table with two colums Type(varchar) and Point(point)
An index on Type(Tindex) and a spatial index on Point(Pindex)
Now a query like
SELECT X(Point) as x,Y(Point) as y,hotels.Type FROM hotels WHERE (Type in ("acco")) AND MBRContains( GeomFromText( 'LINESTRING(4.922 52.909,5.625 52.483)' ), hotels.Point)
;
Results in a
Error in query (1207): Update locks cannot be acquired during a READ UNCOMMITTED transaction
While both
SELECT X(Point) as x,Y(Point) as y,hotels.Type FROM hotels USE INDEX (Pindex) WHERE (Type in ("acco")) AND MBRContains( GeomFromText( 'LINESTRING(4.922 52.909,5.625 52.483)' ), hotels.Point)
;
and
SELECT X(Point) as x,Y(Point) as y,hotels.Type FROM hotels USE INDEX (Tindex) WHERE (Type in ("acco")) AND MBRContains( GeomFromText( 'LINESTRING(4.922 52.909,5.625 52.483)' ), hotels.Point)
;
work fine. As mariadb 10.5.10 did
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
| 1 | SIMPLE | hotels | range|filter | Type,Pindex | Pindex|Type | 34|302 | NULL | 340 (4%) | Using where; Using rowid filter |
The issue is now being tracked as MDEV-26123 (I guess you reported it there). The issue description says that the problem was introduced in MariaDB 10.2.39, 10.3.30, 10.4.20, 10.5.11, 10.6.1.
I ran into the issue after upgrading to MariaDB 10.6.4. I downgraded to 10.6.0, which was possible without having to do any migration of the data. It seems to have fixed the problem for now.
The cause of this appears to be the code fix for MDEV-25594.
I cannot see anything in the commit message or discussion there that indicates that a change to the READ UNCOMMITTED behavior was intentional.
There are no open bug reports on this so I recommend you create a new bug report.
select ##session.autocommit;
set ##session.autocommit=0;
select ##session.autocommit;
#add in my.cnf
autocommit = 0
using mariadb 10.2.40 ( resolved )
https://developpaper.com/transaction-isolation-level-of-mariadb/

(for-each-row scenario).in kusto

Query1
cluster(x).database('$systemdb').Operations
| where Operation == "DatabaseCreate" and Database contains "oci-"| where State =='Completed'
and StartedOn between (datetime(2020-04-07) .. 3d)
| distinct Database , StartedOn
| order by StartedOn desc
Output of my query1 is list of databases , now I have to pass each db value into query2 to get buildnumber
Query2:
set query_take_max_records=5000;
let view=datatable(Property:string,Value:dynamic)[];
let viewFile=datatable(FileName:string)[];
alias database db = cluster(x).database('y');
let latestInfoFile = toscalar((
union isfuzzy=true viewFile,database('db').['TextFileLogs']
| where FileName contains "AzureStackStampInformation"
| distinct FileName
| order by FileName
| take 1));
union isfuzzy=true view,(
database('db').['TextFileLogs']
| where FileName == latestInfoFile
| distinct LineNumber,FileLineContent
| order by LineNumber asc
| summarize StampInfo=(toobject(strcat_array(makelist(FileLineContent,100000), "\r\n")))
| mvexpand bagexpansion=array StampInfo
| project Property=tostring(StampInfo[0]), Value=StampInfo[1]
)|where Property contains "StampVersion" | project BuildNumber = Value;
database() function: is a special scoping function, and it does not support non-constant arguments due to security consideration.
As a result - you cannot use sub-query to fetch list of databases and then operate on this list as input for database() function.
This behavior is described at:
https://learn.microsoft.com/en-us/azure/kusto/query/databasefunction?pivots=azuredataexplorer
Syntax
database(stringConstant)
Arguments
stringConstant: Name of the database that is referenced. Database identified can be either DatabaseName or PrettyName. Argument has to be constant prior of query execution, i.e. cannot come from sub-query evaluation.

Resources