@dataql/sequelize-adapter
v1.4.0
Published
Sequelize adapter for DataQL with zero API changes
Maintainers
Readme
@dataql/sequelize-adapter
Migrate from Sequelize to DataQL with zero API changes. This adapter provides a Sequelize-compatible API that runs on DataQL with automatic scaling, caching, and offline support.
Installation
npm install @dataql/core @dataql/sequelize-adapterQuick Start
import { Sequelize, DataTypes, Op } from "@dataql/sequelize-adapter";
// Initialize DataQL with Sequelize-like API
const sequelize = new Sequelize({
appToken: "your-app-token", // Required for DataQL authentication
env: "prod", // Environment: 'dev' or 'prod'
dbName: "your_app_db", // Database name for data isolation
dialect: "postgres", // Dialect for compatibility (handled by DataQL)
});
// Define models exactly like Sequelize
const User = sequelize.define("User", {
id: {
type: DataTypes.INTEGER,
primaryKey: true,
autoIncrement: true,
},
name: {
type: DataTypes.STRING(255),
allowNull: false,
},
email: {
type: DataTypes.STRING(255),
allowNull: false,
unique: true,
},
age: {
type: DataTypes.INTEGER,
allowNull: true,
},
});
// Use familiar Sequelize syntax - all operations powered by DataQL
await sequelize.authenticate();
await sequelize.sync();
const user = await User.create({
name: "John Doe",
email: "[email protected]",
age: 30,
});
const allUsers = await User.findAll();
const activeUser = await User.findOne({ where: { email: "[email protected]" } });Configuration
const sequelize = new Sequelize({
appToken: "your-app-token", // Required - authentication for DataQL
env: "prod", // Optional - 'dev' or 'prod' (default: 'prod')
devPrefix: "dev_", // Optional - prefix for dev environment tables
dbName: "your_app_db", // Optional - database name for data isolation
customConnection: undefined, // Optional - for custom integrations
dialect: "postgres", // Optional - for compatibility (handled by DataQL)
logging: console.log, // Optional - query logging function
});Configuration Options
- appToken (required): Authentication token for DataQL
- env: Environment - 'dev' or 'prod' (default: 'prod')
- devPrefix: Table prefix for development environment (default: 'dev_')
- dbName: Database name for data isolation (each client gets dedicated database)
- customConnection: Advanced option for custom integrations
- dialect: Database dialect for compatibility (postgres, mysql, sqlite, etc.)
- logging: Function to log SQL queries (optional)
Benefits Over Direct Sequelize
While maintaining 100% Sequelize API compatibility, you get DataQL's enhanced capabilities:
- Simplified Setup: No need to manage database connections, credentials, or servers
- Auto-scaling: Automatic scaling based on usage
- Offline-first: Built-in offline support with automatic sync when online
- Real-time: Live data updates across all connected clients
- Global Performance: Data served from edge locations worldwide for low latency
- Data Isolation: Each client gets their own dedicated database automatically
- Multi-layer Caching: Optimized performance with intelligent caching
Migration Guide
From Sequelize
Replace imports:
// Before import { Sequelize, DataTypes, Op } from "sequelize"; // After import { Sequelize, DataTypes, Op } from "@dataql/sequelize-adapter";Update Sequelize configuration:
// Before - Direct database connection const sequelize = new Sequelize("database", "username", "password", { host: "localhost", dialect: "postgres", port: 5432, }); // After - DataQL powered const sequelize = new Sequelize({ appToken: "your-app-token", // Required for DataQL authentication dbName: "your_app_db", // Your database name dialect: "postgres", // Kept for compatibility });Your models work exactly the same:
// This works exactly the same - but now routes through DataQL infrastructure const User = sequelize.define("User", { name: DataTypes.STRING, email: DataTypes.STRING, });
API Compatibility
Supported Sequelize Features
Data Types
- ✅
STRING,TEXT,INTEGER,BIGINT,FLOAT,DECIMAL - ✅
BOOLEAN,DATE,DATEONLY,TIME - ✅
JSON,JSONB,UUID,BLOB - ✅ Type modifiers: length, precision, scale
Model Definition
- ✅
sequelize.define()- Define models - ✅ Field options:
allowNull,defaultValue,primaryKey,autoIncrement,unique - ✅ Model options:
tableName,timestamps,paranoid,underscored
Model Methods
- ✅
findAll()- Find multiple records - ✅
findOne()- Find single record - ✅
findByPk()- Find by primary key - ✅
findAndCountAll()- Find with count - ✅
create()- Create single record - ✅
bulkCreate()- Create multiple records - ✅
update()- Update records - ✅
destroy()- Delete records - ✅
count(),max(),min(),sum()- Aggregate functions
Query Options
- ✅
where- Filter conditions - ✅
attributes- Select specific fields - ✅
order- Sorting - ✅
limit,offset- Pagination - ✅
group,having- Grouping
Operators
- ✅
Op.eq,Op.ne,Op.gt,Op.gte,Op.lt,Op.lte - ✅
Op.like,Op.notLike,Op.iLike,Op.notILike - ✅
Op.in,Op.notIn,Op.is,Op.not - ✅
Op.between,Op.notBetween - ✅
Op.and,Op.or- Logical operators
Advanced Features
- ✅ Transactions via
sequelize.transaction() - ✅ Model validation (basic)
- ✅ Hooks (simplified)
- ✅ Raw queries (redirected to model methods)
DataQL Enhancements
While maintaining Sequelize compatibility, you also get DataQL's additional features:
- Offline-first: Automatic offline support and sync
- Real-time: Built-in real-time updates
- Multi-region: Global data distribution
- Schema evolution: Dynamic schema updates
- WAL support: Write-ahead logging for reliability
- Unique document creation: Enhanced duplicate prevention
TypeScript Support
Full TypeScript support with type inference:
import { Sequelize, DataTypes, Model } from "@dataql/sequelize-adapter";
interface UserAttributes {
id: number;
name: string;
email: string;
age?: number;
}
const User = sequelize.define<Model<UserAttributes>>("User", {
id: {
type: DataTypes.INTEGER,
primaryKey: true,
autoIncrement: true,
},
name: {
type: DataTypes.STRING,
allowNull: false,
},
email: {
type: DataTypes.STRING,
allowNull: false,
unique: true,
},
age: {
type: DataTypes.INTEGER,
allowNull: true,
},
});
// Full type inference
const user: Model<UserAttributes> | null = await User.findByPk(1);
const users: Model<UserAttributes>[] = await User.findAll();Examples
Basic CRUD Operations
// Create
const user = await User.create({
name: "John Doe",
email: "[email protected]",
age: 30,
});
// Read
const users = await User.findAll({
where: {
age: {
[Op.gt]: 18,
},
},
order: [["createdAt", "DESC"]],
limit: 10,
});
// Update
await User.update(
{ age: 31 },
{
where: { id: user.id },
}
);
// Delete
await User.destroy({
where: { id: user.id },
});Complex Queries
// Multiple conditions
const results = await User.findAll({
where: {
[Op.and]: [
{ age: { [Op.gte]: 18 } },
{
[Op.or]: [
{ name: { [Op.like]: "%John%" } },
{ email: { [Op.like]: "%@company.com" } },
],
},
],
},
});
// Aggregation
const stats = {
count: await User.count(),
maxAge: await User.max("age"),
minAge: await User.min("age"),
totalAge: await User.sum("age"),
};Transactions
const result = await sequelize.transaction(async (t) => {
const user = await User.create(
{
name: "Jane Smith",
email: "[email protected]",
},
{ transaction: t }
);
const profile = await Profile.create(
{
userId: user.id,
bio: "Software Engineer",
},
{ transaction: t }
);
return { user, profile };
});Limitations
Some advanced Sequelize features are not yet supported:
- Complex associations (
hasMany,belongsTo, etc.) - Advanced migration system
- Complex validation rules
- Advanced hooks system
- Raw SQL with complex parameters
- Eager loading with
include
If you need these features, please open an issue.
Performance Considerations
DataQL automatically optimizes your queries through:
- Edge caching: Frequently accessed data cached globally
- Query optimization: Automatic query plan optimization
- Connection pooling: Managed automatically
- Auto-scaling: Resources scale based on demand
No manual optimization required!
License
MIT
