Permalink
Browse files

initial import of epgsql

  • Loading branch information...
wg committed Dec 28, 2008
0 parents commit ba47564c3fbc9a9d43191a8d64eae0c580401f7c
Showing with 1,602 additions and 0 deletions.
  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 test_ebin/.empty
  13. +384 −0 test_src/pgsql_tests.erl
  14. +65 −0 test_src/test_schema.sql
@@ -0,0 +1,4 @@
+\.beam
+\.boot
+\.script
+
10 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.
@@ -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 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).
@@ -0,0 +1,4 @@
+-record(column, {name, type, size, modifier, format}).
+-record(statement, {name, columns, types}).
+
+-record(error, {severity, code, message, extra}).
@@ -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, []}]}.
@@ -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.
@@ -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.
Oops, something went wrong.

0 comments on commit ba47564

Please sign in to comment.