简体   繁体   中英

How to update a Mnesia table in Erlang

I have a little problem with my code. I have a table containing car details, name, price and quantity, so I am trying to create a function called buy which will be used to buy a specific car. When a user buys eg 5 BMW cars, they will call buy_car(bmw,5) . Now after this I want to update the new value of quantity for BMW cars.

My attempt is below but I can't seem to work around it, I am new to Erlang.

buy_car(X,Ncars) ->

    F = fun() ->

        %% ----first i find the number of car X available in the shop
        [Xcars] = mnesia:read({car,X}),
        Nc = Xcars#car.quantity,
        Leftcars = Xcars#car{quantity = Nc - Ncars},

        %% ---now we update the database
        mnesia:write(Leftcars),

    end,
    mnesia:transaction(F).

Please help me with how I can write a function that buys cars from the shop.

But your implementation works fine except you added illegal comma after mnesia:write(Leftcars). Here is code that works (I tried your implementation as buy_car2).

-module(q).

-export([setup/0, buy_car/2, buy_car2/2]).

-record(car, {brand, quantity}).

setup() ->
    mnesia:start(),
    mnesia:create_table(car, [{attributes, record_info(fields, car)}]),
    mnesia:transaction(fun() -> mnesia:write(#car{brand=bmw, quantity=1000}) end).

buy_car(Brand, Ncars) ->
    F = fun() ->
         [Car] = mnesia:read(car, Brand), % crash if the car is missing
         mnesia:write(Car#car{quantity = Car#car.quantity - Ncars})
    end,
    mnesia:transaction(F).

buy_car2(X,Ncars) ->
    F = fun() ->
        %% ----first i find the number of car X available in the shop
        [Xcars] = mnesia:read({car,X}),
        Nc = Xcars#car.quantity,
        Leftcars = Xcars#car{quantity = Nc - Ncars},
        %% ---now we update the database
        mnesia:write(Leftcars)
    end,
    mnesia:transaction(F).

I would do something like below:

Considering the record is defined as :
-record(car_record, {car, quantity}).

The following function will update the data:
buy_car(X,NCars) ->
    Row = #car_record{car = X, quantity = NCars}.
    mnesia:ets(fun()-> mnesia:dirty_write(Row) end),
    mnesia:change_table_copy_type(guiding_data, node(), disc_copies).

To use the above method, mnesia table must be created as "ram_copies" and with no replication nodes. Also, if there are lot of updates happening, you might not want to copy the ram_copies to disk for every update due to performance issues, rather you will do it in time triggered manner.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM