How to delete record in activejdbc with no primary key? - activejdbc

My table does not have a primary key. So when I try to delete a record
Table t = Table.findFirst("col = ?", var);
t.delete();
I get below exception. Any directions?
org.javalite.activejdbc.DBException: java.sql.SQLSyntaxErrorException: ... "ID": invalid identifier

ActiveJDBC does require an PK to operate. In case like yours, you need to override the delete() method, form a query that identifies your record, and call Base.exec() or DB.exec() methods internally. For clues on implementing, see the original Model#delete() method. Do the same, but only generate a different query.

Related

what is local key in laravel eloquent

http://laravel.com/docs/4.2/eloquent#relationships
what does local key mean in this thing? does it mean primary key of the table? or what? for example in this code
return $this->hasOne('Phone', 'foreign_key');
return $this->hasOne('Phone', 'foreign_key', 'local_key');
local_key is the primary key of your table. You only need to specify it if your primary key is not called id AND you do not have the $primaryKey property set in your model.
I believe everything is written in the doc:
ake note that Eloquent assumes the foreign key of the relationship based on the model name. In this case, Phone model is assumed to use a user_id foreign key. If you wish to override this convention, you may pass a second argument to the hasOne method. Furthermore, you may pass a third argument to the method to specify which local column that should be used for the association:
Which basically means that 'local_key' is the name of the table column in your db which is responsible to match the related entity (phone) with your current entity (user).
If you have a look at the db, I'm sure you'll find a table user with a phone_id column, try to change it to something else (like "phone" only) and your eloquent request will crash. Then change your call to return $this->hasOne('Phone', 'user_id', 'phone'); and this might work again.

Create a new record with an assigned PK - Castle ActiveRecord

I have a table with a GUID primary key. In ActiveRecord it is setup with a PrimaryKeyType.GuidComb. Is it possible to create this record with a manually assigned PK? If I set the primary key in the record and run Create() a new ID is assigned. If I run Save() I get an error (as one would expect).
The why:
This table is in two databases. Records need to be copied between these two databases on occasion. I would like to retain the ID as the record moves across the DBs.
No. A primary key is either generated (e.g. GuidComb) or manually assigned, it can't be both. You could create two classes that inherited from a base class defining all properties except the primary key, then each of these two classes would define their primary key as assigned or generated. But I'd recommend using SQL here, as a single INSERT INTO ... SELECT will be more efficient than using NHibernate/ActiveRecord.
I ended up setting the PrimaryKeyType to Assigned. Then I handled it with an overrided Create function:
public override void Create() {
if (ID == default(Guid)) ID = GUIDGenerator.Generate();
base.Create();
}
It would have been better to put this in OnSave, but the primary key cannot be modified in the interceptor. This works for my application, however this code will only be called if the object is explicitly created. It will not work if the object is created by cascade.

#Id for oracle.rowid

Howto declare #Entity class for oracle table w/o PK?
I has received the error message:
Column "rowid" cannot be resolved on table "LOG"
when doing mapping like this:
#Entity
public class Log implements Serializable {
...
#Id
private ROWID rowid;
...
}
Howto declare #Entity class for oracle table w/o PK?
Mapping a ROWID as Id isn't supported by standard JPA and I couldn't find any obvious proof that EclipseLink is providing an extension for this (I only found this message).
But this is not your only option and the JPA wikibook has a good paragraph about this situation:
No Primary Key
Sometimes your object or table has no
primary key. The best solution in this
case is normally to add a generated id
to the object and table. If you do not
have this option, sometimes there is a
column or set of columns in the table
that make up a unique value. You can
use this unique set of columns as your
id in JPA. The JPA Id does not
always have to match the database
table primary key constraint, nor is a
primary key or a unique constraint
required.
If your table truly has no unique
columns, then use all of the columns
as the id. Typically when this occurs
the data is read-only, so even if the
table allows duplicate rows with the
same values, the objects will be the
same anyway, so it does not matter
that JPA thinks they are the same
object. The issue with allowing
updates and deletes is that there is
no way to uniquely identify the
object's row, so all of the matching
rows will be updated or deleted.
If your object does not have an id,
but its' table does, this is fine.
Make the object and Embeddable
object, embeddable objects do not have
ids. You will need a Entity that
contains this Embeddable to persist
and query it.

