Solution 10-2

Here is a suggested solution for Étude 10-2.

phone_records.hrl

-record(phone_call,
  {phone_number, start_date, start_time, end_date, end_time}).
-record(customer,
  {phone_number, last_name, first_name, middle_name, rate}).

phone_mnesia.erl

%% @author J D Eisenberg <jdavid.eisenberg@gmail.com>
%% @doc Read in a database of phone calls and customers.
%% @copyright 2013 J D Eisenberg
%% @version 0.1

-module(phone_mnesia).
-export([setup/2, summary/3]).
-include("phone_records.hrl").
-include_lib("stdlib/include/qlc.hrl").

%% @doc Set up Mnesia tables for phone calls and customers
%% given their file names

-spec(setup(string(), string()) -> atom()).

setup(CallFileName, CustomerFileName) ->

  mnesia:create_schema([node()]),
  mnesia:start(),
  mnesia:delete_table(phone_call),
  mnesia:delete_table(customer),

  fill_table(phone_call, CallFileName, fun add_call/1,
    record_info(fields, phone_call), bag),
  fill_table(customer, CustomerFileName, fun add_customer/1,
    record_info(fields, customer), set).

%% @doc Fill the given table with data from given file name.
%% AdderFunction assigns data to fields and writes it to the table;
%% RecordInfo is used when creating the table, as is the TableType.

fill_table(TableName, FileName, AdderFunction, RecordInfo, TableType) ->
  mnesia:create_table(TableName, [{attributes, RecordInfo}, {type, TableType}]),

  {OpenResult, InputFile} = file:open(FileName, [read]),
  case OpenResult of
    ok ->
      mnesia:transaction(
        fun() -> read_file(InputFile, AdderFunction) end); ...

Get Études for Erlang now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.