Unable to set foreign key SQLite.swift - ios

I am not able to set foreign key using stephencelis SQLite.swift.
t.foreignKey(user_id, references:"user_mstr",user_id)
I have two tables user_master and user_details. How to set user_id as a foreign key in user_detail table. I am getting below error.
Cannot invoke foreignkey with an arguement list of type (Expression<string>),

You're passing string to references. It should be like
let user_id = Expression<String>("user_id")
let user_mstr = Table("user_mstr")
//cate t somehow
t.foreignKey(user_id, references: user_mstr, user_id)

Related

Deleting Entity with Foreign Key Relationship Without Deleting Reference Object

My problem is with the generic "Delete" in the BidController I am getting the typical Error:
The DELETE statement conflicted with the REFERENCE constraint "fkw_....". The conflict occurred in database table ..., column ....
The statement has been terminated.
Thank you so much for any and all help.
Try updating the ActiveBidId with a null value and then delete the bids.That way you break the link between the Item and Bid and than you can remove the Data from Bids.
Try making the relationship as OPTIONAL. This way your items can have null Foreign Keys.
If you are using database first approach:
CREATE TABLE Item(
ItemId INT PRIMARY KEY,
ActiveBidId INT NULL FOREIGN KEY REFERENCES Bid(BidId)
// ...
);
If you already created the table, then you can alter your table as follows:
ALTER TABLE Item
DROP CONSTRAINT FK_ActiveBidConstraint -- The name of your constraint
GO
ALTER TABLE Item
ADD CONSTRAINT FK_ActiveBidConstraint FOREIGN KEY (ActiveBidId) -- The name of your constraint
REFERENCES Bid(BidId);
Apparently I am able to set the GUID to null, so I am posting a simple answer.
In my BidController I have updated my code:
item = null;
This removes the reference to the bid and so the bids are free to be removed!

How to handle an autoincremented ID in HANA from a SAPUI5-application?

in my SAPUI5-Application I got the following function that takes the data and creates an entry in my HANA DB:
onCreateNewCustomer: function(){
var oEntry = {};
oEntry.NAME = this.byId("name").getValue();
oEntry.CITY = this.byId("city").getValue();
oEntry.PHONE = this.byId("phone").getValue();
oEntry.ID = this.byId("id").getValue();
// Post data to the server
this.getOwnerComponent().getModel("CustomerModel").create("/Customer", oEntry, null);
this.byId("createCustomer").close();
//location.reload();
}
The creating process works and my entries get saved. In the next step I wanted to implement my table in HANA in that way, that the ID of the entries will be autoincremented so the user does not have to enter it. I used the following command to create my table:
create column table TABLE
(ID bigint not null primary key generated by default as IDENTITY,
FIRSTNAME nvarchar(30))
That worked, table is created. The problem now is, if I use the code above without providing the ID, the following error is logged by the console:
The following problem occurred: HTTP request failed 400,Bad Request,The serialized resource has an missing value for member 'ID'.
The entry does not get saved in my DB. If I execute the following SQL-Statements in my HANA Workbench without providing the ID, it works:
insert into TABLE (FIRSTNAME) values (‘David’);
insert into TABLE (FIRSTNAME) values (‘Mike’);
insert into TABLE (FIRSTNAME) values (‘Bobby’);
So I did some searching on google but did not find a proper solution on how to do this. My goal is that the entry gets saved and the ID is provided by my HANA DB without providing it from my SAPUI5 Application.
Probably you are using ODataV2 XSODATA implementation which does not support auto-increment. The possible solution here is to use a database sequence and then with a separate request get a value from it and use it in OData create statement.
Did you try creating a new record by commenting out the below code like ?
oEntry.ID = this.byId("id").getValue();
With identity fields, if you provide the value you have to explicitly identify that you are providing the column value. Otherwise, just omit the columnn name and value from the INSERT command.

rails & postgreSQL - How can I update a data with existing primary key?

