I am trying to create a sqlite table containing a foreign key, using the default sqlite3 library from swift/xCode via import sqlite3. The table is getting created without the key, but if I add the foreign key to the statement, I get a syntax error.
Error: [logging] near "date": syntax error
"""
CREATE TABLE IF NOT EXISTS measurement(
measurementid INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
accountid INTEGER NOT NULL,
FOREIGN KEY(accountid) REFERENCES accounts(userid),
date TEXT NOT NULL,
measurementtype TEXT NOT NULL,
moodmeasurementid INTEGER,
healthmeasurementid INTEGER,
bodymeasurementid INTEGER,
workout TEXT NOT NULL
);
"""
"""
CREATE TABLE IF NOT EXISTS accounts(
userid INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
email TEXT NOT NULL,
password TEXT NOT NULL,
firstname TEXT NOT NULL,
lastname TEXT NOT NULL,
birthday TEXT NOT NULL,
gender TEXT NOT NULL,
creationdate TEXT NOT NULL
);
"""
After some research I read, that you might need to activate foreign keys, before using them. So I added the following code, but I still get the same error.
if sqlite3_exec(dbPointer, "PRAGMA foreign_keys = ON", nil, nil, nil) != SQLITE_OK {
let err = String(cString: sqlite3_errmsg(dbPointer))
print("error attempting to enable foreign keys: \(err)")
}
Also adding it to the end of the statement didn't fix it.
You are using the table constraint syntax instead of the column constraint syntax.
You want:
accountid INTEGER NOT NULL
REFERENCES accounts(userid),
The FOREIGN KEY(accountid) would be needed if you were adding the constraint to the table. Also note the removal of the comma after NOT NULL.
See https://www.sqlite.org/lang_createtable.html for complete details of the syntax.
Related
I am receiving an error message when I attempt the following
create table Mycustomers3 (
Name varchar(255) not null primary key,
Gender varchar(255) not NULL,
Address varchar(255) not NULL,
Geo_location_address point
);
insert into Mycustomers3(name,gender,address,geo_location_address) values
('Cust One','female','6 The Street, Bradford','50.82738,-0.14007'),
('Cust Two','male','Flat 99, White Road, Cornwall','50.81831,-0.10645');
select * from Mycustomers3;
it returns this error
"cannot get geometry object from data you send to the geometry field"
I read somewhere that it maybe something to do with NULL data but not sure how to overcome this. Can anyone help please?
Why I encounter the error 'duplicate key'? Actually, I have added the following line in my code:
index({ sn: 1 }, { unique: true, sparse: true})
Then I type the command:
rake db:mongoid:create_indexes
The error appeared, which confuse me.
The error is pointing out that you have documents within your collection that have duplicate keys. This is due to your index requiring their to be unique records for that key.
If you do not need unique records: remove the unique:true from that statement
If you do need unique records: search for documents with duplicated keys and update them
A note on sparse, it means it'll only index if the key exists in the document, and ignore documents that do not have the key sparse docs
Update:
If I am reading the error correctly, the duplicate key may be 'null'. As you are using sparse, if you unset the field where the current entry is null, your index should then work.
I am trying to use boss_db for accessing pgsql. The table should have the column name, id, it should be primary key
The Id type is only be uuid or serial. Is it right?
I want that id is varchar(20), the value of id is decided by the program, not auto decided by DBMS. Is it possible?
create table operators(
id serial primary key, /*I want id is varchar(20), is it possible*/
tag_id varchar(20),
name text,
barcode varchar(20),
tel varchar(12),
mobile varchar(20),
email text,
ldap_user_id varchar(20),
operator_barcode varchar(20)
);
A = operator:new(id,"0102030405060708",
"operator_01","B001","12345678",
"13812345678",
"p001#gmail.com",
"ldap001",
"PB001"),
The follwing codes is from boss_sql_lib.erl file:
infer_type_from_id(Id) when is_list(Id) ->
[Type, TableId] = re:split(Id, "-", [{return, list}, {parts, 2}]),
TypeAtom = list_to_atom(Type),
IdColumn = proplists:get_value(id, boss_record_lib:database_columns(TypeAtom)),
IdValue = case keytype(Type) of
uuid -> TableId;
serial -> list_to_integer(TableId)
end,
{TypeAtom, boss_record_lib:database_table(TypeAtom), IdColumn, IdValue}.
Assign an ID when you create the BossRecord by using your own ID rather than the atom id:
> AutoId = operator:new(id,
"0102030405060708",
"operator_01","B001","12345678",
"13812345678",
"p001#gmail.com",
"ldap001",
"PB001"),
> ManualID = operator:new("operator-01",
"0102030405060708",
"operator_01","B001","12345678",
"13812345678",
"p001#gmail.com",
"ldap001",
"PB001"),
> AutoID:save(), % will just work
> ManualId:save(). % good luck
Record IDs are typically created by the framework. They must be globally unique. I recommend allowing the framework to assign its own IDs, rather than creating them manually as you will probably encounter bugs. However, there is nothing stopping you doing whatever you want.
I have a stored procedure usp_getCashCommissionCustomer like this:
Select
cw.Customercode, name, state as Province, City, Suburb,
Balance As HMCommission, MBalance as MTNCommission
from
customerwallet cw
inner join
customer cu on cw.customercode = cu.customercode
where
iscash = 1
and (balance + mbalance) > 0
order by
customercode
On click on customercode I should open create view of follwing table
CREATE TABLE [dbo].[CustomerLedger]
(
[ID] [bigint] IDENTITY(1,1) NOT NULL,
[CustomerCode] [varchar](25) NULL,
[TransactionType] [varchar](1) NULL,
[Description] [varchar](30) NULL,
[TransactionDate] [datetime] NULL,
[Amount] [float] NULL,
[IsProcessed] [bit] NULL
) ON [PRIMARY]
Please help me.
I am new to ASP.NET MVC 2
I don't know whether you are using ORM or not. If you are not any ORM then you may see an approach to fill the view using stored procedure mentioned here. IF you are using ORM such as L#S or entity framework you may get start from here.
If You want popup of view you find the tutorial here
I simplified the code a little while trying to debug:
[HttpPost]
public ActionResult Register(User model)
{
DateTime bla = new DateTime(2012, 12, 12);
try
{
User user = new User
{
gid = 1,
cid = 1,
firstName = model.firstName,
lastName = model.lastName,
email = model.email,
username = model.username,
password = model.password,
creationDate = bla,
active = 1
};
myContext.Users.AddObject(user);
myContext.SaveChanges();
}
catch (Exception ex)
{
throw ex;
}
return View();
}
The values are transmited accordingly. Users table:
[id] [int] IDENTITY(1,1) NOT NULL,
[cid] [int] NULL,
[gid] [int] NULL,
[firstName] [nvarchar](100) NOT NULL,
[lastName] [nvarchar](100) NOT NULL,
[email] [nvarchar](max) NOT NULL,
[username] [nvarchar](100) NOT NULL,
[password] [nvarchar](100) NOT NULL,
[creationDate] [datetime] NOT NULL,
[active] [int] NOT NULL,
CONSTRAINT [PK_Users_3213E83F0AD2A005] PRIMARY KEY CLUSTERED
I deleted all the foreign keys to be sure that nothing affects it. I am qute certain that at a previous moment it was working, but now I can not figure where the issue is.
It crashes while performing the savechanges:
{"An error occurred while updating the entries. See the inner exception for details."}
{"The member with identity '' does not exist in the metadata collection.\r\nParameter name: identity"}
I had the same error being thrown when I try to insert using EF, the error was
The member with identity 'Id' does not exist in the metadata collection.\r\nParameter name: identity
It wasn't obvious at first but the exception message was very concise because my database knows the column Id int but the property created for the object on my code was int ID so coming back to named mapping, Id is not mapped to ID.
So when an object with property ID is sent to database that only know Id you will get the above error.
I hope this helps, thanks
The issue was reproducing because of a trigger that was on the users table. Removed it and the issue is not reproducing anymore.
There is probably a trigger on the table being updated and it returns output. The output is thrown away but it conflicts with EF. Such output is often used to debug triggers (and forgotten to delete later):
select 'trigger called, i am here'
or there can be missing variable:
select column
instead of
select #variable=column
I think that the best solution is in this post. I used the 3rd option and works.
Here I report the reply in the link:
The issue could be related to a "instead of insert" trigger on one of
your tables.
The EF framework is performing validation on the inserted row of data
by calling scope_identity(). However, an "instead of insert" trigger
will change the context of the insertion in such a way that the EF
system's call to scope_identity will return null.
A couple ways around this:
Use a stored procedure to insert the data ( not tested )
Remove the instead of insert trigger ( triggers can cause other problems, so some people argue not to use them) ( tested, works!)
Turn off validation in the EF framework, so: context.Configuration.ValidateOnSaveEnabled = false ( tested, works!)
I had this same error today and spent a few frustrating hours trying to figure it out.
I was using Entity Framework to insert a record with an identity column into a SQL server database table. Simple enough.
The table had a trigger on it which in turn ran a stored procedure. The stored procedure had a line in it:
select newid()
This is the line that broke Entity Framework.
For tables with identity columns, Entity Framework expects to be returned a single row with a single field that is the identity column.
it's because of trigger pass back value to EF
if you are using trigger. in my problem i must check a value by selecting from other table and using of 'select' cause error in EF, so you must replace 'select' with 'set'.
you can not use this code.
select #any= any from tablename
you should use set instead of select
set #any= (select any from tablename)
Somedays, I hate M$.
The member with identity 'ChangeID' does not exist in the metadata collection.
Parameter name: identity
I've spent two days trying to get around this.
I'm using MVC.
To get all the data I need in one fell swoop, I created a view of the table in the DB for this application, and tables in other databases. (You may update views, with some constraints.)
I do a get, and all my data is present in the record, keys, descriptions, foreign keys, etc.
I created triggers on my view, to update the portion of the view that came from the local table.
Instead of Delete worked fine.
Instead of Update worked fine.
This error kept raising it's head on Instead of Insert. I could NOT get the insert trigger to successfully insert into my table. If I ran an insert on the view, with all fields provided in the SQL Management Studio, it worked fine. I know the exact values being passed because I ran SQL Server Profiler to see the code being passed.
But when the app attempted the update, it failed with The member with identity 'ChangeID' does not exist in the metadata collection.
Clue up above, someone said, "MVC expects table key to be ID"
I renamed ChangeID as ID in my view, changed it in the App, and BAM! Now it works.
What did NOT work:
db.Configuration.ValidateOnSaveEnabled = false;
adding a select to the trigger to get scope identity
Why do I have to modify my DB or my view to satisfy some hidden M$ assumption?
None the less, after two very frustrating days, code is now working. Maybe this will save someone else some time as well.
Try this
[HttpPost]
public ActionResult Register(User model)
{
DateTime bla = new DateTime(2012, 12, 12);
try
{
model.gid = 1;
model.cid = 1;
model.creationDate = bla;
model.active = 1;
myContext.Users.AddObject(model);
myContext.SaveChanges();
}
catch (Exception ex)
{
Console.WriteLine(ex);
throw;
}
return View();
}
I was having this issue and my fix, was that in my connection-string metadata I did not specify my model in the .msl format.
See more info here
In my case, SetName of the entity was incorrect. Shortly, this worked for me:
Use
myContext.AddObject(nameOfSetEntity, user);
Instead of:
myContext.Users.AddObject(user);
To get the whole correct name of the entity (thanks to Nix's answer)
string className = typeof(User).Name;
var container = myContext.MetadataWorkspace.GetEntityContainer(myContext.DefaultContainerName, System.Data.Metadata.Edm.DataSpace.CSpace);
string nameOfSetEntity= (from meta in container.BaseEntitySets
where meta.ElementType.Name == className
select meta.Name).First();
Context.AddObject(nameOfSetEntity, user);