1.0.0 • Published 4 months ago
flow-server-plugin-mariadb-orm v1.0.0
MariaDB ORM Plugin for Flow Server Framework
This plugin provides an Object-Relational Mapping (ORM) layer for MariaDB/MySQL databases in the Flow Server Framework.
Features
- Model definition with attribute casting
- Fluent query builder
- Multiple database connections
- Connection pooling
- Auto-loading of models
- Relationship management
- Dirty tracking for efficient updates
- JSON serialization
Installation
- Clone the repository:
git clone /new-bare3/flow-server-plugin-mariadbOrm.git
- Install dependencies:
cd flow-server-plugin-mariadbOrm
npm install
Configuration
Add the following to your Flow Server Framework configuration file (config.json
):
{
"database": {
"main": {
"host": "localhost",
"user": "root",
"password": "",
"database": "flow",
"waitForConnections": true,
"connectionLimit": 10,
"queueLimit": 0
},
"secondary": {
"host": "localhost",
"user": "root",
"password": "",
"database": "flow_secondary",
"waitForConnections": true,
"connectionLimit": 5,
"queueLimit": 0
}
},
"plugins": {
"mariadbOrm": {
"defaultConnection": "main",
"models": {
"path": "models",
"autoload": true
}
}
}
}
Usage
Defining Models
Create a model file in your models directory:
// models/User.js
const { BaseModel } = require('flow-server-plugin-mariadbOrm');
class User extends BaseModel {
// Define table name
static get tableName() {
return 'users';
}
// Define primary key (default is 'id')
static get primaryKey() {
return 'id';
}
// Define connection name (optional)
static get connection() {
return 'main';
}
// Define attribute casting
static get casts() {
return {
id: 'integer',
active: 'boolean',
settings: 'json',
created_at: 'datetime'
};
}
// Define default attributes
static get defaults() {
return {
active: true,
created_at: new Date()
};
}
// Define custom methods
getFullName() {
return `${this.get('first_name')} ${this.get('last_name')}`;
}
}
module.exports = User;
Using Models
// Get the ORM service
const orm = flow.services.get('mariadbOrm');
// Create a new user
const user = await orm.model('User').create({
first_name: 'John',
last_name: 'Doe',
email: 'john.doe@example.com'
});
// Find a user by ID
const user = await orm.model('User').find(1);
// Query users
const users = await orm.model('User')
.where('active', true)
.orderBy('created_at', 'DESC')
.limit(10)
.get();
// Update a user
user.set('email', 'new.email@example.com');
await orm.model('User').save(user);
// Delete a user
await orm.model('User').destroy(user);
// Execute a raw query
const results = await orm.query('SELECT * FROM users WHERE id > ?', [10]);
Query Builder
The query builder provides a fluent API for building database queries:
// Select specific fields
const users = await orm.model('User')
.select(['id', 'first_name', 'last_name'])
.get();
// Where clauses
const users = await orm.model('User')
.where('active', true)
.where('role', 'admin')
.get();
// Complex where clauses
const users = await orm.model('User')
.where('created_at', '>', '2023-01-01')
.whereIn('role', ['admin', 'moderator'])
.get();
// Joins
const posts = await orm.model('Post')
.select(['posts.*', 'users.name as author_name'])
.join('users', 'users.id = posts.user_id')
.where('posts.published', true)
.get();
// Aggregates
const count = await orm.model('User')
.where('active', true)
.count();
Working with Model Instances
// Create a new instance
const user = new (orm.model('User').model)({
first_name: 'John',
last_name: 'Doe'
});
// Get an attribute
const firstName = user.get('first_name');
// Set an attribute
user.set('email', 'john.doe@example.com');
// Check if an attribute exists
if (user.has('email')) {
// ...
}
// Get all attributes
const attributes = user.getAttributes();
// Convert to JSON
const json = user.toJSON();
// Check if the model is new (not saved to database)
if (user.isNew()) {
// ...
}
// Check if the model has changes
if (user.isDirty()) {
// ...
}
// Get changed attributes
const dirty = user.getDirty();
API Reference
MariaDBOrmPlugin
init(flow)
: Initialize the pluginmodel(name)
: Get a model query builderregister(name, ModelClass)
: Register a modelquery(sql, params, connectionName)
: Execute a raw querycloseAll()
: Close all database connections
BaseModel
constructor(attributes)
: Create a new model instanceget(key)
: Get an attribute valueset(key, value)
: Set an attribute valuehas(key)
: Check if an attribute existsgetAttributes()
: Get all attributesgetDirty()
: Get changed attributesisNew()
: Check if the model is newisDirty()
: Check if the model has changessyncOriginal()
: Sync original attributestoJSON()
: Convert to JSON
Query Builder
select(fields)
: Set the select clausewhere(conditions, operator)
: Add a where clausewhereIn(field, values)
: Add a where in clauseorderBy(field, direction)
: Add an order by clausegroupBy(field)
: Add a group by clauselimit(limit, offset)
: Add a limit clauseoffset(offset)
: Add an offset clausejoin(table, condition, type)
: Add a join clauseleftJoin(table, condition)
: Add a left join clauserightJoin(table, condition)
: Add a right join clauseget()
: Execute the query and get all resultsfirst()
: Execute the query and get the first resultvalue(field)
: Execute the query and get a valuecount(field)
: Execute the query and get a countfind(id)
: Find a model by its primary keyfindBy(attributes)
: Find a model by attributescreate(attributes)
: Create a new modelsave(model)
: Save a modelupdate(attributes)
: Update modelsdelete()
: Delete modelsdestroy(model)
: Delete a model
License
MIT
1.0.0
4 months ago