0.1.1 • Published 6 years ago

ts-brain v0.1.1

Weekly downloads
3
License
ISC
Repository
github
Last release
6 years ago

An elegant database query builder for Typescript

Build Status npm version dependencies Status devDependencies Status

Inspired by Laravel

Package includes both compiled javascript and typescript declaration(.d.ts) files. Developers can continue coding in both typescript and javascript

Features

  • Full featured query builder
  • RawSql supports
  • Driver supports so far: MySql, PostgreSQL

TODO

  • More driver supports such as SQLite and SQL Server
  • Orm

Usage

Connections

import { Connector } from "ts-brain/Connector";
import { DB } from "ts-brain/DB";

let configs: ConfigMap = {
    mysql: {
        driver: DriverType.mysql,
        host: "127.0.0.1",
        port: 3306,
        user: "root",
        password: "root",
        database: "test",
    },
    pgsql: {
        driver: DriverType.pgsql,
        host: "127.0.0.1",
        port: 5432,
        user: "postgres",
        password: "postgres",
        database: "test",
    },
    anotherPg: {
        driver: DriverType.pgsql,
        host: "127.0.0.1",
        port: 5432,
        user: "postgres",
        password: "postgres",
        database: "another",
    },
};
Connector.create(configs, "mysql"); // batch create connections, and you can specify a default connection

// accessing connections
DB.conn(); // access default connection
DB.conn("mysql");
DB.conn("pgsql");
DB.conn("anotherPg");

Retrieving Results

You may use the query method on the Connection class to begin a query:

import { Connection } from "ts-brain/Connection";

let mysql: Connection = DB.conn("mysql");
let query = mysql.query(); // Now we have the query builder instance 🎉

Retrieving All Rows From A Table

The table method constraints the from portion of the sql and returns the query builder instance itself, allowing you to chain more constraints onto the query and then finally get the results using the get method:

let users = await query.table("users").get();

The get method returns an array where each result is an object. You may access each column's value by accessing the column as a property of the object:

users.forEach((user) => {
    console.log(user.id, user.name);
});

Retrieving A Single Row / Column From A Table

If you just need to retrieve a single row from the database table, you may use the first method. This method will return a single object:

let user = await query.table("users").first();

console.log(user.name);

If you don't even need an entire row, you may extract a single value from a record using the value method. This method will return the value of the column directly:

let email = await query.table("users").where("name", "Jack").value("email");

Retrieving A List Of Column Values

If you would like to retrieve a collection containing the values of a single column, you may use the pluck method. In this example, we'll retrieve a collection of role titles as an array:

let titles = await query.table("roles").pluck("title");

titles.forEach((title) => {
    console.log(title);
});

You may also specify a custom key column for the returned collection, so it will return an object:

import { Map } from "ts-brain/query/Builder";

let titles = await query.table("roles").pluck("title", "name") as Map;

Object.keys(titles).forEach((name: string) => {
    console.log(titles[name]);
});

Aggregates

The query builder also provides a variety of aggregate methods such as count, max, min, avg, and sum. You may call any of these methods after constructing your query:

let number = await query.table("users").count();

let price = await query.table("orders").max("price");

Of course, you may combine these methods with other clauses:

let price = await query.table("orders")
        .where("finalized", 1)
        .avg("price");

Selects

Specifying A Select Clause

Of course, you may not always want to select all columns from a database table. Using the select method, you can specify a custom select clause for the query:

let users = await query.table("users").select(["name", "email as user_email"]).get();

If you already have a query builder instance and you wish to add a column to its existing select clause, you may use the addSelect method:

query.table("users").select(["id"]);

let users = await query.addSelect("name").get();

Raw Expressions

Sometimes you may need to use a raw expression in a query. To create a raw expression, you may use the DB.raw method:

import { DB } from "ts-brain/DB";

let users = await query.table("users")
    .select(DB.raw("count(*) as user_count, status"))
    .where("status", "<>", 1)
    .groupBy("status")
    .get();

Raw statements will be injected into the query as strings, so you should be extremely careful to not create SQL injection vulnerabilities.

Raw Methods

Instead of using DB.raw, you may also use the following methods to insert a raw expression into various parts of your query.

