How do i append an auto increment primary key to another field in the same table? - mysql

I'm using yii active records for mysql, and i have a table where there's a field that needs to be appended with the primary key of the same table. The primary key is an auto increment field, hence i can't access the primary key before saving.
$model->append_field = "xyz".$model->id; // nothing is appending
$model->save();
$model->append_field = "xyz".$model->id; //id is now available
How do i do this?
I know that i can update right after insertion, but is there a better method?

Your record is only assigned an id after the INSERT statement is executed. There is no way to determine what that id is prior to INSERT, so you would have to execute an UPDATE with the concatenated field value after your INSERT.
You could write a stored procedure or trigger in MySQL to do this for you, so your app executes a single SQL statement to accomplish this. However, you are just moving the logic into MySQL and in the end both an INSERT and UPDATE are occurring.

Some more workarounds:
This is almost your approach ;)
$model->save();
$model->append_field = "xyz".$model->id; //id is now available
$model->save();
But you could move this functionality to a behavior with a custom afterSave() method, note that you'd have to take care about not looping the event.
Or just write a getter for it
function getFull_append_field(){
return $this->append_field.$this->id;
}
but then you can not use it in a SQL statement, unless you create the attribute there with CONCAT() or something similar.

Anyone else coming to this question might be interested in exactly how i implemented it, so here's the code :
//in the model class
class SomeModel extends CActiveRecord{
...
protected function afterSave(){
parent::afterSave();
if($this->getIsNewRecord()){
$this->append_field=$this->append_field.$this->id;
$this->updateByPk($this->id, array('append_field'=>$this->append_field));
}
}
}
One way to avoid the looping the event(as mentioned by #schmunk) was to use saveAttributes(...) inside the afterSave() method, but saveAttributes(...) checks isNewRecord, and inserts a value only if it is a new record, so that requires us to use setNewRecord(false); before calling saveAttributes(...).
I found that saveAttributes(...) actually calls updateByPk(...) so i directly used updateByPk(...) itself.

Related

Laravel: How to get counter value when inserting with UUID and Auto Increment

My models have both id and counter attributes. The id is a UUID, and the counter is an integer which is auto-incremented by the database.
Both are unique however I rely on id as the primary key. The counter is just a human-friendly name that I sometimes display to the user.
Immediately before an object is created a listener gives it a UUID. This works fine.
When the record is saved, MySQL increments the counter field. This works fine except that the copy of the object which I have in memory does not have the counter value. I can reload the object to find out what its counter is, but that would require another database query.
Is there a way to find the value of the counter without a specific database query? For example, is it returned as part of the response from the database when a record is created?
Few things:
Use create(array $attributes) and you'll get exactly what you want. For this having right, you have to ensure that $fillable array consists all attributes' names passed to create method.
You should use Observer on model instead of listener (most likely creating method).
Personal preference using Eloquent is that you should use id for id (increment field) and forget custom settings between models because by default it is what relations expect and so on
public function secondModels()
{
return $this->hasMany(SecondModel::class);
}
is pretty much no brainer. But for having this working best way would be (also following recommendations of this guy) FirstModel::id, SecondModel::id, SecondModel::first_model_id; first_models, second_models as table names. Avoiding and/or skipping this kind of unification is lot of custom job afterward. I don't say it can't be done but it is lot of non-first-time-successful work done.
Also, if you want visitor to get something other than id field name, you can make computed field with accessor:
/**
* Get the user's counter.
*
* #return string
*/
public function getCounterAttribute(): string
{
return (string)$this->id;
}
Which you call then with $user->counter.
Also personal preference of mine is to have most possible descriptive variable names so uuid field of mine would be something like
$table->uuid('uuid4');
This is some good and easy to make practice of Eloquent use.
Saying all this let me just to say that create() and save() will return created object from database while insert() shall not do it.

Check if IndexedDB objectStore already contains key

Adding an object to an IndexedDB objectStore will fail if the key already exists. How can I check for the existence of an object with a given key – preferably synchronously (no reason for another layer of callbacks) and without pulling the object.
I know how to do get requests asynchronously via transactions, but it seems a bit of an ordeal to go through every time I want to add an object.
note Solution only has to work in Chrome (if that helps)
The best way to check existence of a key is objectStore.count(key). Which is async.
In your case, the best option is openCursor of your key. If exists, cursor will come up.
var req = objectStore.openCursor(key);
req.onsuccess = function(e) {
var cursor = e.target.result;
if (cursor) { // key already exist
cursor.update(obj);
} else { // key not exist
objectStore.add(obj)
}
};
So far none of the browsers have the sync API implemented so you're going to have to do it async. An objectStore exposes a get method which you provide it with a key and it'll return you the object (or null) that matches the key.
There's a really good tutorial on MDN that covers using IDB, and getting a record is covered too, but the inlined code is:
db.transaction("customers").objectStore("customers").get("444-44-4444").onsuccess = function(event) {
alert("Name for SSN 444-44-4444 is " + event.target.result.name);
};
If you don't want retrieve the record then you can always used the count method on an index as explained here in the spec. Based on the result of that you can either use add or put to modify the record, it'll save extracting the record if you don't need to.
A bit late for an answer, but possible it helps others. I still stumbled -as i guess- over the same problem, but it's very simple:
If you want to INSERT or UPDATE records you use objectStore.put(object) (help)
If you only want to INSERT records you use objectStore.add(object) (help)
So if you use add(object), and a record key still exists in DB, it will not overwritten and fires error 0 "ConstraintError: Key already exists in the object store".
If you use put(object), it will be overwritten.
The question is why do you want to know this? Maybe you should use another approach?
You can use auto increment, this way you don't need to check if a key exists, you will always get a unique one.
You can also use the put method instead of the add method. With the put the data will be updated if the key exists and if the key doesn't exist the data is added.
Everything depends on the reason why you want to check if something exists.

Does LINQ to SQL support Single Unit of work only or can I persist the Context and do Next operation?

I have a windows application. I am trying to insert a record through a DataContext. It has Unique identifier in the table. Even I am executing a trigger after insertion. So I am making a select query in the end of the trigger to get the auto generator number and to avoid auto-sync error. As it's a windows application I can keep the Context for longtime. When I create a new object ( for example order) and do the same previous operation, upon SubmitChanges operation, it shows cannot have duplicate key. Why can't I use this same Context to Insert the second record? Or do I need to create a new Context to insert a new Record?(Does this Unit of work Concept comes here?). Creating new Context is bad idea as I need to load all data again..
Any thought?
Some code sample to explain my situation:
CallCenterLogObjCotext = (CallCenterLogObjCotext == null ? (new CallcenterLogContext) : (CallCenterLogObjCotext));
CallDetail newCallDetailsOpenTicket = new CallDetail();
newCallDetailsOpenTicket.CallPurpose = (from callpuposelist in CallCenterLogObjCotext.CallPurposes
where callpuposelist.CallPurposeID == ((CallPurpose)(cbcallpurpose.SelectedItem)).CallPurposeID
select callpuposelist).FirstOrDefault();
Lots of settings like this ...
CallCenterLogObjCotext.CallDetails.InsertOnSubmit(newCallDetailsOpenTicket);
CallCenterLogObjCotext.SubmitChanges();
As I mentioned above, this is a click on Open Ticket button on windows form. I change the values of fname, lname and all in the textboxes available on that form and clicked the same button.
So it will call the same method again. I get the below specified error:
System.Data.Linq.DuplicateKeyException: Cannot add an entity with a key that is already in use.
You can insert more than one row with the same context object, see http://weblogs.asp.net/scottgu/archive/2007/05/19/using-linq-to-sql-part-1.aspx, http://msdn.microsoft.com/en-us/library/bb425822.aspx, and other numerous online examples. The duplicate key issue could be a linq to sql configuration issue, or a database integrity error, i.e. such as if you have a natural primary key on a table and are trying to insert a row with the same natural primary key more than once.

LINQ to SQL Table Extensibility Methods

If I have a LINQ to SQL table that has a field called say Alias.
There is then a method stub called OnAliasChanging(string value);
What I want to do is to grab the value, check the database whether the value already exists and then set the value to the already entered value.
So I may be changing my alias from "griegs" to "slappy" and if slappy exists then I want to revert to the already existing value of "griegs".
So I have;
partial void OnaliasChanging(string value)
{
string prevValue = this.alias;
this.Changed = true;
}
When I check the value of prevValue it's always null.
How can I get the current value of a field?
Update
If I implement something like;
partial void OnaliasChanging(string value)
{
if (this.alias != null)
this.alias = "TEST VALUE";
}
it goes into an infinte loop which is unhealthy.
If I include a check to see whether alias already == "TEST VALUE" the infinate loop still remains as the value is always the original value.
Is there a way to do this?
The code snippets you've posted don't lend themselves to any plausible explanation of why you'd end up with an infinite loop. I'm thinking that this.alias might be a property, as opposed to a field as the character casing would imply, but would need to see more. If it is a property, then you are invoking the OnAliasChanging method before the property is ever set; therefore, trying to set it again in the same method will always cause an infinite loop. Normally the way to design this scenario is to either implement a Cancel property in your OnXyzChanging EventArgs derivative, or save the old value in the OnXyzChanging method and subsequently perform the check/rollback in the OnXyzChanged method if you can't use the first (better) option.
Fundamentally, though, what you're trying to do is not very good design in general and goes against the principles of Linq to SQL specifically. A Linq to SQL entity is supposed to be a POCO with no awareness of sibling entities or the underlying database at all. To perform a dupe-check on every property change not only requires access to the DataContext or SqlConnection, but also causes what could technically be called a side-effect (opening up a new database connection and/or silently discarding the property change). This kind of design just screams for mysterious crashes down the road.
In fact, your particular scenario is one of the main reasons why the DataContext class was made extensible in the first place. This type of operation belongs in there. Let's say that the entity here is called User with table Users.
partial class MyDataContext
{
public bool ChangeAlias(Guid userID, string newAlias)
{
User userToChange = Users.FirstOrDefault(u => u.ID == userID);
if ((userToChange == null) || Users.Any(u => u.Alias == newAlias))
{
return false;
}
userToChange.Alias = newAlias;
// Optional - remove if consumer will make additional changes
SubmitChanges();
return true;
}
}
This encapsulates the operation you want to perform, but doesn't prevent consumers from changing the Alias property directly. If you can live with this, I would stop right there - you should still have a UNIQUE constraint in your database itself, so this method can simply be documented and used as a safe way to attempt a name-change without risking a constraint violation later on (although there is always some risk - you can still have a race condition unless you put this all into a transaction or stored procedure).
If you absolutely must limit access to the underlying property, one way to do this is to hide the original property and make a read-only wrapper. In the Linq designer, click on the Alias property, and on the property sheet, change the Access to Internal and the Name to AliasInternal (but don't touch the Source!). Finally, create a partial class for the entity (I would do this in the same file as the MyDataContext partial class) and write a read-only wrapper for the property:
partial class User
{
public string Alias
{
get { return AliasInternal; }
}
}
You'll also have to update the Alias references in our ChangeAlias method to AliasInternal.
Be aware that this may break queries that try to filter/group on the new Alias wrapper (I believe Linq will complain that it can't find a SQL mapping). The property itself will work fine as an accessor, but if you need to perform lookups on the Alias then you will likely need another GetUserByAlias helper method in MyDataContext, one which can perform the "real" query on AliasInternal.
Things start to get a little dicey when you decide you want to mess with the data-access logic of Linq in addition to the domain logic, which is why I recommend above that you just leave the Alias property alone and document its usage appropriately. Linq is designed around optimistic concurrency; typically when you need to enforce a UNIQUE constraint in your application, you wait until the changes are actually saved and then handle the constraint violation if it happens. If you want to do it immediately your task becomes harder, which is the reason for this verbosity and general kludginess.
One more time - I'm recommending against the additional step of creating the read-only wrapper; I've put up some code anyway in case your spec requires it for some reason.
Is it getting hung up because OnaliasChanging is firing during initialization, so your backing field (alias) never gets initialized so it is always null?
Without more context, that's what it sounds like to me.

How to update in Linq to SqL?

every example I seen shows how to do a update query in linq to sql by doing this.
// grab entity you want to update
entity.UserId = "123"; // update the fields you want to update.
entity.Name = "bob";
Dbcontext.SubmitChanges();
I am wondering can you juse pass in a new object and have it figure it out?
Like could I do this?
Enity myEntity = new Entity();
myEntity.UserId = "123";
myEntity.Name = bob:
// grab entity record
// shove record ito the found record
// it figured out what to update and what no to update
Depending on what exactly you want to do you either need the InsertOnSubmit method, or the Attach method of the respective table (i.e. dbContext.Entities). InsertOnSubmit is used to add a record, while Attach can be used if you want to affect an UPDATE without having to first SELECT the record (you already know the primary key value)
In the case you have the dbContext available and ready, just add InsertOnSubmit:
Entity myEntity = new Entity();
myEntity.UserId = "123";
myEntity.Name = bob:
Dbcontext.InsertOnSubmit(myEntity);
Dbcontext.SubmitChanges();
As the name of the method implies, this will insert your new entity into the database on calling SubmitChanges.
Marc
If you want to do this for performance reasons then you shouldn't worry about it. Linq to Sql will cache objects locally so that just grabbing an entity by ID to modify some fields is very cheap.
It's possible to attach and persist it to the database, however you may want to set a field to check for concurrency (ie LastModified).
If you are going to use the Attach method on the data context, you need to set the primary/composite keys before you attach the entity (so you don't trigger INotifyPropertyChanging, INotifyPropertyChanged events).