{"id":26875055,"url":"https://github.com/coajs/coa-mysql","last_synced_at":"2025-10-25T00:45:25.360Z","repository":{"id":41817006,"uuid":"266057351","full_name":"coajs/coa-mysql","owner":"coajs","description":"☘️ MySQL database components for coajs, including basic data models, cache data models, distributed ID, etc.","archived":false,"fork":false,"pushed_at":"2023-03-06T03:33:55.000Z","size":496,"stargazers_count":1,"open_issues_count":8,"forks_count":4,"subscribers_count":1,"default_branch":"main","last_synced_at":"2025-03-09T19:47:37.351Z","etag":null,"topics":["coa","coa-mysql","coajs","crud","database","knex","model","mysql","redis","typescript"],"latest_commit_sha":null,"homepage":"https://npmjs.org/coa-mysql","language":"TypeScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/coajs.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2020-05-22T08:21:01.000Z","updated_at":"2021-10-02T19:28:53.000Z","dependencies_parsed_at":"2023-02-09T01:01:26.926Z","dependency_job_id":null,"html_url":"https://github.com/coajs/coa-mysql","commit_stats":null,"previous_names":[],"tags_count":10,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/coajs%2Fcoa-mysql","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/coajs%2Fcoa-mysql/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/coajs%2Fcoa-mysql/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/coajs%2Fcoa-mysql/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/coajs","download_url":"https://codeload.github.com/coajs/coa-mysql/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":246320131,"owners_count":20758410,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["coa","coa-mysql","coajs","crud","database","knex","model","mysql","redis","typescript"],"created_at":"2025-03-31T10:22:15.692Z","updated_at":"2025-10-25T00:45:25.289Z","avatar_url":"https://github.com/coajs.png","language":"TypeScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"# coa-mysql\n\n[![GitHub license](https://img.shields.io/badge/license-MIT-green.svg?style=flat-square)](LICENSE)\n[![npm version](https://img.shields.io/npm/v/coa-mysql.svg?style=flat-square)](https://www.npmjs.org/package/coa-mysql)\n[![npm downloads](https://img.shields.io/npm/dm/coa-mysql.svg?style=flat-square)](http://npm-stat.com/charts.html?package=coa-mysql)\n[![PRs Welcome](https://img.shields.io/badge/PRs-welcome-brightgreen.svg?style=flat-square)](https://github.com/coajs/coa-mysql/pulls)\n\nEnglish | [简体中文](README.zh-CN.md)\n\nMySQL database components for coajs, including basic data models, cache data models, distributed ID, etc.\n\n## Feature\n\n- **Functional**: Basic data connection based on [mysql](https://github.com/mysqljs/mysql)，SQL query based on [knex](https://github.com/knex/knex). Pay attention to performance, full-featured, including original library all use methods\n- **Lightweight**: No more than 1,000 lines of code, do not rely on other third-party libraries\n- **Fast and Convenient**: Basic data model comes with CRUD operation, no extra code\n- **Automatic Cache**: Cache data model automatically performs data cache management (cache generation, cache elimination, etc.), cache is based on[coa-redis](https://github.com/coajs/coa-redis)\n- **TypeScript**: All written in TypeScript, type constraint, IDE friendship\n\n## Component\n\n- Basic data model `MysqlNative`: Automatically implement basic CRUD\n- Cache data model `MysqlCache`: Take over data cache logic on the basic data model\n- Distributed ID `MysqlUuid`: Lightweight distributed UUID\n\n## Quick Start\n\n### Install\n\n```shell\nyarn add coa-mysql\n```\n\n### Instance configuration\n\n```typescript\nimport { MysqlBin } from 'coa-mysql'\n\n// MySQL configuration\nconst mysqlConfig = {\n  host: '127.0.0.1',\n  port: 3306,\n  user: 'root',\n  password: 'root',\n  charset: 'utf8mb4',\n  trace: true,\n  debug: false,\n  databases: {\n    main: { database: 'test', ms: 7 * 24 * 3600 * 1000 },\n    other: { database: 'other', ms: 7 * 24 * 3600 * 1000 },\n  },\n}\n\n// Initialize MySQL basic connection,\n// follow-up all models depend on this example\nconst mysqlBin = new MysqlBin(mysqlConfig)\n```\n\n### Basic SQL query\n\nNew user table `user`, the table structure is as follows\n\n```shell\nCREATE TABLE `user` (\n  `id` int(10) unsigned NOT NULL AUTO_INCREMENT COMMENT 'Self-increased primary key',\n  `userId` varchar(32) NOT NULL DEFAULT '' COMMENT 'user ID',\n  `name` varchar(64) NOT NULL DEFAULT '' COMMENT 'name',\n  `mobile` varchar(16) NOT NULL DEFAULT '' COMMENT 'mobile',\n  `avatar` varchar(256) NOT NULL DEFAULT '' COMMENT 'avatar',\n  `gender` int(11) NOT NULL DEFAULT '0' COMMENT 'gender, 1 male, 2 female',\n  `language` varchar(16) NOT NULL DEFAULT '' COMMENT 'language',\n  `status` int(1) NOT NULL DEFAULT '1' COMMENT 'status, 1 normal 2 hidden',\n  `created` bigint(20) NOT NULL DEFAULT '0' COMMENT 'Create time',\n  `updated` bigint(20) NOT NULL DEFAULT '0' COMMENT 'Update time',\n  PRIMARY KEY (`id`) USING BTREE,\n  UNIQUE KEY `user_userid_unique` (`userId`) USING BTREE\n) COMMENT='User Table';\n```\n\nSQL operations on the user table\n\n```typescript\n// Insert data, see https://knexjs.org/#Builder-insert\nmysqlBin.io.table('user').insert({ userId: 'user-a', name: 'A', mobile: '15010001001', gender: 1, language: 'zh-CN', status: 1 })\n\n// Query all data, see https://knexjs.org/#Builder-select\nmysqlBin.io.table('user').select()\nmysqlBin.io.select('*').from('user')\n\n// Conditional queries, see https://knexjs.org/#Builder-where\nmysqlBin.io.table('user').where('status', '=', 1)\n\n// Update data, see http://knexjs.org/#Builder-update\nmysqlBin.io.table('user').update({ name: 'AA', gender: 2 }).where({ userId: 'user-a' })\n\n// Delete data, see http://knexjs.org/#Builder-del%20/%20delete\nmysqlBin.io.table('user').delete().where({ userId: 'user-a' })\n```\n\nThe `io` in this is a `Knex` object, can support **all the usage** of [Knex.js](http://knexjs.org/#Builder)\n\n### Basic data model\n\nIn project engineering, in order to ensure the efficiency and rigor of the query, we will not directly operate the SQL statement. Basic data modules can help us implement CURD operations. Define a basic data model `User` by as follows\n\n```typescript\nimport { MysqlBin, MysqlNative } from 'coa-mysql'\n\n// Define the default structure of User\nconst userScheme = {\n  userId: '' as string,\n  name: '' as string,\n  mobile: '' as string,\n  avatar: '' as string,\n  gender: 1 as number,\n  language: '' as string,\n  status: 1 as number,\n  created: 0 as number,\n  updated: 0 as number,\n}\n// Define the User type (automatically generated by the default structure)\ntype UserScheme = typeof userScheme\n\n// Initialization by base class\nconst User = new (class extends MysqlNative\u003cUserScheme\u003e {\n  constructor() {\n    super(\n      {\n        name: 'User', // Table name, default transformation into a `snackcase` format, such as User-\u003euser UserPhoto-\u003euser_photo\n        title: 'User Table', // Table note name\n        scheme: userScheme, // Default structure of the table\n        pick: ['userId', 'name'], // Field information displayed when querying the list\n      },\n      // Binding configuration instance bin\n      mysqlBin\n    )\n  }\n\n  // Custom method\n  async customMethod() {\n    // Do something\n  }\n})()\n```\n\nGenerally, a data sheet corresponds to a model, and after the model is defined, we can operate the model directly to operate the table\n\n```typescript\n// Insert\nawait User.insert({ name: 'Tom', gender: 1 }) // return 'id001', userId = 'id001' of this data\n\n// Batch insert\nawait User.mInsert([\n  { name: 'Tom', gender: 1 },\n  { name: 'Jerry', gender: 1 },\n]) // return ['id002','id003']\n\n// Update by ID\nawait User.updateById('id002', { name: 'Lily' }) // return 1\n\n// Batch update by ID array\nawait User.updateByIds(['id002', 'id003'], { status: 2 }) // return 2\n\n// Update or insert the ID (id exists if updated, if there is no insert)\nawait User.upsertById('id002', { name: 'Tom', gender: 1 }) // return 1, update one data of userId = 'id02'\nawait User.upsertById('id004', { name: 'Lily', gender: 1 }) // return 0, insert a new data of userId = 'id04'\n\n// Delete by ID array\nawait User.deleteByIds(['id003', 'id004']) // return 2\n\n// Query one by ID, the second parameter settings return the data contained in the result\nawait User.getById('id001', ['name']) // data is {userId:'id001',name:'Tom',gender:1,status:1,...} return {userId:'id001',name:'Tom'}\n\n// Get multiple data by ID array\nawait User.mGetByIds(['id001', 'id002'], ['name']) // return {id001:{userId:'id001',name:'Tom'},id002:{userId:'id002',name:'Lily'}}\n\n// Truncate table\nawait User.truncate() // void, do not report an error is to operate successfully\n\n// Custom method\nawait User.customMethod() // call a custom method\n```\n\nIn the actual project, we may need to define multiple models, and there are some public methods on each model. At this time, we can abstract a base class model, other models inherit this base class model\n\n```typescript\nimport { CoaMysql } from 'coa-mysql'\n\n// Define the base class of a model by mysqlBin, each model can use this base class\nexport class MysqlNativeModel\u003cT\u003e extends MysqlNative\u003cT\u003e {\n  constructor(option: CoaMysql.ModelOption\u003cT\u003e) {\n    // Configure the instance bin binding\n    super(option, mysqlBin)\n  }\n\n  // You can also define some general methods\n  commonMethod() {\n    // do something\n  }\n}\n\n// Define user model by base model\nconst User = new (class extends MysqlNativeModel\u003cUserScheme\u003e {\n  constructor() {\n    super({ name: 'User', title: 'User Table', scheme: userScheme, pick: ['userId', 'name'] })\n  }\n\n  // Custom method\n  async customMethodForUser() {\n    // Do something\n  }\n})()\n\n// Define Manager model by base model\nconst Manager = new (class extends MysqlNativeModel\u003cManagerScheme\u003e {\n  constructor() {\n    super({ name: 'Manager', title: 'Manager Table', scheme: managerScheme, pick: ['managerId', 'name'] })\n  }\n})()\n\n// Both user model and manager model can call common method\nawait User.commonMethod()\nawait Manager.commonMethod()\n\n// Only user models can call custom method\nawait User.customMethodForUser()\n```\n\n### Cache data model\n\nBased on [coa-redis](https://www.npmjs.com/package/coa-redis) to achieve fast and efficient data cache logic, and **unify the cache, maintain the life cycle of the cache, to ensure the consistency of cache and mysql data**\n\nNeed to install `coa-redis` before use, instructions for use to view [here](https://github.com/coajs/coa-redis)\n\nThe method of use of cache data model is exactly the same as the basic data model. Only need to replace the `MysqlNative` to be `MysqlCache`\n\n```typescript\nimport { CoaMysql, MysqlCache } from 'coa-mysql'\nimport { RedisBin, RedisCache } from 'coa-redis'\n\n// Define a Redis instance, detail usage see https://github.com/coajs/coa-redis\nconst redisCache = new RedisCache(new RedisBin({ host: '127.0.0.1' }))\n\n// Define the base class for a cache data model\nexport class MysqlCacheModel\u003cT\u003e extends MysqlCache\u003cT\u003e {\n  constructor(option: CoaMysql.ModelOption\u003cT\u003e) {\n    // Bind the configuration instance and the redisCache instance on this base class\n    super(option, mysqlBin, redisCache)\n  }\n}\n\n// Define cache user model by cache base class\nconst UserCached = new (class extends MysqlCacheModel\u003cUserScheme\u003e {\n  constructor() {\n    super({ name: 'User', title: 'User Table', scheme: userScheme, pick: ['userId', 'name'] })\n  }\n})()\n\n// Query data\nawait User.getById('id001') // First query will read the database\nawait User.getById('id001') // The second call will read data directly from the cache\n\n// Insert, delete, update, just like the basic data model\nawait User.insert({ name: 'Tom', gender: 1 }) // return 'id001'\nawait User.updateById('id001', { name: 'Lily' }) // return 1\n```\n\nThe cache model automatically maintains and manages caches. If the cache already exists, then call `updated` updated the data, and automatically remove the latest data from the database when querying the data again. Realization Principle Click here (todo) Learn more\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fcoajs%2Fcoa-mysql","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fcoajs%2Fcoa-mysql","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fcoajs%2Fcoa-mysql/lists"}