selectRaw

The selectRaw method can be used in place of select(DB.raw(...)). This method accepts an optional array of bindings as its second argument:

let orders = await query.table("orders")
    .selectRaw("price * ? as price_with_tax", [1.0825]) // If the query is on PostgreSQL, the placeholder `?` should be changed to `$1`
    .get();

whereRaw / orWhereRaw

The whereRaw and orWhereRaw methods can be used to inject a raw where clause into your query. These methods accept an optional array of bindings as their second argument:

let orders = await query.table("orders")
    .whereRaw("price > IF(state = 'TX', ?, 100)", [200])
    .get();

havingRaw / orHavingRaw

The havingRaw and orHavingRaw methods may be used to set a raw string as the value of the having clause:

import { DB } from "ts-brain/DB";

let orders = await query.table("orders")
    .select([
        "department",
        DB.raw("SUM(price) as total_sales"),
    ])
    .groupBy("department")
    .havingRaw("SUM(price) > 2500")
    .get();

orderByRaw

The orderByRaw method may be used to set a raw string as the value of the order by clause:

let orders = await query.table("orders")
    .orderByRaw("updated_at - created_at DESC")
    .get();

Joins

Inner Join Clause

The query builder may also be used to write join statements. To perform a basic "inner join", you may use the join method on a query builder instance. The first argument passed to the join method is the name of the table you need to join to, while the remaining arguments specify the column constraints for the join. Of course, as you can see, you can join to multiple tables in a single query:

let users = await query.table("users")
    .join("contacts", "users.id", "=", "contacts.user_id")
    .join("orders", "users.id", "orders.user_id") // You don't have to specify the operator "="
    .select("users.*", "contacts.phone", "orders.price")
    .get();

Left Join Clause

If you would like to perform a "left join" instead of an "inner join", use the leftJoin method. The leftJoin method has the same signature as the join method:

let users = await query.table("users")
    .leftJoin("posts", "users.id", "=", "posts.user_id")
    .get();

Cross Join Clause

To perform a "cross join" use the crossJoin method with the name of the table you wish to cross join to. Cross joins generate a cartesian product between the first table and the joined table:

let styles = await query.table("sizes")
    .crossJoin("colors")
    .get();

Advanced Join Clauses

You may also specify more advanced join clauses. To get started, pass a Closure as the second argument into the join method. The Closure will receive a query builder instance which allows you to specify constraints on the join clause:

import { Builder } from "ts-brain/query/Builder";

let users = await query.table("users")
    .join("contacts", (join: Builder) => {
        join.on("users.id", "=", "contacts.user_id").orOn(...);
    })
    .get();

If you would like to use a "where" style clause on your joins, you may use the where and orWhere methods on a join. Instead of comparing two columns, these methods will compare the column against a value:

import { Builder } from "ts-brain/query/Builder";

let users = await query.table("users")
    .join("contacts", (join: Builder) => {
        join.on("users.id", "=", "contacts.user_id")
            .where("contacts.user_id", ">", 5);
    })
    .get();

Where Clauses

Simple Where Clauses

You may use the where method on a query builder instance to add where clauses to the query. The most basic call to where requires three arguments. The first argument is the name of the column. The second argument is an operator, which can be any of the database's supported operators. Finally, the third argument is the value to evaluate against the column.

For example, here is a query that verifies the value of the "votes" column is equal to 100:

let users = await query.table("users").where("votes", "=", 100).get();

For convenience, if you simply want to verify that a column is equal to a given value, you may pass the value directly as the second argument to the where method:

let users = await query.table("users").where("votes", 100).get();

Of course, you may use a variety of other operators when writing a where clause:

let users = await query.table("users").where("votes", ">=", 100).get();

let users = await query.table("users").where("votes", "<>", 100).get();

let users = await query.table("users").where("name", "like", "J%").get();

Or Statements

You may chain where constraints together as well as add or clauses to the query. The orWhere method accepts the same arguments as the where method:

let users = await query.table("users")
    .where("votes", ">", 100)
    .orWhere("name", "Jack")
    .get();

Additional Where Clauses

whereIn / whereNotIn

The whereIn method verifies that a given column's value is contained within the given array:

