1.0.0 • Published 4 months ago

flow-server-plugin-mariadb-orm v1.0.0

Weekly downloads
-
License
MIT
Repository
github
Last release
4 months ago

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

  1. Clone the repository:
git clone /new-bare3/flow-server-plugin-mariadbOrm.git
  1. 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 plugin
  • model(name): Get a model query builder
  • register(name, ModelClass): Register a model
  • query(sql, params, connectionName): Execute a raw query
  • closeAll(): Close all database connections

BaseModel

  • constructor(attributes): Create a new model instance
  • get(key): Get an attribute value
  • set(key, value): Set an attribute value
  • has(key): Check if an attribute exists
  • getAttributes(): Get all attributes
  • getDirty(): Get changed attributes
  • isNew(): Check if the model is new
  • isDirty(): Check if the model has changes
  • syncOriginal(): Sync original attributes
  • toJSON(): Convert to JSON

Query Builder

  • select(fields): Set the select clause
  • where(conditions, operator): Add a where clause
  • whereIn(field, values): Add a where in clause
  • orderBy(field, direction): Add an order by clause
  • groupBy(field): Add a group by clause
  • limit(limit, offset): Add a limit clause
  • offset(offset): Add an offset clause
  • join(table, condition, type): Add a join clause
  • leftJoin(table, condition): Add a left join clause
  • rightJoin(table, condition): Add a right join clause
  • get(): Execute the query and get all results
  • first(): Execute the query and get the first result
  • value(field): Execute the query and get a value
  • count(field): Execute the query and get a count
  • find(id): Find a model by its primary key
  • findBy(attributes): Find a model by attributes
  • create(attributes): Create a new model
  • save(model): Save a model
  • update(attributes): Update models
  • delete(): Delete models
  • destroy(model): Delete a model

License

MIT

1.0.0

4 months ago