iOS SQLite: How to automatically set foreign key? - ios

My app uses SQLite, and I've sorted out the create table statements. The idea is that table A and B have a one-to-many (or one) relationship, so the foreign key will be in Table B. Now I know about autoincrement for creating the primary key but how will this work for the foreign key? What if I add one row for Table A and 5 rows for Table B (all of which ideally are linked to that single row in Table A)? Won't it just autoincrement from 001-005 in table B?

Yes, if it's one-to-many between A and B, and as you add records in B, you will auto increment B's primary key, but not the foreign key to A (assuming you make it a plain old INTEGER with no AUTOINCREMENT). Given your example, yes, B will have five records, 1-5, which will all point to record 1 in A. So, when you add the record in A, you grab its id via FMDB's lastInsertRowId (or sqlite's sqlite3_last_insert_rowid()), store that in a variable, and then use that when populating the foreign key in B. So, in short, you don't "automatically" set the foreign key, but just do so manually, but it isn't hard.
In terms of how to configure the tables, maybe it helps if we look at an example of a one to many relationships between authors and books (ignoring the possibility of co-authorship, but focusing on the fact that one author can write multiple books). Thus, you have two entities, a author (A) entity, and a book (B) entity. The book.book_author_id is a foreign key referencing author.author_id.
Thus, would look like:
CREATE TABLE author
(
author_id INTEGER PRIMARY KEY AUTOINCREMENT,
author_last_name TEXT,
author_first_name TEXT
);
CREATE TABLE book
(
book_id INTEGER PRIMARY KEY AUTOINCREMENT,
title TEXT,
book_author_id INTEGER,
FOREIGN KEY (book_author_id) REFERENCES author (author_id)
);
INSERT INTO author (author_last_name, author_first_name) VALUES ('William', 'Shakespeare');
INSERT INTO book (title, book_author_id) VALUES ('Hamlet', 1);
INSERT INTO book (title, book_author_id) VALUES ('Macbeth', 1);
INSERT INTO book (title, book_author_id) VALUES ('Othello', 1);
INSERT INTO book (title, book_author_id) VALUES ('King Lear', 1);
INSERT INTO book (title, book_author_id) VALUES ('Henry V', 1);
And if we look at the results, it looks like:
$ sqlite3 test.db
SQLite version 3.7.12 2012-04-03 19:43:07
Enter ".help" for instructions
Enter SQL statements terminated with a ";"
sqlite> .mode column
sqlite> .headers on
sqlite>
sqlite> CREATE TABLE author
...> (
...> author_id INTEGER PRIMARY KEY AUTOINCREMENT,
...> author_last_name TEXT,
...> author_first_name TEXT
...> );
sqlite>
sqlite> CREATE TABLE book
...> (
...> book_id INTEGER PRIMARY KEY AUTOINCREMENT,
...> title TEXT,
...> book_author_id INTEGER,
...> FOREIGN KEY (book_author_id) REFERENCES author (author_id)
...> );
sqlite>
sqlite> INSERT INTO author (author_last_name, author_first_name) VALUES ('William', 'Shakespeare');
sqlite>
sqlite> SELECT * FROM author;
author_id author_last_name author_first_name
---------- ---------------- -----------------
1 William Shakespeare
sqlite>
sqlite> INSERT INTO book (title, book_author_id) VALUES ('Hamlet', 1);
sqlite> INSERT INTO book (title, book_author_id) VALUES ('Macbeth', 1);
sqlite> INSERT INTO book (title, book_author_id) VALUES ('Othello', 1);
sqlite> INSERT INTO book (title, book_author_id) VALUES ('King Lear', 1);
sqlite> INSERT INTO book (title, book_author_id) VALUES ('Henry V', 1);
sqlite>
sqlite> SELECT * FROM book;
book_id title book_author_id
---------- ---------- --------------
1 Hamlet 1
2 Macbeth 1
3 Othello 1
4 King Lear 1
5 Henry V 1
sqlite> .quit
Or, if you want to do it programmatically (I'm using FMDB which makes this much simpler, but clearly the same logic works if you're doing your own sqlite3 calls, but it just takes a lot more code):
- (void)createAuthorTable
{
BOOL result = [_db executeUpdate:
#"CREATE TABLE IF NOT EXISTS author "
"("
"author_id INTEGER PRIMARY KEY AUTOINCREMENT, "
"author_last_name TEXT, "
"author_first_name TEXT "
");"];
NSAssert(result, #"%s - Unable to create author table", __FUNCTION__);
}
- (void)createBookTable
{
BOOL result = [_db executeUpdate:
#"CREATE TABLE IF NOT EXISTS book "
"("
"book_id INTEGER PRIMARY KEY AUTOINCREMENT, "
"title TEXT, "
"book_author_id INTEGER, "
"FOREIGN KEY (book_author_id) REFERENCES author (author_id) "
");"];
NSAssert(result, #"%s - Unable to create book table", __FUNCTION__);
}
- (sqlite_int64)createAuthorWithFirstName:(NSString *)firstName lastName:(NSString *)lastName
{
BOOL result = [_db executeUpdate:#"INSERT INTO author (author_first_name, author_last_name) VALUES (?, ?)", firstName, lastName];
NSAssert(result, #"%s - Unable to insert author record", __FUNCTION__);
return [_db lastInsertRowId];
}
- (sqlite_int64)createBookWithTitle:(NSString *)title authorId:(sqlite_int64)authorId
{
BOOL result = [_db executeUpdate:#"INSERT INTO book (title, book_author_id) VALUES (?, ?)", title, [NSNumber numberWithInt:authorId]];
NSAssert(result, #"%s - Unable to insert book record", __FUNCTION__);
return [_db lastInsertRowId];
}
- (void)testInsert
{
[self openDatabase];
NSArray *bookTitles = [NSArray arrayWithObjects:#"Hamlet", #"Macbeth", #"Othello", #"King Lear", #"Henry V", nil];
[self createAuthorTable];
[self createBookTable];
sqlite_int64 authorId = [self createAuthorWithFirstName:#"William" lastName:#"Shakespeare"];
sqlite_int64 bookId;
for (NSString *bookTitle in bookTitles)
bookId = [self createBookWithTitle:bookTitle authorId:authorId];
[self closeDatabase];
}

But before you can set the foreign keys, you have to turn it ON first. Do this first instead,
PRAGMA foreign_keys=ON;

A column with a foreign key constraint is not typically an autoincrementing value but refers to a (pre-existing) key value in another table. So if your AUTHORS table has an autoincrementing integer primary key, your TITLES.AuthorID column would simply be an integer with no autoincrement capability.
BTW, integer values do not have leading zeroes: 001-005 -- that usually implies a zero-padding which must be represented with a text/varchar datatype.

Related

How to join these Tables with

I want to join table Saleperson with Table Salevolume. The Logic of the join is:
Table Saleperson has key: itemfrom and itemto, Table Salevolume has Key: Item. When the key "Item" from Salevolume is between the key "itemfrom" and "itemto" of saleperson, then i will make sume of salevolume, group by Saleperson
The Key "accountfrom" and "accountto" and "item" have sometime character at the end
Can you please help me ?
Thanks
CREATE TABLE [dbo].[Saleperson](
[Saleperson] [nvarchar](3) NULL,
[itemfrom] [nvarchar](4) NULL,
[itemto] [nvarchar](4) NULL
)
insert into [dbo].[Saleperson]
values
('A','111H','112H'),
('B','122G','125G'),
('C','134F','137F'),
('D','117','119'),
CREATE TABLE [dbo].[Salevolume](
[Item] [nvarchar](6) NULL,
[Salevolume] [int] NULL
)
insert into [dbo].[Salevolume]
values
('112H',30),
('113H',40),
('122G',30),
('134F',50),
('118',100)
You need to fist check if item's last charater is alphabet or not. if it is a alphabet then check whether numeric value and alphabet value of item is between that of numeric value and alphabet value of itemfrom and itemto respectively as shown below:
select p.Saleperson,sum(v.Salevolume)
from Saleperson p
inner join Salevolume v
on v.Item between p.itemfrom and p.itemto
OR (
RIGHT(v.Item,1) between 'A' and 'Z'
and RIGHT(v.Item,1) between RIGHT(p.itemfrom,1) AND RIGHT(p.itemto,1)
and REPLACE(v.item,RIGHT(v.Item,1),'') between REPLACE(p.itemfrom,RIGHT(p.itemfrom,1),'') and REPLACE(p.itemto,RIGHT(p.itemto,1),'')
)
group by p.Saleperson;

SQLite id field - autofill

I've added a new table to my DB:
CREATE TABLE myTable (
myId ID NOT NULL,
aNumber INTEGER NOT NULL,
anUniqueTextId TEXT NOT NULL,
aText TEXT,
PRIMARY KEY(myId, anUniqueTextId) ON CONFLICT IGNORE,
FOREIGN KEY(anUniqueTextId, aNumber) REFERENCES otherTable(otherTableId, otherTableValue2) ON DELETE CASCADE
);
Now I want to insert values without manually finding out which index should I put in myId field:
[myDatabase inTransaction:^(FMDatabase *db, BOOL *rollback) {
[db executeUpdate:#"INSERT INTO myTable VALUES(?,?,?)",
// #(myData.myId), //I don't want to insert it manually
#(aNumber),
myData.anUniqueTextId,
myData.aText];
if (db.lastErrorCode) {
NSLog(#"Huston, we've got a problem: %#", db.lastError.localizedDescription);
}
}];
Ofc, I get here an error telling:
table myTable has 4 columns but 3 values were supplied
Now the question is how to insert the data to make this field autoinsert myId? I'm not sure if my insert code is invalid or CREATE TABLE statement.
-- UPDATE --
I've updated create statement to correct one:
CREATE TABLE myTable (
myId INTEGER PRIMARY KEY DEFAULT 0 NOT NULL,
aNumber INTEGER NOT NULL,
anUniqueTextId TEXT NOT NULL,
aText TEXT,
FOREIGN KEY(anUniqueTextId, aNumber) REFERENCES otherTable(otherTableId, otherTableValue2) ON DELETE CASCADE
);
With respect to your comment you need to specify the PRIMARY KEY with a NULLvalue in the QUERY:
[db executeUpdate:#"INSERT INTO myTable VALUES(?,?,?,?)",
NULL,
#(aNumber),
myData.anUniqueTextId,
myData.aText];
That way the database will fill in the primary key and autoincrement it (SQL Lite specs for PRIMARY KEY).
Here you need to change the schema of table.
To auto insert into myId field, you must have to add constraint AUTOINCREMENT when you create table. Also this field must be use as primary key. So now the schema for table is like:
CREATE TABLE myTable (
myId INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL
aNumber INTEGER NOT NULL,
anUniqueTextId TEXT NOT NULL,
aText TEXT,
FOREIGN KEY(anUniqueTextId, aNumber) REFERENCES otherTable(otherTableId, otherTableValue2) ON DELETE CASCADE
);

select statement extremly slow

I'm creating 4 tables and select from them afterwards. Selecting works perfectly for the first 3 select statements, but the 4th one takes about 10 seconds on the iPhone simulator, and 5 seconds on the sqlite3 console.
Also I get 0 results on the iPhone simulator, but 1 on the console. But that's a problem I want to solve after I solved the performance issue.
I read something about indexes and how they can improve the performance, but I have no clue how to implement them in my code.
sql0 = [[NSString alloc]initWithFormat:#"
create table v%i
as select id_produkt
from v%i natural join produkt_eigenschaft
where id_eigenschaft =
(select id_eigenschaft from eigenschaft where at = '%#')",counter,counter-1,selectedStringItem];
and afterwards:
NSString *sqleig = [[NSString alloc]initWithFormat:#"
select at
from eigenschaft
where id_eigenschaft IN
(select distinct id_eigenschaft
from produkt_eigenschaft
where id_produkt IN (select * from v%i))
AND rubrik = '%i'",counter-1, [sender tag] + 1];
Why is this statement executed so slowly? And how can I solve it?
Thanks in advance.
EDIT: explain query plan and .schema
explain query plan create table v3 as select id_produkt from v2 natural join produkt_eigenschaft where id_eigenschaft = (select id_eigenschaft from eigenschaft where at = '101-170');
0|0|1|SCAN TABLE produkt_eigenschaft (~100000 rows)
0|0|0|EXECUTE SCALAR SUBQUERY 1
1|0|0|SEARCH TABLE eigenschaft USING AUTOMATIC COVERING INDEX (at=?) (~7 rows)
0|1|0|SEARCH TABLE v2 USING AUTOMATIC COVERING INDEX (id_produkt=?) (~7 rows)
explain query plan select at from eigenschaft where id_eigenschaft IN (select distinct id_eigenschaft from produkt_eigenschaft where id_produkt IN (select * from v3)) AND rubrik = '5';
0|0|0|SCAN TABLE eigenschaft (~10000 rows)
0|0|0|EXECUTE LIST SUBQUERY 1
1|0|0|SCAN TABLE produkt_eigenschaft (~100000 rows)
1|0|0|EXECUTE LIST SUBQUERY 2
2|0|0|SCAN TABLE v3 (~1000000 rows)
1|0|0|USE TEMP B-TREE FOR DISTINCT
CREATE TABLE eigenschaft (id_eigenschaft integer,rubrik integer,en text,at text,ba text,bg text,hr text,cz text,hu text,pl text,ro text,ru text,rs text,sk text,si text);
CREATE TABLE farbe (id_farbe integer,hexcode text,farbton integer,farbname text);
CREATE TABLE produkt (id_produkt integer,code text,pdf_link text,image_link text,image_small blob,link text,en text,at text,ba text,bg text,hr text,cz text,hu text,pl text,ro text,ru text,rs text,sk text,si text,active integer);
CREATE TABLE produkt_eigenschaft (id_produkt integer,id_eigenschaft integer);
CREATE TABLE produkt_farbe (id_produkt integer,id_farbe integer);
CREATE TABLE produkt_surface (id_surface integer,id_produkt integer,image_link text);
CREATE TABLE produkt_text (id_produkt integer,en text,at text,ba text,bg text,hr text,cz text,hu text,pl text,ro text,ru text,rs text,sk text,si text);
CREATE TABLE rubrik (id integer,en text,at text,ba text,bg text,hr text,cz text,hu text,pl text,ro text,ru text,rs text,sk text,si text);
CREATE TABLE v0(id_produkt INT);
CREATE TABLE v1(id_produkt INT);
CREATE TABLE v2(id_produkt INT);
CREATE TABLE v3(id_produkt INT);
Solved it with indexes.
create index i on produkt_eigenschaft (id_eigenschaft)
Call this once before selecting

Elegant linq solution for left joins with unique data

I woud like to inquire if my Linq solution below is a good solution or if there is a better way. I am new to using Linq, and am most familiar with MySQL. So I've been converting one of my past projects from PHP to .NET MVC and am trying to learn Linq. I would like to find out if there is a better solution than the one I came up with.
I have the following table structures:
CREATE TABLE maplocations (
ID int NOT NULL AUTO_INCREMENT,
name varchar(35) NOT NULL,
Lat double NOT NULL,
Lng double NOT NULL,
PRIMARY KEY (ID),
UNIQUE KEY name (name)
);
CREATE TABLE reservations (
ID INT NOT NULL AUTO_INCREMENT,
loc_ID INT NOT NULL,
resDate DATE NOT NULL,
user_ID INT NOT NULL,
PRIMARY KEY (ID),
UNIQUE KEY one_per (loc_ID, resDate),
FOREIGN KEY (user_ID) REFERENCES Users (ID),
FOREIGN KEY (loc_ID) REFERENCES MapLocations (ID)
);
CREATE TABLE Users (
ID INT NOT NULL AUTO_INCREMENT,
name VARCHAR(20) NOT NULL,
email VARCHAR(50) NOT NULL,
pass VARCHAR(128) NOT NULL,
salt VARCHAR(5) NOT NULL,
PRIMARY KEY (ID),
UNIQUE KEY unique_names (name),
UNIQUE KEY unique_email (email)
);
In MySQL, I use the following query to get the ealiest reservation at each maplocation with a non null date for any locations that don't have a reservation.
SELECT locs.*, if(res.resDate,res.resDate,'0001-01-01') as resDate, res.Name as User
FROM MapLocations locs
LEFT JOIN (
SELECT loc_ID, resDate, Name
FROM Reservations, Users
WHERE resDate >= Date(Now())
AND user_ID = Users.ID
ORDER BY resDate
) res on locs.ID = res.loc_ID
group by locs.ID
ORDER BY locs.Name;
In Linq, with Visual studio automatically creating much of the structure after connecting to the database, I have come up with the following equivalent to that SQL Query
var resList = (from res in Reservations
where res.ResDate >= DateTime.Today
select res);
var locAndRes =
(from loc in Maplocations
join res in resList on loc.ID equals res.Loc_ID into join1
from res2 in join1.DefaultIfEmpty()
join usr in Users on res2.User_ID equals usr.ID into join2
from usr2 in join2.DefaultIfEmpty()
orderby loc.ID,res2.ResDate
select new {
ID = (int)loc.ID,
Name = (string)loc.Name,
Lat = (double)loc.Lat,
Lng = (double)loc.Lng,
resDate = res2 != null ?(DateTime)res2.ResDate : DateTime.MinValue,
user = usr2 != null ? usr2.Name : null
}).GroupBy(a => a.ID).Select(b => b.FirstOrDefault());
So, I'm wondering is there a better way to perform this query?
Are these equivalent?
Are there any good practices I should be following?
Also, one more question, I'm having trouble getting this from the var to a List. doing something like this doesn't work
List<locAndResModel> locList = locAndRes.AsQueryable().ToList<locAndResModel>();
In the above snippet locAndResModel is just a class which has variables to match the int, string, double double, DateTime, string results of the query. Is there an easy way to get a list without having to do a foreach and passing the results to a constructor override? Or should I just add it to ViewData and return the View?
You'll want to take advantage of the automatic joins performed by the Entity Framework. Give this a try and let me know if it does what you want:
var locAndRes = from maplocation in MapLocations
let earliestReservationDate = maplocation.Reservations.Min(res => res.resDate)
let earliestReservation = (from reservation in mapLocation.Reservations
where reservation.resDate == earliestReservationDate && reservation.resDate >= DateTime.Today
select reservation).FirstOrDefault()
select new locAndResModel( maplocation.ID, maplocation.name, maplocation.Lat, maplocation.Lng, earliestReservation != null ? earliestReservation.resDate : DateTime.MinValue, earliestReservation != null ?earliestReservation.User.name : null)

Uploading a Highscore - How to make it only visible to friends?

I'm wondering if there is a possibility when you upload your highscore you can compare your score with the one of your friends (if simpler, only selected contacts)?
And if so, could someone point me in the right direction, how to do it? I did not find anything useful about this on google.
As far as I pressume it should be possible, because apps like WhatsApp also let you choose specific contacts you want to send a message.
Related to that: Can I just use a/the cloud for uploading highscore or should I use my webspace?
I am not answering this specific to iOS/etc.
What you would typically do is expose a REST (or POX/POJSON - plain old XML or plain old JSON) service on your website that your application communicates with - it would be responsible for negotiating friendships, uploading high scores and retrieving high scores. This would either hit a database under your control or it would connect to a cloud server; there is no problem with either approach (Azure is a good option if you want to apply my SQL concepts).
Inside your database you would maintain a list of friends - this is a very simple structure to set up. Essentially you want two tables that look like the following:
CREATE TABLE [UserAccount]
(
[ID] BIGINT IDENTITY(1,1) PRIMARY KEY,
[Name] NVARCHAR(255),
)
CREATE TABLE [Friendship]
(
[User1] BIGINT, -- Primary key, FK to [UserAccount].[ID]
[User2] BIGINT, -- Primary key, FK to [UserAccount].[ID]
)
This would allow you to indicate friendships along the lines of:
User: ID = 1, Name = Joe
User: ID = 2, Name = Fred
Friendship: User1 = 1, User2 = 2
Friendship: User1 = 2, User1 = 1
You can then query friends using the following query:
SELECT [F1].[User2] AS [ID] FROM [Friendship] AS [F1]
WHERE [F1].[User1] = #CurrentUser
-- Check for symmetric relationship.
AND EXISTS
( SELECT 1 FROM [Friendship] AS [F2]
WHERE [F2].[User2] = [F1].[User1] AND [F2].[User1] = [F1].[User2] );
You could make that a TVF (Table Value Function) if your SQL variant supports them. Next you would create a high score table and a table to map it to users.
CREATE TABLE [Highscore]
{
[ID] BIGINT IDENTITY(1,1) PRIMARY KEY,
[Score] INT,
}
CREATE TABLE [UserHighscore]
{
[UserID] BIGINT, -- Primary key, FK to User.ID
[HighscoreID] BIGINT, -- Primary key, FK to Highscore.ID
}
Some sample data for this would be:
-- In this game you can only score over 9000!
Highscore: ID = 1, Score = 9001
Highscore: ID = 2, Score = 9005
Highscore: ID = 3, Score = 9008
UserHighscore: UserID = 1, HighscoreID = 1
UserHighscore: UserID = 1, HighscoreID = 2
UserHighscore: UserID = 2, HighscoreID = 3
You can then query for your friends' highscores:
SELECT TOP(10) [U].[Name], [H].[Score] FROM [Friendship] AS [F1]
LEFT INNER JOIN [User] AS [U] ON [U].[ID] = [F1].[User2]
LEFT INNER JOIN [HighscoreUser] AS [HU] ON [HU].[UserID] = [F1].[User2]
LEFT INNER JOIN [Highscore] AS [H] ON [H].[ID] = [HU].[UserID]
WHERE [F1].[User1] = #CurrentUser
-- Check for symmetric relationship.
AND EXISTS
( SELECT 1 FROM [Friendship] AS [F2]
WHERE [F2].[User2] = [F1].[User1] AND [F2].[User1] = [F1].[User2] )
ORDER BY [H].[Score] DESC;
That query would give the top 10 score your friends; giving you their name and score.

Resources