Elysia Tools

在一个清晰的工作台里浏览工具、案例、可视化和主题指南。

热门分类

专题

语言
ZHESPTRUFRDEEN

Elysia Tools

导航

数据库

Sequelize 样本:关联、连接计数与分页偏移

四张卡片,用于静态检查 ORM 与 SQL 结构。

案例

这个案例集合中的条目

代码javascript简单

Sequelize 模型定义

数据库模型、关系和模式定义,使用Sequelize

javascript
const { Sequelize, DataTypes, Model, Op } = require('sequelize')

// Initialize Sequelize connection
const sequelize = new Sequelize({
  dialect: 'postgres',
  host: 'localhost',
  port: 5432,
  database: 'myapp',
  username: 'postgres',
  password: 'password',
  logging: console.log,
  pool: {
    max: 5,
    min: 0,
    acquire: 30000,
    idle: 10000
  }
})

// User Model
class User extends Model {}
User.init({
  id: {
    type: DataTypes.INTEGER,
    primaryKey: true,
    autoIncrement: true
  },
  email: {
    type: DataTypes.STRING,
    allowNull: false,
    unique: true,
    validate: {
      isEmail: true
    }
  },
  username: {
    type: DataTypes.STRING,
    allowNull: true,
    unique: true,
    validate: {
      len: [3, 30]
    }
  },
  password: {
    type: DataTypes.STRING,
    allowNull: false,
    validate: {
      len: [6, 100]
    }
  },
  firstName: {
    type: DataTypes.STRING,
    allowNull: true
  },
  lastName: {
    type: DataTypes.STRING,
    allowNull: true
  },
  isActive: {
    type: DataTypes.BOOLEAN,
    defaultValue: true
  },
  role: {
    type: DataTypes.ENUM('USER', 'ADMIN', 'MODERATOR', 'AUTHOR'),
    defaultValue: 'USER'
  },
  lastLoginAt: {
    type: DataTypes.DATE,
    allowNull: true
  },
  profilePicture: {
    type: DataTypes.STRING,
    allowNull: true
  }
}, {
  sequelize,
  modelName: 'User',
  tableName: 'users',
  timestamps: true,
  indexes: [
    {
      unique: true,
      fields: ['email']
    },
    {
      fields: ['username']
    },
    {
      fields: ['isActive']
    }
  ]
})

// Profile Model
class Profile extends Model {}
Profile.init({
  id: {
    type: DataTypes.INTEGER,
    primaryKey: true,
    autoIncrement: true
  },
  userId: {
    type: DataTypes.INTEGER,
    allowNull: false,
    unique: true,
    references: {
      model: User,
      key: 'id'
    }
  },
  bio: {
    type: DataTypes.TEXT,
    allowNull: true
  },
  avatar: {
    type: DataTypes.STRING,
    allowNull: true
  },
  website: {
    type: DataTypes.STRING,
    allowNull: true,
    validate: {
      isUrl: true
    }
  },
  birthDate: {
    type: DataTypes.DATEONLY,
    allowNull: true
  },
  phone: {
    type: DataTypes.STRING,
    allowNull: true
  },
  address: {
    type: DataTypes.JSON,
    allowNull: true
  }
}, {
  sequelize,
  modelName: 'Profile',
  tableName: 'profiles'
})

// Post Model
class Post extends Model {}
Post.init({
  id: {
    type: DataTypes.INTEGER,
    primaryKey: true,
    autoIncrement: true
  },
  title: {
    type: DataTypes.STRING,
    allowNull: false,
    validate: {
      len: [1, 200]
    }
  },
  slug: {
    type: DataTypes.STRING,
    allowNull: false,
    unique: true
  },
  content: {
    type: DataTypes.TEXT,
    allowNull: false
  },
  excerpt: {
    type: DataTypes.STRING,
    allowNull: true
  },
  publishedAt: {
    type: DataTypes.DATE,
    allowNull: true
  },
  status: {
    type: DataTypes.ENUM('DRAFT', 'PUBLISHED', 'ARCHIVED'),
    defaultValue: 'DRAFT'
  },
  featuredImage: {
    type: DataTypes.STRING,
    allowNull: true
  },
  tags: {
    type: DataTypes.JSON,
    allowNull: true,
    defaultValue: []
  },
  viewCount: {
    type: DataTypes.INTEGER,
    defaultValue: 0
  },
  metadata: {
    type: DataTypes.JSON,
    allowNull: true
  }
}, {
  sequelize,
  modelName: 'Post',
  tableName: 'posts',
  indexes: [
    {
      fields: ['authorId']
    },
    {
      fields: ['status']
    },
    {
      fields: ['publishedAt']
    },
    {
      fields: ['slug']
    }
  ]
})

// Comment Model
class Comment extends Model {}
Comment.init({
  id: {
    type: DataTypes.INTEGER,
    primaryKey: true,
    autoIncrement: true
  },
  content: {
    type: DataTypes.TEXT,
    allowNull: false,
    validate: {
      len: [1, 1000]
    }
  },
  postId: {
    type: DataTypes.INTEGER,
    allowNull: false,
    references: {
      model: Post,
      key: 'id'
    }
  },
  authorId: {
    type: DataTypes.INTEGER,
    allowNull: false,
    references: {
      model: User,
      key: 'id'
    }
  },
  parentId: {
    type: DataTypes.INTEGER,
    allowNull: true,
    references: {
      model: 'comments',
      key: 'id'
    }
  },
  isApproved: {
    type: DataTypes.BOOLEAN,
    defaultValue: false
  }
}, {
  sequelize,
  modelName: 'Comment',
  tableName: 'comments',
  indexes: [
    {
      fields: ['postId']
    },
    {
      fields: ['authorId']
    },
    {
      fields: ['parentId']
    }
  ]
})

// Category Model
class Category extends Model {}
Category.init({
  id: {
    type: DataTypes.INTEGER,
    primaryKey: true,
    autoIncrement: true
  },
  name: {
    type: DataTypes.STRING,
    allowNull: false,
    unique: true
  },
  description: {
    type: DataTypes.TEXT,
    allowNull: true
  },
  slug: {
    type: DataTypes.STRING,
    allowNull: false,
    unique: true
  },
  color: {
    type: DataTypes.STRING,
    allowNull: true
  },
  icon: {
    type: DataTypes.STRING,
    allowNull: true
  }
}, {
  sequelize,
  modelName: 'Category',
  tableName: 'categories'
})

// Define Associations (Relationships)
User.hasOne(Profile, {
  foreignKey: 'userId',
  as: 'profile'
})
Profile.belongsTo(User, {
  foreignKey: 'userId',
  as: 'user'
})

User.hasMany(Post, {
  foreignKey: 'authorId',
  as: 'posts'
})
Post.belongsTo(User, {
  foreignKey: 'authorId',
  as: 'author'
})

User.hasMany(Comment, {
  foreignKey: 'authorId',
  as: 'comments'
})
Comment.belongsTo(User, {
  foreignKey: 'authorId',
  as: 'author'
})

Post.hasMany(Comment, {
  foreignKey: 'postId',
  as: 'comments'
})
Comment.belongsTo(Post, {
  foreignKey: 'postId',
  as: 'post'
})

// Self-referencing relationship for nested comments
Comment.hasMany(Comment, {
  foreignKey: 'parentId',
  as: 'replies'
})
Comment.belongsTo(Comment, {
  foreignKey: 'parentId',
  as: 'parent'
})

// Many-to-Many: Posts and Categories
const PostCategory = sequelize.define('PostCategory', {
  postId: {
    type: DataTypes.INTEGER,
    references: {
      model: Post,
      key: 'id'
    }
  },
  categoryId: {
    type: DataTypes.INTEGER,
    references: {
      model: Category,
      key: 'id'
    }
  }
}, {
  tableName: 'post_categories',
  timestamps: false
})

Post.belongsToMany(Category, {
  through: PostCategory,
  foreignKey: 'postId',
  otherKey: 'categoryId',
  as: 'categories'
})

Category.belongsToMany(Post, {
  through: PostCategory,
  foreignKey: 'categoryId',
  otherKey: 'postId',
  as: 'posts'
})

// Hooks and Instance Methods
User.beforeCreate(async (user) => {
  // Hash password before creating user
  const bcrypt = require('bcrypt')
  user.password = await bcrypt.hash(user.password, 10)
})

User.prototype.comparePassword = async function(password) {
  const bcrypt = require('bcrypt')
  return await bcrypt.compare(password, this.password)
}

User.prototype.toJSON = function() {
  const values = Object.assign({}, this.get())
  delete values.password
  return values
}

Post.beforeSave(async (post) => {
  // Generate excerpt if not provided
  if (!post.excerpt && post.content) {
    post.excerpt = post.content.substring(0, 150) + '...'
  }

  // Generate slug if not provided
  if (!post.slug && post.title) {
    post.slug = post.title.toLowerCase()
      .replace(/[^a-z0-9]+/g, '-')
      .replace(/(^-|-$)/g, '')
  }
})

module.exports = {
  sequelize,
  User,
  Profile,
  Post,
  Comment,
  Category,
  PostCategory
}
代码javascript简单

CRUD 操作

完整的CRUD操作、查询和数据操作,使用Sequelize

javascript
const { User, Profile, Post, Comment } = require('./models')

// CREATE Operations
async function createUser(userData) {
  try {
    const user = await User.create({
      email: userData.email,
      username: userData.username,
      password: userData.password,
      firstName: userData.firstName,
      lastName: userData.lastName,
      role: userData.role || 'USER'
    })

    return user
  } catch (error) {
    console.error('Error creating user:', error)
    throw error
  }
}

