The time after the 11th hour. Midnight is a NodeJS ORM for SQLite and Turso with full TypeScript support without needing to generate any code. Even complex SQL queries can be written inside of JavaScript.
Tables are written in JavaScript like this:
There are two levels of API. The first is a table-level syntax for basic queries.
Includes are specified at the time of the query, rather than in the schema.
The second type of syntax is much like SQL and builds on many of the new features that JavaScript has added to its language in recent times.
This syntax allows you to perform queries that usually aren't possible in ORMs.
Assuming you had a database already setup with a clouds table:
You probably want to use the migration system to create and modify tables though. See the sample project to get an idea of how a basic project can be setup.
Every table has get, many, first, query, update, upsert, insert, insertMany, and remove methods available to it, along with any of the custom methods that are created when you add a new SQL file to the corresponding table's folder.
insert inserts a row into the database. For batch inserts you can use insertMany, which takes an array of objects.
update takes an object with an optional where property, and a set property. It returns a number representing the number of rows that were affected by the query. For example:
If you want to update columns based on their existing value, you can pass a function into the set properties like this:
All of the built-in SQLite functions are available, in addition to the mathematical operators plus, minus, divide, and multiply.
upsert will update the row if the target's uniqueness contraint is violated by the insert. If target or set are not provided, the upsert will do nothing when there is a conflict. upsert returns the primary key of the inserted or updated row.
get and many take two optional arguments. The first argument represents the where clause. For example:
If an array is passed in, an in clause is used, such as:
If null is passed in as the value, the SQL will use is null.
The second argument to get or many selects which columns to return. It can be one of the following:
- a string representing a column to select. In this case, the result returned is a single value or array of single values, depending on whether get or many is used.
- an array of strings, representing the columns to select.
You can use the query or first syntax for more complex queries. query returns an array in the same way as many, and first returns an object or undefined if nothing is found. The additional keywords are:
select: a string or array of strings representing the columns to select.
omit: a string or array of strings representing the columns to omit. All of the other columns will be selected.
include: include other tables in the result.
orderBy: a string or an array representing the column or columns to order the result by. This can also be a function that utilises the built-in SQLite functions.
desc: set to true when using orderBy if you want the results in descending order.
limit and offset: corresponding to the SQL keywords with the same name.
distinct: adds the distinct keywords to the start of the select clause.
debug: when set to true, the result will include debug information such as the raw SQL used in the query.
For example:
You can also include additional relations.
While the default interpretation of the query parameters is =, you can pass in a function to use not, gt, gte, lt, lte, like, match or glob.
For example:
If you need to perform complex logic in the where clause, you can use the and or or properties. For example:
You should only include one condition per object.
There are multiple functions that aggregate the results into a single value. These include count, avg, min, max, and sum. Despite its name, sum uses the SQLite function total to determine the results.
All of these functions take three arguments:
where: the where clause
column: the column to aggregate. This is optional for count.
distinct: the same as column but it aggregates by distinct values.
There is also an exists function that takes one argument representing the where clause.
You can write group by statements like this:
An aggregate function should come after the groupBy method. distinct can be used instead of column to aggregate by distinct values. distinct or column needs to be an object with a single property representing the alias for the aggregrate function, and the column to aggregate by.
In addition to aggregate functions such as avg or count, there is also an array function that simply groups the rows into an array. The select option takes an object with a single property representing the name of the resulting array, and the column or columns to select.
remove takes one argument representing the where clause and returns the number of rows affected by the query.
Transactions involve locking writes to the database with getTransaction. If multiple transactions try to run at the same time, they will wait until the current transaction is complete.
You can also run multiple statements inside a single transaction without any logic using batch.
The client returned from getClient has three methods that can be used to create a migration system. This includes:
getSchema: return the tables loaded into the getClient method in a format suitable for saving as JSON.
diff: takes a saved schema and diffs it with the currently loaded schema to create a migration.
migrate: takes a SQL string representing the migration. This method defers the foreign keys and wraps the SQL in a transaction.
See the sample project for an example of how to use these functions to create a migration system.
In addition to the built-in SQLite types of Integer, Real, Text, and Blob, Midnight adds a few extra types. Boolean is stored in the database as a 1 or a 0, Date is stored as an ISO8601 string, and Json is a JSONB blob.
To create a table, you simply extend the Table class. Columns start with a lowercase letter.
To specify the primary key, you use one of the modified types that has Primary at the end.
Column types can be wrapped in many different methods:
Null: assert that the column can contain nulls.
Index: add an index to the column.
Unique: add a unique index to the column.
Constraints can be represented as either an array of valid values, or one or more comparison functions.
Constraints can also be defined in the Attributes function and span across multiple columns.
Foreign keys do not need to specify a column type, as the type will be determined by the table that is referenced.
By default, an index is created for the foreign key, and the column is set to not null. Also, the related column in the referenced table is assumed to be the primary key of that table.
Cascade is simply a shorthand version of References that has the onDelete property set to cascade.
For indexes that span multiple columns or are based on expressions, you can define an Attributes function on the class.
Partial indexes can be defined on a class field.
Indexes can also be defined inside the Attributes function if they span across multiple columns.
The above example applies a partial index on name where alive is true.
Computed fields use the built-in SQLite functions and therefore can be used in any part of a query.
Midnight alllows you to create complex SQL queries without leaving JavaScript.
The following query uses a window function to rank trees by their height.
The built-in SQLite functions are just JavaScript functions. This query gets the tree planted the furthest time away from the supplied date.
The c parameter of the query represents the context of the database, including both tables and functions.
The group function represents json_group_array or json_group_object depending on the number of parameters supplied to the function.
If you want to create a subquery for use in many different queries, you can use the subquery method.
The query below creates a list of people that have sighted a particular animalId.
You can now use this subquery in other queries.
Subqueries can also be used instead of tables in the stanadard API with the use method.
The object returned from the query and subquery methods can include the following:
select, optional, distinct, join, where, groupBy, having, orderBy, desc, limit, and offset.
optional: the same as select but provides hints to TypeScript that these columns may be null. This is useful for columns that come from a left join.
In the above example, moon will be of type string or null even though it is normally not null.
distinct: used instead of select when you want the results to be distinct.
join: a tuple or array of tuples representing the keys to join on.
.png)
