{"bugs":{"url":"https://github.com/drizzle-team/drizzle-orm/issues"},"dist":{"shasum":"ce5ba756c7896ad8470e2cbfd6004410f565d8f8","tarball":"https://registry.npmjs.org/drizzle-orm-mysql/-/drizzle-orm-mysql-0.15.2.tgz","fileCount":195,"integrity":"sha512-PT68MYtm4QkZpqgHkwICVnhpV8oEqQzesIBs82AXR4xZhJ5UxqzDKO1vPS8bEcCXvGjwpjoBIIFt+eGo8Wn6cQ==","signatures":[{"sig":"MEUCIQDfWqzXdeDCCNINPlU+FSRwEboP3ipuXnoHFjPU5PWXdgIgFmddARWIJcgnNaoWp/db2iaWMoAlEGsQ78ZbzfkbyrY=","keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA"}],"unpackedSize":292959,"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v4.10.10\r\nComment: https://openpgpjs.org\r\n\r\nwsFzBAEBCAAGBQJjxVotACEJED1NWxICdlZqFiEECWMYAoorWMhJKdjhPU1b\r\nEgJ2VmpRBw/+L0jbOyG8FOLbumm1iCeTE+tmK+IVyYllyCYHJow33F8usa2J\r\nXAFDjhu7P16mjhEXVtFz8tRdrw4bV5GmPyGzeGlA2vATcjO6xbS8jw4Jnfi+\r\nKylTjYCGBNIhZ3CG1uT0HLfM8PX0UarKE9yu//O/W8fXfIL+OG3t3PvZrXFe\r\nHBIMUsacLamsjCmUGfOACiFb6hMTzlQt+UJQdXEtPhWBtn5T4gXZB7suyNfU\r\npO0AArRGJv4171mvGledipvA72PwS6momm0UOrGo4yb+FP8pLyGZbGwsSjVT\r\nJhspMImJ/AA3oAXMJ2b4rUgTuMTf6nl8T6mGg+YYLrsQ34CeiLq4dF7Le68O\r\nwMIzr0jcerfMMofqp288UBXuHpmBBnKRFvrcxgbOsU45q9VCuc28TbwD721R\r\noTk42rBwRsONqikR96m+IE7bAebDHfDVOCjG4dVO6i8/LyBauihm+49LY9ly\r\n5KYPBp361NbTH1d1yHhmen8I9g0fDqtlGk5IwP28ESEmcZrYtD5FmBhiROlE\r\n7T2V5c14aDGyXPiB8rmIVS2AmaF3eCSdiVW7nhM+eaJKME/oMMkPKkwX+9Oj\r\nmtZ5AzCSUaIz3CLjxmgC4QzVoqPCXJvHFuBZgFmzDksJ+9xpzkVy4kB2NkZh\r\nLeNRP/WwwPbf6m8dvO7ZkY7iUtOLS4rwwWY=\r\n=Gdt4\r\n-----END PGP SIGNATURE-----\r\n"},"name":"drizzle-orm-mysql","_from":"file:package.tgz","types":"./index.d.ts","author":{"name":"Drizzle Team"},"readme":"<div align='center'>\n<h1>Drizzle ORM | MySQL <a href=''><img alt='npm' src='https://img.shields.io/npm/v/drizzle-orm-mysql?label='></a></h1>\n<img alt='npm' src='https://img.shields.io/npm/dm/drizzle-orm-mysql'>\n<img alt='pg version' src='https://img.shields.io/npm/dependency-version/drizzle-orm-mysql/peer/mysql2'>\n<img alt='npm bundle size' src='https://img.shields.io/bundlephobia/min/drizzle-orm-mysql'>\n<a href='https://discord.gg/yfjTbVXMW4'><img alt='Discord' src='https://img.shields.io/discord/1043890932593987624'></a>\n<img alt='NPM' src='https://img.shields.io/npm/l/drizzle-orm-mysql'>\n<h6><i>If you know SQL, you know Drizzle ORM</i></h6>\n<hr />\n</div>\n\nDrizzle ORM is a TypeScript ORM for SQL databases designed with maximum type safety in mind. It comes with a [drizzle-kit](https://github.com/drizzle-team/drizzle-kit-mirror) CLI companion for automatic SQL migrations generation. This is the documentation for Drizzle ORM version for PostgreSQL.\n\n## Installation\n\n```bash\n# npm\nnpm i drizzle-orm drizzle-orm-mysql mysql2\nnpm i -D drizzle-kit\n\n# yarn\nyarn add drizzle-orm drizzle-orm-mysql mysql2\nyarn add -D drizzle-kit\n\n# pnpm\npnpm add drizzle-orm drizzle-orm-mysql2 mysql2\npnpm add -D drizzle-kit\n```\n\n## SQL schema declaration\n\nWith `drizzle-orm` you declare SQL schema in TypeScript. You can have either one `schema.ts` file with all declarations or you can group them logically in multiple files. We prefer to use single file schema.\n\n### Single schema file example\n\n```\n📦 <project root>\n └ 📂 src\n    └ 📂 db\n       └ 📜schema.ts\n```\n\n### Multiple schema files example\n\n```\n📦 <project root>\n └ 📂 src\n    └ 📂 db\n       └ 📂 schema\n          ├ 📜users.ts\n          ├ 📜countries.ts\n          ├ 📜cities.ts\n          ├ 📜products.ts\n          ├ 📜clients.ts\n          ├ 📜enums.ts\n          └ 📜etc.ts\n```\n\n## Quick start\n\n```typescript\n// schema.ts\nexport const users = mysqlTable('users', {\n  id: serial('id').primaryKey(),\n  fullName: text('full_name'),\n  phone: varchar('phone', { length: 256 }),\n});\n```\n\n### Connect using mysql2 Pool (recommended)\n\n```typescript\n// db.ts\nimport { drizzle } from 'drizzle-orm-mysql/mysql2';\n\nimport mysql from 'mysql2/promise';\nimport { users } from './schema';\n\n// create the connection\nconst poolConnection = mysql.createPool({\n    host:'localhost', \n    user: 'root',\n    database: 'test'\n});\n\nconst db = drizzle(poolConnection);\n\nconst allUsers = await db.select(users);\n```\n\n### Connect using mysql2 Client\n\n```typescript\n// db.ts\nimport { drizzle } from 'drizzle-orm-mysql/mysql2';\n\nimport mysql from 'mysql2/promise';\nimport { users } from './schema';\n\n// create the connection\nconst connection = await mysql.createConnection({\n    host:'localhost', \n    user: 'root', \n    database: 'test'\n});\n\nconst db = drizzle(connection);\n\nconst allUsers = await db.select(users);\n```\n\n## Schema declaration\n\nThis is how you declare SQL schema in `schema.ts`. You can declare tables, indexes and constraints, foreign keys and enums. Please pay attention to `export` keyword, they are mandatory if you'll be using [drizzle-kit SQL migrations generator](#migrations).\n\n```typescript\n// db.ts\nimport { int, mysqlEnum, mysqlTable, serial, uniqueIndex, varchar } from 'drizzle-orm-mysql';\n\n// declaring enum in database\nexport const countries = mysqlTable('countries', {\n\tid: serial('id').primaryKey(),\n\tname: varchar('name', { length: 256 }),\n}, (countries) => ({\n\tnameIndex: uniqueIndex('name_idx').on(countries.name),\n}));\n\nexport const cities = mysqlTable('cities', {\n\tid: serial('id').primaryKey(),\n\tname: varchar('name', { length: 256 }),\n\tcountryId: int('country_id').references(() => countries.id),\n\tpopularity: mysqlEnum('popularity', ['unknown', 'known', 'popular']),\n});\n```\n\n### Database and table entity types\n\n```typescript\n// db.ts\nimport { InferModel, MySqlDatabase, MySqlRawQueryResult, mysqlTable, serial, text, varchar } from 'drizzle-orm-mysql';\nimport mysql from 'mysql2/promise';\nimport { drizzle } from 'drizzle-orm-mysql/mysql2';\n\nconst users = mysqlTable('users', {\n  id: serial('id').primaryKey(),\n  fullName: text('full_name'),\n  phone: varchar('phone', { length: 256 }),\n});\n\nexport type User = InferModel<typeof users>; // return type when queried\nexport type NewUser = InferModel<typeof users, 'insert'>; // insert type\n...\n\n// init node-postgres Pool or Client\nconst poolConnection = mysql.createPool({\n    host:'localhost', \n    user: 'root',\n    database: 'test'\n});\n\nexport const db: MySqlDatabase = drizzle(poolConnection);\n\nconst result: User[] = await db.select(users);\n\n/* type MySqlRawQueryExample is a response from mysql2 driver\n   type MySqlRawQueryResult = [ResultSetHeader, FieldPacket[]];\n   type ResultSetHeader = {\n      affectedRows: number;\n      fieldCount: number;\n      info: string;\n      insertId: number;\n      serverStatus: number;\n      warningStatus: number;\n      changedRows?: number;\n    }\n*/\nexport async function insertUser(user: NewUser): Promise<MySqlRawQueryResult> {\n  return db.insert(users).values(user);\n}\n```\n\n### Declaring indexes and foreign keys\n\n```typescript\n// db.ts\nimport { foreignKey, index, int, mysqlTable, serial, uniqueIndex, varchar } from 'drizzle-orm-mysql';\n\nexport const countries = mysqlTable('countries', {\n    id: serial('id').primaryKey(),\n    name: varchar('name', { length: 256 }),\n    population: int('population'),\n  }, (table) => ({\n    nameIdx: index('name_idx').on(table.name), // one column\n    namePopulationIdx: index('name_population_idx').on(table.name, table.population), // multiple columns\n    uniqueIdx: uniqueIndex('unique_idx').on(table.name), // unique index\n  })\n);\n\nexport const cities = mysqlTable('cities', {\n  id: serial('id').primaryKey(),\n  name: varchar('name', { length: 256 }),\n  countryId: int('country_id').references(() => countries.id), // inline foreign key\n  countryName: varchar('country_id', { length: 256 }),\n}, (cities) => ({\n  // explicit foreign key with 1 column\n  countryFk: foreignKey(({\n    columns: [cities.countryId],\n    foreignColumns: [countries.id],\n  })),\n  // explicit foreign key with multiple columns\n  countryIdNameFk: foreignKey(({\n    columns: [cities.countryId, cities.countryName],\n    foreignColumns: [countries.id, countries.name],\n  })),\n}));\n\n// Index declaration reference\nindex('name_idx')\n    .on(table.column1, table.column2, ...)\n    .using('btree' | 'hash')\n    .lock('default' | 'none' | 'shared' | 'exclusive')\n    .algorythm('default' | 'inplace' | 'copy')\n```\n\n## Column types\n\n\n```typescript\nmysqlEnum('popularity', ['unknown', 'known', 'popular'])\n\nint('...');\ntinyint('name');\nsmallint('name');\nmediumint('name');\nbigint('...', { mode: 'number' });\n\nreal('name', { precision: 1, scale: 1 });\ndecimal('name', { precision: 1, scale: 1 });\ndouble('name', { precision: 1, scale: 1 });\nfloat('name',);\n\nserial('name');\n\nbinary('name');\nvarbinary('name', { length: 2 });\n\nchar('name');\nvarchar('name', { length: 2 });\ntext('name');\n\nboolean('name');\n\ndate('...');\ndatetime('...', { mode: 'date' | 'string', fsp: 0..6 });\ntime('...', { mode: 'date' | 'string', fsp: 0..6 });\nyear('...');\n\ntimestamp('name');\ntimestamp('...', { mode: 'date' | 'string', fsp: 0..6 })\ntimestamp('...').defaultNow()\n\njson('name');\njson<string[]>('name');\n```\n\n## Table schemas\n> **Warning**\n> If you will have tables with same names in different schemas then drizzle will respond with `never[]` error in result types and error from database\n> \n> In this case you may use [alias syntax](https://github.com/drizzle-team/drizzle-orm/tree/main/drizzle-orm-mysql#join-aliases-and-self-joins)\n\n---\n\nUsage example\n```typescript\n// Table in default schema\nconst publicUsersTable = mysqlTable('users', {\n\tid: serial('id').primaryKey(),\n\tname: text('name').notNull(),\n\tverified: boolean('verified').notNull().default(false),\n\tjsonb: json<string[]>('jsonb'),\n\tcreatedAt: timestamp('created_at', { fsp: 2 }).notNull().defaultNow(),\n});\n\n\n// Table in custom schema\nconst mySchema = mysqlSchema('mySchema');\n\nconst mySchemaUsersTable = mySchema('users', {\n\tid: serial('id').primaryKey(),\n\tname: text('name').notNull(),\n\tverified: boolean('verified').notNull().default(false),\n\tjsonb: json<string[]>('jsonb'),\n\tcreatedAt: timestamp('created_at', { fsp: 2 }).notNull().defaultNow(),\n});\n```\n\n## Select, Insert, Update, Delete\n\n### Select\n\nQuerying, sorting and filtering. We also support partial select.\n\n```typescript\n...\nimport { mysqlTable, serial, text, varchar } from 'drizzle-orm-mysql';\nimport { drizzle } from 'drizzle-orm-mysql/mysql2';\nimport { and, asc, desc, eq, or } from 'drizzle-orm/expressions';\n\nconst users = mysqlTable('users', {\n  id: serial('id').primaryKey(),\n  name: text('full_name'),\n});\n\nconst db = drizzle(...);\n\nawait db.select(users);\nawait db.select(users).where(eq(users.id, 42));\n\n// you can combine filters with eq(...) or or(...)\nawait db.select(users)\n  .where(and(eq(users.id, 42), eq(users.name, 'Dan')));\n\nawait db.select(users)\n  .where(or(eq(users.id, 42), eq(users.id, 1)));\n\n// partial select\nconst result = await db.select(users).fields({\n    mapped1: users.id,\n    mapped2: users.name,\n  });\nconst { mapped1, mapped2 } = result[0];\n\n// limit, offset & order by\nawait db.select(users).limit(10).offset(10);\nawait db.select(users).orderBy(asc(users.name));\nawait db.select(users).orderBy(desc(users.name));\n// you can pass multiple order args\nawait db.select(users).orderBy(asc(users.name), desc(users.name));\n\n// list of all filter operators\neq(column, value)\neq(column1, column2)\nne(column, value)\nne(column1, column2)\n\nnotEq(column, value)\nless(column, value)\nlessEq(column, value)\n\ngt(column, value)\ngt(column1, column2)\ngte(column, value)\ngte(column1, column2)\nlt(column, value)\nlt(column1, column2)\nlte(column, value)\nlte(column1, column2)\n\nisNull(column)\nisNotNull(column)\n\ninArray(column, values[])\ninArray(column, sqlSubquery)\nnotInArray(column, values[])\nnotInArray(column, sqlSubquery)\n\nexists(sqlSubquery)\nnotExists(sqlSubquery)\n\nbetween(column, min, max)\nnotBetween(column, min, max)\n\nlike(column, value)\nlike(column, value)\nilike(column, value)\nnotIlike(column, value)\n\nnot(sqlExpression)\n\nand(expressions: SQL[])\nor(expressions: SQL[])\n```\n\n### Insert\n\n```typescript\nimport { mysqlTable, serial, text, timestamp, InferModel } from 'drizzle-orm-mysql';\nimport { drizzle } from 'drizzle-orm-mysql/mysql2';\n\nconst users = mysqlTable('users', {\n  id: serial('id').primaryKey(),\n  name: text('name'),\n  createdAt: timestamp('created_at'),\n});\n\ntype NewUser = InferModel<typeof users>;\n\nconst db = drizzle(...);\n\nawait db.insert(users)\n  .values({\n    name: 'Andrew',\n    createdAt: new Date(),\n  });\n\n// accepts vararg of items\nawait db.insert(users)\n  .values(\n    {\n      name: 'Andrew',\n      createdAt: new Date(),\n    },\n    {\n      name: 'Dan',\n      createdAt: new Date(),\n    },\n  );\n\nconst newUsers: NewUser[] = [\n  {\n      name: 'Andrew',\n      createdAt: new Date(),\n  },\n  {\n    name: 'Dan',\n    createdAt: new Date(),\n  },\n];\n\nawait db.insert(users).values(...newUsers);\n```\n\n### Update and Delete\n\n```typescript\nawait db.update(users)\n  .set({ name: 'Mr. Dan' })\n  .where(eq(users.name, 'Dan'));\n\t\nawait db.delete(users)\n  .where(eq(users.name, 'Dan'));\n```\n\n### Joins\n\nLast but not least. Probably the most powerful feature in the library🚀\n\n#### Many-to-one\n\n```typescript\nconst cities = mysqlTable('cities', {\n  id: serial('id').primaryKey(),\n  name: text('name'),\n});\n\nconst users = mysqlTable('users', {\n  id: serial('id').primaryKey(),\n  name: text('name'),\n  cityId: int('city_id').references(() => cities.id)\n});\n\nconst result = db.select(cities)\n  .leftJoin(users, eq(cities2.id, users2.cityId));\n```\n\n#### Many-to-many\n\n```typescript\nconst users = mysqlTable('users', {\n  id: serial('id').primaryKey(),\n  name: text('name'),\n});\n\nconst chatGroups = mysqlTable('chat_groups', {\n  id: serial('id').primaryKey(),\n  name: text('name'),\n});\n\nconst usersToChatGroups = mysqlTable('usersToChatGroups', {\n  userId: integer('user_id').notNull().references(() => users.id),\n  groupId: integer('group_id').notNull().references(() => chatGroups.id),\n});\n\n// querying user group with id 1 and all the participants(users)\nconst result = await db.select(usersToChatGroups)\n  .leftJoin(users, eq(usersToChatGroups.userId, users.id))\n  .leftJoin(chatGroups, eq(usersToChatGroups.groupId, chatGroups.id))\n  .where(eq(chatGroups.id, 1));\n```\n\n#### Join aliases and self-joins\n\n```typescript\nimport { ..., alias } from 'drizzle-orm-mysql';\n\nexport const files = mysqlTable('folders', {\n  name: text('name').notNull(),\n  parent: text('parent_folder')\n})\n\nconst nestedFiles = alias(files, 'nested_files');\n\n// will return files and folders and nested files for each folder at root dir\nconst result = await db.select(files)\n  .leftJoin(nestedFiles, eq(files.name, nestedFiles.name))\n  .where(eq(files.parent, '/'));\n```\n\n#### Join using partial select\n\n```typescript\n// Select user ID and city ID and name\nconst result1 = await db.select(cities).fields({\n  userId: users.id,\n  cityId: cities.id,\n  cityName: cities.name\n}).leftJoin(users, eq(users.cityId, cities.id));\n\n// Select all fields from users and only id and name from cities\nconst result2 = await db.select(cities).fields({\n  // Supports any level of nesting!\n  user: users,\n  city: {\n    id: cities.id,\n    name: cities.name\n  },\n}).leftJoin(users, eq(users.cityId, cities.id));\n```\n\n\n## Prepared statements\n\n```typescript\nconst query = db.select(users)\n  .where(eq(users.name, 'Dan'))\n  .prepare();\n\nconst result = await query.execute();\n```\n\n### Prepared statements with parameters\n\n```typescript\nimport { placeholder } from 'drizzle-orm-mysql';\n\nconst query = db.select(users)\n  .where(eq(users.name, placeholder('name')))\n  .prepare();\n\nconst result = await query.execute({ name: 'Dan' });\n```\n\n## Raw queries execution\n\nIf you have some complex queries to execute and drizzle-orm can't handle them yet, you can use the `db.execute` method to execute raw queries.\n\n```typescript\n// it will automatically run a parametrized query!\nconst res: MySqlQueryResult<{ id: number; name: string; }> = await db.execute<{ id: number, name: string }>(sql`select * from ${users} where ${users.id} = ${userId}`);\n```\n\n## Migrations\n\n### Automatic SQL migrations generation with drizzle-kit\n\n[DrizzleKit](https://www.npmjs.com/package/drizzle-kit) - is a CLI migrator tool for DrizzleORM. It is probably one and only tool that lets you completely automatically generate SQL migrations and covers ~95% of the common cases like deletions and renames by prompting user input.\n\nCheck out the [docs for DrizzleKit](https://github.com/drizzle-team/drizzle-kit-mirror)\n\nFor schema file:\n\n```typescript\nimport { index, integer, mysqlTable, serial, varchar } from 'drizzle-orm-mysql';\n\nexport const users = mysqlTable('users', {\n  id: serial('id').primaryKey(),\n  fullName: varchar('full_name', { length: 256 }),\n}, (users) => ({\n  nameIdx: index('name_idx').on(users.fullName),\n}));\n\nexport const authOtps = mysqlTable('auth_otp', {\n  id: serial('id').primaryKey(),\n  phone: varchar('phone', { length: 256 }),\n  userId: int('user_id').references(() => users.id),\n}\n```\n\nIt will generate:\n\n```SQL\nCREATE TABLE `users` (\n `id` int PRIMARY KEY,\n `full_name` varchar(256)\n);\n\n\nCREATE TABLE `auth_otp` (\n `id` serial PRIMARY KEY,\n `phone` varchar(256),\n `user_id` int\n);\n\n\nALTER TABLE auth_otp ADD CONSTRAINT auth_otp_user_id_users_id_fk FOREIGN KEY (`user_id`) REFERENCES users(`id`) ;\nCREATE INDEX name_idx ON users (`full_name`);\n```\n\nAnd you can run migrations manually or using our embedded migrations module\n\n```typescript\nimport { drizzle } from 'drizzle-orm-mysql/mysql2';\nimport { migrate } from 'drizzle-orm-mysql/mysql2/migrator';\nimport mysql from 'mysql2/promise';\n\n// create the connection\nconst poolConnection = mysql.createPool({\n    host:'localhost', \n    user: 'root',\n    database: 'test'\n});\n\nconst db = drizzle(poolConnection);\n\n// this will automatically run needed migrations on the database\nawait migrate(db, { migrationsFolder: './drizzle' })\n```\n","license":"Apache-2.0","scripts":{"pack":"(cd dist && pnpm pack --pack-destination ..) && rm -f package.tgz && mv *.tgz package.tgz","build":"tsc -p tsconfig.build.json && resolve-tspaths && cp README.md package.json dist/","release":"pnpm build && pnpm run pack && pnpm run publish","test:types":"cd tests && tsc","release:beta":"pnpm build && pnpm run pack && pnpm run publish --tag beta"},"_npmUser":{"name":"dankochetov","email":"danil.kochetov@gmail.com"},"homepage":"https://github.com/drizzle-team/drizzle-orm#readme","keywords":["orm","mysql","database","sql","typescript","drizzle","drizzle-orm","drizzle-orm-mysql"],"_resolved":"/home/runner/work/drizzle-orm/drizzle-orm/drizzle-orm-mysql/package.tgz","_integrity":"sha512-PT68MYtm4QkZpqgHkwICVnhpV8oEqQzesIBs82AXR4xZhJ5UxqzDKO1vPS8bEcCXvGjwpjoBIIFt+eGo8Wn6cQ==","deprecated":"This package is merged into drizzle-orm starting from 0.17.0. See https://www.npmjs.com/package/drizzle-orm","repository":{"url":"git+https://github.com/drizzle-team/drizzle-orm.git","type":"git"},"_npmVersion":"8.19.3","description":"Drizzle ORM package for MySQL database","directories":{},"maintainers":[{"name":"alexblokh","email":"aleksandrblokh@gmail.com"},{"name":"sheriman","email":"andreysherman11@gmail.com"},{"name":"dankochetov","email":"danil.kochetov@gmail.com"}],"_nodeVersion":"16.19.0","_hasShrinkwrap":false,"readmeFilename":"README.md","devDependencies":{"mysql2":"^2.3.3","@types/node":"^18.11.12","drizzle-orm":"link:../drizzle-orm/dist"},"peerDependencies":{"mysql2":">=2 <3","drizzle-orm":">=0.15 <0.16"},"peerDependenciesMeta":{"mysql2":{"optional":true}},"_npmOperationalInternal":{"tmp":"tmp/drizzle-orm-mysql_0.15.2_1673878061331_0.010217108317063905","host":"s3://npm-registry-packages"},"_id":"drizzle-orm-mysql@0.15.2","version":"0.15.2"}