// Create user with profile
async function createUserWithProfile(userData) {
  const user = await User.create(userData, {
    include: [{
      association: User.Profile,
      as: 'profile'
    }]
  })
  return user
}

// Create multiple users
async function createMultipleUsers(usersData) {
  const users = await User.bulkCreate(usersData, {
    validate: true,
    individualHooks: true
  })
  return users
}

// READ Operations
async function getUserById(id) {
  const user = await User.findByPk(id, {
    include: [
      {
        model: Profile,
        as: 'profile'
      },
      {
        model: Post,
        as: 'posts',
        include: [
          {
            model: Comment,
            as: 'comments'
          }
        ]
      }
    ]
  })
  return user
}

async function getUserByEmail(email) {
  const user = await User.findOne({
    where: { email },
    attributes: ['id', 'email', 'username', 'firstName', 'lastName', 'role', 'createdAt']
  })
  return user
}

async function getAllUsers(options = {}) {
  const {
    page = 1,
    limit = 10,
    search,
    role,
    sortBy = 'createdAt',
    sortOrder = 'DESC'
  } = options

  const offset = (page - 1) * limit

  const where = {
    [Op.and]: []
  }

  if (search) {
    where[Op.and].push({
      [Op.or]: [
        { username: { [Op.like]: `%${search}%` } },
        { email: { [Op.like]: `%${search}%` } },
        { firstName: { [Op.like]: `%${search}%` } },
        { lastName: { [Op.like]: `%${search}%` } }
      ]
    })
  }

  if (role) {
    where[Op.and].push({ role })
  }

  where[Op.and].push({ isActive: true })

  const { count, rows } = await User.findAndCountAll({
    where,
    offset,
    limit,
    include: [
      {
        model: Profile,
        as: 'profile',
        attributes: ['bio', 'avatar', 'website']
      }
    ],
    order: [[sortBy, sortOrder.toUpperCase()]]
  })

  return {
    users: rows,
    pagination: {
      page,
      limit,
      total: count,
      pages: Math.ceil(count / limit)
    }
  }
}

// UPDATE Operations
async function updateUser(id, updateData) {
  const user = await User.update(updateData, {
    where: { id },
    returning: true,
    include: [{
      model: Profile,
      as: 'profile'
    }]
  })

  return user[1][0] // Return the updated user
}

async function updateOrCreateProfile(userId, profileData) {
  const [profile, created] = await Profile.findOrCreate({
    where: { userId },
    defaults: {
      userId,
      ...profileData
    }
  })

  if (!created) {
    await profile.update(profileData)
  }

  return profile
}

// DELETE Operations
async function deleteUser(id) {
  // Soft delete
  const user = await User.update(
    { isActive: false },
    { where: { id } }
  )
  return user
}

async function hardDeleteUser(id) {
  const user = await User.destroy({
    where: { id }
  })
  return user
}

// Complex Queries
async function getUserWithPostStats(userId) {
  const user = await User.findByPk(userId, {
    attributes: [
      'id', 'email', 'username', 'firstName', 'lastName', 'role'
    ],
    include: [
      {
        model: Post,
        as: 'posts',
        attributes: [
          'id', 'title', 'publishedAt', 'viewCount', 'status'
        ],
        include: [
          {
            model: Comment,
            as: 'comments',
            attributes: ['id'],
            required: false
          }
        ]
      }
    ]
  })

  // Add post counts
  const userWithStats = user.toJSON()
  userWithStats.stats = {
    totalPosts: user.posts.length,
    publishedPosts: user.posts.filter(p => p.status === 'PUBLISHED').length,
    totalComments: user.posts.reduce((sum, post) => sum + post.comments.length, 0),
    totalViews: user.posts.reduce((sum, post) => sum + post.viewCount, 0)
  }

  return userWithStats
}

// Advanced Search
async function searchPosts(query) {
  const posts = await Post.findAll({
    where: {
      [Op.and]: [
        {
          [Op.or]: [
            { title: { [Op.like]: `%${query}%` } },
            { content: { [Op.like]: `%${query}%` } },
            { excerpt: { [Op.like]: `%${query}%` } }
          ]
        },
        { status: 'PUBLISHED' },
        { publishedAt: { [Op.not]: null } }
      ]
    },
    include: [
      {
        model: User,
        as: 'author',
        attributes: ['id', 'username', 'firstName', 'lastName']
      },
      {
        model: Comment,
        as: 'comments',
        attributes: ['id'],
        required: false
      }
    ],
    order: [['publishedAt', 'DESC']],
    limit: 20
  })

  return posts
}

// Aggregation Queries
async function getPostAnalytics() {
  const analytics = await Post.findAll({
    attributes: [
      [sequelize.fn('COUNT', sequelize.col('id')), 'totalPosts'],
      [sequelize.fn('COUNT', sequelize.col('id')), 'publishedPosts'],
      [sequelize.fn('AVG', sequelize.col('viewCount')), 'avgViews'],
      [sequelize.fn('SUM', sequelize.col('viewCount')), 'totalViews']
    ],
    where: {
      [Op.or]: [
        { status: 'PUBLISHED' },
        { status: 'DRAFT' }
      ]
    },
    raw: true
  })

  return analytics[0]
}

// Raw SQL Queries
async function getUsersWithMostPosts() {
  const users = await sequelize.query(`
    SELECT
      u.id,
      u.username,
      u.email,
      COUNT(DISTINCT p.id) as post_count,
      COUNT(DISTINCT c.id) as comment_count
    FROM users u
    LEFT JOIN posts p ON u.id = p.author_id
    LEFT JOIN comments c ON u.id = c.author_id
    WHERE u.is_active = true
    GROUP BY u.id, u.username, u.email
    HAVING COUNT(DISTINCT p.id) > 0
    ORDER BY post_count DESC
    LIMIT 10
  `, {
    type: Sequelize.QueryTypes.SELECT
  })

  return users
}

// Transaction Operations
async function transferPostOwnership(postId, newAuthorId) {
  const result = await sequelize.transaction(async (t) => {
    const post = await Post.findByPk(postId, {
      include: [{
        model: User,
        as: 'author'
      }],
      transaction: t
    })

    if (!post) {
      throw new Error('Post not found')
    }

    const updatedPost = await post.update({
      authorId: newAuthorId
    }, { transaction: t })

    return {
      previousAuthor: post.author,
      updatedPost
    }
  })

  return result
}

// Bulk Operations
async function archiveOldPosts(daysOld = 365) {
  const cutoffDate = new Date()
  cutoffDate.setDate(cutoffDate.getDate() - daysOld)

  const [affectedCount] = await Post.update(
    {
      status: 'ARCHIVED',
      archivedAt: new Date()
    },
    {
      where: {
        publishedAt: {
          [Op.lt]: cutoffDate
        },
        status: 'PUBLISHED'
      }
    }
  )

  return affectedCount
}

module.exports = {
  createUser,
  createUserWithProfile,
  createMultipleUsers,
  getUserById,
  getUserByEmail,
  getAllUsers,
  updateUser,
  updateOrCreateProfile,
  deleteUser,
  hardDeleteUser,
  getUserWithPostStats,
  searchPosts,
  getPostAnalytics,
  getUsersWithMostPosts,
  transferPostOwnership,
  archiveOldPosts
}
代码text中等

Sequelize 迁移

数据库迁移、种子数据和模式变更的版本控制

text
// Migration Example: 20231201000001-create-users.js
module.exports = {
  up: async (queryInterface, Sequelize) => {
    await queryInterface.createTable('users', {
      id: {
        type: Sequelize.INTEGER,
        primaryKey: true,
        autoIncrement: true
      },
      email: {
        type: Sequelize.STRING,
        allowNull: false,
        unique: true
      },
      username: {
        type: Sequelize.STRING,
        allowNull: true,
        unique: true
      },
      password: {
        type: Sequelize.STRING,
        allowNull: false
      },
      firstName: {
        type: Sequelize.STRING,
        allowNull: true
      },
      lastName: {
        type: Sequelize.STRING,
        allowNull: true
      },
      isActive: {
        type: Sequelize.BOOLEAN,
        defaultValue: true
      },
      role: {
        type: Sequelize.ENUM('USER', 'ADMIN', 'MODERATOR', 'AUTHOR'),
        defaultValue: 'USER'
      },
      lastLoginAt: {
        type: Sequelize.DATE,
        allowNull: true
      },
      createdAt: {
        type: Sequelize.DATE,
        allowNull: false,
        defaultValue: Sequelize.literal('CURRENT_TIMESTAMP')
      },
      updatedAt: {
        type: Sequelize.DATE,
        allowNull: false,
        defaultValue: Sequelize.literal('CURRENT_TIMESTAMP')
      }
    })

    // Create indexes
    await queryInterface.addIndex('users', ['email'], { unique: true })
    await queryInterface.addIndex('users', ['username'])
    await queryInterface.addIndex('users', ['isActive'])
  },

  down: async (queryInterface, Sequelize) => {
    await queryInterface.dropTable('users')
  }
}

// Migration Example: 20231201000002-create-profiles.js
module.exports = {
  up: async (queryInterface, Sequelize) => {
    await queryInterface.createTable('profiles', {
      id: {
        type: Sequelize.INTEGER,
        primaryKey: true,
        autoIncrement: true
      },
      userId: {
        type: Sequelize.INTEGER,
        allowNull: false,
        unique: true,
        references: {
          model: 'users',
          key: 'id'
        },
        onUpdate: 'CASCADE',
        onDelete: 'CASCADE'
      },
      bio: {
        type: Sequelize.TEXT,
        allowNull: true
      },
      avatar: {
        type: Sequelize.STRING,
        allowNull: true
      },
      website: {
        type: Sequelize.STRING,
        allowNull: true
      },
      birthDate: {
        type: Sequelize.DATEONLY,
        allowNull: true
      },
      phone: {
        type: Sequelize.STRING,
        allowNull: true
      },
      address: {
        type: Sequelize.JSON,
        allowNull: true
      },
      createdAt: {
        type: Sequelize.DATE,
        allowNull: false,
        defaultValue: Sequelize.literal('CURRENT_TIMESTAMP')
      },
      updatedAt: {
        type: Sequelize.DATE,
        allowNull: false,
        defaultValue: Sequelize.literal('CURRENT_TIMESTAMP')
      }
    })

    await queryInterface.addIndex('profiles', ['userId'], { unique: true })
  },

  down: async (queryInterface, Sequelize) => {
    await queryInterface.dropTable('profiles')
  }
}

// Migration Example: 20231201000003-add-user-profile-field.js
module.exports = {
  up: async (queryInterface, Sequelize) => {
    await queryInterface.addColumn('users', 'profilePicture', {
      type: Sequelize.STRING,
      allowNull: true
    })
  },

  down: async (queryInterface, Sequelize) => {
    await queryInterface.removeColumn('users', 'profilePicture')
  }
}

// Seeders Example: 20231201000001-users-seeder.js
module.exports = {
  up: async (queryInterface, Sequelize) => {
    const bcrypt = require('bcrypt')

    const users = [
      {
        email: '[email protected]',
        username: 'admin',
        password: await bcrypt.hash('admin123', 10),
        firstName: 'Admin',
        lastName: 'User',
        role: 'ADMIN',
        isActive: true,
        createdAt: new Date(),
        updatedAt: new Date()
      },
      {
        email: '[email protected]',
        username: 'john_doe',
        password: await bcrypt.hash('password123', 10),
        firstName: 'John',
        lastName: 'Doe',
        role: 'USER',
        isActive: true,
        createdAt: new Date(),
        updatedAt: new Date()
      },
      {
        email: '[email protected]',
        username: 'jane_smith',
        password: await bcrypt.hash('password123', 10),
        firstName: 'Jane',
        lastName: 'Smith',
        role: 'AUTHOR',
        isActive: true,
        createdAt: new Date(),
        updatedAt: new Date()
      }
    ]

    await queryInterface.bulkInsert('users', users)
  },

  down: async (queryInterface, Sequelize) => {
    await queryInterface.bulkDelete('users', {
      email: {
        [Sequelize.Op.in]: [
          '[email protected]',
          '[email protected]',
          '[email protected]'
        ]
      }
    })
  }
}

// Database Configuration
const { Sequelize } = require('sequelize')

const sequelize = new Sequelize({
  dialect: 'postgres',
  host: process.env.DB_HOST || 'localhost',
  port: process.env.DB_PORT || 5432,
  database: process.env.DB_NAME || 'myapp',
  username: process.env.DB_USER || 'postgres',
  password: process.env.DB_PASSWORD || 'password',
  logging: process.env.NODE_ENV === 'development' ? console.log : false,
  pool: {
    max: parseInt(process.env.DB_POOL_MAX) || 5,
    min: parseInt(process.env.DB_POOL_MIN) || 0,
    acquire: parseInt(process.env.DB_POOL_ACQUIRE) || 30000,
    idle: parseInt(process.env.DB_POOL_IDLE) || 10000
  }
})

module.exports = sequelize
代码javascript复杂

Sequelize 高级功能

Sequelize高级功能,包括事务、作用域、钩子和性能优化

javascript
const { Sequelize, DataTypes, Model, Op } = require('sequelize')

// 1. Advanced Scopes
class User extends Model {
  // Instance methods
  getFullName() {
    return `${this.firstName} ${this.lastName}`
  }

  async getRecentPosts(limit = 5) {
    return await this.getPosts({
      where: {
        status: 'PUBLISHED',
        publishedAt: {
          [Op.not]: null
        }
      },
      order: [['publishedAt', 'DESC']],
      limit
    })
  }

  async deactivate() {
    return await this.update({ isActive: false })
  }
}

User.init({
  // ... fields
}, {
  sequelize,
  modelName: 'User',

  // Scopes for reusable queries
  scopes: {
    active: {
      where: { isActive: true }
    },
    admins: {
      where: { role: 'ADMIN' }
    },
    recent: (days = 30) => ({
      where: {
        createdAt: {
          [Op.gte]: new Date(Date.now() - days * 24 * 60 * 60 * 1000)
        }
      }
    }),
    withProfile: {
      include: [{
        model: Profile,
        as: 'profile'
      }]
    },
    withStats: {
      attributes: {
        include: [
          [
            sequelize.literal(`(
              SELECT COUNT(*)
              FROM posts
              WHERE posts.author_id = User.id
              AND posts.status = 'PUBLISHED'
            )`),
            'publishedPostCount'
          ],
          [
            sequelize.literal(`(
              SELECT COUNT(*)
              FROM comments
              WHERE comments.author_id = User.id
            )`),
            'commentCount'
          ]
        ]
      }
    }
  }
})

// Using scopes
async function getActiveAdminsWithStats() {
  const users = await User.scope([
    'active',
    'admins',
    'withProfile',
    'withStats'
  ]).findAll()

  return users
}

async function getRecentUsers(days = 7) {
  return await User.scope('recent', days).findAll({
    order: [['createdAt', 'DESC']]
  })
}

// 2. Advanced Hooks and Middleware
User.addHook('beforeCreate', async (user) => {
  console.log('Creating user:', user.email)

  // Additional validation
  if (user.email && user.email.endsWith('@spam.com')) {
    throw new Error('Spam emails not allowed')
  }
})

User.addHook('afterCreate', async (user) => {
  // Send welcome email
  await sendWelcomeEmail(user.email, user.getFullName())
})

User.addHook('beforeUpdate', async (user) => {
  if (user.changed('password')) {
    // Rehash password if changed
    const bcrypt = require('bcrypt')
    user.password = await bcrypt.hash(user.password, 10)
  }
})

User.addHook('afterDestroy', async (user) => {
  // Soft delete related data
  await Post.update(
    { authorId: null },
    { where: { authorId: user.id } }
  )
})

// 3. Advanced Transactions
async function complexTransaction() {
  const result = await sequelize.transaction({
    isolationLevel: Sequelize.Transaction.ISOLATION_LEVELS.SERIALIZABLE,
    type: Sequelize.Transaction.TYPES.DEFERRED
  }, async (t) => {

    // Create user
    const user = await User.create({
      email: '[email protected]',
      password: 'password123'
    }, { transaction: t })

    // Create profile
    const profile = await Profile.create({
      userId: user.id,
      bio: 'New user bio'
    }, { transaction: t })

    // Create initial post
    const post = await Post.create({
      title: 'Welcome Post',
      content: 'My first post',
      authorId: user.id,
      status: 'PUBLISHED'
    }, { transaction: t })

    // If any operation fails, all changes are rolled back
    return { user, profile, post }
  })

  return result
}

// Parallel transactions
async function processBatchUsers(userDataArray) {
  const promises = userDataArray.map(userData =>
    sequelize.transaction(async (t) => {
      const user = await User.create(userData, { transaction: t })
      await Profile.create({
        userId: user.id,
        bio: `Bio for ${user.email}`
      }, { transaction: t })
      return user
    })
  )

  const results = await Promise.all(promises)
  return results
}

// 4. Performance Optimization

// Eager loading with nested associations
async function getPostsWithFullDetails(postIds) {
  const posts = await Post.findAll({
    where: {
      id: { [Op.in]: postIds }
    },
    include: [
      {
        model: User,
        as: 'author',
        attributes: ['id', 'username', 'firstName', 'lastName'],
        include: [{
          model: Profile,
          as: 'profile',
          attributes: ['avatar', 'bio']
        }]
      },
      {
        model: Comment,
        as: 'comments',
        include: [{
          model: User,
          as: 'author',
          attributes: ['username', 'firstName']
        }],
        where: { isApproved: true },
        required: false
      },
      {
        model: Category,
        as: 'categories',
        attributes: ['id', 'name', 'slug']
      }
    ],
    order: [
      ['publishedAt', 'DESC'],
      [{ model: Comment, as: 'comments' }, 'createdAt', 'ASC']
    ]
  })

  return posts
}

// Query optimization with limit and pagination
async function getOptimizedUserList(options = {}) {
  const { page = 1, limit = 20, search, sortBy = 'createdAt' } = options
  const offset = (page - 1) * limit

  const where = {
    isActive: true
  }

  if (search) {
    where[Op.or] = [
      { username: { [Op.iLike]: `%${search}%` } },
      { email: { [Op.iLike]: `%${search}%` } },
      [sequelize.fn('CONCAT', sequelize.col('firstName'), ' ', sequelize.col('lastName')),
       { [Op.iLike]: `%${search}%` }]
    ]
  }

  const { count, rows } = await User.findAndCountAll({
    where,
    offset,
    limit,
    attributes: ['id', 'username', 'email', 'firstName', 'lastName', 'role', 'createdAt'],
    order: [[sortBy, 'DESC']],
    include: [
      {
        model: Profile,
        as: 'profile',
        attributes: ['avatar'],
        required: false
      }
    ]
  })

  return {
    users: rows,
    pagination: {
      page,
      limit,
      total: count,
      pages: Math.ceil(count / limit)
    }
  }
}

// 5. Raw Query Optimization
async function getDashboardStats() {
  const stats = await sequelize.query(`
    SELECT
      (SELECT COUNT(*) FROM users WHERE is_active = true) as total_users,
      (SELECT COUNT(*) FROM posts WHERE status = 'PUBLISHED') as published_posts,
      (SELECT COUNT(*) FROM comments WHERE is_approved = true) as approved_comments,
      (SELECT COUNT(*) FROM categories) as total_categories,
      (SELECT AVG(view_count) FROM posts WHERE status = 'PUBLISHED') as avg_post_views,
      (SELECT
        COUNT(CASE WHEN status = 'PUBLISHED' THEN 1 END) * 100.0 / COUNT(*)
        FROM posts
        WHERE published_at >= NOW() - INTERVAL '30 days'
      ) as recent_publish_rate
  `, {
    type: Sequelize.QueryTypes.SELECT,
    plain: true
  })

  return stats
}

// 6. Caching Layer
class CacheService {
  constructor(ttl = 300) { // 5 minutes default TTL
    this.cache = new Map()
    this.ttl = ttl * 1000
  }

  set(key, value) {
    this.cache.set(key, {
      value,
      timestamp: Date.now()
    })
  }

  get(key) {
    const item = this.cache.get(key)
    if (!item) return null

    if (Date.now() - item.timestamp > this.ttl) {
      this.cache.delete(key)
      return null
    }

    return item.value
  }

  has(key) {
    return this.get(key) !== null
  }

  delete(key) {
    return this.cache.delete(key)
  }
}

const cache = new CacheService()

async function getCachedUserWithPosts(userId) {
  const cacheKey = `user_with_posts_${userId}`

  let cached = cache.get(cacheKey)
  if (cached) return cached

  const user = await User.findByPk(userId, {
    include: [
      {
        model: Post,
        as: 'posts',
        where: { status: 'PUBLISHED' },
        required: false,
        order: [['publishedAt', 'DESC']]
      }
    ]
  })

  cache.set(cacheKey, user)
  return user
}

// 7. Connection Pool Management
async function getConnectionPoolStats() {
  const pool = sequelize.connectionManager.pool

  return {
    total: pool.total,
    all: pool.all,
    waiting: pool.waiting,
    idle: pool.idle,
    used: pool.used,
    max: pool.max,
    min: pool.min
  }
}

// 8. Error Handling and Validation
class ValidationError extends Error {
  constructor(message, field) {
    super(message)
    this.name = 'ValidationError'
    this.field = field
  }
}

async function createUserWithValidation(userData) {
  try {
    // Custom validation
    if (userData.email && userData.email.endsWith('@blocked.com')) {
      throw new ValidationError('Email domain is blocked', 'email')
    }

    if (userData.username && userData.username.length < 3) {
      throw new ValidationError('Username must be at least 3 characters', 'username')
    }

    const user = await User.create(userData)
    return user
  } catch (error) {
    if (error.name === 'SequelizeUniqueConstraintError') {
      const field = error.errors[0]?.path
      throw new ValidationError(`${field} already exists`, field)
    }

    if (error.name === 'SequelizeValidationError') {
      const field = error.errors[0]?.path
      const message = error.errors[0]?.message
      throw new ValidationError(message, field)
    }

    throw error
  }
}

module.exports = {
  User,
  getActiveAdminsWithStats,
  getRecentUsers,
  complexTransaction,
  processBatchUsers,
  getPostsWithFullDetails,
  getOptimizedUserList,
  getDashboardStats,
  getCachedUserWithPosts,
  getConnectionPoolStats,
  createUserWithValidation,
  ValidationError,
  cache
}

工具

经常与该案例搭配使用的工具

相关内容

相关案例集合

相关内容

相关专题

工具使用指南

帮助搜索与理解工作流的案例说明

概览

只用新造 ID 和计数。双子表聚合已修正为不同标识符计数,未对数据库做基准测试。

源代码阅读练习

四张卡片,用于静态检查 ORM 与 SQL 结构。

源代码阅读练习
卡片源文件
Sequelize 模型定义javascript
CRUD 操作javascript
Sequelize 迁移text
Sequelize 高级功能javascript

使用方式

  1. 1将具名卡片作为静态文本检查。不连接数据库、不调用驱动、不运行迁移或粘贴连接值。练习仅使用新造数字。

常见失败与 edge cases

  • 限制

    仅检查静态源代码并做虚构算术。未测试数据库、执行计划、提供方、认证、性能或生产行为。示例银行或医疗表结构不应用于真实决策。

示例

1. 读取双向关联

如何使用

«Sequelize 模型定义» — 检查 Post、Category 的 belongsToMany。

结果

两者均使用 PostCategory;Post 用 postId、otherKey categoryId,Category 反向使用。这是从两侧声明同一个连接模型。

2. 识别连接膨胀

如何使用

«CRUD 操作» — 读取修正后的文章/评论计数;自造一个用户、两篇文章、三条评论。

结果

双子表连接产生 2 × 3 = 6 对。普通计数均为 6;COUNT(DISTINCT p.id)、COUNT(DISTINCT c.id) 在此虚构例中为 2、3。

3. 分开计算偏移与数量

如何使用

«CRUD 操作» — 读取 getAllUsers;自造 page 2、limit 10、count 23。

结果

offset = (2 − 1) × 10 = 10,pages = ceil(23 / 10) = 3。公式不证明任意 include 配置的关联计数都正确。

专题

药代动力学教学模型与结果核查

用于教学或 QA 的药代公式、模型假设和结果一致性核查,不提供用药剂量、诊断或临床建议。

专题

经典与现代密码工具

在安全的教学或 CTF 场景中比较可逆的经典变换与现代加密,并明确玩具密码不等于安全防护。

专题

文本前后缀与包裹符号批处理,整行整词一次到位

给文本行或词批量添加前后缀,为 SQL、配置和 Markdown 给每个值加引号或反引号包裹,并剥掉粘贴列表带来的编号、符号和装饰。

专题

数学与数字转换工作流

按清晰的精度检查流程转换计量单位、进制、分数、科学计数法、罗马数字以及字节/位数值。

首页
工具3216
案例593
可视化473
文件查看器103
专题239
标签333
图像、音频与视频657

图像、音频、视频处理、转换与优化工具

数学、日期与金融647

计算器、数值计算、日期逻辑、统计与金融工具

设计与颜色298

颜色、版式、图形、视觉样式与设计辅助工具

文本与写作209

写作、清洗、格式化、提取与文本分析工具

开发与 Web194

开发者工具、网络处理、Web 调试与自动化辅助工具

转换与编码175

格式、文件、压缩包、单位与编码转换工具

潜客测验发布与联系人交接
讣告、悼词与纪念卡的家属复核及交付
本地习惯记录的备份、恢复演练与分享前检查
长文改编 X 串文与 LinkedIn 帖子的事实复核与交付
Markdown 互动课件审校、离线演示与交付

© 2026 Elysia Tools. 保留所有权利。

文档价格关于我们服务条款隐私政策Cookie 政策联系我们

Development

SQL 执行计划可视化器

粘贴 EXPLAIN / EXPLAIN ANALYZE 输出(PostgreSQL/MySQL/SQLite),渲染为成本树,标注估算行数与实际行数的偏差热点,并给出具体的索引建议

Format Conversion

CSV 转多方言 SQL INSERT 生成器

解析 CSV/Excel-CSV/TSV(自动方言检测,RFC 4180),生成 MySQL/PostgreSQL/SQLite/SQL Server 的批量 INSERT,带类型推断和 ON CONFLICT/IGNORE 变体

Development

数据库 Schema 对比

比较两个数据库 Schema 并生成迁移草案

Development

SQL 方言互译桥

在 MySQL / PostgreSQL / SQLite / BigQuery / Snowflake / Redshift 之间互译 DDL、DML、函数与类型,并标注不支持的写法

Security

SQL注入检测器

检测输入字符串中的常见SQL注入攻击模式

Development

SQL 查询格式化器 & 压缩器

美化或压缩 SQL,完全可控 SQL 方言(PostgreSQL、MySQL、SQLite、SQL Server/T-SQL、BigQuery、Snowflake 等)、关键字/标识符/函数大小写、缩进风格(标准、左对齐表格、右对齐表格)以及语句间空行。输出带语法高亮、可直接复制的结果,并显示大小与语句数统计。

Development

数据库备份生成器

为数据库表生成SQL备份脚本

Development

数据库迁移生成器

为数据库架构更改生成SQL迁移脚本

数据库

PostgreSQL 高级示例

高级 PostgreSQL 数据库示例,包括优化策略、复杂查询、索引和性能调优

数据格式

SQL 脚本示例

各种场景和用例的 SQL 查询示例和数据库脚本

数据库

Prisma 示例

Prisma现代数据库工具包和ORM,包含模式定义、迁移、关系和类型安全的数据库访问

Python

Web Python 数据库示例

Web Python 数据库示例,包括SQLite连接、SQL查询和事务处理

数据库

MySQL 数据库示例

各种复杂度级别的MySQL数据库脚本示例,从简单表到企业ERP系统

数据库

MongoDB 示例

全面的MongoDB NoSQL数据库示例,包括CRUD操作、聚合框架、索引和扩展策略