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 | 7x 40x 40x 40x 40x 40x 3x 37x 1x 36x 1x 35x 40x 35x 35x 35x 1x 34x 35x 35x 1x 1x 1x 1x 35x 31x 31x 35x 4x 5x 35x 35x 35x 3x 6x 3x 3x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 37x 37x 37x 39x 39x 2x 1x 38x 2x 1x 37x 3x 3x 3x 3x 3x 3x 34x 34x 34x 37x | /**
* Pure Object-based Query Builder for Coherent.js Database Layer
*
* @fileoverview Provides pure JavaScript object structure for building database queries
* with a declarative, object-based approach.
*/
/**
* Creates a database query configuration object
*
* @typedef {Object} QueryConfig
* @property {string} [table] - The table to query
* @property {string|string[]} [select] - Columns to select
* @property {Object} [where] - Query conditions
* @property {Object} [orderBy] - Sort configuration
* @property {number} [limit] - Maximum number of results
* @property {number} [offset] - Number of rows to skip
* @property {Object} [insert] - Data to insert
* @property {Object} [update] - Data to update
* @property {boolean} [delete] - Whether to delete
*/
/**
* Creates a query configuration object
*
* @param {QueryConfig} config - Query configuration
* @returns {QueryConfig} The query configuration object
*
* @example
* // Basic select
* const userQuery = createQuery({
* table: 'users',
* select: ['id', 'name', 'email'],
* where: { active: true },
* orderBy: { created_at: 'DESC' },
* limit: 10
* });
*
* // Insert
* const insertQuery = createQuery({
* table: 'users',
* insert: { name: 'John', email: 'john@example.com' }
* });
*
* // Update
* const updateQuery = createQuery({
* table: 'users',
* update: { last_login: new Date() },
* where: { id: 1 }
* });
*
* // Delete
* const deleteQuery = createQuery({
* table: 'users',
* where: { inactive_days: { '>': 365 } },
* delete: true
* });
*/
export function createQuery(config) {
return { ...config };
}
/**
* Executes a query using the provided configuration
*
* @param {Object} db - Database connection/manager
* @param {QueryConfig} query - Query configuration
* @returns {Promise<*>} Query result
*/
export async function executeQuery(db, query) {
const { sql, params } = buildSQL(query);
return await db.query(sql, params);
}
// Internal SQL building functions
function buildSQL(query) {
const params = [];
let sql = '';
if (query.insert) {
sql = buildInsertSQL(query, params);
} else if (query.update) {
sql = buildUpdateSQL(query, params);
} else if (query.delete) {
sql = buildDeleteSQL(query, params);
} else {
sql = buildSelectSQL(query, params);
}
return { sql, params };
}
function buildSelectSQL(query, params) {
const columns = Array.isArray(query.select)
? query.select.join(', ')
: (query.select || '*');
// Handle from with optional alias
const fromTable = query.from || query.table;
let fromClause;
if (typeof fromTable === 'object' && fromTable.table) {
fromClause = fromTable.alias
? `${fromTable.table} ${fromTable.alias}`
: fromTable.table;
} else {
fromClause = fromTable;
}
let sql = `SELECT ${columns} FROM ${fromClause}`;
// Handle joins
if (query.joins && Array.isArray(query.joins)) {
for (const join of query.joins) {
const joinType = join.type || 'INNER';
const joinTable = join.alias
? `${join.table} ${join.alias}`
: join.table;
sql += ` ${joinType} JOIN ${joinTable} ON ${join.condition}`;
}
}
if (query.where) {
const whereClause = buildWhereClause(query.where, params);
Eif (whereClause) sql += ` WHERE ${whereClause}`;
}
if (query.orderBy) {
sql += ` ORDER BY ${ Object.entries(query.orderBy)
.map(([col, dir]) => `${col} ${dir.toUpperCase()}`)
.join(', ')}`;
}
if (query.limit) sql += ` LIMIT ${query.limit}`;
if (query.offset) sql += ` OFFSET ${query.offset}`;
return sql;
}
function buildInsertSQL(query, params) {
const columns = Object.keys(query.insert);
const placeholders = columns.map(() => '?').join(', ');
params.push(...Object.values(query.insert));
return `INSERT INTO ${query.table} (${columns.join(', ')}) VALUES (${placeholders})`;
}
function buildUpdateSQL(query, params) {
const setClause = Object.entries(query.update)
.map(([col]) => `${col} = ?`)
.join(', ');
params.push(...Object.values(query.update));
let sql = `UPDATE ${query.table} SET ${setClause}`;
Eif (query.where) {
const whereClause = buildWhereClause(query.where, params);
Eif (whereClause) sql += ` WHERE ${whereClause}`;
}
return sql;
}
function buildDeleteSQL(query, params) {
let sql = `DELETE FROM ${query.table}`;
Eif (query.where) {
const whereClause = buildWhereClause(query.where, params);
Eif (whereClause) sql += ` WHERE ${whereClause}`;
}
return sql;
}
function buildWhereClause(conditions, params, operator = 'AND') {
Iif (!conditions) return '';
const clauses = [];
for (const [key, value] of Object.entries(conditions)) {
Iif (value === undefined) continue;
// Handle logical operators at the top level
if (key === '$or' && Array.isArray(value)) {
const orClauses = value.map(c => `(${buildWhereClause(c, params)})`);
clauses.push(`(${orClauses.join(' OR ')})`);
} else if (key === '$and' && Array.isArray(value)) {
const andClauses = value.map(c => `(${buildWhereClause(c, params)})`);
clauses.push(`(${andClauses.join(' AND ')})`);
} else if (typeof value === 'object' && value !== null && !Array.isArray(value)) {
// Handle field operators like { '>': 10 } or { 'in': [1, 2, 3] }
for (const [op, val] of Object.entries(value)) {
Iif (op === 'in' && Array.isArray(val)) {
const placeholders = val.map(() => '?').join(', ');
clauses.push(`${key} IN (${placeholders})`);
params.push(...val);
} else Iif (op === 'between' && Array.isArray(val) && val.length === 2) {
clauses.push(`${key} BETWEEN ? AND ?`);
params.push(...val);
} else Eif (['>', '>=', '<', '<=', '!=', '<>', 'LIKE'].includes(op)) {
clauses.push(`${key} ${op} ?`);
params.push(val);
}
}
} else Iif (value === null) {
clauses.push(`${key} IS NULL`);
} else {
clauses.push(`${key} = ?`);
params.push(value);
}
}
return clauses.join(` ${operator} `);
}
|