Mnesia is a distributed database management system that comes with erlangotp. The implementation of mnesia with erlang is almost ideal, but it is unsatisfactory in actual use and there will always be some shortcomings. The mnesia data table does not have the primary key auto-increment function, but there is an auto-Increment Function in the mnesia function that can be used to generate auto-increment IDs. The subsequent content will show how to implement auto-increment of the primary key.
Mnesia is a distributed database management system that comes with erlang/otp. The implementation of mnesia with erlang is almost ideal, but it is unsatisfactory in actual use and there will always be some shortcomings. The mnesia data table does not have the primary key auto-increment function, but there is an auto-Increment Function in the mnesia function that can be used to generate auto-increment IDs. The subsequent content will show how to implement auto-increment of the primary key.
Mnesia is a distributed database management system that comes with erlang/otp. The implementation of mnesia with erlang is almost ideal, but it is unsatisfactory in actual use and there will always be some shortcomings. The mnesia data table does not have the primary key auto-increment function, but there is an auto-Increment Function in the mnesia function that can be used to generate auto-increment IDs. The following content describes how to implement the primary key auto-increment function.
By reference to SQLite, a separate sqlite_sequence table is created in the database to create an auto-incrementing index table for other tables. Similarly, we have created such a table erlang_sequence to index the auto-increment IDs of other tables. It seems troublesome and the effect is still very satisfactory.
-Module (m ). -export ([init/0, reg/2]). -record (user, {id, name, age }). -record (erlang_sequence, {name, seq }). % auto-increment index table: Maintain the auto-increment idinit ()-> mnesia: create_schema ([node ()]), mnesia: start (), mnesia: create_table (erlang_sequence, [{attributes, record_info (fields, erlang_sequence)}, {type, set}, {disc_copies, [node ()]}]), mnesia: create_table (user, [{attributes, record_info (fields, user)}, {type, set}, {disc_copies, [node ()]}]), OK. reg (Name, Age)-> F = fun ()-> UserId = mnesia: dirty_update_counter (erlang_sequence, user, 1), User = # user {id = UserId, name = Name, age = Age}, mnesia: write (User) end, mnesia: transaction (F), OK.
Run the Code:
D:\>erl -mnesia dir '"mnesia"'Eshell V5.10.2 (abort with ^G)1> c(m).{ok,m}2> m:init().ok3> m:reg("xiaomin",18).ok4> m:reg("xiaohong",17).ok5> tv:start().<0.92.0>
Mnesia database view: