How to understand whether a schema is in BCNF - mysql

I understood the concept of BCNF very well so someone gives me a relationship in this format like
R = {P, Q, S}
F = {PQ->S, PS->Q, QS->P}
I can easily say that the relation is in BCNF since all the keys on left hand side are also super keys. But If I get a real world questions like the below image:
then how will I determine whether this schema is in BCNF? How will I create functional dependencies from the schema and then found out about super keys? could anyone give me some pointers to solve such questions?
If you convert the schema into :
Code -> City, State
Flightnum -> .....
model -> ...
cid -> ....
Cid, flightnum, date -> ...
then obviously this is not in BCNF but the answer is that the following schema is BCNF, and I am not able understood how they derived the equation for it.

Informally, a schema is in BCNF if all of its relations are in BCNF.
How will I create functional dependencies from the schema . . .
Without any other context, I'd assume that underlined attributes in the image are attributes in the primary key.
So I'd read that image as saying
code->city, state
cid->name, city
etc.
Those are your functional dependencies.

Related

Overwrite function only for a particular instance in LUA

I basically don't look for an answer on how to do something but I found how to do it, yet want more information. Hope this kind of question is OK here.
Since I just discovered this the code of a game I'm modding I don't have any idea what should I google for.
In Lua, I can have for example:
Account = {balance = 0}
function Account.withdraw (v)
self.balance = self.balance - v
end
I can have (in another lua file)
function Account.withdrawBetter (v)
if self.balance > v then
self.balance = self.balance - v
end
end
....
--somewhere in some function, with an Account instance:
a1.withdraw = a1.withdrawBetter
`
What's the name for this "technique" so I can find some more information about it (possible pitfalls, performance considerations vs. override/overwrite, etc)? note I'm only changing withdraw for the particular instance (a1), not for every Account instance.
Bonus question: Any other oo programming languages with such facility?
Thanks
OO in Lua
First of all, it should be pointed out that Lua does not implement Object Oriented Programming; it has no concept of objects, classes, inheritance, etc.
If you want OOP in Lua, you have to implement it yourself. Usually this is done by creating a table that acts as a "class", storing the "instance methods", which are really just functions that accept the instance as its first argument.
Inheritance is then achieved by having the "constructor" (also just a function) create a new table and set its metatable to one with an __index field pointing to the class table. When indexing the "instance" with a key it doesn't have, it will then search for that key in the class instead.
In other words, an "instance" table may have no functions at all, but indexing it with, for example, "withdraw" will just try indexing the class instead.
Now, if we take a single "instance" table and add a withdraw field to it, Lua will see that it has that field and not bother looking it up in the class. You could say that this value shadows the one in the class table.
What's the name for this "technique"
It doesn't really have one, but you should definitely look into metatables.
In languages that do support this sort of thing, like in Ruby (see below) this is often done with singleton classes, meaning that they only have a single instance.
Performance considerations
Indexing tables, including metatables takes some time. If Lua finds a method in the instance table, then that's a single table lookup; if it doesn't, it then needs to first get the metatable and index that instead, and if that doesn't have it either and has its own metatable, the chain goes on like that.
So, in other words, this is actually faster. It does use up some more space, but not really that much (technically it could be quite a lot, but you really shouldn't worry about that. Nonetheless, here's where you can read up on that, if you want to).
Any other oo programming languages with such facility?
Yes, lots of 'em. Ruby is a good example, where you can do something like
array1 = [1, 2, 3]
array2 = [4, 5, 6]
def array1.foo
puts 'bar'
end
array1.foo # prints 'bar'
array2.foo # raises `NoMethodError`

Retrieve and create Persistent entities with relations using JSON

Haskell persistent library allows me to create entities with relations. I would like to be able to get entities (and also create them) using REST JSON calls. But I don't seem to understand how to approach the problem of combining a resulting entity when it is split amongst tables or how to split it when I need to save it (so that the needed parts are saved into needed tables).
An example:
share [mkPersist sqlSettings, mkMigrate "migrateAll"] [persistLowerCase|
Problem
name T.Text
description T.Text
Solution
problemId ProblemId
author T.Text
solution T.Text
|]
So, let's say we have a single problem and multiple solutions to it. How can I get a combined information (which is a problem with all related solutions). Do I need to create a data type which could look something like this:
data Solution =
Solution { author :: T.Text
, solution :: T.Text
}
data Problem =
Problem { name :: T.Text
, description :: T.Text
, solutions :: [Solution]
}
... and then define toJSON, so that I can send it to the caller? Or is there some other approach?
And what about creating entries in DB when I want to add a problem with several solutions (from a single REST call). How would that look like?
I hope I explained my problem correctly and you understand what I am struggling with.
Thank you

Find Table object in query

Using sqlalchemy 0.7.2
Is there a way to find the table class from the query object? For example:
q = session.query(Customers)
how can I find Customers in q? Possible? Not Possible?
Yes. You need column_descriptions.
It's a long road to the table, though. sqlalchemy.orm.Query.column_descriptions returns a list of dicts, describing each query entity as it was given to query. in your example, there's only one entity, so you need the first item from that list. And since you're interested in the type of the query entity, rather than its' structure, you want the "type" key from that list:
q_entity = q.column_descriptions[0]['type']
assert q_entity == Customer
Accessing the table for the mapped class requires snooping around in the mapper subsystem. for that, you should use manager_of_class. The table is accessible from the manager through the mapper.mapped_table attribute:
from sqlalchemy.orm.attribute import manager_of_class
q_table = manager_of_class(q_entity).mapper.mapped_table
Resist the urge to skip strait to the mapper through Customer.__mapper__, or even Customer.__table__; That's specific to sqlalchemy.ext.declarative, and won't work with classes that are mapped by other means.

How to get EF 4.1 RC code-first to use correct foreign key?

I was using CTP5 and switched to RC1. With no changes to the EntityTypeConfiguration, EF is now trying to look something up by the wrong column name. It is using the singular rather than the plural of the column name and I can't figure out where it is getting that idea.
Example: Many-to-many
//User.Roles
//Role.Users
//User EntityTypeConfiguration
this.HasKey(x => x.Id);
this.HasMany(x => x.Roles)
.WithMany().Map(m => {
m.MapLeftKey("Users_Id");
m.MapRightKey("Roles_Id");
m.ToTable("UserRoleLinks");
});
Then I get the error:
Invalid column name 'User_Id'.
Where is it getting "User_Id"? The table Id is "Id"; The join table is explicitly stated as "Users_Id" What changed between CTP5 and RC1 that would have caused this?
UPDATE:
I am using the "modelBuilder.Conventions.Remove<IncludeMetadataConvention>()" is that one not supported anymore? Could this be the problem? I'm not sure what the default behavior is now.
protected override void OnModelCreating(DbModelBuilder modelBuilder) {
modelBuilder.Conventions.Remove<IncludeMetadataConvention>();
modelBuilder.Configurations.Add(new UserConfig());
}
I figured out what I was doing wrong. The short answer is that I needed to define both sides of the many-to-many relationship because each class participates with a reciprocal collection (User.Roles and Role.Users). Apparently that wasn't necessary with CTP5.
See: Many to Many mapping not working - EF 4.1 RC
To stick with my example, here is the correct syntax.
this.HasMany(x => x.Roles)
.WithMany(r => r.Users).Map(m => {
m.MapLeftKey("Users_Id");
m.MapRightKey("Roles_Id");
m.ToTable("UserRoleLinks");
});
There are a couple pitfalls which obscured the simple solution for me.
1) Only define the relationship once. I was defining the many-to-many relationship from both perspectives in different EntityTypeConfiguration<T> classes, which is not necessary and brings its own errors.
2) Don't mix up the fields you use for the MapLeftKey and MapRightKey. The order is intuitive but I am guessing it is easily something that could get mixed up through copy/paste and what-not.
The Foreign Key naming convention changed in EF 4.1 RC.
The problem is basically that EF now expects the FK to be called User_ID (singular), and the RC provides no ability to configure custom conventions.
If EF recreated the database for you, just change your mappings to User_Id. If you're stuck with a production database I'd recommend using sp_rename to rename the Foreign Keys in your database.
This answer (gotten from a question of mine, see below) worked for me painlessly and seamlessly on a production database.
Useful references
A question of mine about EF 4.1 RC
naming conventions:
EF 4.1 messing things up. Has FK naming strategy changed?.
For further reference, here's a list
of changes in
RC.

Class design: entity ID vs entity reference

If I've got Foo with a property of type Bar. Both are persisted in a database which can be retrieved by an ID. (The IDs are actually used in the line of business by customer service claims. So they're not just index placeholders.) I could take the approach shown with b1 or b2.
Chaining entities together scares me since if you push that too far, it's easy to get Null's popping up. On the other hand, having the ID show up everywhere seems like it's adding unnecessary wordiness.
int fooKey = 123;
Foo f = new Foo(fooKey);
Bar b1 = new Bar(Foo.BarID); //This?
Bar b2 = Foo.Bar; // Or This?
Note: This is NOT about the .NET Entity framework. The word entity is used here in the general sense.
As a general rule I try to avoid chaining, because it usually introduces unncessary tight coupling. All depends on the context, but in terms of business objects it might be a good idea to keep the entities loosely coupled so they can grow independently.
In the example you provide I don't think tight coupling is warranted. If the intersection was greater this might be warranted, but this isn't the general case with Business entities, I've found.
Take a look at the way MSFT implemented LINQ to SQL. They let you set either/or. Their mapper is smart enough to expose both properties and lazy-load as necessary. IMO you should go the simplest way (use an ID) or use an O/R mapper like Hibernate/NHibernate, Linq to SQL, or Linq to Entities if you want fanciness.