Creating Functional Dependencies - normalization

Ive been trying to normalize a map i have created for a database im making and im having some trouble defining what the FDs would be.
I have a table:
User(userID(primary key), Fname, Lname, AccntType, Utype, RegDate, Status, Email, Uname, Pword)
It seems as if I would have to put all of those tables in the one FD, though it doesnt seem right to do this. Any suggestions?

Related

Why is TypeORM returning no records in this simple query?

I'm trying to get all the users on my system that match a complex where conditional with TypeORM. My end query would look something like this:
connection.createQueryBuilder()
.select().from(User, "user")
.where("email IS NULL OR email NOT LIKE '%#example.com'")
.getMany()
If I run that query with getCount() it works and tells me how many I have, but getMany() return []
In fact, I simplified it to this:
console.log(
await connection.createQueryBuilder()
.select().from(User, "user")
.getManyAndCount())
I get this surprising result (with logging enabled):
query: SELECT * FROM "user" "user"
query: SELECT COUNT(DISTINCT("user"."id")) as "cnt" FROM "user" "user"
[ [], 14 ]
Any ideas why I would get no users when the count shows 14? I run the query manually and it obviously shows the users... what's going on here?
The code that Carlo offered in one of the answers:
await connection.getRepository(User).findAndCount()
works, but that won't let me have my where clause (as far as I know, I'm still new to TypeORM). I'm just sharing this to show that the User model seems to be working fine, except when I use it with the query builder to select a bunch of users (counting and deleting works).
Keep your code syntax as simple as possible since TypeORM docs (now) are't perfect.
Try using Find Options since I can't find any getManyAndCount() method for QueryBuilder:
const users = await connection
.getRepository(User)
.findAndCount();
EDIT:
Of course you can have (complex) where clause with find.
You can chain multiple where clauses (OR) with a really simple syntax. Check out all options here.
Example that map your "raw" query:
const users = await connection
.getRepository(User)
.findAndCount({
where: [
{
email: IsNull(),
},
{
email: Not(Like('%#example.com')),
},
],
});
Hope it helps :)
Let me divide that step-by-step approach
despite of getManyAndCount() use getRawEntities()
you will get the data for sure by using 1st point
now concentrate on the keys you are getting on data
use the same key on your select query and done
if you didn't get records using getRawEntities():
I. try to use select * i.e, select()
II. check the column name and correct that
Additionally, It can also depend on your entity structure. Carefully check that too.

Rails 5.1 has_many through - associated fields

(See example schema image below)
I am attempting to query a single user from the users table using the email field, along with the id & key fields from the applications table. The results should contain the user found (if any), along with the application (referenced using the key & id fields) and the applications_users associated data.
I can easily write SQL manually to perform this operation:
SELECT
"users".*,
"applications_users"."scopes",
"jwt_applications".*
FROM
"users"
INNER JOIN
"applications_users" ON "applications_users"."user_id" = "users"."id"
INNER JOIN
"jwt_applications" ON "jwt_applications"."id" = "applications_users"."application_id"
WHERE
"users"."email" = 'rainbows#unicorns.net'
AND "jwt_applications"."id" = '01daafc9-2169-4c78-83e9-37ac0a473e3d'
AND "jwt_applications"."key" = 'follow_the_rainbow'
LIMIT 1
However, I cannot for the life of me get the query correct when using ActiveRecord.
These are the unsuccessful attempts I have made thus far:
user = User.where(email: args[:username]).joins(:applications).merge(
JwtApplication.where(id: args[:application][:id], key: args[:application][:key])
).take!
This gets the user correctly, however Rails performs a second SQL query when I attempt to access user.applications (and it also returns all applications associated with the user; so it appears to disregard the id & key conditions)
user = User.where(email: args[:username]).joins(:applications).merge(
JwtApplication.where(id: args[:application][:id], key: args[:application][:key])
).references(:applications_users).take!
This gets the user correctly and also the correct application (yay!), however Rails performs a second SQL query if I attempt to call user.applications_users -- it also returns a collection for all data inside the applications_users table (again, disregarding the id & key conditions)
user = User.where(email: args[:username]).joins(:applications).where(
jwt_applications: {
id: args[:application][:id],
key: args[:application][:key]
}
).take!
This gets the correct user, however Rails performs another SQL query when I attempt to access user.applications -- also returning all applications.
Anyway, hopefully a Rails genius can shed some light on this question! I will be the first to admit that I am by no means a Rails expert; I have spent the last 10 years of my professional career coding in PHP & C++, so please bear with me if this comes off as a stupid question :)
Not sure if this is something you're looking for but...
You can write ActiveRecord query like (join model should be implicitly added to your query):
User.joins(:applications).where(email: email).where(applications: { key: key, id: id})
Where email, key and id as params to pass to the query.
On top of that query you can use select fields to get everything you need:
user = User.joins(:applications).where(email: email).where(applications: { key: key, id: id}).select('users.*, applications.id as appid applications.key as appkey').first
That will give you back the user model (if present) or empty relation if nothing matches your criteria.
You can then call the fields like
user.appid
user.appkey
You can always call select ('users.*, application_users.scopes, applications.*) which will return you all the fields in single instance (still under User model) BUT duplicate fields like id will only be shown once, that's why it's better to grab just the fields you want and give them unique identifiers like I've shown with appid and appkey.
Again, might not be exactly what you're after, but hopefully it points you in the right direction!

Multiple nesting in Falcor query

I am trying to query a multiple nested object with Falcor. I have an user which has beside other the value follower which itself has properties like name.
I want to query the name of the user and the first 10 follower.
My Falcor server side can be seen on GitHub there is my router and resolver.
I query the user with user["KordonDev"]["name", "stars"]. And the follower with user["KordonDev"].follower[0.10]["name", "stars"].
The route for follower is user[{keys:logins}].follower[{integers:indexes}] but this doesn't catch the following query.
I tried to add it as string query.
user["KordonDev"]["name", "stars", "follower[0..10].name"] doesn't work.
The second try was to query with arrays of keys. ["user", "KordonDev", "follower", {"from":0, "to":10}, "name"] but here I don't know how to query the name of the user.
As far as I know and looking on the path parser. There is no way to do nested queries.
What you want to do is batch the query and do two queries.
user["KordonDev"]["name", "stars"]
user["KordonDev"]["follower"][0..10].name
It seems that falcor does not support this, there is even a somewhat old issue discussing how people trying to do nested queries.
to the point about the current syntax leading people to try this:
['lolomo', 0, 0, ['summary', ['item', 'summary']]]
I can see folks trying to do the same thing with the new syntax:
"lolomo[0][0]['summary', 'item.summary']"
As soon as they know they can do:
"lolomo[0][0]['summary', 'evidence']"
So it seems deep nested queries is not a functionality.

Rails 4 how to know if update has been executed

I have this code in Rails 4:
mmkBase = Mmk::Base.find_or_initialize_by(id: id)
mmkBase.update(name: name, city: city, country: country, address: address, region_ids: regionIds, latitude: latitude,
longitude: longitude)
The code is working ok, but now I would need to gather some statistics, like:
Number of bases.
Number of new bases.
Number of loaded (updated) bases.
Number of bases is not a problem. Number of new bases, I think I could check if the object mmkBase returned by find_or_initialize comes with more attributes than just the id, for example with a name.
However, I don´t know how can I check if the update operation is run.
Is there any way to know this? Is there a better way to achieve this? Maybe, I should use a more traditional way to do it, with a select first?
However, I don´t know how can I check if the update operation is run
You can simply use...
if mmkbase.update mkbase_params
...
else
...
This will invoke the update method, generating a response determined by whether it was successful or not (true = success; false = validation failure)
Number of new bases
As mentioned, the new_record? method is what you need here...
if mmkbase.new_record? #-> mmkbase hasn't been saved to db yet
I'd do this:
mmkBase.find_or_create_by(mmkbase_params) do |base|
#do something if new base
end
private
def mmkbase_params
params.require(:mmkbase).permit(:name, :city, :country, :address, :region_ids, :latitude, :longitude)
end
If you're having to pull this type of data by its primary key (find_or_initialize_by id:), you're in trouble... how do you know if the primary key will remain constant?
Of course, this is not always the case. Changing user details would require you to reference the user id - however that data is rigid. IE a user registered (with name and email), and you're now looking for that user (it can't be created on the fly).
I don't know your schema; anything which can be created like this should be referenced by its core data (name, city, etc)...
mmkbase.find_by(name: ....)
In relational databases, you need to be dealing with the data, not the primary keys. In other types of db, you can deal with indexes, but with this type of setup, it's much better to work with the pure data.
You want to distinguish between an already existing record and a newly created record. On a new record which was only initialized by find_or_initialize_by, new_record? returns true. So for example you could write:
mmkBase = Mmk::Base.find_or_initialize_by(id: id)
new_base = mmkBase.new_record?
if mmkBase.update(name: name, city: city, country: country, address: address, region_ids: regionIds, latitude: latitude,
longitude: longitude)
# update was successful
if new_base
new_bases += 1
else
updated_bases += 1
end
else
# error handling
end
Note that it is probably not a good idea to use find_or_initialize_by with the ID of the record. See Rich Peck's answer.
You could probably check the updated_at timestamp on the object to see if it has been updated recently but the Rails 4 update method doesn't tell you whether an object was updated or not.
http://apidock.com/rails/ActiveRecord/Base/update/class

Update Contour form(records) using the record ID

I can successfully create entries in contour programmatically(C#) but I am not able to update the created record using the record ID. After digging my head around can’t find a reason why the following code doesn’t work. It’s very basic and all That I am trying to do is get the record that exist in the contour.
RecordStorage recordStorage = new RecordStorage();
Record r = recordStorage.GetRecord(new Guid("15d654cb-a7c6-4f1f-8b55-0ecd7d19b0e3"));
recordStorage.Dispose();
Just to start with the update process, I am trying to get the record object using it’s id but can’t proceed further as it throws a weird error “An item with the same key has already been added.” I can’t understand while it’s trying to set the value when I call the “storage.GetRecord()”. Following is the stack trace
**An item with the same key has already been added.**
at System.Collections.Generic.Dictionary`2.Insert(TKey key, TValue value, Boolean add)
at Umbraco.Forms.Data.Storage.RecordFieldStorage.GetAllRecordFields(Record record)
at Umbraco.Forms.Data.Storage.RecordStorage.GetRecord(Object id)
at MauriceBlackburn.Service.ContourFormService.InsertRecord(ContourFormFields unionContourForm)
Any thoughts, have I missed something, I have been digging all day around and still not able to figure this out. Thanks in advance.
Much Appreciated.
First off, try deleting the workflow and re-adding it.
You could also create two simple workflows, one that will write the record and a second to manipulate it (using the id when written).
Make sure that there are no records with the same ID in database. You might have inserted them before.

Resources