• Stars
    star
    489
  • Rank 89,990 (Top 2 %)
  • Language
    Haskell
  • License
    MIT License
  • Created about 10 years ago
  • Updated over 1 year ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

The fastest PostgreSQL libpq-based driver for Haskell

Summary

Hasql is a highly efficient PostgreSQL driver for Haskell with a typesafe yet flexible mapping API. It targets both the users, who need maximum control, and the users who face the typical tasks of DB-powered applications, providing them with higher-level APIs. Currently it is known to be the fastest driver in the Haskell ecosystem.

Hasql also is one of the supported targets of the pGenie code generator, which empowers it with schema and query validation, and relieves you from boilerplate.

Status

Hackage

Hasql is production-ready, actively maintained and the API is pretty stable. It's used by many companies and most notably by the Postgrest project.

Ecosystem

Hasql is not just a single library, it is a granular ecosystem of composable libraries, each isolated to perform its own task and stay simple.

  • "hasql" - the root of the ecosystem, which provides the essential abstraction over the PostgreSQL client functionality and mapping of values. Everything else revolves around that library.

  • "hasql-th" - Template Haskell utilities, providing compile-time syntax checking and easy statement declaration.

  • "hasql-transaction" - an STM-inspired composable abstraction over database transactions providing automated conflict resolution.

  • "hasql-dynamic-statements" - a toolkit for generating statements based on the parameters.

  • "hasql-cursor-query" - a declarative abstraction over cursors.

  • "hasql-cursor-transaction" - a lower-level abstraction over cursors, which however allows to fetch from multiple cursors simultaneously. Generally though "hasql-cursor-query" is the recommended alternative.

  • "hasql-pool" - a Hasql-specialized abstraction over the connection pool.

  • "hasql-migration" - A port of postgresql-simple-migration for use with hasql.

  • "hasql-listen-notify" / "hasql-notifications" - Support for PostgreSQL asynchronous notifications.

  • "hasql-optparse-applicative" - "optparse-applicative" parsers for Hasql.

  • "hasql-implicits" - implicit definitions, such as default codecs for standard types.

  • "hasql-interpolate" - a QuasiQuoter that supports interpolating Haskell expressions into Hasql queries.

Benefits of being an ecosystem

  • Simplicity. Each library in isolation provides a simple API, which is hopefully easier to comprehend.

  • Flexibility and composability. The user picks and chooses the features, thus precisely matching the level of abstraction that he needs for his task.

  • Much more stable and more descriptive semantic versioning. E.g., a change in the API of the "hasql-transaction" library won't affect any of the other libraries and it gives the user a more precise information about which part of his application he needs to update to conform.

  • Interchangeability and competition of the ecosystem components. E.g., not everyone will agree with the restrictive design decisions made in the "hasql-transaction" library. However those decisions are not imposed on the user, and instead of having endless debates about how to abstract over transactions, another extension library can simply be released, which will provide a different interpretation of what the abstraction over transactions should be.

  • Horizontal scalability of the ecosystem. Instead of posting feature- or pull-requests, the users are encouraged to release their own small extension-libraries, with themselves becoming the copyright owners and taking on the maintenance responsibilities. Compare this model to the classical one, where some core-team is responsible for everything. One is scalable, the other is not.

Tutorials

Short Example

Following is a complete application, which performs some arithmetic in Postgres using Hasql.

{-# LANGUAGE OverloadedStrings, QuasiQuotes #-}
import Prelude
import Data.Int
import Data.Functor.Contravariant
import Hasql.Session (Session)
import Hasql.Statement (Statement(..))
import qualified Hasql.Session as Session
import qualified Hasql.Decoders as Decoders
import qualified Hasql.Encoders as Encoders
import qualified Hasql.Connection as Connection


main :: IO ()
main = do
  Right connection <- Connection.acquire connectionSettings
  result <- Session.run (sumAndDivModSession 3 8 3) connection
  print result
  where
    connectionSettings = Connection.settings "localhost" 5432 "postgres" "" "postgres"


-- * Sessions
-- 
-- Session is an abstraction over the database connection and all possible errors.
-- It is used to execute statements.
-- It is composable and has a Monad instance.
-- 
-- It's recommended to define sessions in a dedicated 'Sessions'
-- submodule of your project.
-------------------------

sumAndDivModSession :: Int64 -> Int64 -> Int64 -> Session (Int64, Int64)
sumAndDivModSession a b c = do
  -- Get the sum of a and b
  sumOfAAndB <- Session.statement (a, b) sumStatement
  -- Divide the sum by c and get the modulo as well
  Session.statement (sumOfAAndB, c) divModStatement


-- * Statements
-- 
-- Statement is a definition of an individual SQL-statement,
-- accompanied by a specification of how to encode its parameters and
-- decode its result.
-- 
-- It's recommended to define statements in a dedicated 'Statements'
-- submodule of your project.
-------------------------

sumStatement :: Statement (Int64, Int64) Int64
sumStatement = Statement sql encoder decoder True where
  sql = "select $1 + $2"
  encoder =
    (fst >$< Encoders.param (Encoders.nonNullable Encoders.int8)) <>
    (snd >$< Encoders.param (Encoders.nonNullable Encoders.int8))
  decoder = Decoders.singleRow (Decoders.column (Decoders.nonNullable Decoders.int8))

divModStatement :: Statement (Int64, Int64) (Int64, Int64)
divModStatement = Statement sql encoder decoder True where
  sql = "select $1 / $2, $1 % $2"
  encoder =
    (fst >$< Encoders.param (Encoders.nonNullable Encoders.int8)) <>
    (snd >$< Encoders.param (Encoders.nonNullable Encoders.int8))
  decoder = Decoders.singleRow row where
    row =
      (,) <$>
      Decoders.column (Decoders.nonNullable Decoders.int8) <*>
      Decoders.column (Decoders.nonNullable Decoders.int8)

For the general use-case it is advised to prefer declaring statements using the "hasql-th" library, which validates the statements at compile-time and generates codecs automatically. So the above two statements could be implemented the following way:

import qualified Hasql.TH as TH -- from "hasql-th"

sumStatement :: Statement (Int64, Int64) Int64
sumStatement =
  [TH.singletonStatement|
    select ($1 :: int8 + $2 :: int8) :: int8
    |]

divModStatement :: Statement (Int64, Int64) (Int64, Int64)
divModStatement =
  [TH.singletonStatement|
    select
      (($1 :: int8) / ($2 :: int8)) :: int8,
      (($1 :: int8) % ($2 :: int8)) :: int8
    |]

More Repositories

1

record

Anonymous records
Haskell
243
star
2

refined

Refinement types with static checking
Haskell
179
star
3

hasql-th

Template Haskell utilities for Hasql
Haskell
105
star
4

strelka

A simple, flexible and composable web-router
Haskell
85
star
5

jsonifier

Fast and simple JSON encoding toolkit
Haskell
83
star
6

install-to-project-repo

A script for installing jars to an in-project Maven repository
Python
79
star
7

stm-containers

Containers for STM
Haskell
62
star
8

graph-db

An experimental native Haskell graph database
Haskell
58
star
9

typeclasses

Explicit typeclasses for Elm
Elm
54
star
10

neat-interpolation

A quasiquoter for neat and simple multiline text interpolation
Haskell
53
star
11

domain

Focused domain model declaration toolkit for Haskell
Haskell
47
star
12

sext

A small extensions library for Scala
Scala
37
star
13

compound-types

Sum and Product types and such
Haskell
28
star
14

base-prelude

The most complete prelude formed only from the "base" package
Haskell
27
star
15

rebase

A more progressive alternative to the "base" package
Haskell
26
star
16

slave-thread

A principal solution to ghost threads and silent exceptions
Haskell
23
star
17

hasql-postgres

[Deprecated] A "PostgreSQL" driver for the "hasql" library
Haskell
19
star
18

postgresql-binary

Encoders and decoders for the PostgreSQL's binary format
Haskell
19
star
19

hasql-tutorial1

Tutorial on organisation of Hasql code in a Postgres-integration layer
Haskell
17
star
20

bytestring-tree-builder

A very efficient ByteString builder implementation based on the binary tree
Haskell
17
star
21

rerebase

Reexports from "base" with a bunch of other standard libraries
Haskell
16
star
22

vector-builder

Vector builder
Haskell
15
star
23

postgresql-syntax

PostgreSQL SQL syntax utilities
Yacc
15
star
24

deque

Double-ended queues
Haskell
14
star
25

hasql-pool

A pool of connections for Hasql
Haskell
13
star
26

list-t

ListT done right
Haskell
12
star
27

record-preprocessor

Compiler preprocessor introducing a syntactic extension for anonymous records
Haskell
12
star
28

hasql-transaction

A composable abstraction over retriable transactions for Hasql
Haskell
12
star
29

focus

A general abstraction for manipulating elements of container data structures
Haskell
11
star
30

stm-hamt

STM-specialised Hash Array Mapped Trie
Haskell
9
star
31

hashing-containers

Hashing-based container datastructures for Elm
Elm
9
star
32

bytestring-strict-builder

An efficient strict bytestring builder
Haskell
8
star
33

deferred-folds

Abstractions over deferred folds
Haskell
8
star
34

ptr-poker

Pointer poking action construction and composition toolkit
Haskell
8
star
35

hasql-cursor-query

A declarative abstraction over PostgreSQL Cursor
Haskell
7
star
36

acc

Sequence optimized for monoidal construction and folding
Haskell
7
star
37

ptr

Abstractions for operations on pointers
Haskell
7
star
38

theatre

Minimalistic actor library for Haskell
Haskell
7
star
39

laika

Minimalistic type-checked compile-time template engine
Haskell
7
star
40

conversion

Universal converter between values of different types
Haskell
7
star
41

html-entities

A codec library for HTML-escaped text and HTML-entities
Haskell
7
star
42

binary-parser

A highly-efficient but limited parser API specialised for bytestrings
Haskell
6
star
43

partial-handler

A composable exception handler
Haskell
6
star
44

th-instance-reification

Fixed versions of instances reification functions
Haskell
5
star
45

embrace

A tiny extension library embracing a braceless coding style in Scala
Scala
5
star
46

ez-couch

A CouchDB client library for Haskell
Haskell
5
star
47

messageless

Messageless effects model for Elm
Elm
5
star
48

bit-array

A bit array (aka bitset, bitmap, bit vector) API for numeric types
Haskell
5
star
49

hasql-dynamic-statements

Dynamic statements for Hasql
Haskell
5
star
50

newtype-deriving

Instance derivers for newtype wrappers
Haskell
5
star
51

futures

Haskell
5
star
52

cases

A converter for spinal, snake and camel case
Haskell
5
star
53

text-builder

An efficient strict text builder
Haskell
5
star
54

isomorphism-class

Isomorphism typeclass solving the conversion problem
Haskell
4
star
55

structure-kit

Immutable data structures for all kinds of purposes
Haskell
4
star
56

iri

Haskell
4
star
57

strelka-helloworld

A "Helloworld" application showcasing the "strelka" library
Haskell
4
star
58

optima

Simple and composable options parser
Haskell
4
star
59

success

A version of Either specialised for encoding of success or failure
Haskell
4
star
60

wobsurv

A simple and highly performant HTTP file server
Haskell
4
star
61

strelka-demo

Haskell
4
star
62

strict-list

Strict linked list implementation for Haskell
Haskell
4
star
63

unsequential

An extension removing the sequentiality from monads
Haskell
4
star
64

record-syntax

A library for parsing and processing the Haskell syntax sprinkled with anonymous records
Haskell
4
star
65

transition

Like state-monad but with optional updates
Haskell
3
star
66

supplemented

Early termination for monads
Haskell
3
star
67

fonts

Loading of fonts for Elm
Elm
3
star
68

attoparsec-data

Parsers for the standard Haskell data types
Haskell
3
star
69

remotion

A library for client-server applications based on custom protocols
Haskell
3
star
70

edit-cabal-version.github-action

Haskell
3
star
71

validation

Value validation library for Elm
Elm
3
star
72

json-bytes-builder

Direct-to-bytes JSON Builder
Haskell
3
star
73

kindly

Horizontally composable effects
Haskell
3
star
74

json-incremental-decoder

Incremental JSON parser with early termination and a declarative DSL
Haskell
3
star
75

numeric-qq

Quasi-quoters for numbers of various bases
Haskell
3
star
76

grafika

UI utils for Elm
Elm
3
star
77

hashtables-plus

Extensions for a "hashtables" library
Haskell
3
star
78

conversion-bytestring

"Conversion" instances for the "bytestring" library
Haskell
3
star
79

rebase-generator

A utility for the generation of the "rebase" project
Haskell
3
star
80

html-tokenizer

An "attoparsec"-based HTML tokenizer
Haskell
3
star
81

curly

High level HTTP client based on libcurl
Haskell
3
star
82

contravariant-extras

Extras for the "contravariant" package
Haskell
3
star
83

Fury

A platform independent library of higher order functions for function composing, overloading and asynchronicity in JavaScript and CoffeeScript
CoffeeScript
3
star
84

postgresql-error-codes

PostgreSQL error codes
Haskell
3
star
85

conversion-text

"Conversion" instances for the "text" library
Haskell
3
star
86

lazy

Haskell
3
star
87

mtl-prelude

Reexports of most definitions from "mtl" and "transformers"
Haskell
3
star
88

hasql-cursor-transaction

An abstraction for simultaneous fetching from multiple PostgreSQL cursors
Haskell
3
star
89

json-ast-quickcheck

Compatibility layer for "json-ast" and "QuickCheck"
Haskell
2
star
90

stm-graphs

Experiments with mutable graphs in STM
Haskell
2
star
91

hasql-backend

A backend for Hasql
Haskell
2
star
92

html-compacting

Algorithms for compacting HTML
Haskell
2
star
93

list-t-attoparsec

An "attoparsec" adapter for "list-t"
Haskell
2
star
94

template-haskell-compat-v0208

A backwards compatibility layer for Template Haskell newer than 2.8
Haskell
2
star
95

FuellSys

Fuell library extension of system utilities for node.js
CoffeeScript
2
star
96

markright

Haskell
2
star
97

folding

Elm
2
star
98

url-decoders

Decoders for URL-encoding (aka Percent-encoding)
Haskell
2
star
99

json-ast-json-encoder

Integration of "json-ast" and "json-encoder"
Haskell
2
star
100

bytearray-parsing

Parsing of bytearray-based data
Haskell
2
star