How could I create relationships between tables in JetBrains' DataGrip? - jetbrains-ide

I am using DataGrip by JetBrains in my work. It is ok, but I don't know how to create relationships between tables like in this picture:

It's a two step procedure. In the first step, you must modify your table to add foreign key constraint definitions. In the second step, you can display the table diagram.
First, right click on the name of your table in DataGrip, then choose Modify Table. You will see four tabs: Columns, Keys, Indices, and Foreign Keys. Choose the Columns tab. Right click on the column name you want to become a foreign key, and choose New Foreign Key. The window will switch to its Foreign Keys tab with some information filled in. Fill in your "target table". You may also have to write in the target column name in the SQL statement's REFERENCES phrase. Review all the information now in the Modify Table window, and, when satisfied, click "Execute".
Second, right click again on the name of your table in DataGrip, and this time choose Diagrams > Show Visualisation. You should now see a diagram displaying the relations between your original table and the referenced tables.
In DataGrip Help, you can look at the Working with the Database Tool Window page for its Modifying the definition of a table, column, index, or a primary or foreign key section. There is a very short procedure description, there.
Wikipedia has an example in its Defining foreign keys article section that may be useful to you while working in DataGrip's Modify Table window.
I did this procedure in DataGrip 2017.1.3, and I don't know whether other versions vary.

Generally: from the context menu or by pressing Ctrl+Alt+U.
If you have found this picture, one more step was to go deeper in the website and you would get to this page:
https://www.jetbrains.com/datagrip/features/other.html
And there is an explanation how to do it.

Try this small SQL script which creates 3 tables. I think you will find this work well.
CREATE TABLE product (
category INT NOT NULL, id INT NOT NULL,
price DECIMAL,
PRIMARY KEY(category, id)
);
CREATE TABLE customer (
id INT NOT NULL,
PRIMARY KEY (id)
);
CREATE TABLE product_order (
no INT NOT NULL AUTO_INCREMENT,
product_category INT NOT NULL,
product_id INT NOT NULL,
customer_id INT NOT NULL,
PRIMARY KEY(no),
INDEX (product_category, product_id),
INDEX (customer_id),
FOREIGN KEY (product_category, product_id)
REFERENCES product(category, id)
ON UPDATE CASCADE ON DELETE RESTRICT,
FOREIGN KEY (customer_id)
REFERENCES customer(id)
) ;

Related

add new (missing) entry to referenced table from SQLFORM (SQLFORM.grid) in web2py

In this minimal case situation I have table with filed referencing another table entries.
When I'm adding main_entries entry, I have dropdown with entries from referenced table. When there isn't entry in referenced table I need, how can I create this new entry from this view (i.e. not leaving main_entries form)?
have this situation:
Model:
db.define_table('main_entries',
Field('type', 'reference entry_type' )
)
db.define_table('entry_type',
Field('label')
)
Controller:
def entries_edit():
form = SQLFORM.grid(db.main_entries)
return dict(form=form)
View:
{{extend 'layout.html'}}
{{=form}}
You can manage this by using the left option of SQLFORM.grid
left is an optional left join expressions used to build ...select(left=...).
It makes sense to combine this with the field option to specify the fields of both tables which should be displayed.
fields is a list of fields to be fetched from the database. It is also used to determine which fields to be shown in the grid view. However, it doesn't control what is displayed in the separate form used to edit rows. For that, use the readable and writable attribute of the database fields.
And don't forget to reference the leading table by the field_id option
field_id must be the field of the table to be used as ID, for example db.mytable.id. This is useful when the grid query is a join of several tables. Any action button on the grid(add record, view, edit, delete) will work over db.mytable.
cf. SQLFORM.grid signature
You must specify relationship in query.
You can try something like this:
def entries_edit():
query = db(db.main_entries.type == db.entry_type.id)
form = SQLFORM.grid(query)
return dict(form=form)

Dynamics CRM 2011 SQL MetadataSchema Primary Name Attribute

I am trying to create a custom Audit summary report based on a date range that needs to be emailed nightly. I've got most of it working, but need some help with getting the primary name/field/attribute for a referenced entity. I noticed in the Audit view for a referenced entity, the data is stored like 'systemuser;'. What I would like to do is grab the Primary Field (Primary Name, Primary Attribute, whatever it's called) to display on the report. Does anyone know how to find the Primary Name attribute for an entity using the MetadataSchema views in the CRM SQL database? I have found the Primary Key field by looking at the MetadataSchema.Attribute.IsPKAttribute field, but I don't see anything for the Primary Name field.
Also, I am grabbing the current values from the entities if there are no following audit entries. For the lookup fields (like owner or customer) how can I tell from the Metadata what field stores the ObjectTypeCode? For example, if I was looking up the customer on a sales order, I know I can look at CustomerIdType field to find the ObjectTypeCode, but I need to find that the field is called CustomerIdType from the metadata.
If anyone has any good references on the Metadata from the SQL side of CRM, I would greatly appreciate it.
SQL query to get primary fields for all entities
SELECT e.Name as 'entity', a.Name as 'primary field'
FROM [dbo].EntityView e
left join [dbo].AttributeView a on e.EntityId = a.EntityId
where (a.DisplayMask & 256) > 0 --256 is for primary field
order by e.name
There are two cases to get object type code of lookup
append Type to field name (i.e. CustomerIdType)
if above is not available, get it from AttributeMetadata
SELECT ReferencedEntityObjectTypeCode
FROM [Discworld_MSCRM].[dbo].[AttributeView]
where name = '<field name>' and entityid = '<entity id>'
I'm not sure what exact rules are for Type fields to exist

DB2 backup and restore db table preserving foreign key constraints

I'm currently having issue going through a test backup and restore of database table on my development machine for db2. Was never entirely successful. Although I was able to restore all data after a drop and re-create of the table, I wasn't able to reset the foreign key constraint as I got SQL error complaining that keys don't match. Here's my exact steps, I'm sure not entirely the right way to do it, but it does eventually restore the 5423 rows of data:
The process
export to /export/home/dale/comments.ixf of ixf messages /export/home/dale/msg.txt select * from .comments
Note: step 1 exports 5423 rows of data to a location
drop table .comments
import from /export/home/dale/comments.ixf of ixf create into .comments
Note: step 3 here creates the table but does not insert any data rows
load client from /export/home/dale/comments.ixf of ixf modified by identityoverride replace into .comments
Note: up until this step, I'm able to insert the 5423 rows of data in the recreated db table
alter table .comments add FOREIGN KEY (comments_id) REFERENCES .news (article_key)
Note: here alter table fails as db2 complaints that some comments_id does not match article_key
Could anyone help with my problem here? Thanks in advance
The error means that some of the rows you IMPORT into the Comments table refer to rows that do not exist in the News table.
You might not be forming the constraint correctly. The column name "comment_id" sounds like the primary key to the Comments table. You want the foreign key, which matches the primary key of the News table. It might also be called "article_key" or "article_id".
ALTER TABLE Comments
ADD FOREIGN KEY( article_key)
REFERENCES News( article_key);
If "comment_id" is really not the primary key of the "Comments" table, then the problem comes from not backing up and restoring both the News and Comments table at the same time.
You can either EXPORT and IMPORT the News table along with the Comments table, or remove the Comments that refer to missing News rows with something like this
DELETE FROM Comments
WHERE comments_id NOT IN (
SELECT article_key
FROM News
)
Before you do this, you might want to try listing the Comments which would be deleted by the above query
SELECT *
FROM Comments
WHERE comments_id NOT IN (
SELECT article_key
FROM News
)
I found a solution to my problem as well as my comments above,
user980717 resolved my first problem where I set the wrong column as the foreign key
For my 2nd issue, i.e. "SQL0668N Operation not allowed for reason code "1" on table "tablename". SQLSTATE=57016", I need to run the following command "set integrity for niwps.comments immediate checked" to ensure data satisfied all constraints defined in the table. And thanks to all who took the effort in helping me with my problems. Cheers

Composite Foreign Key in Sharepoint List

I have two sharepoint List.
List1 - This contains all users and has primary key as UserId
List2 - This contains all courses and has primary key as CourseId
Now I want to define third list that would have its primary key as composite key.
List3 - This contains users to courses mapping. So the primary key is (UserId, CourseId) combination.
When I define List3, I add columns from the List Settings page. When I create a new column, I can choose Lookup and choose the foreign key from another list. But I am unable to define a composite key. (where the keys come from different list).
Is there a way to define composite key for a list in sharepoint 2010?
Thanks
Sharepoint is not a database and lists are not tables. There are no primary, foreign keys or relations (in the DB sense) in Sharepoint. While the DB metaphor is used to explain Sharepoint it is just an metaphor, not the way Sharepoint works. The closest thing to Sharepoint you can find in the database world are document databases.
Perhaps you are confusing lookup fields with primary keys. A lookup field is a field whose values come from another list. They do not define a relation between the lists. That said, Sharepoint 2010 allows you to enforce deletion constraints so that you can't delete a list item that is used as a lookup value in another list. This is set at the lookup field level and only if the lookup field allows a single choice.
To set the restriction programmatically, use the SPFieldLookup.RelationshipDeleteBehavior property. To set the restriction from the UI, locate the lookup field in the target list's settings, open its settings and enable "Enforce Relationship Behavior" in the Relations section.

How to retrieve from two tables with same foreign key repeated more than once?

How to display the data of tables that are linked by a primary key and foreign key where the foreign key of the data repeats?
For ex. I have two tables, ParentTable and Childtable.
The primary key of ParentTable acts as the foreign key of ChildTable.
There are more than one record with same ParentId in ChildTable. How to retrieve them and display in a single Grid or List or any type of view?
As for the query: if you are using Oracle you may use a CONNECT BY statement in your query; otherwise you can just use a JOIN on the foreign key to retrieve the list of couples Parent-Child and handle them in your C# business logic.
As for the presentation: this is the classic tree structure, so you may find a Treeview useful.

Resources