drizzle-orm 0.11.0 → 0.11.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +11 -11
- package/builders/aggregators/selectAggregator.d.ts +1 -9
- package/builders/aggregators/selectAggregator.js +1 -55
- package/builders/aggregators/selectAggregatorV1.d.ts +39 -0
- package/builders/aggregators/selectAggregatorV1.js +143 -0
- package/builders/highLvlBuilders/joins/selectJoinBuilder.d.ts +1 -0
- package/builders/highLvlBuilders/joins/selectJoinBuilder.js +5 -1
- package/builders/highLvlBuilders/selectRequestBuilder.d.ts +5 -5
- package/builders/joinBuilders/builders/abstractJoinBuilder.js +1 -1
- package/builders/lowLvlBuilders/selects/select.d.ts +4 -1
- package/builders/lowLvlBuilders/selects/select.js +27 -1
- package/builders/lowLvlBuilders/selects/selectFrom.d.ts +25 -11
- package/builders/lowLvlBuilders/selects/selectFrom.js +48 -5
- package/builders/lowLvlBuilders/selects/selectJoined.d.ts +22 -9
- package/builders/lowLvlBuilders/selects/selectJoined.js +44 -7
- package/builders/lowLvlBuilders/selects/whereSelect.d.ts +13 -0
- package/builders/lowLvlBuilders/selects/whereSelect.js +24 -0
- package/builders/requestBuilders/where/and.d.ts +10 -0
- package/builders/requestBuilders/where/and.js +17 -0
- package/builders/requestBuilders/where/const.d.ts +7 -0
- package/builders/requestBuilders/where/const.js +10 -0
- package/builders/requestBuilders/where/constArray.d.ts +7 -0
- package/builders/requestBuilders/where/constArray.js +25 -0
- package/builders/requestBuilders/where/eqWhere.d.ts +10 -0
- package/builders/requestBuilders/where/eqWhere.js +5 -0
- package/builders/requestBuilders/where/greater.d.ts +10 -0
- package/builders/requestBuilders/where/greater.js +5 -0
- package/builders/requestBuilders/where/greaterEq.d.ts +10 -0
- package/builders/requestBuilders/where/greaterEq.js +5 -0
- package/builders/requestBuilders/where/in.d.ts +10 -0
- package/builders/requestBuilders/where/in.js +5 -0
- package/builders/requestBuilders/where/isNotNull.d.ts +10 -0
- package/builders/requestBuilders/where/isNotNull.js +4 -0
- package/builders/requestBuilders/where/isNull.d.ts +10 -0
- package/builders/requestBuilders/where/isNull.js +4 -0
- package/builders/requestBuilders/where/less.d.ts +10 -0
- package/builders/requestBuilders/where/less.js +5 -0
- package/builders/requestBuilders/where/lessEq.d.ts +10 -0
- package/builders/requestBuilders/where/lessEq.js +5 -0
- package/builders/requestBuilders/where/like.d.ts +10 -0
- package/builders/requestBuilders/where/like.js +5 -0
- package/builders/requestBuilders/where/notEqWhere.d.ts +10 -0
- package/builders/requestBuilders/where/notEqWhere.js +5 -0
- package/builders/requestBuilders/where/or.d.ts +10 -0
- package/builders/requestBuilders/where/or.js +17 -0
- package/builders/requestBuilders/where/rawWhere.d.ts +10 -0
- package/builders/requestBuilders/where/rawWhere.js +1 -0
- package/builders/requestBuilders/where/static.d.ts +4 -1
- package/builders/requestBuilders/where/static.js +9 -4
- package/builders/requestBuilders/where/static.spec.d.ts +1 -0
- package/builders/requestBuilders/where/static.spec.js +59 -0
- package/builders/requestBuilders/where/var.d.ts +10 -0
- package/builders/requestBuilders/where/var.js +4 -0
- package/builders/requestBuilders/where/where.d.ts +10 -0
- package/docs/cases/simple_join.js +2 -2
- package/package.json +4 -4
- package/test.d.ts +0 -1
- package/test.js +176 -165
|
@@ -2,8 +2,11 @@ import { AbstractColumn } from '../../../columns/column';
|
|
|
2
2
|
import ColumnType from '../../../columns/types/columnType';
|
|
3
3
|
import { ExtractCodeType } from '../../../tables/inferTypes';
|
|
4
4
|
import Expr from './where';
|
|
5
|
+
export declare const eq: <TLeft extends AbstractColumn<ColumnType<any>, boolean, boolean, any>, TRight extends AbstractColumn<ColumnType<any>, boolean, boolean, any>>(left: TLeft, right: TRight | ExtractCodeType<TLeft>) => Expr;
|
|
6
|
+
/**
|
|
7
|
+
@deprecated use {@link eq}
|
|
8
|
+
*/
|
|
5
9
|
export declare const onEq: <T extends AbstractColumn<ColumnType<any>, boolean, boolean, any>, T1 extends AbstractColumn<ColumnType<any>, boolean, boolean, any>>(left: T, right: T1) => Expr;
|
|
6
|
-
export declare const eq: <T extends AbstractColumn<ColumnType<any>, boolean, boolean, any>>(left: T, value: ExtractCodeType<T>) => Expr;
|
|
7
10
|
export declare const raw: (customQuery: string) => Expr;
|
|
8
11
|
export declare const and: (expressions: Expr[]) => Expr;
|
|
9
12
|
export declare const or: (expressions: Expr[]) => Expr;
|
|
@@ -3,7 +3,9 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
|
3
3
|
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
4
4
|
};
|
|
5
5
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
6
|
-
exports.notEq = exports.isNotNull = exports.isNull = exports.lessEq = exports.greaterEq = exports.less = exports.greater = exports.inArray = exports.like = exports.or = exports.and = exports.raw = exports.
|
|
6
|
+
exports.notEq = exports.isNotNull = exports.isNull = exports.lessEq = exports.greaterEq = exports.less = exports.greater = exports.inArray = exports.like = exports.or = exports.and = exports.raw = exports.onEq = exports.eq = void 0;
|
|
7
|
+
/* eslint-disable max-len */
|
|
8
|
+
const column_1 = require("../../../columns/column");
|
|
7
9
|
const and_1 = __importDefault(require("./and"));
|
|
8
10
|
const const_1 = __importDefault(require("./const"));
|
|
9
11
|
const constArray_1 = __importDefault(require("./constArray"));
|
|
@@ -20,11 +22,14 @@ const notEqWhere_1 = __importDefault(require("./notEqWhere"));
|
|
|
20
22
|
const or_1 = __importDefault(require("./or"));
|
|
21
23
|
const rawWhere_1 = __importDefault(require("./rawWhere"));
|
|
22
24
|
const var_1 = __importDefault(require("./var"));
|
|
23
|
-
const onEq = (left, right) => new eqWhere_1.default(new var_1.default(left), new var_1.default(right));
|
|
24
|
-
exports.onEq = onEq;
|
|
25
25
|
// eslint-disable-next-line max-len
|
|
26
|
-
const eq = (left,
|
|
26
|
+
const eq = (left, right) => new eqWhere_1.default(new var_1.default(left), right instanceof column_1.AbstractColumn ? new var_1.default(right) : new const_1.default(right));
|
|
27
27
|
exports.eq = eq;
|
|
28
|
+
/**
|
|
29
|
+
@deprecated use {@link eq}
|
|
30
|
+
*/
|
|
31
|
+
const onEq = (left, right) => exports.eq(left, right);
|
|
32
|
+
exports.onEq = onEq;
|
|
28
33
|
const raw = (customQuery) => new rawWhere_1.default(customQuery);
|
|
29
34
|
exports.raw = raw;
|
|
30
35
|
const and = (expressions) => new and_1.default(expressions);
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
|
3
|
+
if (k2 === undefined) k2 = k;
|
|
4
|
+
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
|
|
5
|
+
}) : (function(o, m, k, k2) {
|
|
6
|
+
if (k2 === undefined) k2 = k;
|
|
7
|
+
o[k2] = m[k];
|
|
8
|
+
}));
|
|
9
|
+
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
|
|
10
|
+
Object.defineProperty(o, "default", { enumerable: true, value: v });
|
|
11
|
+
}) : function(o, v) {
|
|
12
|
+
o["default"] = v;
|
|
13
|
+
});
|
|
14
|
+
var __importStar = (this && this.__importStar) || function (mod) {
|
|
15
|
+
if (mod && mod.__esModule) return mod;
|
|
16
|
+
var result = {};
|
|
17
|
+
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
|
|
18
|
+
__setModuleDefault(result, mod);
|
|
19
|
+
return result;
|
|
20
|
+
};
|
|
21
|
+
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
22
|
+
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
23
|
+
};
|
|
24
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
25
|
+
const uvu_1 = require("uvu");
|
|
26
|
+
const assert = __importStar(require("uvu/assert"));
|
|
27
|
+
const abstractTable_1 = __importDefault(require("@/tables/abstractTable"));
|
|
28
|
+
const utils_1 = require("@/../tests/utils");
|
|
29
|
+
const db_1 = require("@/db");
|
|
30
|
+
const static_1 = require("./static");
|
|
31
|
+
class TestTable extends abstractTable_1.default {
|
|
32
|
+
constructor() {
|
|
33
|
+
super(...arguments);
|
|
34
|
+
this.id = this.serial('id').primaryKey();
|
|
35
|
+
this.age = this.int('age');
|
|
36
|
+
}
|
|
37
|
+
tableName() {
|
|
38
|
+
return 'test';
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
const t = uvu_1.suite('static', {
|
|
42
|
+
testSession: undefined,
|
|
43
|
+
testTable: undefined,
|
|
44
|
+
});
|
|
45
|
+
t.before(async (context) => {
|
|
46
|
+
context.testSession = new utils_1.TestSession();
|
|
47
|
+
context.testTable = new TestTable(new db_1.DB(context.testSession));
|
|
48
|
+
});
|
|
49
|
+
t('eq accepts both column and raw value as right argument', (context) => {
|
|
50
|
+
const { testSession, testTable } = context;
|
|
51
|
+
const { query, values } = static_1.and([
|
|
52
|
+
static_1.eq(testTable.id, 1),
|
|
53
|
+
static_1.eq(testTable.id, testTable.age),
|
|
54
|
+
]).toQuery({ session: testSession });
|
|
55
|
+
assert.is(query, '(test."id"=$1 and test."id"=test."age")');
|
|
56
|
+
assert.is(values.length, 1);
|
|
57
|
+
assert.is(values[0], 1);
|
|
58
|
+
});
|
|
59
|
+
t.run();
|
|
@@ -12,4 +12,14 @@ export default class Var<T extends AbstractColumn<ColumnType<any>, boolean, bool
|
|
|
12
12
|
query: string;
|
|
13
13
|
values: Array<any>;
|
|
14
14
|
};
|
|
15
|
+
toQueryV1: ({ position, tableCache, session, }: {
|
|
16
|
+
position?: number | undefined;
|
|
17
|
+
tableCache?: {
|
|
18
|
+
[tableName: string]: string;
|
|
19
|
+
} | undefined;
|
|
20
|
+
session: ISession;
|
|
21
|
+
}) => {
|
|
22
|
+
query: string;
|
|
23
|
+
values: Array<any>;
|
|
24
|
+
};
|
|
15
25
|
}
|
|
@@ -12,6 +12,10 @@ class Var extends where_1.default {
|
|
|
12
12
|
const tableName = this.column.getParentName();
|
|
13
13
|
return { query: `${tableName}.${ecranate_1.ecranate(this.column.getColumnName())}`, values: [] };
|
|
14
14
|
};
|
|
15
|
+
this.toQueryV1 = ({ position, tableCache, session, }) => {
|
|
16
|
+
const tableName = tableCache && tableCache[this.column.getParentName()] ? tableCache[this.column.getParentName()] : this.column.getParentName();
|
|
17
|
+
return { query: `${tableName}.${ecranate_1.ecranate(this.column.getColumnName())}`, values: [] };
|
|
18
|
+
};
|
|
15
19
|
this.column = column;
|
|
16
20
|
}
|
|
17
21
|
}
|
|
@@ -7,4 +7,14 @@ export default abstract class Expr {
|
|
|
7
7
|
query: string;
|
|
8
8
|
values: Array<any>;
|
|
9
9
|
};
|
|
10
|
+
abstract toQueryV1({ position, tableCache, session, }: {
|
|
11
|
+
position?: number;
|
|
12
|
+
tableCache?: {
|
|
13
|
+
[tableName: string]: string;
|
|
14
|
+
};
|
|
15
|
+
session: ISession;
|
|
16
|
+
}): {
|
|
17
|
+
query: string;
|
|
18
|
+
values: Array<any>;
|
|
19
|
+
};
|
|
10
20
|
}
|
|
@@ -57,9 +57,9 @@ const usersToUserGroups_1 = __importDefault(require("../tables/usersToUserGroups
|
|
|
57
57
|
groupId: (_f = userGroups[1]) === null || _f === void 0 ? void 0 : _f.id,
|
|
58
58
|
}]).execute();
|
|
59
59
|
// map case
|
|
60
|
-
const userWithCities = await citiesTable.select({ id: citiesTable.
|
|
60
|
+
const userWithCities = await citiesTable.select({ id: citiesTable.userId })
|
|
61
61
|
.where(builders_1.eq(citiesTable.id, 1))
|
|
62
|
-
.
|
|
62
|
+
.innerJoinV1(usersTable_1.default, (city) => city.userId, (users) => users.id)
|
|
63
63
|
.execute();
|
|
64
64
|
const citiesWithUserObject = userWithCities.map((city, user) => ({ city: city.id, user }));
|
|
65
65
|
// foreach case
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "drizzle-orm",
|
|
3
|
-
"version": "0.11.
|
|
3
|
+
"version": "0.11.1",
|
|
4
4
|
"description": "",
|
|
5
5
|
"main": "dist/index.js",
|
|
6
6
|
"types": "dist/index.d.ts",
|
|
@@ -35,10 +35,10 @@
|
|
|
35
35
|
"pg": "^8.6.0"
|
|
36
36
|
},
|
|
37
37
|
"scripts": {
|
|
38
|
-
"test": "uvu -r esbuild-register
|
|
38
|
+
"test": "uvu -r esbuild-register",
|
|
39
39
|
"ts": "tsc",
|
|
40
40
|
"lint": "eslint ./src --ext .ts",
|
|
41
|
-
"run": "ts-node src/
|
|
41
|
+
"run": "ts-node src/docs/cases/simple_join.ts"
|
|
42
42
|
},
|
|
43
|
-
"readme": "# DrizzleORM\n\n**DrizzleORM** is an ORM framework for \n[TypeScript](https://www.typescriptlang.org/).\nIt offers you several levels of Database communication:\n* Typesafe Table View approach \n* Typesafe Query Builder\n* Simple SQL query execution\n\nDrizzle ORM is highly influenced by [Exposed](https://github.com/JetBrains/Exposed) and Jetbrains development methodology\n\n## Supported Databases\n\n* PostgreSQL\n\n## Links\n\nIn Progress\n\n## Installing\n\n```bash\nnpm install drizzle-orm drizzle-kit\n```\n#### **In Progress**\n```bash\nyarn add drizzle-orm drizzle-kit\nbower install drizzle-orm drizzle-kit\n```\n\n## Connecting to database\n\n```tsx\nimport { DbConnector } from \"drizzle-orm\";\n\n// connect via postgresql connection url\nconst db = await new DbConnector()\n\t.connectionString(\"postgres://user:password@host:port/db\")\n\t.connect();\n\n// or by params\nconst db = await new DbConnector()\n\t.params({\n\t\thost: '0.0.0.0',\n\t\tport: 5432,\n\t\tuser: 'user',\n\t\tpassword: 'password',\n\t\tdb: 'optional_db_name'\n\t}).connect();\n```\n## Project structure\n- tables folder\n- migrations folder\n\n## Create tables\n### Users Table\n---\n```typescript\n\nexport const rolesEnum = createEnum({ alias: 'test-enum', values: ['user', 'guest', 'admin'] });\n\nexport default class UsersTable extends AbstractTable<UsersTable> {\n public id = this.serial('id').primaryKey();\n public fullName = this.text('full_name');\n\n public phone = this.varchar('phone', { size: 256 });\n public media = this.jsonb<string[]>('media');\n public decimalField = this.decimal('test', { precision: 100, scale: 2 }).notNull();\n public bigIntField = this.bigint('test1', 'max_bytes_53');\n public role = this.type(rolesEnum, 'name_in_table').notNull();\n\n public createdAt = this.timestamp('created_at').notNull();\n\n public createdAtWithTimezone = this.timestamptz('created_at_time_zone');\n\n public updatedAt = this.timestamp('updated_at').defaultValue(Defaults.CURRENT_TIMESTAMP);\n public isArchived = this.bool('is_archived').defaultValue(false);\n\n public phoneFullNameIndex = this.index([this.phone, this.fullName]);\n public phoneIndex = this.uniqueIndex(this.phone);\n\n public tableName(): string {\n return 'users';\n }\n}\n```\n### Cities Table\n---\n```typescript\ninterface CityMeta {\n population: number,\n connection: string,\n}\n\nexport default class CitiesTable extends AbstractTable<CitiesTable> {\n public id = this.serial('id').primaryKey();\n\n public foundationDate = this.timestamp('name').notNull();\n public location = this.varchar('page', { size: 256 });\n\n public userId = this.int('user_id').foreignKey(UsersTable, (table) => table.id, { onUpdate: 'CASCADE' });\n\n public metadata = this.jsonb<CityMeta>('metadata');\n\n public tableName(): string {\n return 'cities';\n }\n}\n```\n### User Groups Table\n---\n```typescript\nexport default class UserGroupsTable extends AbstractTable<UserGroupsTable> {\n public id = this.serial('id').primaryKey();\n\n public name = this.varchar('name');\n public description = this.varchar('description');\n\n public tableName(): string {\n return 'user_groups';\n }\n}\n```\n### User to User Groups Table\n---\n#### Many to many connection between Users and User Groups\n```typescript\nexport default class UsersToUserGroupsTable extends AbstractTable<UsersToUserGroupsTable> {\n public groupId = this.int('city_id').foreignKey(UserGroupsTable, (table) => table.id, { onDelete: 'CASCADE' });\n public userId = this.int('user_id').foreignKey(UsersTable, (table) => table.id, { onDelete: 'CASCADE' });\n\n public manyToManyIndex = this.index([this.groupId, this.userId]);\n\n public tableName(): string {\n return 'users_to_user_groups';\n }\n}\n```\n\n## CRUD\n### **SELECT**\n---\n```typescript\nconst db = await new DbConnector()\n .connectionString('postgresql://postgres@127.0.0.1/drizzle')\n .connect();\n\nconst usersTable = new UsersTable(db);\n\n// select all\nconst allSelect = await usersTable.select().all();\n\n// select first\nconst firstSelect = await usersTable.select().findOne();\n```\n#### **Sorting and Filtering**\n---\n##### Select all records from `Users` where phone is `\"hello\"`\n```typescript\nconst eqSelect = await usersTable.select().where(\n eq(usersTable.phone, 'hello')\n).all();\n```\n##### Select all records from `Users` where **both** phone is `\"hello\"` **and** phone is `\"hello\"`\n```typescript\nconst andSelect = await usersTable.select().where(\n and([\n eq(usersTable.phone, 'hello'),\n eq(usersTable.phone, 'hello')\n ]),\n).all();\n```\n##### Select all records from `Users` where **either** phone is `\"hello\"` **or** phone is `\"hello\"`\n```typescript\nconst orSelect = await usersTable.select().where(\n or([eq(usersTable.phone, 'hello')]),\n).all();\n```\n##### Select all records from `Users` using **LIMIT** and **OFFSET**\n```typescript\nconst limitOffsetSelect = await usersTable.select().limit(10).offset(10).all();\n```\n##### Select all records from `Users` where `phone` contains `\"hello\"`\n```typescript\nconst likeSelect = await usersTable.select().where(\n like(usersTable.phone, '%hello%')\n).all();\n```\n##### Select all records from `Users` where `phone` equals to some of values from array\n```typescript\nconst inArraySelect = usersTable.select().where(\n inArray(usersTable.phone, ['hello'])\n).all();\n```\n##### Select all records from `Users` where `phone` greater(**>**) than `\"hello\"`\n```typescript\nconst greaterSelect = usersTable.select().where(\n greater(usersTable.phone, 'hello')\n).all();\n```\n##### Select all records from `Users` where `phone` less(**<**) than `\"hello\"`\n```typescript\nconst lessSelect = usersTable.select().where(\n less(usersTable.phone, 'hello')\n).all();\n```\n##### Select all records from `Users` where `phone` greater or equals(**>=**) than `\"hello\"`\n```typescript\nconst greaterEqSelect = usersTable.select().where(\n greaterEq(usersTable.phone, 'hello')\n).all();\n```\n##### Select all records from `Users` where `phone` less or equals(**<=**) \n```typescript\nconst lessEqSelect = usersTable.select().where(\n lessEq(usersTable.phone, 'hello')\n).all();\n```\n##### Select all records from `Users` where `phone` is **NULL**\n```typescript\nconst isNullSelect = usersTable.select().where(\n isNull(usersTable.phone)\n).all();\n```\n##### Select all records from `Users` where `phone` not equals to `\"hello\"`\n```typescript\nconst notEqSelect = usersTable.select().where(\n notEq(usersTable.phone, 'hello')\n).all();\n```\n##### Select all records from `Users` ordered by `phone` in ascending order\n```typescript\nconst ordered = await usersTable.select().orderBy((table) => table.phone, Order.ASC).all();\n```\n#### **Partial Selecting**\n ```typescript\n const partialSelect = await usersTable.select({\n mappedId: usersTable.id,\n mappedPhone: usersTable.phone,\n }).all();\n\n // Usage\n const { mappedId, mappedPhone } = partialSelect;\n ```\n\n\n### **Update**\n---\n##### Update `fullName` to `newName` in `Users` where phone is `\"hello\"`\n```typescript\nawait usersTable.update()\n .where(eq(usersTable.phone, 'hello'))\n .set({ fullName: 'newName' })\n .execute();\n```\n##### Update `fullName` to `newName` in `Users` where phone is `\"hello\"` returning updated `User` model\n```typescript\nawait usersTable.update()\n .where(eq(usersTable.phone, 'hello'))\n .set({ fullName: 'newName' })\n .all();\n```\n##### Update `fullName` to `newName` in `Users` where phone is `\"hello\"` returning updated `User` model\n```typescript\nawait usersTable.update()\n .where(eq(usersTable.phone, 'hello'))\n .set({ fullName: 'newName' })\n .findOne();\n```\n\n### **Delete**\n##### Delete `user` where phone is `\"hello\"`\n```typescript\nawait usersTable.delete()\n .where(eq(usersTable.phone, 'hello'))\n .execute();\n```\n##### Delete `user` where phone is `\"hello\"` returning updated `User` model\n```typescript\nawait usersTable.delete()\n .where(eq(usersTable.phone, 'hello'))\n .all();\n```\n##### Delete `user` where phone is `\"hello\"` returning updated `User` model\n```typescript\nawait usersTable.delete()\n .where(eq(usersTable.phone, 'hello'))\n .findOne();\n```\n\n### **Insert**\n##### Insert `user` with required fields\n```typescript\nawait usersTable.insert({\n test: 1,\n createdAt: new Date(),\n}).execute();\n```\n##### Insert `user` with required fields and get all rows as array\n```typescript\nconst user = await usersTable.insert({\n test: 1,\n createdAt: new Date(),\n}).all();\n```\n##### Insert `user` with required fields and get inserted entity\n```typescript\nconst user = await usersTable.insert({\n test: 1,\n createdAt: new Date(),\n}).findOne();\n```\n##### Insert many `users` with required fields and get all inserted entities\n```typescript\nconst users = await usersTable.insertMany([{\n test: 1,\n createdAt: new Date(),\n }, {\n test: 2,\n createdAt: new Date(),\n }]).all();\n```\n##### Insert many `users` with required fields and get all inserted entities. If such user already exists - update `phone` field\n```typescript\nawait usersTable.insertMany([{\n test: 1,\n createdAt: new Date(),\n }, {\n test: 2,\n createdAt: new Date(),\n }])\n .onConflict(\n (table) => table.phoneIndex,\n { phone: 'confilctUpdate' },\n ).all();\n```\n\n## Joins\n### Join One-To-Many Tables\n##### Join Cities with Users and map to city object with full user\n```typescript\nconst usersTable = new UsersTable(db);\nconst citiesTable = new CitiesTable(db);\n\nconst userWithCities = await citiesTable.select()\n .where(eq(citiesTable.id, 1))\n .leftJoin(usersTable, (cities, users) => onEq(cities.userId, users.id))\n .execute();\n\nconst citiesWithUserObject = userWithCities.map((city, user) => ({ ...city, user }));\n```\n\n### Join Many-To-Many Tables\n##### Join User Groups with Users, using many-to-many table\n```typescript\n const usersWithUserGroups = await usersToUserGroupsTable.select()\n .where(eq(userGroupsTable.id, 1))\n .leftJoin(usersTable, (usersToUserGroups, users) => onEq(usersToUserGroups.userId, users.id))\n .leftJoin(userGroupsTable, (usersToUserGroups, _users, userGroups) => onEq(usersToUserGroups.groupId, userGroups.id))\n .execute();\n```\n### Join using partial field select\n##### Join Cities with Users getting only needed fields form request\n```typescript\n await citiesTable.select({\n id: citiesTable.id,\n userId: citiesTable.userId,\n })\n .where(eq(citiesTable.id, 1))\n .leftJoin(usersTable, (cities, users) => onEq(cities.userId, users.id))\n .execute();\n\nconst citiesWithUserObject = userWithCities.map((city, user) => ({ ...city, user }));\n```\n### Another join examples with different callback ON statements\n```typescript\nawait citiesTable.select()\n .where(eq(citiesTable.location, 'q'))\n .leftJoin(usersTable, (cities, _users) => eq(cities.id, 13))\n .execute();\n// Join statement generated from query\n// LEFT JOIN users AS users_1\n// ON cities.\"id\"=$1\n// WHERE cities.\"page\"=$2\n//\n// Values: [13, 'q']\n\nawait citiesTable.select()\n .leftJoin(usersTable, (cities, _users) => and([\n eq(cities.id, 13), notEq(cities.id, 14),\n ]))\n .execute();\n// Join statement generated from query\n// LEFT JOIN users AS users_1\n// ON (cities.\"id\"=$1 and cities.\"id\"!=$2)\n//\n// Values: [13, 14]\n\nawait citiesTable.select()\n .where(eq(citiesTable.location, 'location'))\n .leftJoin(usersTable, (_cities, _users) => raw('<custom expression after ON statement>'))\n .execute();\n// Join statement generated from query\n// LEFT JOIN users AS users_1\n// ON <custom expression after ON statement>\n// WHERE cities.\"page\"=$1\n// \n// Values: ['location']\n```\n\n\n## Migrations\n#### To run migrations generated by drizzle-kit you could use `Migrator` class\n##### Provide drizzle-kit config path\n```typescript\nawait drizzle.migrator(db).migrate('src/drizzle.config.yaml');\n```\n##### Another possibility is to provide object with path to folder with migrations\n```typescript\nawait drizzle.migrator(db).migrate({ migrationFolder: 'drizzle' });\n```\n\n\n## Raw query usage\n#### If you have some complex queries to execute and drizzle-orm can't handle them yet, then you could use `rawQuery` execution\n\n\n##### Execute custom raw query\n```typescript\nconst res: QueryResult<any> = await db.session().execute('SELECT * FROM users WHERE user.id = $1', [1]);\n```"
|
|
43
|
+
"readme": "# DrizzleORM\n\n**DrizzleORM** is an ORM framework for \n[TypeScript](https://www.typescriptlang.org/).\nIt offers you several levels of Database communication:\n* Typesafe Table View approach \n* Typesafe Query Builder\n* Simple SQL query execution\n\nDrizzle ORM is highly influenced by [Exposed](https://github.com/JetBrains/Exposed) and Jetbrains development methodology\n\n## Supported Databases\n\n* PostgreSQL\n\n## Links\n\nIn Progress\n\n## Installing\n\n```bash\nnpm install drizzle-orm drizzle-kit\n```\n#### **In Progress**\n```bash\nyarn add drizzle-orm drizzle-kit\nbower install drizzle-orm drizzle-kit\n```\n\n## Connecting to database\n\n```tsx\nimport { DbConnector } from \"drizzle-orm\";\n\n// connect via postgresql connection url\nconst db = await new DbConnector()\n\t.connectionString(\"postgres://user:password@host:port/db\")\n\t.connect();\n\n// or by params\nconst db = await new DbConnector()\n\t.params({\n\t\thost: '0.0.0.0',\n\t\tport: 5432,\n\t\tuser: 'user',\n\t\tpassword: 'password',\n\t\tdb: 'optional_db_name'\n\t}).connect();\n```\n## Project structure\n- tables folder\n- migrations folder\n\n## Create tables\n### Users Table\n---\n```typescript\n\nexport const rolesEnum = createEnum({ alias: 'test-enum', values: ['user', 'guest', 'admin'] });\n\nexport default class UsersTable extends AbstractTable<UsersTable> {\n public id = this.serial('id').primaryKey();\n public fullName = this.text('full_name');\n\n public phone = this.varchar('phone', { size: 256 });\n public media = this.jsonb<string[]>('media');\n public decimalField = this.decimal('test', { precision: 100, scale: 2 }).notNull();\n public bigIntField = this.bigint('test1', 'max_bytes_53');\n public role = this.type(rolesEnum, 'name_in_table').notNull();\n\n public createdAt = this.timestamp('created_at').notNull();\n\n public createdAtWithTimezone = this.timestamptz('created_at_time_zone');\n\n public updatedAt = this.timestamp('updated_at').defaultValue(Defaults.CURRENT_TIMESTAMP);\n public isArchived = this.bool('is_archived').defaultValue(false);\n\n public phoneFullNameIndex = this.index([this.phone, this.fullName]);\n public phoneIndex = this.uniqueIndex(this.phone);\n\n public tableName(): string {\n return 'users';\n }\n}\n```\n### Cities Table\n---\n```typescript\ninterface CityMeta {\n population: number,\n connection: string,\n}\n\nexport default class CitiesTable extends AbstractTable<CitiesTable> {\n public id = this.serial('id').primaryKey();\n\n public foundationDate = this.timestamp('name').notNull();\n public location = this.varchar('page', { size: 256 });\n\n public userId = this.int('user_id').foreignKey(UsersTable, (table) => table.id, { onUpdate: 'CASCADE' });\n\n public metadata = this.jsonb<CityMeta>('metadata');\n\n public tableName(): string {\n return 'cities';\n }\n}\n```\n### User Groups Table\n---\n```typescript\nexport default class UserGroupsTable extends AbstractTable<UserGroupsTable> {\n public id = this.serial('id').primaryKey();\n\n public name = this.varchar('name');\n public description = this.varchar('description');\n\n public tableName(): string {\n return 'user_groups';\n }\n}\n```\n### User to User Groups Table\n---\n#### Many to many connection between Users and User Groups\n```typescript\nexport default class UsersToUserGroupsTable extends AbstractTable<UsersToUserGroupsTable> {\n public groupId = this.int('city_id').foreignKey(UserGroupsTable, (table) => table.id, { onDelete: 'CASCADE' });\n public userId = this.int('user_id').foreignKey(UsersTable, (table) => table.id, { onDelete: 'CASCADE' });\n\n public manyToManyIndex = this.index([this.groupId, this.userId]);\n\n public tableName(): string {\n return 'users_to_user_groups';\n }\n}\n```\n\n## CRUD\n### **SELECT**\n---\n```typescript\nconst db = await new DbConnector()\n .connectionString('postgresql://postgres@127.0.0.1/drizzle')\n .connect();\n\nconst usersTable = new UsersTable(db);\n\n// select all\nconst allSelect = await usersTable.select().all();\n\n// select first\nconst firstSelect = await usersTable.select().findOne();\n```\n#### **Sorting and Filtering**\n---\n##### Select all records from `Users` where phone is `\"hello\"`\n```typescript\nconst eqSelect = await usersTable.select().where(\n eq(usersTable.phone, 'hello')\n).all();\n```\n##### Select all records from `Users` where **both** phone is `\"hello\"` **and** phone is `\"hello\"`\n```typescript\nconst andSelect = await usersTable.select().where(\n and([\n eq(usersTable.phone, 'hello'),\n eq(usersTable.phone, 'hello')\n ]),\n).all();\n```\n##### Select all records from `Users` where **either** phone is `\"hello\"` **or** phone is `\"hello\"`\n```typescript\nconst orSelect = await usersTable.select().where(\n or([eq(usersTable.phone, 'hello')]),\n).all();\n```\n##### Select all records from `Users` using **LIMIT** and **OFFSET**\n```typescript\nconst limitOffsetSelect = await usersTable.select().limit(10).offset(10).all();\n```\n##### Select all records from `Users` where `phone` contains `\"hello\"`\n```typescript\nconst likeSelect = await usersTable.select().where(\n like(usersTable.phone, '%hello%')\n).all();\n```\n##### Select all records from `Users` where `phone` equals to some of values from array\n```typescript\nconst inArraySelect = usersTable.select().where(\n inArray(usersTable.phone, ['hello'])\n).all();\n```\n##### Select all records from `Users` where `phone` greater(**>**) than `\"hello\"`\n```typescript\nconst greaterSelect = usersTable.select().where(\n greater(usersTable.phone, 'hello')\n).all();\n```\n##### Select all records from `Users` where `phone` less(**<**) than `\"hello\"`\n```typescript\nconst lessSelect = usersTable.select().where(\n less(usersTable.phone, 'hello')\n).all();\n```\n##### Select all records from `Users` where `phone` greater or equals(**>=**) than `\"hello\"`\n```typescript\nconst greaterEqSelect = usersTable.select().where(\n greaterEq(usersTable.phone, 'hello')\n).all();\n```\n##### Select all records from `Users` where `phone` less or equals(**<=**) \n```typescript\nconst lessEqSelect = usersTable.select().where(\n lessEq(usersTable.phone, 'hello')\n).all();\n```\n##### Select all records from `Users` where `phone` is **NULL**\n```typescript\nconst isNullSelect = usersTable.select().where(\n isNull(usersTable.phone)\n).all();\n```\n##### Select all records from `Users` where `phone` not equals to `\"hello\"`\n```typescript\nconst notEqSelect = usersTable.select().where(\n notEq(usersTable.phone, 'hello')\n).all();\n```\n##### Select all records from `Users` ordered by `phone` in ascending order\n```typescript\nconst ordered = await usersTable.select().orderBy((table) => table.phone, Order.ASC).all();\n```\n#### **Partial Selecting**\n ```typescript\n const partialSelect = await usersTable.select({\n mappedId: usersTable.id,\n mappedPhone: usersTable.phone,\n }).all();\n\n // Usage\n const { mappedId, mappedPhone } = partialSelect;\n ```\n\n\n### **Update**\n---\n##### Update `fullName` to `newName` in `Users` where phone is `\"hello\"`\n```typescript\nawait usersTable.update()\n .where(eq(usersTable.phone, 'hello'))\n .set({ fullName: 'newName' })\n .execute();\n```\n##### Update `fullName` to `newName` in `Users` where phone is `\"hello\"` returning updated `User` model\n```typescript\nawait usersTable.update()\n .where(eq(usersTable.phone, 'hello'))\n .set({ fullName: 'newName' })\n .all();\n```\n##### Update `fullName` to `newName` in `Users` where phone is `\"hello\"` returning updated `User` model\n```typescript\nawait usersTable.update()\n .where(eq(usersTable.phone, 'hello'))\n .set({ fullName: 'newName' })\n .findOne();\n```\n\n### **Delete**\n##### Delete `user` where phone is `\"hello\"`\n```typescript\nawait usersTable.delete()\n .where(eq(usersTable.phone, 'hello'))\n .execute();\n```\n##### Delete `user` where phone is `\"hello\"` returning updated `User` model\n```typescript\nawait usersTable.delete()\n .where(eq(usersTable.phone, 'hello'))\n .all();\n```\n##### Delete `user` where phone is `\"hello\"` returning updated `User` model\n```typescript\nawait usersTable.delete()\n .where(eq(usersTable.phone, 'hello'))\n .findOne();\n```\n\n### **Insert**\n##### Insert `user` with required fields\n```typescript\nawait usersTable.insert({\n test: 1,\n createdAt: new Date(),\n}).execute();\n```\n##### Insert `user` with required fields and get all rows as array\n```typescript\nconst user = await usersTable.insert({\n test: 1,\n createdAt: new Date(),\n}).all();\n```\n##### Insert `user` with required fields and get inserted entity\n```typescript\nconst user = await usersTable.insert({\n test: 1,\n createdAt: new Date(),\n}).findOne();\n```\n##### Insert many `users` with required fields and get all inserted entities\n```typescript\nconst users = await usersTable.insertMany([{\n test: 1,\n createdAt: new Date(),\n }, {\n test: 2,\n createdAt: new Date(),\n }]).all();\n```\n##### Insert many `users` with required fields and get all inserted entities. If such user already exists - update `phone` field\n```typescript\nawait usersTable.insertMany([{\n test: 1,\n createdAt: new Date(),\n }, {\n test: 2,\n createdAt: new Date(),\n }])\n .onConflict(\n (table) => table.phoneIndex,\n { phone: 'confilctUpdate' },\n ).all();\n```\n\n## Joins\n### Join One-To-Many Tables\n##### Join Cities with Users and map to city object with full user\n```typescript\nconst usersTable = new UsersTable(db);\nconst citiesTable = new CitiesTable(db);\n\nconst userWithCities = await citiesTable.select()\n .leftJoin(usersTable, (cities, users) => eq(cities.userId, users.id))\n .where((cities, users) => eq(cities.id, 1))\n .execute();\n\nconst citiesWithUserObject = userWithCities.map((city, user) => ({ ...city, user }));\n```\n\n### Join Many-To-Many Tables\n##### Join User Groups with Users, using many-to-many table\n```typescript\nconst usersWithUserGroups = await usersToUserGroupsTable.select()\n .leftJoin(usersTable, (usersToUserGroups, users) => eq(usersToUserGroups.userId, users.id))\n .leftJoin(userGroupsTable, (usersToUserGroups, _users, userGroups) => eq(usersToUserGroups.groupId, userGroups.id))\n .where((usersToUserGroups, _users, userGroups) => eq(userGroups.id, 1))\n .execute();\n```\n### Join using partial field select\n##### Join Cities with Users getting only needed fields form request\n```typescript\n await citiesTable.select({\n id: citiesTable.id,\n userId: citiesTable.userId,\n })\n .leftJoin(usersTable, (cities, users) => eq(cities.userId, users.id))\n .where((cities, users) => eq(cities.id, 1))\n .execute();\n\nconst citiesWithUserObject = userWithCities.map((city, user) => ({ ...city, user }));\n```\n### Another join examples with different callback ON statements\n```typescript\nawait citiesTable.select()\n .leftJoin(usersTable, (cities, _users) => eq(cities.id, 13))\n .where((cities, _users) => eq(cities.location, 'q'))\n .execute();\n// Join statement generated from query\n// LEFT JOIN users AS users_1\n// ON cities.\"id\"=$1\n// WHERE cities.\"page\"=$2\n//\n// Values: [13, 'q']\n\nawait citiesTable.select()\n .leftJoin(usersTable, (cities, _users) => and([\n eq(cities.id, 13), notEq(cities.id, 14),\n ]))\n .execute();\n// Join statement generated from query\n// LEFT JOIN users AS users_1\n// ON (cities.\"id\"=$1 and cities.\"id\"!=$2)\n//\n// Values: [13, 14]\n\nawait citiesTable.select()\n .leftJoin(usersTable, (_cities, _users) => raw('<custom expression after ON statement>'))\n .where((cities, _users) => eq(cities.location, 'location'))\n .execute();\n// Join statement generated from query\n// LEFT JOIN users AS users_1\n// ON <custom expression after ON statement>\n// WHERE cities.\"page\"=$1\n// \n// Values: ['location']\n```\n\n\n## Migrations\n#### To run migrations generated by drizzle-kit you could use `Migrator` class\n##### Provide drizzle-kit config path\n```typescript\nawait drizzle.migrator(db).migrate('src/drizzle.config.yaml');\n```\n##### Another possibility is to provide object with path to folder with migrations\n```typescript\nawait drizzle.migrator(db).migrate({ migrationFolder: 'drizzle' });\n```\n\n\n## Raw query usage\n#### If you have some complex queries to execute and drizzle-orm can't handle them yet, then you could use `rawQuery` execution\n\n\n##### Execute custom raw query\n```typescript\nconst res: QueryResult<any> = await db.session().execute('SELECT * FROM users WHERE user.id = $1', [1]);\n```"
|
|
44
44
|
}
|
package/test.d.ts
CHANGED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
export {};
|