I've got a homemade ORM system that currently only supports auto-incrementing primary keys. This has worked well, but the time has come to support composite primary keys. I'm aware of the holy war between surrogate vs. composite primary keys, and I personally think there's a place for each. Anyway... :)
With an auto-incrementing primary key, it's easy to tell if an INSERT
or UPDATE
statement has to be run when the model is saved: it depends on whether the primary key is set or not.
But with (non-auto-incrementing) composite primary keys, it's not easy to tell, since you have to set all the composite primary key field values even if you're doing an INSERT
.
So, to my question: How do I determine if an INSERT
or UPDATE
statement should be run when working with a composite primary key?
Here are the solutions I've come up with:
- Query for whether a record exists with the composite primary key beforehand. This seems like the best option, even though an additional query has to be run on every save.
- Use MySQL's
INSERT ... ON DUPLICATE KEY UPDATE
syntax. But there are other operations that my Model class completes that require knowing whether a record is new or not, like whether to validate all columns (when the record is new) or just the modified columns (when the record already exists).
Do you have a better solution? Or is one of these my best bet? Thanks for your insight!