I want to update some data in Lecture(id, name, etc.) table.
For example, there is a data(id: 1, name: "first") in the Lecture.
When I typed Lecture.create(id: 1, name: "newer") =>
PG::UniqueViolation: ERROR: duplicate key value violates unique constraint "lectures_pkey"
Is there any way to update data?
Try this:
Lecture.find(1).update(name: "newer")
Find more information on update here: http://guides.rubyonrails.org/active_record_basics.html#update
The reason it didn't work is because the id is unique. When you were using create, it was trying to create a NEW record with id of 1, not edit the same record.
PG::UniqueViolation: ERROR: duplicate key value violates unique
constraint "lectures_pkey"
id is the default primary key which shouldn't be changed or duplicated. As you are inserting a row with an existing id, you get that error.
Instead, you need to do like below.
#lecture = Lecture.find(1)
#lecture.update_attributes(name: "newer")
You can use
lec = Lecture.find(1)
lec.update_attributes(name: "newer")
You are getting error PG::UniqueViolation: ERROR: duplicate key value violates unique constraint "lectures_pkey" due to you can not create record with same id. Id is primary key in table.
All of the current answers are correct if you don't mind loading the record and then updating it. If you don't need to actually load the record, and just want to update data in the database you can do
Lecture.where(id: 1).update_all(name: "newer")
This will skip all validations, etc and just do a direct sql update of the data in the database of the record with id == 1

Updating a primary key value on grails gorm

I'm wondering if I can change a value of a primary key member of a composite primary key in a Grails Domain class? For example having this domain:
class StudentHistory implements Serializable {
String studentNumber
String schoolYear
Integer yearLevel
String section
Float average
String status
static mapping = {
...
id composite: ["studentNumber", "schoolYear", "yearLevel", "section"]
...
}
}
Let say, On the schoolYear: "2014-2015", a certain yearLevel: 1 student with studentNumber: "2011-488-MN-0" transferred section from section: "1D" to section: "1N". Now to perform this record update, we do something similar inside a service:
StudentHistory record = StudentHistory.find {
eq("studentNumber", "2014-488-MN-0")
eq("schoolYear", "2014-2015")
eq("yearLevel", 1)
eq("section", "1D")
}
record.setSection("1N")
record.save(flush: true, insert: false)
The problem is that the update on the primary key doesn't take effect but when I tried to update other non-Primary fields such as average and status, updating them works fine (I tried performing an SQL directly on the database to confirm). How can I update primary keys?
PS: Now, based on this design, I know some will suggest that why not just create another record, then just fetch the record that has been last entered? But what I am required to do is to update that composite primary key instead.
PPS: Please don't suggest on removing the old instance, and create a new one, copying the old details except for the section. I cannot do that since many tables are connected to this table.
I believe it is a good practice to avoid changing primary keys. Primary key is a unique identifier of an object and changing it effectively means creating a new object. So if your composite primary key is mutable (or can mutate) then you should use a surrogate key - an artificial primary key. At the same time you can create a unique constraint on the 4 fields currently being your primary key.
In your case it would be:
static mapping = {
...
}
static constraints = {
studentNumber(unique: ["schoolYear", "yearLevel", "section"])
}
Hope it makes sense.

Update association by ID other than primary key

Let's say I want to update an association by passing in a key other than the primary key, like social security number:
Teacher.find(params[:id]).update({'student_ids'=>['123-45-6789','987-65-4321']})
How can I make my Teacher model understand that it will be receiving SSN, and not database IDs? A SSN uniquely identifies a student.
Edit: I like Pavling's solution, as it keeps the logic in the model. However this fails:
Teacher.new({name:'Miss Molly',student_ssns:['123-45-6789','987-65-4321']})
With ActiveRecord::UnknownAttributeError: unknown attribute: student_ssns
How about...
student_ids = Student.where(ssn:['123-45-6789','987.65.4321']).map(&:id)
Teacher.find(params[:id]).update({'student_ids'=> student_ids})
If SSN is a unique identifier for your student rows, you could make it the primary key instead of the default integer - but convention would advise to leave the 'normal' ID field there.
So how about a method on Teacher which takes student_ssns rather than student_ids, and inside that method, find the student ids (similar to Kevin Monk's answer)?
# teacher.rb
def student_ssns=(ssns)
student_ids = Student.where(ssn: ssns).pluck(:id)
update({student_ids: student_ids})
end
Then you can use it thus:
Teacher.find(params[:id]).student_ssns(['123-45-6789','987.65.4321'])
Using Pavling's solution, but changing the definition line to:
def student_ssns=(ssns)
should get it working properly for you.

Resources