Best practice for updating a record if it exists otherwise creating a new one

When manually managing objects in X3, a common process is to update the object, if it exists, or to create a new object.

There are a couple of methods to do this in Version 7, but the recommended method is the following:

  1. Create a NewInstance.
  2. Read the instance to be updated.
    1. If success, then set updated properties and update the instance.
    2. Free the instance to clear the read errors, create a new instance, set all properties on the instance, and then insert the new instance.

An example of such code is provided below:

# In a given class, two properties (MYKEY, MYSTRING) have to be created in MYTABLE if they don't exist# Otherwise, update MYSTRING propertyLocal File MYTABLELocal Instance MY_TABLE Using C_MYTABLEMY_TABLE = NewInstance C_MYTABLE AllocGroup null[L]ASTATUS = fmet MY_TABLE.AREAD(this.MYKEY)If [L]ASTATUS = [V]CST_AOKMY_TABLE.MYSTRING = this.MYSTRING[L]ASTATUS = fmet MY_TABLE.AUPDATE()If [L]ASTATUS<>[V]CST_AOK[L]ASTATUS = fmet this.ASETERROR("MYSTRING","Error updating record"-this.MYKEY,[V]CST_AERROR)EndifElse# Initialize InstanceFreeGroup MY_TABLE : # Remove error on readMY_TABLE = NewInstance C_MYTABLE AllocGroup null : # create new instance[L]ASTATUS = fmet MY_TABLE.AINIT()If [L]ASTATUS=[V]CST_AOKMY_TABLE.MYKEY = this.MYKEYMY_TABLE.MYSTRING = this.MYKEY[L]ASTATUS = fmet MY_TABLE.AINSERT()If [L]ASTATUS<>[V]CST_AOK[L]ASTATUS = fmet this.ASETERROR("MYKEY","Error creating record"-this.MYKEY,[V]CST_AERROR)EndifElse# Error upon table initialization[L]ASTATUS = fmet this.ASETERROR("MYKEY","Error upon initialization of"-this.MYKEY,[V]CST_AERROR)EndifEndifFreeGroup MY_TABLE