Search code examples
databasetransactionserlangmnesia

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.


Solution

  • 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).