Grails / Gorm : Difference between declaring object and describing relationship? - grails

I'm having trouble understanding the difference between declaring a domain-object in another domain and specifying the relationship between the domains.
Sample code:
class User {
Book book
}
versus
class User {
static hasOne = Book
}
class Book {
String name
}

The hasOne relationship will put the key on the child object, so in the db you'll find book.user_id with hasOne rather than user.book_id if you just declare Book book on User. You'll see the difference in the DDL generated if you use grails schema-export.
Here's the DDL with hasOne in place:
create table book (id bigint generated by default as identity (start with 1), version bigint not null, user_id bigint not null, primary key (id), unique (user_id));
create table user (id bigint generated by default as identity (start with 1), version bigint not null, primary key (id));
alter table book add constraint FK2E3AE98896CD4A foreign key (user_id) references user;
Here's the DDL with just Book book on User:
create table book (id bigint generated by default as identity (start with 1), version bigint not null, primary key (id));
create table user (id bigint generated by default as identity (start with 1), version bigint not null, book_id bigint not null, primary key (id));
alter table user add constraint FK36EBCB952E108A foreign key (book_id) references book;
Notice that the book table has the reference in the first example and the user has it in the 2nd.
Long answer: I strongly recommend watching Burt Beckwith's presentation on GORM/collections/mapping. Lots of great info around GORM and the consequences of various advantages/problems with describing relationships with hasMany/belongsTo, etc.

The main difference is that when using hasOne the foreign key reference is stored in the child table instead of the parent table, i.e. a user_id column would be stored in the book table instead of a book_id column being stored in the user table. If you didn't use hasOne, then a book_id column would be generated in the user table.
There is an explanation and example in the Grails documentation for hasOne.
Hope this helps.

Related

Unable to find column names in a FK constraint

I have created two tables in Snowflake.
create or replace TRANSIENT TABLE TESTPARENT (
COL1 NUMBER(38,0) NOT NULL,
COL2 VARCHAR(16777216) NOT NULL,
COL3 VARCHAR(16777216) NOT NULL,
constraint UNIQ_COL3 unique (COL3)
);
create or replace TRANSIENT TABLE TESTCHILD3 (
COL_A NUMBER(38,0) NOT NULL,
COL_B NUMBER(38,0) NOT NULL,
ABCDEF VARCHAR(16777216) NOT NULL,
constraint FKEY_1 foreign key (COL_A, COL_B) references TEST_DB.PUBLIC.TESTPARENT1(COL1,COL2),
constraint FKEY_2 foreign key (ABCDEF) references TEST_DB.PUBLIC.TESTPARENT(COL3)
);
Now I want to execute a query and see the names of columns that are involved in FKEY_2 FOREIGN KEY
in Table TESTCHILD3, but it seems like there are no DB Table/View that keeps this information. I can find out the column names for UNIQUE KEY & PRIMARY KEY but there is nothing for FOREIGN KEYS.
EDIT
I have already tried INFORMATION_SCHEMA.TABLE_CONSTRAINTS, along with INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS and all the other system tables. No luck. Only DESC TABLE is giving me some info related to CONSTRAINTS and COLUMNS but that also has FOREIGN KEY CONSTRAINTS information missing.
SHOW IMPORTED KEYS IN TABLE <fk_table_name>;
Updated answer:
I was checking on something unrelated and noticed a very efficient way to list all primary and foreign keys:
show exported keys in account; -- Foreign keys
show primary keys in account;
When you limit the call to a table, it appears you have to request the foreign keys that point to the parent table:
show exported keys in table "DB_NAME"."SCHEMA_NAME"."PARENT_TABLE";
You can check the documentation for how to limit the show command to a specific database or schema, but this returns rich information in a table very quickly.
maybe you can try to query this view: INFORMATION_SCHEMA.TABLE_CONSTRAINTS
Note: TABLE_CONSTRAINTS only displays objects for which the current role for the session has been granted access privileges.
For more see: https://docs.snowflake.net/manuals/sql-reference/info-schema/table_constraints.html

Save a list of strings to sqlite database in Swift 4

Is it possible to save a list of strings into a SQLite column in swift4?
If you're looking for an array data type like you find in some SQL engines, SQLite does not have that. You theoretically could encode this list somehow (e.g. a JSON array), but that's pretty kludgy. So, I'd probably go ahead and normalize that, putting the multiple strings in a separate table.
E.g. Let's say you wanted a table users, that had user_id, name, and an array of privileges. You'd probably instead do something like:
CREATE TABLE users (
user_id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL
);
CREATE TABLE users_privileges (
user_privilege_id INTEGER PRIMARY KEY AUTOINCREMENT,
user_id INTEGER NOT NULL,
privilege TEXT NOT NULL,
FOREIGN KEY (user_id) REFERENCES users (user_id)
);

Fluent Migrate Candidate Key