IntegrityError: foreign key violation upon delete

I have Order and Shipment model. Shipment has a foreign key to Order.
class Order(...):
...
class Shipment()
order = m.ForeignKey('Order')
...
Now in one of my views I want do delete order object along with all related objects. So I invoke order.delete().
I have Django 1.0.4, PostgreSQL 8.4 and I use transaction middleware, so whole request is enclosed in single transaction.
The problem is that upon order.delete() I get:
...
File "/usr/local/lib/python2.6/dist-packages/django/db/backends/__init__.py", line 28, in _commit
return self.connection.commit()
IntegrityError: update or delete on table "main_order" violates
foreign key constraint "main_shipment_order_id_fkey" on table "main_shipment"
DETAIL: Key (id)=(45) is still referenced from table "main_shipment".
I checked in connection.queries that proper queries are executed in proper order. First shipment is deleted, after that django executes delete on order row:
{'time': '0.000', 'sql': 'DELETE FROM "main_shipment" WHERE "id" IN (17)'},
{'time': '0.000', 'sql': 'DELETE FROM "main_order" WHERE "id" IN (45)'}
Foreign key have ON DELETE NO ACTION (default) and is initially deferred. I don't know why I get foreign key constraint violation.
I also tried to register pre_delete signal and manually delete shipment objects before delete on order is called, but it resulted in the same error.
I can change ON DELETE behaviour for this key in Postgres but it would be just a hack, I wonder if anyone has a better idea what's going on here.
There is also a small detail, my Order model inherits from Cart model, so it actually doesn't have id field but cart_ptr_id and after DELETE on order is executed there is also DELETE on cart, but it seems unrelated? to the shipment->order problem so I simplified it in the example.
DETAIL: Key (id)=(45) is still
referenced from table "main_shipment".
There is still a record referencing to id 45. You did delete record 17 in main_shipment before, but there might be others as well. You have to delete all records in main_shipment referencing to id 45 in main_order. If not, the database protects you from doing harm to your data.

NHibernate throwing SQL CE Error 25026

I am using NHibernate with a SQL CE desktop database, and I'm getting an odd error when I try to do an update. SQL CE is throwing Error 25026: "A foreign key value cannot be inserted because a corresponding primary key value does not exist."
The exception occurs when performing a cascading update of a collection property of an entity object. The entity object is an Owner, and the collection property is Projects (IList), the projects for a particular Owner. In my database, the primary key of the Owners table is a three-character string (the owner's initials), with a corresponding foreign key in the Projects table.
Here's why I am puzzled: NHibernate can fetch all of the records for a particular owner (for example, "DCV"). And in my code, I can add a new Project object to Owner.Projects with no problem. I take the owner ID value directly from the Owner object fetched from the database, so I know the primary key exists in the Owners table. But when I do an ISession.SaveOrUpdate() on my Owner object, I get the foreign key error described above.
Am I dealing with some idiosyncracy of NHibernate, or some mundane error in my code or mappings? Any thoughts that would help me troubleshoot this problem greatly appreciated!
David Veeneman
Foresight Systems
I found the answer. It has to do with how NHibernate handles one-to-many associations. From the NHibernate Documentation, Sec. 6.4, One-To-Many Associations:
Very Important Note: If the
column of a association
is declared NOT NULL, NHibernate may
cause constraint violations when it
creates or updates the association. To
prevent this problem, you must use a
bidirectional association with the
many valued end (the set or bag)
marked as inverse="true". See the
discussion of bidirectional
associations later in this chapter.
If you are having this problem, remove the foreign key constraint temporarily and run your code, outputting NHibernate's SQL to the console. You will see that NHibernate first inserts the new record without the foreign key, then calls up the record, then inserts the foreign key into the record. The first operation is what generates the foreign key error.
The solution, as the NHibernate documentation points out, is to make the relation bidirectional.