let users = await query.table("users")
    .whereIn("id", [1, 2, 3])
    .get();

The whereNotIn method verifies that the given column's value is not contained in the given array

let users = await query.table("users")
    .whereNotIn("id", [1, 2, 3])
    .get();

whereNull / whereNotNull

The whereNull method verifies that the value of the given column is NULL:

let users = await query.table("users")
    .whereNull("email")
    .get();

The whereNotNull method verifies that the column's value is not NULL:

let users = await query.table("users")
    .whereNotNull("email")
    .get();

whereColumn

The whereColumn method may be used to verify that two columns are equal:

let users = await query.table("users")
    .whereColumn("first_name", "last_name")
    .get();

You may also pass a comparison operator to the method:

let users = await query.table("users")
    .whereColumn("updated_at", ">", "created_at")
    .get();

Parameter Grouping

Sometimes you may need to create more advanced where clauses such as nested parameter groupings. The query builder can handle these as well. To get started, let's look at an example of grouping constraints within parenthesis:

import { Builder } from "ts-brain/query/Builder";

let users = await query.table("users")
    .where("name", "Jack")
    .orWhere((q: Builder) => {
        q.where("votes", ">", 100)
            .where("title", "<>", "admin");
    })
    .get();

As you can see, passing a Closure into the orWhere method instructs the query builder to begin a constraint group. The Closure will receive a query builder instance which you can use to set the constraints that should be contained within the parenthesis group. The example above will produce the following SQL:

select * from users where name = 'Jack' or (votes > 100 and title <> 'admin')

Ordering, Grouping, Limit, & Offset

orderBy

The orderBy method allows you to sort the result of the query by a given column. The first argument to the orderBy method should be the column you wish to sort by, while the second argument controls the direction of the sort and may be either asc or desc:

let users = await query.table("users")
    .orderBy("id", "desc")
    .get();

groupBy / having

The groupBy and having methods may be used to group the query results. The having method's signature is similar to that of the where method:

let users = await query.table("users")
    .groupBy("account_id")
    .having("account_id", ">", 100)
    .get();

limit / offset

To limit the number of results returned from the query, or to skip a given number of results in the query, you may use the limit and offset methods:

let users = await query.table("users")
    .limit(100)
    .offset(10)
    .get();

Inserts

The query builder also provides an insert method for inserting records into the database table. The insert method accepts an object of column names and values:

let affectedRows = await query.table('users').insert({
    email: "jack@example.com",
    votes: 0,
});

You may even insert several records into the table with a single call to insert by passing an array of objects. Each object represents a row to be inserted into the table:

let affectedRows = await query.table('users').insert([
    {
        email: "jack@example.com",
        votes: 0,
    },
    {
        email: "john@example.com",
        votes: 10,
    },
]);

Auto-Incrementing IDs

If the table has an auto-incrementing id, use the insertGetId method to insert a record and then retrieve the ID:

let id = await query.table("users").insertGetId({
    email: "jack@example.com",
    votes: 0,
});

When using PostgreSQL the insertGetId method expects the auto-incrementing column to be named id. If you would like to retrieve the ID from a different "sequence", you may pass the column name as the second parameter to the insertGetId method

Updates

Of course, in addition to inserting records into the database, the query builder can also update existing records using the update method. The update method, like the insert method, accepts an object of column and value pairs containing the columns to be updated. You may constrain the update query using where clauses:

let affectedRows = await query.table("users")
    .where("id", 1)
    .update({
        votes: 2,
    });

Deletes

The query builder may also be used to delete records from the table via the delete method. You may constrain delete statements by adding where clauses before calling the delete method:

let affectedRows = await query.table("users").delete();

let affectedRows = await query.table("users").where("votes", ">", 100).delete();

If you wish to truncate the entire table, which will remove all rows and reset the auto-incrementing ID to zero, you may use the truncate method:

let affectedRows = await query.table("users").truncate();
0.1.1

6 years ago

0.1.0

6 years ago

0.0.7

6 years ago

0.0.6

6 years ago

0.0.5

6 years ago

0.0.4

6 years ago

0.0.3

6 years ago

0.0.2

6 years ago

0.0.1

6 years ago