or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

tessl/npm-sequelize

Promise-based Node.js ORM tool for Postgres, MySQL, MariaDB, SQLite, Microsoft SQL Server, Amazon Redshift and Snowflake's Data Cloud with solid transaction support, relations, eager and lazy loading, read replication and more

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
npmpkg:npm/sequelize@6.37.x

To install, run

npx @tessl/cli install tessl/npm-sequelize@6.37.0

0

# Sequelize

1

2

Sequelize is a promise-based Node.js ORM tool for Postgres, MySQL, MariaDB, SQLite, Microsoft SQL Server, Amazon Redshift and Snowflake's Data Cloud. It features solid transaction support, relations, eager and lazy loading, read replication and more.

3

4

## Package Information

5

6

- **Package Name**: sequelize

7

- **Package Type**: npm

8

- **Language**: JavaScript/TypeScript

9

- **Installation**: `npm install sequelize`

10

11

## Core Imports

12

13

```typescript

14

import { Sequelize, Model, DataTypes, Op } from "sequelize";

15

```

16

17

For CommonJS:

18

19

```javascript

20

const { Sequelize, Model, DataTypes, Op } = require("sequelize");

21

```

22

23

## Basic Usage

24

25

```typescript

26

import { Sequelize, Model, DataTypes } from "sequelize";

27

28

// Initialize database connection

29

const sequelize = new Sequelize("postgresql://user:pass@localhost:5432/database");

30

31

// Define a model

32

class User extends Model {}

33

User.init({

34

firstName: DataTypes.STRING,

35

lastName: DataTypes.STRING,

36

email: DataTypes.STRING

37

}, { sequelize, modelName: 'user' });

38

39

// Sync models and perform operations

40

await sequelize.sync();

41

42

// Create a user

43

const user = await User.create({

44

firstName: "John",

45

lastName: "Doe",

46

email: "john@example.com"

47

});

48

49

// Find users

50

const users = await User.findAll({

51

where: {

52

firstName: "John"

53

}

54

});

55

```

56

57

## Architecture

58

59

Sequelize is built around several key components:

60

61

- **Sequelize Instance**: Central connection manager and configuration hub

62

- **Model Class**: Base class for defining database models with attributes, validations, and associations

63

- **DataTypes**: Type system for defining column types with database-specific mappings

64

- **Query Interface**: Database-agnostic interface for schema operations and raw queries

65

- **Transaction System**: ACID-compliant transaction management with isolation levels

66

- **Association System**: Relationship definitions (BelongsTo, HasOne, HasMany, BelongsToMany)

67

- **Migration System**: Schema versioning and deployment management

68

- **Hook System**: Lifecycle event system for extending model and query behavior

69

70

## Capabilities

71

72

### Database Connection & Configuration

73

74

Core database connection management, configuration, and instance-level operations for managing database connections across multiple supported dialects.

75

76

```typescript { .api }

77

class Sequelize {

78

constructor(database: string, username?: string, password?: string, options?: Options);

79

constructor(uri: string, options?: Options);

80

81

authenticate(): Promise<void>;

82

sync(options?: SyncOptions): Promise<Sequelize>;

83

close(): Promise<void>;

84

}

85

86

interface Options {

87

dialect: 'mysql' | 'postgres' | 'sqlite' | 'mariadb' | 'mssql' | 'db2' | 'snowflake' | 'oracle';

88

host?: string;

89

port?: number;

90

logging?: boolean | ((sql: string, timing?: number) => void);

91

pool?: PoolOptions;

92

timezone?: string;

93

dialectOptions?: any;

94

}

95

```

96

97

[Database Connection](./database-connection.md)

98

99

### Model Definition & Management

100

101

Model creation, configuration, and lifecycle management including attributes, validations, scopes, and schema operations.

102

103

```typescript { .api }

104

class Model {

105

static init(attributes: ModelAttributes, options: InitOptions): typeof Model;

106

static sync(options?: SyncOptions): Promise<Model>;

107

static drop(options?: DropOptions): Promise<void>;

108

109

save(options?: SaveOptions): Promise<this>;

110

destroy(options?: InstanceDestroyOptions): Promise<void>;

111

reload(options?: FindOptions): Promise<this>;

112

}

113

114

interface ModelAttributes {

115

[name: string]: DataType | ModelAttributeColumnOptions;

116

}

117

```

118

119

[Model Definition](./model-definition.md)

120

121

### Querying & CRUD Operations

122

123

Data querying, creation, updating, and deletion operations with advanced filtering, ordering, and aggregation capabilities.

124

125

```typescript { .api }

126

class Model {

127

static findAll(options?: FindOptions): Promise<Model[]>;

128

static findOne(options?: FindOptions): Promise<Model | null>;

129

static findByPk(identifier: Identifier, options?: Omit<FindOptions, 'where'>): Promise<Model | null>;

130

static create(values?: CreationAttributes, options?: CreateOptions): Promise<Model>;

131

static update(values: Partial<Attributes>, options: UpdateOptions): Promise<[number, Model[]]>;

132

static destroy(options: DestroyOptions): Promise<number>;

133

}

134

135

interface FindOptions {

136

where?: WhereOptions;

137

attributes?: FindAttributeOptions;

138

include?: Includeable | Includeable[];

139

order?: Order;

140

group?: GroupOption;

141

having?: WhereOptions;

142

limit?: number;

143

offset?: number;

144

}

145

```

146

147

[Querying](./querying.md)

148

149

### Associations & Relationships

150

151

Model relationship definitions and operations including one-to-one, one-to-many, and many-to-many associations with eager loading.

152

153

```typescript { .api }

154

class Model {

155

static hasOne(target: ModelCtor, options?: HasOneOptions): HasOne;

156

static belongsTo(target: ModelCtor, options?: BelongsToOptions): BelongsTo;

157

static hasMany(target: ModelCtor, options?: HasManyOptions): HasMany;

158

static belongsToMany(target: ModelCtor, options: BelongsToManyOptions): BelongsToMany;

159

}

160

161

interface HasOneOptions {

162

foreignKey?: string | ForeignKeyOptions;

163

sourceKey?: string;

164

hooks?: boolean;

165

as?: string | { singular: string; plural: string; };

166

scope?: AssociationScope;

167

}

168

```

169

170

[Associations](./associations.md)

171

172

### Data Types & Validation

173

174

Comprehensive data type system with database-specific mappings and validation rules for model attributes.

175

176

```typescript { .api }

177

interface DataTypes {

178

STRING(length?: number): DataType;

179

TEXT: DataType;

180

INTEGER: DataType;

181

BIGINT: DataType;

182

FLOAT: DataType;

183

DECIMAL(precision?: number, scale?: number): DataType;

184

DATE: DataType;

185

BOOLEAN: DataType;

186

JSON: DataType;

187

UUID: DataType;

188

ENUM(...values: string[]): DataType;

189

ARRAY(type: DataType): DataType;

190

}

191

192

interface ModelAttributeColumnOptions {

193

type: DataType;

194

allowNull?: boolean;

195

defaultValue?: any;

196

primaryKey?: boolean;

197

unique?: boolean | string;

198

validate?: ModelValidateOptions;

199

}

200

```

201

202

[Data Types](./data-types.md)

203

204

### Transactions

205

206

Database transaction management with support for multiple isolation levels, savepoints, and automatic rollback on errors.

207

208

```typescript { .api }

209

class Transaction {

210

commit(): Promise<void>;

211

rollback(): Promise<void>;

212

afterCommit(fn: (transaction: Transaction) => void): void;

213

}

214

215

interface TransactionOptions {

216

isolationLevel?: Transaction.ISOLATION_LEVELS;

217

type?: Transaction.TYPES;

218

deferrable?: Deferrable;

219

readOnly?: boolean;

220

}

221

222

class Sequelize {

223

transaction<T>(options: TransactionOptions, autoCallback: (t: Transaction) => PromiseLike<T>): Promise<T>;

224

transaction(options?: TransactionOptions): Promise<Transaction>;

225

}

226

```

227

228

[Transactions](./transactions.md)

229

230

### Query Operators & Raw SQL

231

232

Advanced query operators for complex WHERE clauses and raw SQL execution for custom database operations.

233

234

```typescript { .api }

235

interface OpTypes {

236

eq: symbol; // =

237

ne: symbol; // !=

238

gt: symbol; // >

239

gte: symbol; // >=

240

lt: symbol; // <

241

lte: symbol; // <=

242

like: symbol; // LIKE

243

in: symbol; // IN

244

between: symbol; // BETWEEN

245

and: symbol; // AND

246

or: symbol; // OR

247

}

248

249

const Op: OpTypes;

250

251

class Sequelize {

252

query(sql: string, options?: QueryOptions): Promise<any>;

253

fn(fn: string, ...args: any[]): Fn;

254

col(col: string): Col;

255

literal(val: string): Literal;

256

where(attr: any, comparator: any, logic?: any): Where;

257

}

258

```

259

260

[Query Operators](./query-operators.md)

261

262

### Hooks & Lifecycle Events

263

264

Lifecycle event system for extending model and query behavior with customizable hooks that execute at specific points during database operations.

265

266

```typescript { .api }

267

interface ModelHooks {

268

// Validation hooks

269

beforeValidate: (instance: Model, options: ValidationOptions) => Promise<void> | void;

270

afterValidate: (instance: Model, options: ValidationOptions) => Promise<void> | void;

271

validationFailed: (instance: Model, options: ValidationOptions, error: ValidationError) => Promise<void> | void;

272

273

// CRUD hooks

274

beforeCreate: (instance: Model, options: CreateOptions) => Promise<void> | void;

275

afterCreate: (instance: Model, options: CreateOptions) => Promise<void> | void;

276

beforeUpdate: (instance: Model, options: UpdateOptions) => Promise<void> | void;

277

afterUpdate: (instance: Model, options: UpdateOptions) => Promise<void> | void;

278

beforeSave: (instance: Model, options: SaveOptions) => Promise<void> | void;

279

afterSave: (instance: Model, options: SaveOptions) => Promise<void> | void;

280

beforeDestroy: (instance: Model, options: InstanceDestroyOptions) => Promise<void> | void;

281

afterDestroy: (instance: Model, options: InstanceDestroyOptions) => Promise<void> | void;

282

283

// Query hooks

284

beforeFind: (options: FindOptions) => Promise<void> | void;

285

afterFind: (instances: Model | Model[] | null, options: FindOptions) => Promise<void> | void;

286

287

// Bulk operation hooks

288

beforeBulkCreate: (instances: Model[], options: BulkCreateOptions) => Promise<void> | void;

289

afterBulkCreate: (instances: Model[], options: BulkCreateOptions) => Promise<void> | void;

290

beforeBulkUpdate: (options: UpdateOptions) => Promise<void> | void;

291

afterBulkUpdate: (options: UpdateOptions) => Promise<void> | void;

292

beforeBulkDestroy: (options: DestroyOptions) => Promise<void> | void;

293

afterBulkDestroy: (options: DestroyOptions) => Promise<void> | void;

294

}

295

296

/**

297

* Add hook to model or sequelize instance

298

*/

299

addHook(hookType: string, name: string, fn: Function): void;

300

addHook(hookType: string, fn: Function): void;

301

302

/**

303

* Remove hook from model or sequelize instance

304

*/

305

removeHook(hookType: string, name: string): boolean;

306

```

307

308

[Hooks](./hooks.md)

309

310

### Error Handling

311

312

Comprehensive error hierarchy for handling database-specific errors, validation failures, and connection issues.

313

314

```typescript { .api }

315

class BaseError extends Error {

316

name: string;

317

message: string;

318

stack?: string;

319

}

320

321

class ValidationError extends BaseError {

322

errors: ValidationErrorItem[];

323

}

324

325

class DatabaseError extends BaseError {

326

sql?: string;

327

parameters?: any[];

328

}

329

330

class ConnectionError extends BaseError {}

331

class TimeoutError extends BaseError {}

332

class UniqueConstraintError extends ValidationError {}

333

class ForeignKeyConstraintError extends DatabaseError {}

334

```

335

336

[Error Handling](./error-handling.md)

337

338

## Global Types

339

340

```typescript { .api }

341

type Identifier = number | string | Buffer;

342

type Logging = boolean | ((sql: string, timing?: number) => void);

343

344

interface PoolOptions {

345

max?: number;

346

min?: number;

347

idle?: number;

348

acquire?: number;

349

evict?: number;

350

}

351

352

interface SyncOptions {

353

force?: boolean;

354

alter?: boolean | SyncAlterOptions;

355

logging?: Logging;

356

schema?: string;

357

searchPath?: string;

358

hooks?: boolean;

359

}

360

361

type Optional<T, K extends keyof T> = Omit<T, K> & Partial<Pick<T, K>>;

362

```