Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

drizzle-orm

Package Overview
Dependencies
Maintainers
2
Versions
927
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

drizzle-orm - npm Package Compare versions

Comparing version 0.10.30 to 0.10.31

builders/aggregators/abstractAggregator.d.ts

12

package.json
{
"name": "drizzle-orm",
"version": "0.10.30",
"version": "0.10.31",
"description": "",
"main": "dist/index.js",
"types": "dist/index.d.ts",
"files": [
"dist"
],
"main": "index.js",
"types": "index.d.ts",
"repository": {

@@ -40,4 +37,3 @@ "type": "git",

"run": "ts-node src/tables/newAbstractTable.ts"
},
"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\n const userWithCities = await citiesTable.select()\n .where(eq(citiesTable.id, 1))\n .leftJoin(UsersTable,\n (city) => city.userId,\n (users) => 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 and map response to get user object with groups array\n```typescript\n const usersWithUserGroups = await usersToUserGroupsTable.select()\n .where(eq(userGroupsTable.id, 1))\n .leftJoin(UsersTable,\n (userToGroup) => userToGroup.userId,\n (users) => users.id)\n .leftJoin(UsersToUserGroupsTable, UserGroupsTable,\n (userToGroup) => userToGroup.groupId,\n (users) => users.id)\n .execute();\n\n const userGroupWithUsers = usersWithUserGroups.group({\n one: (_, dbUser, dbUserGroup) => dbUser!,\n many: (_, dbUser, dbUserGroup) => dbUserGroup!,\n });\n\n const userWithGroups: ExtractModel<UsersTable> & { groups: ExtractModel<UserGroupsTable>[] } = {\n ...userGroupWithUsers.one,\n groups: userGroupWithUsers.many,\n };\n```\n##### Join User Groups with Users, using many-to-many table and map response to get user group object with users array\n```typescript\n const usersWithUserGroups = await usersToUserGroupsTable.select()\n .where(eq(userGroupsTable.id, 1))\n .leftJoin(UsersTable,\n (userToGroup) => userToGroup.userId,\n (users) => users.id)\n .leftJoin(UsersToUserGroupsTable, UserGroupsTable,\n (userToGroup) => userToGroup.groupId,\n (users) => users.id)\n .execute();\n\n const userGroupWithUsers = usersWithUserGroups.group({\n one: (_, dbUser, dbUserGroup) => dbUserGroup!,\n many: (_, dbUser, dbUserGroup) => dbUser!,\n });\n\n const userWithGroups: ExtractModel<UserGroupsTable> & { users: ExtractModel<UsersTable>[] } = {\n ...userGroupWithUsers.one,\n users: userGroupWithUsers.many,\n };\n```\n### Join using partial field select\n##### Join Cities with Users getting only needed fields form request\n```typescript\nawait citiesTable.select({\n id: citiesTable.id,\n userId: citiesTable.userId,\n })\n .where(eq(citiesTable.id, 1))\n .leftJoin(UsersTable,\n (city) => city.userId,\n (users) => users.id,\n {\n id: usersTable.id,\n })\n .execute();\n\nconst citiesWithUserObject = userWithCities.map((city, user) => ({ ...city, user }));\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```"
}
}
SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc