Skip to content

scull7/bs-sql-composer

Repository files navigation

Build Status Coverage Status

bs-sql-composer

A library for SQL composition in BucklesScript

Usage

Basic Select

  SqlComposer.Select.(
    make()
    |. field("*")
    |. from("test")
    |. toSql
    |. Js.log
  );
SELECT
  *
FROM test
WHERE 1=1

Where Clause

There is an implicit WHERE 1=1 added to every query. This is done to eliminate confusion with compound queries regarding the concatenation of where clauses.

  SqlComposer.Select.(
    make()
    |. field("*")
    |. from("test")
    |. where("AND test.foo = ?")
    |. toSql
    |. Js.log
  );
SELECT
  *
FROM test
WHERE 1=1
AND test.foo = ?

Join Clause

  SqlComposer.Select.(
    make()
    |. field("*")
    |. from("test")
    |. join("JOIN foo ON test.foo_id = foo.id")
    |. toSql
    |. Js.log
  )
SELECT
  *
FROM test
JOIN foo ON test.foo_id = foo.id
WHERE 1=1

Adding to a base query

  let base_query = SqlComposer.Select.(
    make()
    |. from("test")
    |. field("foo")
    |. field("bar")
  );

  SqlComposer.Select.(
    base_query
    |. where("AND test.foo = ?")
    |. toSql
    |. Js.log
  );
SELECT
  foo
, bar
FROM test
WHERE 1=1
AND test.foo = ?

Alias a field

SqlComposer.Select.(
  make()
  |. from("test")
  |. field("foo AS bar")
  |. toSql
  |. Js.log
);
SELECT
  foo AS bar
FROM test
WHERE 1=1

Order By

SqlComposer.Select.(
  make()
  |. from("test")
  |. field("*")
  |. orderBy(`Asc("foo"))
  |. orderBy(`Desc("bar"))
  |. toSql
  |. Js.log
);
SELECT
  *
FROM test
WHERE 1=1
ORDER BY
  foo ASC
, bar DESC

Group By

SqlComposer.Select.(
  make()
  |. from("test")
  |. field("foo AS bar")
  |. groupBy("foo")
  |. groupBy("thing")
);
SELECT
  foo AS bar
FROM test
WHERE 1=1
GROUP BY
  foo
, thing

Select Distinct

SqlComposer.Select.(
  make()
  |. field("foo")
  |. from("test")
  |. modifier(`Distinct)
);
SELECT DISTINCT
  foo
FROM test
WHERE 1=1

How do I install it?

Inside of a BuckleScript project:

yarn install --save bs-sql-composer

Then add bs-sql-composer to your bs-dependencies in bsconfig.json:

{
  "bs-dependencies": [ "bs-sql-composer" ]
}

About

A library for SQL composition in BucklesScript

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages