All files / examples database-queries.js

0% Statements 0/319
0% Branches 0/1
0% Functions 0/1
0% Lines 0/319

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               
/**
 * @file Coherent.js Database - Pure JavaScript Object Query Builder Examples
 * 
 * This example demonstrates how to use Coherent.js QueryBuilder with pure JavaScript objects
 * for both model definitions and database queries, without using classes.
 * 
 * This example uses the in-memory database adapter for simplicity.
 */

// Using factory functions (recommended pure JS object approach)
import { createDatabaseManager, createQuery, executeQuery } from '../src/coherent.js';
import { MemoryAdapter } from '../src/database/adapters/memory.js';

// Alternative: Direct imports (also available)
// import { DatabaseManager, QueryBuilder, createQuery, executeQuery } from '../src/database/index.js';

console.log('Setting up in-memory database connection...');

// Setup in-memory database connection using factory function
const db = createDatabaseManager({
  adapter: new MemoryAdapter(),
  store: {
    name: 'example-store'
  },
  debug: true
});

console.log('Connecting to database...');
try {
  await db.connect();
  console.log('Successfully connected to database');
} catch (error) {
  console.error('Failed to connect to database:', error);
  throw error;
}

// Model definitions as plain objects
const models = {
  users: {
    tableName: 'users',
    attributes: {
      id: { type: 'integer', primaryKey: true, autoIncrement: true },
      name: { type: 'string', required: true },
      email: { type: 'string', required: true, unique: true },
      age: { type: 'number' },
      role: { type: 'string', default: 'user' },
      active: { type: 'boolean', default: true },
      created_at: { type: 'datetime', default: 'CURRENT_TIMESTAMP' }
    },
    indexes: [
      { fields: ['email'], unique: true },
      { fields: ['role'] },
      { fields: ['created_at'] }
    ]
  },
  posts: {
    tableName: 'posts',
    attributes: {
      id: { type: 'integer', primaryKey: true, autoIncrement: true },
      title: { type: 'string', required: true },
      content: { type: 'text' },
      user_id: { type: 'integer', required: true },
      category_id: { type: 'integer' },
      published: { type: 'boolean', default: false },
      created_at: { type: 'datetime', default: 'CURRENT_TIMESTAMP' },
      updated_at: { type: 'datetime', default: 'CURRENT_TIMESTAMP' }
    },
    indexes: [
      { fields: ['user_id'] },
      { fields: ['category_id'] },
      { fields: ['published'] }
    ],
    relationships: {
      user: {
        type: 'belongsTo',
        model: 'users',
        foreignKey: 'user_id'
      }
    }
  }
};

// Initialize the database with our schema
async function initializeDatabase() {
  // For in-memory adapter, we just need to store the schema
  for (const [modelName, modelDef] of Object.entries(models)) {
    // Store the model schema in the database
    await db.query('SET_SCHEMA', {
      model: modelName,
      schema: modelDef
    });
    
    // Create a collection/table for this model
    await db.query('CREATE_COLLECTION', {
      name: modelDef.tableName || modelName,
      schema: modelDef.attributes
    });
  }
  
  console.log('Database schema initialized');
}

// Initialize the database with our schema
await initializeDatabase();

// Helper function to execute queries with the in-memory adapter
const query = (modelName) => {
  // Get the model definition
  const modelDef = models[modelName];
  if (!modelDef) {
    throw new Error(`Model ${modelName} not found`);
  }
  
  const tableName = modelDef.tableName || modelName;
  
  return {
    // Find all records
    async find(options = {}) {
      const { where = {}, limit, offset, orderBy } = options;
      
      // Get all records from the table
      const results = await db.query('FIND', {
        table: tableName,
        where,
        limit,
        offset,
        orderBy
      });
      
      return results;
    },
    
    // Find a single record by ID
    async findById(id, options = {}) {
      const results = await this.find({
        where: { id },
        limit: 1,
        ...options
      });
      return results[0] || null;
    },
    
    // Alias for findById for compatibility
    async findOne(where = {}, options = {}) {
      const results = await this.find({
        where,
        limit: 1,
        ...options
      });
      return results[0] || null;
    },
    
    // Create a new record
    async create(data) {
      const result = await db.query('INSERT', {
        table: tableName,
        data
      });
      return this.findById(result.id);
    },
    
    // Update records matching the where clause
    async update(where, data) {
      await db.query('UPDATE', {
        table: tableName,
        where,
        data
      });
      return this.find({ where });
    },
    
    // Delete records matching the where clause
    async delete(where) {
      return db.query('DELETE', {
        table: tableName,
        where
      });
    },
    
    // Count records matching the where clause
    async count(where = {}) {
      const results = await db.query('COUNT', {
        table: tableName,
        where
      });
      return results.count;
    },
    
    // Execute a custom query
    async raw(operation, params = {}) {
      return db.query(operation, {
        ...params,
        table: tableName
      });
    }
  };
};

// Create query interfaces for each model
const User = query('users');
const Post = query('posts');

console.log('๐Ÿงช Testing Pure JavaScript Object Query Structure...\n');

// =============================================================================
// 1. BASIC CRUD OPERATIONS
// =============================================================================

console.log('1. Basic CRUD Operations');
console.log('========================');

// Create some test data
const testUser = await User.create({
  name: 'John Doe',
  email: 'john@example.com',
  age: 30,
  role: 'admin',
  active: true
});

console.log('โœ“ Created test user:', testUser);

// Create a test post
const testPost = await Post.create({
  title: 'Hello World',
  content: 'This is a test post',
  user_id: testUser.id,
  published: true
});

console.log('โœ“ Created test post:', testPost);

// Find a single user
const foundUser = await User.findOne({ id: testUser.id });

console.log('โœ“ Found user by ID:', foundUser);

// Update the user
const updatedUser = await User.update(
  { id: testUser.id },
  { name: 'John Updated' }
);

console.log('โœ“ Updated user:', updatedUser);

// =============================================================================
// 2. QUERY EXAMPLES
// =============================================================================

console.log('\n2. Query Examples');
console.log('=================');

// Find with complex conditions
const activeAdmins = await User.find({
  where: { 
    active: true,
    role: 'admin'
  },
  orderBy: ['created_at', 'DESC'],
  limit: 5
});

console.log('โœ“ Found active admins:', activeAdmins);

// Simple published posts query (joins not supported in MemoryAdapter)
const postsWithAuthors = await Post.find({
  where: {
    published: true
  },
  orderBy: ['created_at', 'DESC'],
  limit: 10
});

console.log('โœ“ Posts with authors:', postsWithAuthors);

// Skip transaction example for in-memory adapter
console.log('โ„น๏ธ Skipping transaction example for in-memory adapter');

// =============================================================================
// 3. ADVANCED QUERIES
// =============================================================================

console.log('\n3. Advanced Queries');
console.log('===================');

// Simple post listing (aggregation not supported in MemoryAdapter)
const userPostCounts = await Post.find({
  orderBy: ['created_at', 'DESC'],
  limit: 5
});

console.log('โœ“ User post counts:', userPostCounts);

// Recent published posts
const recentPopularPosts = await Post.find({
  where: {
    published: true
  },
  orderBy: ['created_at', 'DESC'],
  limit: 10
});

console.log('โœ“ Recent popular posts:', recentPopularPosts);

// =============================================================================
// 4. CLEANUP
// =============================================================================

// Clean up test data
await Post.delete({ id: testPost.id });
await User.delete({ id: testUser.id });

console.log('โœ“ Cleaned up test data');

// Close the database connection
await db.close();
console.log('โœ“ Database connection closed');

console.log('\nโœ… All examples completed successfully!');