This is a creation in Article, where the information may have evolved or changed.
Problems encountered
Golang for basic type initialization, the default value is assigned to the base type automatically. Like what:
var i int//在这里如果不对i做任何赋值,那么i的值为零
This feature avoids the embarrassment of accessing uninitialized variables in many places, but it also raises the question of what should be done if the database access operation is to be treated with such a default value.
Now let's assume a scenario where table A has 3 fields {AID int,afield1 string,afield2 string}, Table B also has 3 fields {ID int,bfield1 string,ref_aid int}, where the ref_ in table B Aid is a foreign key corresponding to the aid in table A. The data structure corresponding to go should be:
type A struct{ AID int//主键 AField1 string AField2 string}type B struct{ BID int//主键 BField1 string REF_AID int//外键,对应AID}
In the new object B, the three values in B are initialized by default to {0, "", 0}, if you do not do anything at this time, the direct execution of the insertion, the problem can become very serious, because a is likely to have no one record ID value of 0, the database error, this insertion is bound to fail. But only at the database level, the structure of the database is not a problem, table B ref_aid can be empty, in other languages, if the specific data is not initialized, the property will be empty, corresponding to the insertion time is also empty, but in Golang, because of the language level of the default initialization, This insert process will have a large number of 0 of the existence, violated the original table constraint rules, resulting in the insertion failure.
In the ORM also did not see can solve this problem, may be I use not careful, this to wait for later.
Own a little idea
- Add a default 0-ID record to all the related tables in the database, which does not need to make sense, but is used to prevent ambiguity and failure of the constraint-specific operations, especially some ref_ tables, where data changes are small, but there are often foreign key relationships with some other tables. Doing so will bring some extra overhead to the database, but as a temporary workaround it seems to be good, at least for the data processing process to run correctly.
- Solve the problem from the ORM. This is just an idea, but this is likely to become a
无理
requirement because it requires an ORM to determine whether the 0 you're Field
storing is the 0 value you want to specify, or the 0 that you don't want to be initialized by the language default.
- Write your own SQL statement execution, which is probably the stupidest way to do it, but it ensures that things are done exactly what you want them to do.