Close Tables All
Clear
Create Table Persons (id Integer Autoinc, Firstname V(32), Lastname V(32))
Insert Into Persons (Firstname, Lastname) values ('Rajeesh','Karunkaran') && errors for demonstation purposes
Use
* Say User 1 and User 2 start their editing sessions quite at the same time
Set Multilocks On
Select 0
Use Persons Alias Persons1 && workarea of User 1. Usually just named 'Persons' on his own computer
CursorSetProp('Buffering',5) && buffering of workarea 'Persons1' set to optimisitc table buffering
Select 0
Use Persons Alias Persons2 Again && workarea of User 2
CursorSetProp('Buffering',5) && buffering of workarea 'Persons2' set to optimisitc table buffering
* User 1 and User 2 edit a tthe same time
Select Persons1
Replace Lastname With 'Karunakaran'
Select Persons2
Replace Firstname With 'Rajesh'
Select Persons1
llConflict = .F.
lcStates = GetFldState(-1)
For lnState = 2 to Len(lcStates)
If Val(Substr(lcStates,lnState,1))>1
? 'Status of field '+ Field(lnState-1)+' is '+Substr(lcStates,lnState,1)
? 'Oldval:'+ OldVal(Field(lnState-1))
? 'Curval:'+ CurVal(Field(lnState-1))
? 'User 1 changed this field value to "'+ Evaluate(Field(lnState-1))+'"'
* Step 2: Check difference in OLDVAL and CURVAL:
If Not OldVal(Field(lnState-1))==CurVal(Field(lnState-1))
llConflict = .T.
Endif
EndIf
EndFor
If llConflict
? 'A conflict is to be expected.'
EndIf
llSuccess = TableUpdate(1,.F.)
? 'User 1 lastname change success:', llSuccess
? '----------------------'
* Now the section of code of interest, how to detect possible conflicts
* Step 1: Determine changed fields
Select Persons2
llConflict = .F.
lcStates = GetFldState(-1)
For lnState = 2 to Len(lcStates)
If Val(Substr(lcStates,lnState,1))>1
? 'Status of field '+ Field(lnState-1)+' is '+Substr(lcStates,lnState,1)
? 'Oldval:'+ OldVal(Field(lnState-1))
? 'Curval:'+ CurVal(Field(lnState-1))
? 'User 2 changed this field value to "'+ Evaluate(Field(lnState-1))+'"'
* Step 2: Check difference in OLDVAL and CURVAL:
If Not OldVal(Field(lnState-1))==CurVal(Field(lnState-1))
llConflict = .T.
Endif
EndIf
EndFor
If llConflict
? 'A conflict is to be expected.'
EndIf
llSuccess = TableUpdate(1,.F.)
? 'User 2 first name change success:', llSuccess
If NOT llSuccess
* Retry after TABLEREVERT and restoring the changes:
[highlight #FCE94F] lcFieldlist = '' && list of changed fields
lcStates = GetFldState(-1)
For lnState = 2 to Len(lcStates)
If Val(Substr(lcStates,lnState,1))>1
lcFieldlist = lcFieldlist+','+Field(lnState-1)
EndIf
EndFor
lcFieldlist = Substr(lcFieldlist,2)
If !Empty(lcFieldlist)
Scatter Fields &lcFieldlist Name loChanges
TableRevert(.F.)
Gather Name loChanges
EndIf[/highlight]
? 'Retry of the same change:'
llSuccess = TableUpdate(1,.F.)
? 'User 2 first name change success:', llSuccess
EndIf
Select 0
Use Persons Again
? 'Name in the DBF:', Persons.Firstname, Persons.Lastname