Mammoth
Search…
Defining tables
Now that you created your db instance let’s zoom into why and how to define your tables. You define your tables so Mammoth understands the types of your columns and the command line interface can help you generate migrations. To define your tables you use the defineTable call and you pass the result to your db instance to make the table available through the db instance.
The defineTable syntax should be very similar to SQL’s CREATE TABLE syntax.
Node.js
1
import { defineTable, uuid, text, integer } from '@ff00ff/mammoth';
2
3
export const foo = defineTable({
4
id: uuid().primaryKey().default(`gen_random_uuid()`),
5
name: text().notNull(),
6
value: integer(),
7
});
Copied!
This is equivalent to the below SQL.
1
CREATE TABLE foo (
2
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
3
name text NOT NULL,
4
value integer
5
);
Copied!

Data types

The Mammoth data types map to the equally-named Postgres data type and an equivalent TypeScript return type. E.g. Mammoth's text() configures Postgres's text and maps to TypeScript string.
Postgres's built-in general-purpose data types should all be supported in Mammoth already. If not, please file an issue. In the meantime, you can always create a custom data type.
You can always re-configure the TypeScript type. For example, if you reconfigured pg to map bigint to JavaScript's BigInt like the below.
1
// Type Id 20 = BIGINT | BIGSERIAL
2
pg.types.setTypeParser(20, BigInt);
3
4
// 1016 = Type Id for arrays of BigInt values
5
const parseBigIntArray = pg.types.getTypeParser(1016);
6
pg.types.setTypeParser(1016, a => parseBigIntArray(a).map(BigInt));
Copied!
Currently pg returns string instead of the newly-added BigInt type. See for some context and a workaround. https://github.com/brianc/node-pg-types/issues/78
You can just pass a different type to the bigint() call.
1
const foo = defineTable({
2
bar: bigint<BigInt>().notNull(),
3
});
Copied!
To avoid having to specify the type every time you may consider creating a reusable data type.
1
// You can name this as you wish e.g. bigint
2
export const bigintAsJsBigInt = () => dataType<BigInt>(`bigint`);
Copied!
And you can also create a reusable custom data type. For example if you wish to add an unsupported data type.
1
export const mySpecialType = () => dataType<number>(`myspecialtype`);
Copied!
Which allows you to define the column like below. Please note that you must wrap the dataType function in a function as dataType() returns a mutable object.
1
const foo = defineTable({
2
bar: mySpecialType().notNull(),
3
});
Copied!
Last modified 1yr ago
Copy link
Contents
Data types