Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Browse files

Merge branch 'master' of git://github.com/dryfish/erlang_pgsql

  • Loading branch information...
commit 9f660e8ed29233a1273c722d54c0ee37fd53eeb2 2 parents aea6365 + 0f2fc32
@dryfish dryfish authored
Showing with 71 additions and 0 deletions.
  1. +14 −0 example/insert_example.erl
  2. +57 −0 src/pgsql_helper.erl
View
14 example/insert_example.erl
@@ -0,0 +1,14 @@
+-module(insert_example).
+-author('john@dryfish.org').
+
+-export([test/0]).
+
+-include("database_defs.hrl").
+
+test() ->
+ {ok, Db} = pgsql:connect(?HOST, ?DB, ?USER, ?PASS),
+ {ok, Status, ParamTypes, ResultTypes}
+ = pgsql:prepare(Db, dummynew, "INSERT INTO dummy (stuff) VALUES ($1)"),
+ {ok,{'INSERT', NRows}} = pgsql:execute(Db, dummynew, ["canada goose"]),
+ io:format("NRows: ~p~n", [NRows]).
+
View
57 src/pgsql_helper.erl
@@ -0,0 +1,57 @@
+-module(pgsql_helper).
+-author('john@dryfish.org').
+
+-export([prepare_insert/3, prepare_select/3, do_insert/2, transaction/3]).
+
+join(_Sep, [ Head ]) ->
+ Head;
+join(Sep, [ Head | Tail ]) ->
+ Head ++ Sep ++ join(Sep, Tail).
+
+times(1, Of) ->
+ [ Of ];
+times(N, Of) ->
+ [ Of ] ++ times(N - 1, Of).
+
+columns(I, I) ->
+ "$" ++ integer_to_list(I);
+columns(I, N) ->
+ "$" ++ integer_to_list(I) ++ ", " ++ columns(I + 1, N).
+
+prepare_insert(Db, Name, Fields) ->
+ StmtName = list_to_atom("insert_" ++ atom_to_list(Name)),
+ StmtSQL = "INSERT INTO " ++ atom_to_list(Name)
+ ++ " (" ++ join(", ", lists:map(fun(A) -> atom_to_list(A) end, Fields))
+ ++ ") VALUES (" ++ columns(1, length(Fields)) ++ ")",
+ pgsql:prepare(Db, StmtName, StmtSQL).
+
+prepare_select(Db, Name, Fields) ->
+ StmtName = list_to_atom("select_" ++ Name),
+ StmtSQL = "SELECT " ++ join(", ", Fields) ++ " FROM " ++ Name,
+ pgsql:prepare(Db, StmtName, StmtSQL).
+
+any_to_list(Any) when is_float(Any) ->
+ float_to_list(Any);
+any_to_list(Any) when is_integer(Any) ->
+ integer_to_list(Any);
+any_to_list(Any) when is_atom(Any) ->
+ atom_to_list(Any);
+any_to_list(Any) ->
+ Any.
+
+do_insert(Db, Record) ->
+ [ Name | Values ] = tuple_to_list(Record),
+ StmtName = list_to_atom("insert_" ++ atom_to_list(Name)),
+ pgsql:execute(Db, StmtName, lists:map(Values)).
+
+transaction(Db, Fun, Args) ->
+ {ok, _} = pgsql:squery(Db, "BEGIN WORK;"),
+ Return = apply(Fun, Args),
+ case Return of
+ {'EXIT', _Term} ->
+ {ok, _Query} = pgsql:squery(Db, "ROLLBACK WORK;"),
+ {rollback, Return};
+ _Else ->
+ {ok, _} = pgsql:squery(Db, "COMMIT WORK;"),
+ {commit, Return}
+ end.
Please sign in to comment.
Something went wrong with that request. Please try again.