Will 16 лет назад
Сommit
ba47564c3f
14 измененных файлов с 1602 добавлено и 0 удалено
  1. 4 0
      .hgignore
  2. 10 0
      LICENSE
  3. 44 0
      Makefile
  4. 58 0
      README
  5. 1 0
      ebin/epgsql.app
  6. 4 0
      include/pgsql.hrl
  7. 8 0
      src/epgsql.app
  8. 168 0
      src/pgsql.erl
  9. 54 0
      src/pgsql_binary.erl
  10. 642 0
      src/pgsql_connection.erl
  11. 160 0
      src/pgsql_types.erl
  12. 0 0
      test_ebin/.empty
  13. 384 0
      test_src/pgsql_tests.erl
  14. 65 0
      test_src/test_schema.sql

+ 4 - 0
.hgignore

@@ -0,0 +1,4 @@
+\.beam
+\.boot
+\.script
+

+ 10 - 0
LICENSE

@@ -0,0 +1,10 @@
+Copyright (c) 2008, Will Glozer
+All rights reserved.
+
+Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
+
+    * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
+    * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
+    * Neither the name of Will Glozer nor the names of his contributors may be used to endorse or promote products derived from this software without specific prior written permission.
+
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

+ 44 - 0
Makefile

@@ -0,0 +1,44 @@
+NAME		:= epgsql
+VERSION		:= 0.1
+
+ERL  		:= erl
+ERLC 		:= erlc
+
+# ------------------------------------------------------------------------
+
+ERLC_FLAGS	:= -Wall -I include
+
+SRC			:= $(wildcard src/*.erl)
+TESTS 		:= $(wildcard test_src/*.erl)
+RELEASE		:= $(NAME)-$(VERSION).tar.gz
+
+APPDIR		:= $(NAME)-$(VERSION)
+BEAMS		:= $(SRC:src/%.erl=ebin/%.beam) 
+
+compile: $(BEAMS)
+
+app: compile
+	@mkdir -p $(APPDIR)/ebin
+	@cp -r ebin/* $(APPDIR)/ebin/
+	@cp -r include $(APPDIR)
+
+release: app
+	@tar czvf $(RELEASE) $(APPDIR)
+
+clean:
+	@rm -f ebin/*.beam
+	@rm -rf $(NAME)-$(VERSION) $(NAME)-*.tar.gz
+
+test: $(TESTS:test_src/%.erl=test_ebin/%.beam) $(BEAMS)
+	$(ERL) -pa ebin/ -pa test_ebin/ -noshell -s pgsql_tests run_tests -s init stop
+
+# ------------------------------------------------------------------------
+
+.SUFFIXES: .erl .beam
+.PHONY:    app compile clean test
+
+ebin/%.beam : src/%.erl
+	$(ERLC) $(ERLC_FLAGS) -o $(dir $@) $<
+
+test_ebin/%.beam : test_src/%.erl
+	$(ERLC) $(ERLC_FLAGS) -o $(dir $@) $<

+ 58 - 0
README

@@ -0,0 +1,58 @@
+Erlang PostgreSQL Database Client
+
+* Connect
+
+  {ok, C} = pgsql:connect(Host, [Username, Password, Opts]).
+
+  Opts is a property list. The following properties are supported:
+
+  - database
+  - port
+
+  ok = pgsql:close(C).
+
+* Simple Query
+
+  {ok, Columns, Rows} = pgsql:squery(C, Sql).
+
+  Columns       - list of column records, see pgsql.hrl for definition.
+  Rows          - list of tuples, one for each row.
+
+  The simple query protocol returns all columns as text (Erlang binaries)
+  and does not support binding parameters.
+
+* Extended Query
+
+  {ok, Columns, Rows} = pgsql:equery(C, Sql, [Parameters]).
+
+  Parameters    - list of values to be bound to $1, $2, $3, etc.
+
+  The extended query protocol combines parse, bind, and execute using
+  the unnamed prepared statement and portal. PostgreSQL's binary format
+  is used to return integers as Erlang integers, floats as floats,
+  bytea/text/varchar columns as binaries, bools as true/false, etc.
+  For details see pgsql_binary.erl.
+
+* Parse/Bind/Execute
+
+  {ok, Statement} = pgsql:parse(C, [StatementName], Sql, [ParameterTypes]).
+
+  StatementName   - optional, reusable, name for the prepared statement.
+  ParameterTypes  - optional list of PostgreSQL types for each parameter.
+
+  For valid type names see pgsql_types.erl.
+  
+  ok = pgsql:bind(C, Statement, [PortalName], ParameterValues).
+
+  PortalName- optional name for the result portal.
+  
+  {ok | partial, Rows} = pgsql:execute(C, Statement, [PortalName], [MaxRows]).
+
+  PortalName      - optional portal name used in bind/4.
+  MaxRows         - maximum number of rows to return (0 for all rows).
+
+  execute returns {partial, Rows} when more rows are available.
+
+  ok = pgsql:close(C, Statement).
+  ok = pgsql:close(C, statement | portal, Name).
+  ok = pgsql:sync(C).

+ 1 - 0
ebin/epgsql.app

@@ -0,0 +1 @@
+../src/epgsql.app

+ 4 - 0
include/pgsql.hrl

@@ -0,0 +1,4 @@
+-record(column,    {name, type, size, modifier, format}).
+-record(statement, {name, columns, types}).
+
+-record(error,  {severity, code, message, extra}).

+ 8 - 0
src/epgsql.app

@@ -0,0 +1,8 @@
+{application, epgsql,
+ [{description, "PostgreSQL Database Client"},
+  {vsn, "0.1"},
+  {modules, [pgsql, pgsql_binary, pgsql_connection, pgsql_types]},
+  {registered, []},
+  {mod, {epgsql, []}},
+  {applications, [kernel, stdlib, crypto, sasl},
+  {included_applications, []}]}.

+ 168 - 0
src/pgsql.erl

@@ -0,0 +1,168 @@
+%%% Copyright (C) 2008 - Will Glozer.  All rights reserved.
+
+-module(pgsql).
+
+-export([connect/2, connect/3, connect/4, close/1]).
+-export([get_parameter/2, squery/2, equery/2, equery/3]).
+-export([parse/2, parse/3, parse/4, describe/2, describe/3]).
+-export([bind/3, bind/4, execute/2, execute/3, execute/4]).
+-export([close/2, close/3, sync/1]).
+-export([with_transaction/2]).
+
+-include("pgsql.hrl").
+
+-define(timeout, 5000).
+
+%% -- client interface --
+
+connect(Host, Opts) ->
+    connect(Host, os:getenv("USER"), "", Opts).
+
+connect(Host, Username, Opts) ->
+    connect(Host, Username, "", Opts).
+
+connect(Host, Username, Password, Opts) ->
+    {ok, C} = pgsql_connection:start_link(),
+    pgsql_connection:connect(C, Host, Username, Password, Opts).
+    
+close(C) when is_pid(C) ->
+    catch pgsql_connection:stop(C),
+    ok.
+
+get_parameter(C, Name) ->
+    pgsql_connection:get_parameter(C, Name).
+
+squery(C, Sql) ->
+    ok = pgsql_connection:squery(C, Sql),
+    case receive_results(C, []) of
+        [Result] -> Result;
+        Results  -> Results
+    end.
+
+equery(C, Sql) ->
+    equery(C, Sql, []).
+
+equery(C, Sql, Parameters) ->
+    case pgsql_connection:parse(C, "", Sql, []) of
+        {ok, #statement{types = Types} = S} ->
+            Typed_Parameters = lists:zip(Types, Parameters),
+            ok = pgsql_connection:equery(C, S, Typed_Parameters),
+            receive_result(C);
+        Error ->
+            Error
+    end.
+
+%% parse
+
+parse(C, Sql) ->
+    parse(C, "", Sql, []).
+
+parse(C, Sql, Types) ->
+    parse(C, "", Sql, Types).
+
+parse(C, Name, Sql, Types) ->
+    pgsql_connection:parse(C, Name, Sql, Types).
+
+%% bind
+
+bind(C, Statement, Parameters) ->
+    bind(C, Statement, "", Parameters).
+
+bind(C, Statement, PortalName, Parameters) ->
+    pgsql_connection:bind(C, Statement, PortalName, Parameters).
+
+%% execute
+
+execute(C, S) ->
+    execute(C, S, "", 0).
+
+execute(C, S, N) ->
+    execute(C, S, "", N).
+
+execute(C, S, PortalName, N) ->
+    pgsql_connection:execute(C, S, PortalName, N),
+    receive_extended_result(C).
+
+%% statement/portal functions
+
+describe(C, #statement{name = Name}) ->
+    pgsql_connection:describe(C, statement, Name).
+
+describe(C, Type, Name) ->
+    pgsql_connection:describe(C, Type, Name).
+
+close(C, #statement{name = Name}) ->
+    pgsql_connection:close(C, statement, Name).
+
+close(C, Type, Name) ->
+    pgsql_connection:close(C, Type, Name).
+
+sync(C) ->
+    pgsql_connection:sync(C).
+
+%% misc helper functions
+with_transaction(C, F) ->
+    try {ok, [], []} = squery(C, "BEGIN"),
+        R = F(C),
+        {ok, [], []} = squery(C, "COMMIT"),
+        R
+    catch
+        _:Why ->
+            squery(C, "ROLLBACK"),
+            {rollback, Why}
+    end.
+
+%% -- internal functions --
+
+receive_result(C) ->
+    R = receive_result(C, [], []),
+    receive
+        {pgsql, C, done} -> R
+    end.
+            
+receive_results(C, Results) ->
+    case receive_result(C, [], []) of
+        done -> lists:reverse(Results);
+        R    -> receive_results(C, [R | Results])
+    end.
+            
+receive_result(C, Cols, Rows) ->
+    receive
+        {pgsql, C, {columns, Cols2}} ->
+            receive_result(C, Cols2, Rows);
+        {pgsql, C, {data, Row}} ->
+            receive_result(C, Cols, [Row | Rows]);
+        {pgsql, C, {error, _E} = Error} ->
+            Error;
+        {pgsql, C, {complete, {_Type, Count}}} ->
+            {ok, Count};
+        {pgsql, C, {complete, _Type}} ->
+            {ok, Cols, lists:reverse(Rows)};
+        {pgsql, C, {notice, _N}} ->
+            receive_result(C, Cols, Rows);
+        {pgsql, C, done} ->
+            done
+    after
+        ?timeout -> {error, timeout}
+    end.
+
+receive_extended_result(C)->
+    receive_extended_result(C, []).
+
+receive_extended_result(C, Rows) ->
+    receive
+        {pgsql, C, {data, Row}} ->
+            receive_extended_result(C, [Row | Rows]);
+        {pgsql, C, {error, _E} = Error} ->
+            Error;
+        {pgsql, C, suspended} ->
+            {partial, lists:reverse(Rows)};
+        {pgsql, C, {complete, {_Type, Count}}} ->
+            {ok, Count};
+        {pgsql, C, {complete, _Type}} ->
+            {ok, lists:reverse(Rows)};
+        {pgsql, C, {notice, _N}} ->
+            receive_extended_result(C, Rows)
+    after
+        ?timeout -> {error, timeout}
+    end.

+ 54 - 0
src/pgsql_binary.erl

@@ -0,0 +1,54 @@
+%%% Copyright (C) 2008 - Will Glozer.  All rights reserved.
+
+-module(pgsql_binary).
+
+-export([encode/2, decode/2, supports/1]).
+
+-define(int32, 1/big-signed-unit:32).
+
+encode(_Any, null)  -> <<-1:?int32>>;
+encode(bool, true)  -> <<1:?int32, 1:1/big-signed-unit:8>>;
+encode(bool, false) -> <<1:?int32, 0:1/big-signed-unit:8>>;
+encode(bpchar, C)   -> <<1:?int32, C:1/big-unsigned-unit:8>>;
+encode(int2, N)     -> <<2:?int32, N:1/big-signed-unit:16>>;
+encode(int4, N)     -> <<4:?int32, N:1/big-signed-unit:32>>;
+encode(int8, N)     -> <<8:?int32, N:1/big-signed-unit:64>>;
+encode(float4, N)   -> <<4:?int32, N:1/big-float-unit:32>>;
+encode(float8, N)   -> <<8:?int32, N:1/big-float-unit:64>>;
+encode(bytea, B) when is_binary(B)   -> <<(byte_size(B)):?int32, B/binary>>;
+encode(text, B) when is_binary(B)    -> <<(byte_size(B)):?int32, B/binary>>;
+encode(varchar, B) when is_binary(B) -> <<(byte_size(B)):?int32, B/binary>>;
+encode(Type, L) when is_list(L)      -> encode(Type, list_to_binary(L));
+encode(_Type, _Value)                -> {error, unsupported}.
+
+decode(bool, <<1:1/big-signed-unit:8>>)     -> true;
+decode(bool, <<0:1/big-signed-unit:8>>)     -> false;
+decode(bpchar, <<C:1/big-unsigned-unit:8>>) -> C;
+decode(int2, <<N:1/big-signed-unit:16>>)    -> N;
+decode(int4, <<N:1/big-signed-unit:32>>)    -> N;
+decode(int8, <<N:1/big-signed-unit:64>>)    -> N;
+decode(float4, <<N:1/big-float-unit:32>>)   -> N;
+decode(float8, <<N:1/big-float-unit:64>>)   -> N;
+decode(record, <<_:?int32, Rest/binary>>)   -> list_to_tuple(decode_record(Rest, []));
+decode(_Other, Bin)                         -> Bin.
+
+decode_record(<<>>, Acc) ->
+    lists:reverse(Acc);
+decode_record(<<_Type:?int32, -1:?int32, Rest/binary>>, Acc) ->
+    decode_record(Rest, [null | Acc]);
+decode_record(<<Type:?int32, Len:?int32, Value:Len/binary, Rest/binary>>, Acc) ->
+    Value2 = decode(pgsql_types:oid2type(Type), Value),
+    decode_record(Rest, [Value2 | Acc]).
+
+supports(bool)    -> true;
+supports(bpchar)  -> true;
+supports(int2)    -> true;
+supports(int4)    -> true;
+supports(int8)    -> true;
+supports(float4)  -> true;
+supports(float8)  -> true;
+supports(bytea)   -> true;
+supports(text)    -> true;
+supports(varchar) -> true;
+supports(record)  -> true;
+supports(_Type)   -> false.

+ 642 - 0
src/pgsql_connection.erl

@@ -0,0 +1,642 @@
+%%% Copyright (C) 2008 - Will Glozer.  All rights reserved.
+
+-module(pgsql_connection).
+
+-behavior(gen_fsm).
+
+-export([start_link/0, stop/1, connect/5, get_parameter/2]).
+-export([squery/2, equery/3]).
+-export([parse/4, bind/4, execute/4, describe/3]).
+-export([close/3, sync/1]).
+
+-export([init/1, handle_event/3, handle_sync_event/4]).
+-export([handle_info/3, terminate/3, code_change/4]).
+-export([read/3]).
+
+-export([startup/3, auth/2, initializing/2, ready/2, ready/3]).
+-export([querying/2, parsing/2, binding/2, describing/2]).
+-export([executing/2, closing/2, synchronizing/2]).
+
+-include("pgsql.hrl").
+
+-record(state, {
+          reader,
+          sock,
+          parameters = [],
+          reply,
+          reply_to,
+          backend,
+          statement,
+          txstatus}).
+
+-define(int16, 1/big-signed-unit:16).
+-define(int32, 1/big-signed-unit:32).
+
+%% -- client interface --
+
+start_link() ->
+    gen_fsm:start_link(?MODULE, [], []).
+
+stop(C) ->
+    gen_fsm:send_all_state_event(C, stop).
+
+connect(C, Host, Username, Password, Opts) ->
+    gen_fsm:sync_send_event(C, {connect, Host, Username, Password, Opts}).
+
+get_parameter(C, Name) ->
+    gen_fsm:sync_send_event(C, {get_parameter, to_binary(Name)}).
+
+squery(C, Sql) ->
+    gen_fsm:sync_send_event(C, {squery, Sql}).
+
+equery(C, Statement, Parameters) ->
+    gen_fsm:sync_send_event(C, {equery, Statement, Parameters}).
+
+parse(C, Name, Sql, Types) ->
+    gen_fsm:sync_send_event(C, {parse, Name, Sql, Types}).
+
+bind(C, Statement, PortalName, Parameters) ->
+    gen_fsm:sync_send_event(C, {bind, Statement, PortalName, Parameters}).
+
+execute(C, Statement, PortalName, MaxRows) ->
+    gen_fsm:sync_send_event(C, {execute, Statement, PortalName, MaxRows}).
+
+describe(C, Type, Name) ->
+    gen_fsm:sync_send_event(C, {describe, Type, Name}).
+
+close(C, Type, Name) ->
+    gen_fsm:sync_send_event(C, {close, Type, Name}).
+
+sync(C) ->
+    gen_fsm:sync_send_event(C, sync).
+
+%% -- gen_fsm implementation --
+
+init([]) ->
+    process_flag(trap_exit, true),
+    {ok, startup, #state{}}.
+
+handle_event({notice, Notice}, State_Name, State) ->
+    notify(State, {notice, Notice}),
+    {next_state, State_Name, State};
+
+handle_event({parameter_status, Name, Value}, State_Name, State) ->
+    Parameters2 = lists:keystore(Name, 1, State#state.parameters, {Name, Value}),
+    {next_state, State_Name, State#state{parameters = Parameters2}};
+    
+handle_event(stop, _State_Name, State) ->
+    {stop, normal, State};
+
+handle_event(Event, _State_Name, State) ->
+    {stop, {unsupported_event, Event}, State}.
+
+handle_sync_event(Event, _From, _State_Name, State) ->
+    {stop, {unsupported_sync_event, Event}, State}.
+
+handle_info({'EXIT', Pid, Reason}, _State_Name, State = #state{reader = Pid}) ->
+    {stop, Reason, State};
+
+handle_info(Info, _State_Name, State) ->
+    {stop, {unsupported_info, Info}, State}.
+    
+terminate(_Reason, _State_Name, State = #state{sock = Sock}) 
+  when Sock =/= undefined ->
+    send(State, $X, []),
+    gen_tcp:close(Sock);
+
+terminate(_Reason, _State_Name, _State) ->
+    ok.
+
+code_change(_Old_Vsn, State_Name, State, _Extra) ->
+    {ok, State_Name, State}.
+
+%% -- states --
+
+startup({connect, Host, Username, Password, Opts}, From, State) ->
+    Port      = proplists:get_value(port, Opts, 5432),    
+    Sock_Opts = [{active, false}, {packet, raw}, binary],
+    case gen_tcp:connect(Host, Port, Sock_Opts) of
+        {ok, Sock} ->
+            Reader = spawn_link(?MODULE, read, [self(), Sock, <<>>]),
+
+            Opts2 = ["user", 0, Username, 0],
+            case proplists:get_value(database, Opts, undefined) of
+                undefined -> Opts3 = Opts2;
+                Database  -> Opts3 = [Opts2 | ["database", 0, Database, 0]]
+            end,
+            
+            put(username, Username),
+            put(password, Password),
+            State2 = State#state{reader   = Reader,
+                                 sock     = Sock,
+                                 reply_to = From},
+            send(State2, [<<196608:32>>, Opts3, 0]),
+    
+            {next_state, auth, State2};
+        Error ->
+            {stop, normal, Error, State}
+    end.
+
+%% AuthenticationOk
+auth({$R, <<0:?int32>>}, State) ->
+    {next_state, initializing, State};
+
+%% AuthenticationCleartextPassword
+auth({$R, <<3:?int32>>}, State) ->
+    send(State, $p, [get(password), 0]),
+    {next_state, auth, State};
+
+%% AuthenticationMD5Password
+auth({$R, <<5:?int32, Salt:4/binary>>}, State) ->
+    Digest1 = hex(crypto:md5([get(password), get(username)])),
+    Str = ["md5", hex(crypto:md5([Digest1, Salt])), 0],
+    send(State, $p, Str),
+    {next_state, auth, State};
+
+auth({$R, <<M:?int32, _/binary>>}, State) ->
+    case M of
+        2 -> Method = kerberosV5;
+        4 -> Method = crypt;
+        6 -> Method = scm;
+        7 -> Method = gss;
+        8 -> Method = sspi;
+        _ -> Method = unknown
+    end,
+    Error = {error, {unsupported_auth_method, Method}},
+    gen_fsm:reply(State#state.reply_to, Error),
+    {stop, normal, State};
+
+%% ErrorResponse
+auth({$E, Bin}, State) ->
+    Error = decode_error(Bin),
+    case Error#error.code of
+        <<"28000">> -> Why = invalid_authorization_specification;
+        Any         -> Why = Any
+    end,
+    gen_fsm:reply(State#state.reply_to, {error, Why}),
+    {stop, normal, State}.
+
+%% BackendKeyData
+initializing({$K, <<Pid:?int32, Key:?int32>>}, State) ->
+    State2 = State#state{backend = {Pid, Key}},
+    {next_state, initializing, State2};
+
+%% ErrorResponse
+initializing({$E, Bin}, State) ->
+    Error = decode_error(Bin),
+    case Error#error.code of
+        <<"28000">> -> Why = invalid_authorization_specification;
+        Any         -> Why = Any
+    end,
+    gen_fsm:reply(State#state.reply_to, {error, Why}),
+    {stop, normal, State};
+
+%% ReadyForQuery
+initializing({$Z, <<Status:8>>}, State) ->
+    erase(username),
+    erase(password),
+    gen_fsm:reply(State#state.reply_to, {ok, self()}),
+    {next_state, ready, State#state{txstatus = Status}}.
+
+ready(Data, State) ->
+    error_logger:info_msg("unexpected msg when ready: ~p~n", Data),
+    {next_state, ready, State}.
+
+%% execute simple query
+ready({squery, Sql}, From, State) ->
+    send(State, $Q, [Sql, 0]),
+    State2 = State#state{statement = #statement{}, reply_to = From},
+    {reply, ok, querying, State2};
+
+%% execute extended query
+ready({equery, Statement, Parameters}, From, State) ->
+    #statement{name = StatementName, columns = Columns} = Statement,
+    Bin1 = encode_parameters(Parameters),
+    Bin2 = encode_formats(Columns),
+    send(State, $B, ["", 0, StatementName, 0, Bin1, Bin2]),
+    send(State, $E, ["", 0, <<0:?int32>>]),
+    send(State, $C, [$S, "", 0]),
+    send(State, $S, []),
+    State2 = State#state{statement = Statement, reply_to = From},
+    {reply, ok, querying, State2};
+
+ready({get_parameter, Name}, _From, State) ->
+    case lists:keysearch(Name, 1, State#state.parameters) of
+        {value, {Name, Value}} -> Value;
+        false                  -> Value = undefined
+    end,
+    {reply, {ok, Value}, ready, State};
+
+ready({parse, Name, Sql, Types}, From, State) ->
+    Bin = encode_types(Types),
+    send(State, $P, [Name, 0, Sql, 0, Bin]),
+    send(State, $D, [$S, Name, 0]),
+    send(State, $H, []),
+    S = #statement{name = Name},
+    {next_state, parsing, State#state{statement = S, reply_to = From}};
+
+ready({bind, Statement, PortalName, Parameters}, From, State) ->
+    #statement{name = StatementName, columns = Columns, types = Types} = Statement,
+    Typed_Parameters = lists:zip(Types, Parameters),
+    Bin1 = encode_parameters(Typed_Parameters),
+    Bin2 = encode_formats(Columns),
+    send(State, $B, [PortalName, 0, StatementName, 0, Bin1, Bin2]),
+    send(State, $H, []),
+    {next_state, binding, State#state{statement = Statement, reply_to = From}};
+
+ready({execute, Statement, PortalName, MaxRows}, From, State) ->
+    send(State, $E, [PortalName, 0, <<MaxRows:?int32>>]),
+    send(State, $H, []),
+    {reply, ok, executing, State#state{statement = Statement, reply_to = From}};
+
+ready({describe, Type, Name}, From, State) ->
+    case Type of
+        statement -> Type2 = $S;
+        portal    -> Type2 = $P
+    end,
+    send(State, $D, [Type2, Name, 0]),
+    send(State, $H, []),
+    {next_state, describing, State#state{reply_to = From}};
+
+ready({close, Type, Name}, From, State) ->
+    case Type of
+        statement -> Type2 = $S;
+        portal    -> Type2 = $P
+    end,
+    send(State, $C, [Type2, Name, 0]),
+    send(State, $H, []),
+    {next_state, closing, State#state{reply_to = From}};
+
+ready(sync, From, State) ->
+    send(State, $S, []),
+    {next_state, synchronizing, State#state{reply = ok, reply_to = From}}.
+
+%% BindComplete
+querying({$2, <<>>}, State) ->
+    #state{statement = #statement{columns = Columns}} = State,
+    notify(State, {columns, Columns}),
+    {next_state, querying, State};
+
+%% CloseComplete
+querying({$3, <<>>}, State) ->
+    {next_state, querying, State};
+
+%% RowDescription
+querying({$T, <<Count:?int16, Bin/binary>>}, State) ->
+    Columns = decode_columns(Count, Bin),
+    S2 = (State#state.statement)#statement{columns = Columns},    
+    notify(State, {columns, Columns}),
+    {next_state, querying, State#state{statement = S2}};
+
+%% DataRow
+querying({$D, <<_Count:?int16, Bin/binary>>}, State) ->
+    #state{statement = #statement{columns = Columns}} = State,
+    Data = decode_data(Columns, Bin),
+    notify(State, {data, Data}),
+    {next_state, querying, State};
+
+%% CommandComplete
+querying({$C, Bin}, State) ->
+    Complete = decode_complete(Bin),
+    notify(State, {complete, Complete}),
+    {next_state, querying, State};
+
+%% EmptyQueryResponse
+querying({$I, _Bin}, State) ->
+    notify(State, {complete, empty}),
+    {next_state, querying, State};
+
+%% ErrorResponse
+querying({$E, Bin}, State) ->
+    Error = decode_error(Bin),
+    notify(State, {error, Error}),
+    {next_state, querying, State};
+
+%% ReadyForQuery
+querying({$Z, <<_Status:8>>}, State) ->
+    notify(State, done),
+    {next_state, ready, State#state{reply_to = undefined}}.
+
+%% ParseComplete
+parsing({$1, <<>>}, State) ->
+    {next_state, describing, State};
+
+%% ErrorResponse
+parsing({$E, Bin}, State) ->
+    Reply = {error, decode_error(Bin)},
+    send(State, $S, []),
+    {next_state, parsing, State#state{reply = Reply}};
+
+%% ReadyForQuery
+parsing({$Z, <<Status:8>>}, State) ->
+    #state{reply = Reply, reply_to = Reply_To} = State,
+    gen_fsm:reply(Reply_To, Reply),
+    {next_state, ready, State#state{reply = undefined, txstatus = Status}}.
+
+%% BindComplete
+binding({$2, <<>>}, State) ->
+    gen_fsm:reply(State#state.reply_to, ok),
+    {next_state, ready, State};
+
+%% ErrorResponse
+binding({$E, Bin}, State) ->
+    Reply = {error, decode_error(Bin)},
+    send(State, $S, []),
+    {next_state, binding, State#state{reply = Reply}};
+
+%% ReadyForQuery
+binding({$Z, <<Status:8>>}, State) ->
+    #state{reply = Reply, reply_to = Reply_To} = State,
+    gen_fsm:reply(Reply_To, Reply),
+    {next_state, ready, State#state{reply = undefined, txstatus = Status}}.
+
+%% ParameterDescription
+describing({$t, <<_Count:?int16, Bin/binary>>}, State) ->
+    Types = [pgsql_types:oid2type(Oid) || <<Oid:?int32>> <= Bin],
+    S2 = (State#state.statement)#statement{types = Types},
+    {next_state, describing, State#state{statement = S2}};
+
+%% RowDescription
+describing({$T, <<Count:?int16, Bin/binary>>}, State) ->
+    Columns = decode_columns(Count, Bin),
+    Columns2 = [C#column{format = format(C#column.type)} || C <- Columns],
+    S2 = (State#state.statement)#statement{columns = Columns2},
+    gen_fsm:reply(State#state.reply_to, {ok, S2}),
+    {next_state, ready, State};
+
+%% NoData
+describing({$n, <<>>}, State) ->
+    S2 = (State#state.statement)#statement{columns = []},
+    gen_fsm:reply(State#state.reply_to, {ok, S2}),
+    {next_state, ready, State};
+
+%% ErrorResponse
+describing({$E, Bin}, State) ->
+    Reply = {error, decode_error(Bin)},
+    send(State, $S, []),
+    {next_state, describing, State#state{reply = Reply}};
+
+%% ReadyForQuery
+describing({$Z, <<Status:8>>}, State) ->
+    #state{reply = Reply, reply_to = Reply_To} = State,
+    gen_fsm:reply(Reply_To, Reply),
+    {next_state, ready, State#state{reply = undefined, txstatus = Status}}.
+
+%% DataRow
+executing({$D, <<_Count:?int16, Bin/binary>>}, State) ->
+    #state{statement = #statement{columns = Columns}} = State,
+    Data = decode_data(Columns, Bin),
+    notify(State, {data, Data}),
+    {next_state, executing, State};
+
+%% PortalSuspended
+executing({$s, <<>>}, State) ->
+    notify(State, suspended),
+    {next_state, ready, State};
+
+%% CommandComplete
+executing({$C, Bin}, State) ->
+    notify(State, {complete, decode_complete(Bin)}),
+    {next_state, ready, State};
+
+%% EmptyQueryResponse
+executing({$I, _Bin}, State) ->
+    notify(State, {complete, empty}),
+    {next_state, ready, State};
+
+%% ErrorResponse
+executing({$E, Bin}, State) ->
+    notify(State, {error, decode_error(Bin)}),
+    {next_state, executing, State}.
+
+%% CloseComplete
+closing({$3, <<>>}, State) ->
+    gen_fsm:reply(State#state.reply_to, ok),
+    {next_state, ready, State};
+
+%% ErrorResponse
+closing({$E, Bin}, State) ->
+    Error = {error, decode_error(Bin)},
+    gen_fsm:reply(State#state.reply_to, Error),
+    {next_state, ready, State}.
+
+%% ErrorResponse
+synchronizing({$E, Bin}, State) ->
+    Reply = {error, decode_error(Bin)},
+    {next_state, synchronizing, State#state{reply = Reply}};
+
+%% ReadyForQuery
+synchronizing({$Z, <<Status:8>>}, State) ->
+    #state{reply = Reply, reply_to = Reply_To} = State,
+    gen_fsm:reply(Reply_To, Reply),
+    {next_state, ready, State#state{reply = undefined, txstatus = Status}}.
+
+%% -- internal functions --
+
+%% decode a single null-terminated string
+decode_string(Bin) ->
+    decode_string(Bin, <<>>).
+
+decode_string(<<0, Rest/binary>>, Str) ->
+    {Str, Rest};
+decode_string(<<C, Rest/binary>>, Str) ->
+    decode_string(Rest, <<Str/binary, C>>).
+
+%% decode multiple null-terminated string
+decode_strings(Bin) ->
+    decode_strings(Bin, []).
+
+decode_strings(<<>>, Acc) ->
+    lists:reverse(Acc);
+decode_strings(Bin, Acc) ->
+    {Str, Rest} = decode_string(Bin),
+    decode_strings(Rest, [Str | Acc]).
+
+%% decode field
+decode_fields(Bin) ->
+    decode_fields(Bin, []).
+
+decode_fields(<<0>>, Acc) ->
+    Acc;
+decode_fields(<<Type:8, Rest/binary>>, Acc) ->
+    {Str, Rest2} = decode_string(Rest),
+    decode_fields(Rest2, [{Type, Str} | Acc]).
+
+%% decode data
+decode_data(Columns, Bin) ->
+    decode_data(Columns, Bin, []).
+
+decode_data([], _Bin, Acc) ->
+    list_to_tuple(lists:reverse(Acc));
+decode_data([_C | T], <<-1:?int32, Rest/binary>>, Acc) ->
+    decode_data(T, Rest, [null | Acc]);
+decode_data([C | T], <<Len:?int32, Value:Len/binary, Rest/binary>>, Acc) ->
+    case C of
+        #column{type = Type, format = 1}   -> Value2 = pgsql_binary:decode(Type, Value);
+        #column{}                          -> Value2 = Value
+    end,
+    decode_data(T, Rest, [Value2 | Acc]).
+
+%% decode column information
+decode_columns(Count, Bin) ->
+    decode_columns(Count, Bin, []).
+
+decode_columns(0, _Bin, Acc) ->
+    lists:reverse(Acc);
+decode_columns(N, Bin, Acc) ->
+    {Name, Rest} = decode_string(Bin),
+    <<_Table_Oid:?int32, _Attrib_Num:?int16, Type_Oid:?int32,
+     Size:?int16, Modifier:?int32, Format:?int16, Rest2/binary>> = Rest,
+    Desc = #column{
+      name     = Name,
+      type     = pgsql_types:oid2type(Type_Oid),
+      size     = Size,
+      modifier = Modifier,
+      format   = Format},
+    decode_columns(N - 1, Rest2, [Desc | Acc]).
+
+%% decode command complete msg
+decode_complete(Bin) ->
+    {Str, _} = decode_string(Bin),
+    case string:tokens(binary_to_list(Str), " ") of
+        [Type]             -> lower_atom(Type);
+        [Type, _Oid, Rows] -> {lower_atom(Type), list_to_integer(Rows)};
+        [Type, Rows]       -> {lower_atom(Type), list_to_integer(Rows)}
+    end.
+
+%% decode ErrorResponse
+decode_error(Bin) ->
+    Fields = decode_fields(Bin),
+    Error = #error{
+      severity = lower_atom(proplists:get_value($S, Fields)),
+      code     = proplists:get_value($C, Fields),
+      message  = proplists:get_value($M, Fields),
+      extra    = decode_error_extra(Fields)},
+    Error.
+
+decode_error_extra(Fields) ->
+    Types = [{$D, detail}, {$H, hint}, {$P, position}],
+    decode_error_extra(Types, Fields, []).
+    
+decode_error_extra([], _Fields, Extra) ->
+    Extra;
+decode_error_extra([{Type, Name} | T], Fields, Extra) ->
+    case proplists:get_value(Type, Fields) of
+        undefined -> decode_error_extra(T, Fields, Extra);
+        Value     -> decode_error_extra(T, Fields, [{Name, Value} | Extra])
+    end.
+
+%% encode types
+encode_types(Types) ->
+    encode_types(Types, 0, <<>>).
+
+encode_types([], Count, Acc) ->
+    <<Count:?int16, Acc/binary>>;
+
+encode_types([Type | T], Count, Acc) ->
+    case Type of
+        undefined -> Oid = 0;
+        _Any      -> Oid = pgsql_types:type2oid(Type)
+    end,
+    encode_types(T, Count + 1, <<Acc/binary, Oid:?int32>>).
+
+%% encode column formats
+encode_formats(Columns) ->
+    encode_formats(Columns, 0, <<>>).
+
+encode_formats([], Count, Acc) ->
+    <<Count:?int16, Acc/binary>>;
+
+encode_formats([#column{format = Format} | T], Count, Acc) ->
+    encode_formats(T, Count + 1, <<Acc/binary, Format:?int16>>).
+
+format(Type) ->
+    case pgsql_binary:supports(Type) of
+        true  -> 1;
+        false -> 0
+    end.
+
+%% encode parameters
+encode_parameters(Parameters) ->
+    encode_parameters(Parameters, 0, <<>>, <<>>).
+
+encode_parameters([], Count, Formats, Values) ->
+    <<Count:?int16, Formats/binary, Count:?int16, Values/binary>>;
+
+encode_parameters([P | T], Count, Formats, Values) ->
+    {Format, Value} = encode_parameter(P),
+    Formats2 = <<Formats/binary, Format:?int16>>,
+    Values2 = <<Values/binary, Value/binary>>,
+    encode_parameters(T, Count + 1, Formats2, Values2).
+
+%% encode parameter
+
+encode_parameter({Type, Value}) ->
+    case pgsql_binary:encode(Type, Value) of
+        Bin when is_binary(Bin) -> {1, Bin};
+        {error, unsupported}    -> {0, Value}
+    end;
+encode_parameter(null)                 -> {1, pgsql_binary:encode(null, null)};
+encode_parameter(A) when is_atom(A)    -> {0, encode_list(atom_to_list(A))};
+encode_parameter(B) when is_binary(B)  -> {0, <<(byte_size(B)):?int32, B/binary>>};
+encode_parameter(I) when is_integer(I) -> {0, encode_list(integer_to_list(I))};
+encode_parameter(F) when is_float(F)   -> {0, encode_list(float_to_list(F))};
+encode_parameter(L) when is_list(L)    -> {0, encode_list(L)}.
+
+encode_list(L) ->
+    Bin = list_to_binary(L),
+    <<(byte_size(Bin)):?int32, Bin/binary>>.
+
+notify(#state{reply_to = {Pid, _Tag}}, Msg) ->
+    Pid ! {pgsql, self(), Msg}.
+
+lower_atom(Str) when is_binary(Str) ->
+    lower_atom(binary_to_list(Str));
+lower_atom(Str) when is_list(Str) ->
+    list_to_atom(string:to_lower(Str)).
+
+to_binary(B) when is_binary(B) -> B;
+to_binary(L) when is_list(L)   -> list_to_binary(L).
+
+hex(Bin) ->
+    HChar = fun(N) when N < 10 -> $0 + N;
+               (N) when N < 16 -> $W + N
+            end,
+    <<<<(HChar(H)), (HChar(L))>> || <<H:4, L:4>> <= Bin>>.
+
+%% send data to server
+
+send(#state{sock = Sock}, Type, Data) ->
+    Bin = iolist_to_binary(Data),
+    gen_tcp:send(Sock, <<Type:8, (byte_size(Bin) + 4):?int32, Bin/binary>>).    
+
+send(#state{sock = Sock}, Data) ->
+    Bin = iolist_to_binary(Data),
+    gen_tcp:send(Sock, <<(byte_size(Bin) + 4):?int32, Bin/binary>>).
+
+%% -- socket read loop --
+
+read(Fsm, Sock, Tail) ->
+    case gen_tcp:recv(Sock, 0) of
+        {ok, Bin} -> decode(Fsm, Sock, <<Tail/binary, Bin/binary>>);
+        Error     -> exit(Error)
+    end.
+
+decode(Fsm, Sock, <<Type:8, Len:?int32, Rest/binary>> = Bin) ->
+    Len2 = Len - 4,
+    case Rest of
+        <<Data:Len2/binary, Tail/binary>> when Type == $N ->
+            gen_fsm:send_all_state_event(Fsm, {notice, decode_error(Data)}),
+            decode(Fsm, Sock, Tail);
+        <<Data:Len2/binary, Tail/binary>> when Type == $S ->
+            [Name, Value] = decode_strings(Data),
+            gen_fsm:send_all_state_event(Fsm, {parameter_status, Name, Value}),
+            decode(Fsm, Sock, Tail);
+        <<Data:Len2/binary, Tail/binary>> ->
+            gen_fsm:send_event(Fsm, {Type, Data}),
+            decode(Fsm, Sock, Tail);
+        _Other ->
+            read(Fsm, Sock, Bin)
+    end;
+decode(Fsm, Sock, Bin) ->
+    read(Fsm, Sock, Bin).

+ 160 - 0
src/pgsql_types.erl

@@ -0,0 +1,160 @@
+-module(pgsql_types).
+
+-export([oid2type/1, type2oid/1]).
+
+oid2type(16)   -> bool;
+oid2type(17)   -> bytea;
+oid2type(18)   -> char;
+oid2type(19)   -> name;
+oid2type(20)   -> int8;
+oid2type(21)   -> int2;
+oid2type(22)   -> int2vector;
+oid2type(23)   -> int4;
+oid2type(24)   -> regproc;
+oid2type(25)   -> text;
+oid2type(26)   -> oid;
+oid2type(27)   -> tid;
+oid2type(28)   -> xid;
+oid2type(29)   -> cid;
+oid2type(30)   -> oidvector;
+oid2type(71)   -> pg_type_reltype;
+oid2type(75)   -> pg_attribute_reltype;
+oid2type(81)   -> pg_proc_reltype;
+oid2type(83)   -> pg_class_reltype;
+oid2type(142)  -> xml;
+oid2type(600)  -> point;
+oid2type(601)  -> lseg;
+oid2type(602)  -> path;
+oid2type(603)  -> box;
+oid2type(604)  -> polygon;
+oid2type(628)  -> line;
+oid2type(700)  -> float4;
+oid2type(701)  -> float8;
+oid2type(702)  -> abstime;
+oid2type(703)  -> reltime;
+oid2type(704)  -> tinterval;
+oid2type(705)  -> unknown;
+oid2type(718)  -> circle;
+oid2type(790)  -> cash;
+oid2type(829)  -> macaddr;
+oid2type(869)  -> inet;
+oid2type(650)  -> cidr;
+oid2type(1007) -> int4array;
+oid2type(1021) -> float4array;
+oid2type(1033) -> aclitem;
+oid2type(1263) -> cstringarray;
+oid2type(1042) -> bpchar;
+oid2type(1043) -> varchar;
+oid2type(1082) -> date;
+oid2type(1083) -> time;
+oid2type(1114) -> timestamp;
+oid2type(1184) -> timestamptz;
+oid2type(1186) -> interval;
+oid2type(1266) -> timetz;
+oid2type(1560) -> bit;
+oid2type(1562) -> varbit;
+oid2type(1700) -> numeric;
+oid2type(1790) -> refcursor;
+oid2type(2202) -> regprocedure;
+oid2type(2203) -> regoper;
+oid2type(2204) -> regoperator;
+oid2type(2205) -> regclass;
+oid2type(2206) -> regtype;
+oid2type(2211) -> regtypearray;
+oid2type(3614) -> tsvector;
+oid2type(3642) -> gtsvector;
+oid2type(3615) -> tsquery;
+oid2type(3734) -> regconfig;
+oid2type(3769) -> regdictionary;
+oid2type(2249) -> record;
+oid2type(2275) -> cstring;
+oid2type(2276) -> any;
+oid2type(2277) -> anyarray;
+oid2type(2278) -> void;
+oid2type(2279) -> trigger;
+oid2type(2280) -> language_handler;
+oid2type(2281) -> internal;
+oid2type(2282) -> opaque;
+oid2type(2283) -> anyelement;
+oid2type(2776) -> anynonarray;
+oid2type(3500) -> anyenum;
+oid2type(Oid)  -> {unknown_oid, Oid}.
+
+type2oid(bool)                  -> 16;
+type2oid(bytea)                 -> 17;
+type2oid(char)                  -> 18;
+type2oid(name)                  -> 19;
+type2oid(int8)                  -> 20;
+type2oid(int2)                  -> 21;
+type2oid(int2vector)            -> 22;
+type2oid(int4)                  -> 23;
+type2oid(regproc)               -> 24;
+type2oid(text)                  -> 25;
+type2oid(oid)                   -> 26;
+type2oid(tid)                   -> 27;
+type2oid(xid)                   -> 28;
+type2oid(cid)                   -> 29;
+type2oid(oidvector)             -> 30;
+type2oid(pg_type_reltype)       -> 71;
+type2oid(pg_attribute_reltype)  -> 75;
+type2oid(pg_proc_reltype)       -> 81;
+type2oid(pg_class_reltype)      -> 83;
+type2oid(xml)                   -> 142;
+type2oid(point)                 -> 600;
+type2oid(lseg)                  -> 601;
+type2oid(path)                  -> 602;
+type2oid(box)                   -> 603;
+type2oid(polygon)               -> 604;
+type2oid(line)                  -> 628;
+type2oid(float4)                -> 700;
+type2oid(float8)                -> 701;
+type2oid(abstime)               -> 702;
+type2oid(reltime)               -> 703;
+type2oid(tinterval)             -> 704;
+type2oid(unknown)               -> 705;
+type2oid(circle)                -> 718;
+type2oid(cash)                  -> 790;
+type2oid(macaddr)               -> 829;
+type2oid(inet)                  -> 869;
+type2oid(cidr)                  -> 650;
+type2oid(int4array)             -> 1007;
+type2oid(float4array)           -> 1021;
+type2oid(aclitem)               -> 1033;
+type2oid(cstringarray)          -> 1263;
+type2oid(bpchar)                -> 1042;
+type2oid(varchar)               -> 1043;
+type2oid(date)                  -> 1082;
+type2oid(time)                  -> 1083;
+type2oid(timestamp)             -> 1114;
+type2oid(timestamptz)           -> 1184;
+type2oid(interval)              -> 1186;
+type2oid(timetz)                -> 1266;
+type2oid(bit)                   -> 1560;
+type2oid(varbit)                -> 1562;
+type2oid(numeric)               -> 1700;
+type2oid(refcursor)             -> 1790;
+type2oid(regprocedure)          -> 2202;
+type2oid(regoper)               -> 2203;
+type2oid(regoperator)           -> 2204;
+type2oid(regclass)              -> 2205;
+type2oid(regtype)               -> 2206;
+type2oid(regtypearray)          -> 2211;
+type2oid(tsvector)              -> 3614;
+type2oid(gtsvector)             -> 3642;
+type2oid(tsquery)               -> 3615;
+type2oid(regconfig)             -> 3734;
+type2oid(regdictionary)         -> 3769;
+type2oid(record)                -> 2249;
+type2oid(cstring)               -> 2275;
+type2oid(any)                   -> 2276;
+type2oid(anyarray)              -> 2277;
+type2oid(void)                  -> 2278;
+type2oid(trigger)               -> 2279;
+type2oid(language_handler)      -> 2280;
+type2oid(internal)              -> 2281;
+type2oid(opaque)                -> 2282;
+type2oid(anyelement)            -> 2283;
+type2oid(anynonarray)           -> 2776;
+type2oid(anyenum)               -> 3500;
+type2oid(Type)                  -> {unknown_type, Type}.
+

+ 0 - 0
test_ebin/.empty


+ 384 - 0
test_src/pgsql_tests.erl

@@ -0,0 +1,384 @@
+-module(pgsql_tests).
+
+-export([run_tests/0]).
+
+-include_lib("eunit/include/eunit.hrl").
+-include("pgsql.hrl").
+
+-define(host, "localhost").
+
+connect_test() ->
+    connect_only([[]]).
+
+connect_to_db_test() ->
+    connect_only([[{database, "epgsql_test_db1"}]]).
+
+connect_as_test() ->
+    connect_only(["epgsql_test1", [{database, "epgsql_test_db1"}]]).
+
+connect_with_cleartext_test() ->
+    connect_only(["epgsql_test_cleartext",
+                  "epgsql_test_cleartext",
+                  [{database, "epgsql_test_db1"}]]).
+
+connect_with_md5_test() ->
+    connect_only(["epgsql_test_md5",
+                  "epgsql_test_md5",
+                  [{database, "epgsql_test_db1"}]]).
+
+connect_with_invalid_password_test() ->
+    {error, invalid_authorization_specification} =
+        pgsql:connect(?host,
+                      "epgsql_test_md5",
+                      "epgsql_test_sha1",
+                      [{database, "epgsql_test_db1"}]).
+
+select_test() ->
+    with_connection(
+      fun(C) ->
+              {ok, Cols, Rows} = pgsql:squery(C, "select * from test_table1"),
+              [#column{name = <<"id">>, type = int4, size = 4},
+               #column{name = <<"value">>, type = text, size = -1}] = Cols,
+              [{<<"1">>, <<"one">>}, {<<"2">>, <<"two">>}] = Rows
+      end).
+
+insert_test() ->
+    with_rollback(
+      fun(C) ->
+              {ok, 1} = pgsql:squery(C, "insert into test_table1 (id, value) values (3, 'three')")
+      end).
+
+delete_test() ->
+    with_rollback(
+      fun(C) ->
+              {ok, 1} = pgsql:squery(C, "insert into test_table1 (id, value) values (3, 'three')"),
+              {ok, 1} = pgsql:squery(C, "insert into test_table1 (id, value) values (4, 'four')"),
+              {ok, 2} = pgsql:squery(C, "delete from test_table1 where id > 2"),
+              {ok, _, [{<<"2">>}]} = pgsql:squery(C, "select count(*) from test_table1")
+      end).
+
+update_test() ->
+    with_rollback(
+      fun(C) ->
+              {ok, 1} = pgsql:squery(C, "insert into test_table1 (id, value) values (3, 'three')"),
+              {ok, 1} = pgsql:squery(C, "insert into test_table1 (id, value) values (4, 'four')"),
+              {ok, 2} = pgsql:squery(C, "update test_table1 set value = 'foo' where id > 2"),
+              {ok, _, [{<<"2">>}]} = pgsql:squery(C, "select count(*) from test_table1 where value = 'foo'")
+      end).
+
+multiple_result_test() ->
+    with_connection(
+      fun(C) ->
+              [{ok, _, [{<<"1">>}]}, {ok, _, [{<<"2">>}]}] = pgsql:squery(C, "select 1; select 2"),
+              [{ok, _, [{<<"1">>}]}, {error, #error{}}] = pgsql:squery(C, "select 1; select foo;")
+      end).
+
+extended_select_test() ->
+    with_connection(
+      fun(C) ->
+              {ok, Cols, Rows} = pgsql:equery(C, "select * from test_table1", []),
+              [#column{name = <<"id">>, type = int4, size = 4},
+               #column{name = <<"value">>, type = text, size = -1}] = Cols,
+              [{1, <<"one">>}, {2, <<"two">>}] = Rows
+      end).
+
+extended_sync_ok_test() ->
+    with_connection(
+      fun(C) ->
+              {ok, _Cols, [{<<"one">>}]} = pgsql:equery(C, "select value from test_table1 where id = $1", [1]),
+              {ok, _Cols, [{<<"two">>}]} = pgsql:equery(C, "select value from test_table1 where id = $1", [2])
+      end).
+
+extended_sync_error_test() ->
+    with_connection(
+      fun(C) ->
+              {error, #error{}} = pgsql:equery(C, "select _alue from test_table1 where id = $1", [1]),
+              {ok, _Cols, [{<<"one">>}]} = pgsql:equery(C, "select value from test_table1 where id = $1", [1])
+      end).
+
+
+parse_test() ->
+    with_connection(
+      fun(C) ->
+              {ok, S} = pgsql:parse(C, "select * from test_table1"),
+              [#column{name = <<"id">>}, #column{name = <<"value">>}] = S#statement.columns,
+              ok = pgsql:close(C, S),
+              ok = pgsql:sync(C)
+      end).
+
+parse_column_format_test() ->
+    with_connection(
+      fun(C) ->
+              {ok, S} = pgsql:parse(C, "select 1::int4, false::bool, 2.0::float4"),
+              [#column{type = int4},
+               #column{type = bool},
+               #column{type = float4}] = S#statement.columns,
+              ok = pgsql:bind(C, S, []),
+              {ok, [{1, false, 2.0}]} = pgsql:execute(C, S, 0),
+              ok = pgsql:close(C, S),
+              ok = pgsql:sync(C)
+      end).
+
+parse_error_test() ->
+    with_connection(
+      fun(C) ->
+              {error, #error{}} = pgsql:parse(C, "select _ from test_table1"),
+              {ok, S} = pgsql:parse(C, "select * from test_table1"),
+              [#column{name = <<"id">>}, #column{name = <<"value">>}] = S#statement.columns,
+              ok = pgsql:close(C, S),
+              ok = pgsql:sync(C)
+      end).
+
+parse_and_close_test() ->
+    with_connection(
+      fun(C) ->
+              Parse = fun() -> pgsql:parse(C, "test", "select * from test_table1", []) end,
+              {ok, S} = Parse(),
+              {error, #error{code = <<"42P05">>}} = Parse(),
+              pgsql:close(C, S),
+              {ok, S} = Parse(),
+              ok = pgsql:sync(C)
+      end).
+
+bind_test() ->
+    with_connection(
+      fun(C) ->
+              {ok, S} = pgsql:parse(C, "select value from test_table1 where id = $1"),
+              ok = pgsql:bind(C, S, [1]),
+              ok = pgsql:close(C, S),
+              ok = pgsql:sync(C)
+      end).
+
+bind_parameter_format_test() ->
+    with_connection(
+      fun(C) ->
+              {ok, S} = pgsql:parse(C, "select $1, $2, $3", [int2, text, bool]),
+              [int2, text, bool] = S#statement.types,
+              ok = pgsql:bind(C, S, [1, "hi", true]),
+              {ok, [{1, <<"hi">>, true}]} = pgsql:execute(C, S, 0),
+              ok = pgsql:close(C, S),
+              ok = pgsql:sync(C)
+      end).
+
+bind_error_test() ->
+    with_connection(
+      fun(C) ->
+              {ok, S} = pgsql:parse(C, "select $1::char"),
+              {error, #error{}} = pgsql:bind(C, S, [0]),
+              ok = pgsql:bind(C, S, [$A]),
+              ok = pgsql:close(C, S),
+              ok = pgsql:sync(C)
+      end).
+
+bind_and_close_test() ->
+    with_connection(
+      fun(C) ->
+              {ok, S} = pgsql:parse(C, "select * from test_table1"),
+              ok = pgsql:bind(C, S, "one", []),
+              {error, #error{code = <<"42P03">>}} = pgsql:bind(C, S, "one", []),
+              ok = pgsql:close(C, portal, "one"),
+              ok = pgsql:bind(C, S, "one", []),
+              ok = pgsql:sync(C)
+      end).
+
+describe_test() ->
+    with_connection(
+      fun(C) ->
+              {ok, S} = pgsql:parse(C, "select * from test_table1"),
+              [#column{name = <<"id">>}, #column{name = <<"value">>}] = S#statement.columns,
+              {ok, S} = pgsql:describe(C, S),
+              ok = pgsql:close(C, S),
+              ok = pgsql:sync(C)
+      end).
+
+describe_with_param_test() ->
+    with_connection(
+      fun(C) ->
+              {ok, S} = pgsql:parse(C, "select id from test_table1 where id = $1"),
+              [int4] = S#statement.types,
+              [#column{name = <<"id">>}] = S#statement.columns,
+              {ok, S} = pgsql:describe(C, S),
+              ok = pgsql:close(C, S),
+              ok = pgsql:sync(C)
+      end).
+
+describe_named_test() ->
+    with_connection(
+      fun(C) ->
+              {ok, S} = pgsql:parse(C, "name", "select * from test_table1", []),
+              [#column{name = <<"id">>}, #column{name = <<"value">>}] = S#statement.columns,
+              {ok, S} = pgsql:describe(C, S),
+              ok = pgsql:close(C, S),
+              ok = pgsql:sync(C)
+      end).
+
+describe_error_test() ->
+    with_connection(
+      fun(C) ->
+              {error, #error{}} = pgsql:describe(C, statement, ""),
+              {ok, S} = pgsql:parse(C, "select * from test_table1"),
+              {ok, S} = pgsql:describe(C, statement, ""),
+              ok = pgsql:sync(C)
+      
+      end).
+
+portal_test() ->
+    with_connection(
+      fun(C) ->
+              {ok, S} = pgsql:parse(C, "select value from test_table1"),
+              ok = pgsql:bind(C, S, []),
+              {partial, [{<<"one">>}]} = pgsql:execute(C, S, 1),
+              {partial, [{<<"two">>}]} = pgsql:execute(C, S, 1),
+              {ok, []} = pgsql:execute(C, S,1),
+              ok = pgsql:close(C, S),
+              ok = pgsql:sync(C)
+      end).
+
+multiple_statement_test() ->
+    with_connection(
+      fun(C) ->
+              {ok, S1} = pgsql:parse(C, "one", "select value from test_table1 where id = 1", []),
+              ok = pgsql:bind(C, S1, []),
+              {partial, [{<<"one">>}]} = pgsql:execute(C, S1, 1),
+              {ok, S2} = pgsql:parse(C, "two", "select value from test_table1 where id = 2", []),
+              ok = pgsql:bind(C, S2, []),
+              {partial, [{<<"two">>}]} = pgsql:execute(C, S2, 1),
+              {ok, []} = pgsql:execute(C, S1, 1),
+              {ok, []} = pgsql:execute(C, S2, 1),
+              ok = pgsql:close(C, S1),
+              ok = pgsql:close(C, S2),
+              ok = pgsql:sync(C)
+      end).
+
+multiple_portal_test() ->
+    with_connection(
+      fun(C) ->
+              {ok, S} = pgsql:parse(C, "select value from test_table1 where id = $1"),
+              ok = pgsql:bind(C, S, "one", [1]),
+              ok = pgsql:bind(C, S, "two", [2]),
+              {ok, [{<<"one">>}]} = pgsql:execute(C, S, "one", 0),
+              {ok, [{<<"two">>}]} = pgsql:execute(C, S, "two", 0),
+              ok = pgsql:close(C, S),
+              ok = pgsql:sync(C)
+      end).
+
+execute_function_test() ->
+    with_rollback(
+      fun(C) ->
+              {ok, _Cols1, [{3}]} = pgsql:equery(C, "select insert_test1(3, 'three')"),
+              {ok, _Cols2, [{<<>>}]} = pgsql:equery(C, "select do_nothing()")
+      end).
+
+parameter_get_test() ->
+    with_connection(
+      fun(C) ->
+              {ok, <<"off">>} = pgsql:get_parameter(C, "integer_datetimes")
+      end).
+
+parameter_set_test() ->
+    with_connection(
+      fun(C) ->
+              {ok, [], []} = pgsql:squery(C, "set DateStyle = 'ISO, MDY'"),
+              {ok, <<"ISO, MDY">>} = pgsql:get_parameter(C, "DateStyle"),
+              {ok, _Cols, [{<<"2000-01-02">>}]} = pgsql:squery(C, "select '2000-01-02'::date"),
+              {ok, [], []} = pgsql:squery(C, "set DateStyle = 'German'"),
+              {ok, <<"German, DMY">>} = pgsql:get_parameter(C, "DateStyle"),
+              {ok, _Cols, [{<<"02.01.2000">>}]} = pgsql:squery(C, "select '2000-01-02'::date")
+      end).
+
+decode_binary_format_test() ->
+    with_connection(
+      fun(C) ->
+              {ok, [#column{type = unknown}], [{null}]} = pgsql:equery(C, "select null"),
+              {ok, [#column{type = bool}], [{true}]} = pgsql:equery(C, "select true"),
+              {ok, [#column{type = bool}], [{false}]} = pgsql:equery(C, "select false"),
+              {ok, [#column{type = bpchar}], [{$A}]} = pgsql:equery(C, "select 'A'::char"),
+              {ok, [#column{type = int2}], [{1}]} = pgsql:equery(C, "select 1::int2"),
+              {ok, [#column{type = int2}], [{-1}]} = pgsql:equery(C, "select -1::int2"),
+              {ok, [#column{type = int4}], [{1}]} = pgsql:equery(C, "select 1::int4"),
+              {ok, [#column{type = int4}], [{-1}]} = pgsql:equery(C, "select -1::int4"),
+              {ok, [#column{type = int8}], [{1}]} = pgsql:equery(C, "select 1::int8"),
+              {ok, [#column{type = int8}], [{-1}]} = pgsql:equery(C, "select -1::int8"),
+              {ok, [#column{type = float4}], [{1.0}]} = pgsql:equery(C, "select 1.0::float4"),
+              {ok, [#column{type = float4}], [{-1.0}]} = pgsql:equery(C, "select -1.0::float4"),
+              {ok, [#column{type = float8}], [{1.0}]} = pgsql:equery(C, "select 1.0::float8"),
+              {ok, [#column{type = float8}], [{-1.0}]} = pgsql:equery(C, "select -1.0::float8"),
+              {ok, [#column{type = bytea}], [{<<1, 2>>}]} = pgsql:equery(C, "select E'\001\002'::bytea"),
+              {ok, [#column{type = text}], [{<<"hi">>}]} = pgsql:equery(C, "select 'hi'::text"),
+              {ok, [#column{type = varchar}], [{<<"hi">>}]} = pgsql:equery(C, "select 'hi'::varchar"),
+              {ok, [#column{type = record}], [{{1, null, <<"hi">>}}]} = pgsql:equery(C, "select (1, null, 'hi')")
+      end).
+
+encode_binary_format_test() ->
+    with_connection(
+      fun(C) ->
+              {ok, 1} = pgsql:equery(C, "insert into test_table2 (c_bool) values ($1)", [null]),
+              {ok, 1} = pgsql:equery(C, "insert into test_table2 (c_bool) values ($1)", [true]),
+              {ok, 1} = pgsql:equery(C, "insert into test_table2 (c_bool) values ($1)", [false]),
+              {ok, 1} = pgsql:equery(C, "insert into test_table2 (c_char) values ($1)", [$A]),
+              {ok, 1} = pgsql:equery(C, "insert into test_table2 (c_int2) values ($1)", [1]),
+              {ok, 1} = pgsql:equery(C, "insert into test_table2 (c_int2) values ($1)", [-1]),
+              {ok, 1} = pgsql:equery(C, "insert into test_table2 (c_int4) values ($1)", [1]),
+              {ok, 1} = pgsql:equery(C, "insert into test_table2 (c_int4) values ($1)", [-1]),
+              {ok, 1} = pgsql:equery(C, "insert into test_table2 (c_int8) values ($1)", [1]),
+              {ok, 1} = pgsql:equery(C, "insert into test_table2 (c_int8) values ($1)", [-1]),
+              {ok, 1} = pgsql:equery(C, "insert into test_table2 (c_float4) values ($1)", [1.0]),
+              {ok, 1} = pgsql:equery(C, "insert into test_table2 (c_float4) values ($1)", [-1.0]),
+              {ok, 1} = pgsql:equery(C, "insert into test_table2 (c_float8) values ($1)", [1.0]),
+              {ok, 1} = pgsql:equery(C, "insert into test_table2 (c_float8) values ($1)", [-1.0]),
+              {ok, 1} = pgsql:equery(C, "insert into test_table2 (c_bytea) values ($1)", [<<1, 2>>]),
+              {ok, 1} = pgsql:equery(C, "insert into test_table2 (c_bytea) values ($1)", [[1, 2]]),
+              {ok, 1} = pgsql:equery(C, "insert into test_table2 (c_text) values ($1)", [<<"hi">>]),
+              {ok, 1} = pgsql:equery(C, "insert into test_table2 (c_text) values ($1)", ["hi"]),
+              {ok, 1} = pgsql:equery(C, "insert into test_table2 (c_varchar) values ($1)", [<<"hi">>]),
+              {ok, 1} = pgsql:equery(C, "insert into test_table2 (c_varchar) values ($1)", ["hi"])
+      end).
+
+%% -- run all tests --
+
+run_tests() ->
+    crypto:start(),
+    Files = filelib:wildcard("test_ebin/*tests.beam"),
+    Mods = [list_to_atom(filename:basename(F, ".beam")) || F <- Files],
+    eunit:test(Mods, []).
+
+%% -- internal functions --
+
+connect_only(Args) ->
+    {ok, C} = apply(pgsql, connect, [?host | Args]),
+    pgsql:close(C),
+    flush().
+
+with_connection(F) ->
+    {ok, C} = pgsql:connect(?host, "epgsql_test1", [{database, "epgsql_test_db1"}]),
+    try
+        F(C)
+    after
+        pgsql:close(C)
+    end,
+    flush().
+
+
+with_rollback(F) ->
+    with_connection(
+      fun(C) ->
+              try
+                  pgsql:squery(C, "begin"),
+                  F(C)
+                  after
+                      pgsql:squery(C, "rollback")
+                  end
+      end).
+
+%% flush mailbox
+flush() ->
+    ?assertEqual([], flush([])).
+
+flush(Acc) ->
+    receive
+        {'EXIT', _Pid, normal} -> flush(Acc);
+        M                      -> flush([M | Acc])
+    after
+        0 -> lists:reverse(Acc)
+    end.
+

+ 65 - 0
test_src/test_schema.sql

@@ -0,0 +1,65 @@
+-- script to create test schema for epgsql unit tests --
+--
+-- this script should be run as the same user the tests will be run as,
+-- so that the test for connecting as the 'current user' succeeds
+--
+-- the following lines must be added to pg_hba.conf for the relevant
+-- auth tests to succeed:
+--
+-- host    epgsql_test_db1 epgsql_test_md5         127.0.0.1/32    md5
+-- host    epgsql_test_db1 epgsql_test_cleartext   127.0.0.1/32    password
+
+
+CREATE USER epgsql_test;
+CREATE USER epgsql_test_md5 WITH PASSWORD 'epgsql_test_md5';
+CREATE USER epgsql_test_cleartext WITH PASSWORD 'epgsql_test_cleartext';
+
+CREATE DATABASE epgsql_test_db1;
+CREATE DATABASE epgsql_test_db2;
+
+GRANT ALL ON DATABASE epgsql_test_db1 to epgsql_test;
+GRANT ALL ON DATABASE epgsql_test_db1 to epgsql_test_md5;
+GRANT ALL ON DATABASE epgsql_test_db1 to epgsql_test_cleartext;
+GRANT ALL ON DATABASE epgsql_test_db2 to epgsql_test;
+
+\c epgsql_test_db1;
+
+CREATE TABLE test_table1 (id integer primary key, value text);
+
+INSERT INTO test_table1 (id, value) VALUES (1, 'one');
+INSERT INTO test_table1 (id, value) VALUES (2, 'two');
+
+CREATE TABLE test_table2 (
+  c_bool bool,
+  c_char char,  
+  c_int2 int2,
+  c_int4 int4,
+  c_int8 int8,
+  c_float4 float4,
+  c_float8 float8,
+  c_bytea bytea,
+  c_text text,
+  c_varchar varchar(64));
+
+CREATE LANGUAGE plpgsql;
+
+CREATE OR REPLACE FUNCTION insert_test1(_id integer, _value text)
+returns integer
+as $$
+begin
+  insert into test_table1 (id, value) values (_id, _value);
+  return _id;
+end
+$$ language plpgsql;
+
+CREATE OR REPLACE FUNCTION do_nothing()
+returns void
+as $$
+begin
+end
+$$ language plpgsql;
+
+GRANT ALL ON TABLE test_table1 TO epgsql_test1;
+GRANT ALL ON TABLE test_table2 TO epgsql_test1;
+GRANT ALL ON FUNCTION insert_test1(integer, text) TO epgsql_test1;
+GRANT ALL ON FUNCTION do_nothing() TO epgsql_test1;