I have two tables One named "Root" which has columns Id,RootNumber, in which Id is primary Key.
Now when I tried to create another table with RootNumber as the foreign key I get below error
InnerException {"There are no primary or candidate keys in the
referenced table 'dbo.Root' that match the referencing column list in
the foreign key ("FK_CNTR_Root", \r\nCould not create constraint or
index. See previous errors."} System.Exception
{System.Data.SqlClient.SqlException}
this.CreateTableWithId32("CNTR", "Id", s => s
.WithColumn("CNTRNumber").AsString(10).NotNullable()
.WithColumn("CNTRName").AsString(10).NotNullable()
.WithColumn("RootNum").AsInt32().NotNullable()
.ForeignKey("FK_CNTR_Root", "Root", "RootNumber")
The error is very clear. You can make only the PrimaryKey column to be referenced as ForeignKey in another table. So Either make Id as a foreign key in other table or Change RootNumber to PrimaryKey of Root table.
Refer to this basic Foreign Key definition.

Creating a 'join' table - sqlite3

I think I'm pretty close on this one, but can't get it to click.
I've got two simple tables set up.
Table A:
CREATE TABLE customer(
id INTEGER PRIMARY KEY,
first_name TEXT,
last_name TEXT,
email TEXT UNIQUE NOT NULL,
password TEXT NOT NULL,
create_time TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP
);
I've got two rows of data populating correctly in Table A.
Table B:
CREATE TABLE address(
...> id INTEGER PRIMARY KEY,
...> street_address_1 TEXT NOT NULL,
...> street_address_2 TEXT,
...> street_address_3 TEXT,
...> city TEXT NOT NULL,
...> state TEXT NOT NULL,
...> zip TEXT NOT NULL);
And I've successfully imported a CSV file into that table.
I'm trying to create a 3rd table that joins Table A to Table B with the use of Foreign Keys.
I can create the table with the code below, but when I try to select the table, I'm getting a blank, which means I'm obviously doing something wrong. I'm expecting to see data where the two tables overlap on mutual Id numbers, i.e. where the ID from customer = Id from address I'd like to see the data from both tables for those rows appear in Table C.
Table C (the join table):
CREATE TABLE customer_address(
id INTEGER PRIMARY KEY,
customer_id INTEGER,
address_id INTEGER,
first_name TEXT NOT NULL,
last_name TEXT NOT NULL,
email TEXT NOT NULL,
password TEXT NOT NULL,
street_address_1 TEXT NOT NULL,
street_address_2 TEXT,
street_address_3 TEXT,
city TEXT NOT NULL,
state TEXT NOT NULL,
zip TEXT NOT NULL,
FOREIGN KEY (customer_id) REFERENCES customer(id),
FOREIGN KEY (address_id) REFERENCES address(id)
);
Thanks!
I imported the data to the address table using this:
sqlite> .mode csv
sqlite> .import address.csv address
I manually typed in data to the first table using this:
insert into customer(first_name, last_name, email, password)
values('Ad','Mac','a.Mac#gmail.com','Mab'),('Brian','Obrien','bob#example.com','123456');
Don't duplicate the data in your join table (often called a bridge table). This should do for Table C:
CREATE TABLE customer_address(
id INTEGER PRIMARY KEY,
customer_id INTEGER,
address_id INTEGER,
FOREIGN KEY (customer_id) REFERENCES customer(id),
FOREIGN KEY (address_id) REFERENCES address(id));
Duplicating columns is bad practice because it 1)defeats the purpose of using a relational model; 2)can lead to conflicting records if information is updated or deleted in one table, but not another.
Furthermore, you shouldn't have street_address_1, street_address_2, street_address_3 all in the same table. That's a violation of First Normal Form. Think of it this way, can a person have more than three addresses? Can they have two addresses in different cities? Do all three of those addresses have the same zip?

TEntity Remove method fails on many to many relationship that was created using database first

I am using Entity Framework 6.1.3 and a database first approach.
It is a small database with a many to many relationship between Tags and BoxedItems, a table named ItemsTags holds the relationship.
I get an exception when using the scaffolded code to delete a BoxedItem:
db.BoxedItems.Remove(boxedItem);
db.SaveChanges();
SqlException: The DELETE statement conflicted with the REFERENCE
constraint "FK_ItemsTags_Items". The conflict occurred in database
"TimeBox", table "dbo.ItemsTags", column 'IdItem'.
The relationship table code is bellow. The PK for BoxedItem needs to be a Guid and for Tags is a INT IDENTITY (1, 1).
CREATE TABLE [dbo].[ItemsTags] (
[IdItem] UNIQUEIDENTIFIER NOT NULL,
[IdTag] INT NOT NULL,
CONSTRAINT [PK_ItemsTags] PRIMARY KEY CLUSTERED ([IdItem] ASC, [IdTag] ASC),
CONSTRAINT [FK_ItemsTags_Tags] FOREIGN KEY ([IdTag]) REFERENCES [dbo].[Tags] ([Id]),
CONSTRAINT [FK_ItemsTags_Items] FOREIGN KEY ([IdItem]) REFERENCES [dbo].[BoxedItems] ([Id])
);
Would the EF auto generated code work out of the box if my BoxedItem PK was INT IDENTITY (1, 1)? EF seems to like it more for auto generated code.
Is there a smarter way to delete the BoxedItem, other than a custom SQL instruction?

Resources