{"id":16592,"library":"apemandb","title":"ApemanDB","description":"ApemanDB is a database abstraction layer built as a thin wrapper around the popular Sequelize ORM, specifically optimized for use within the 'apeman' project ecosystem. It simplifies database interactions by abstracting direct Sequelize usage, particularly for defining models through a structured JSON schema. The library is currently at version 8.7.4 and, while no explicit release cadence is documented, its version history suggests active development. A key differentiator is its tight integration with `apemanenv` for environment-specific database configurations, allowing developers to manage database settings (like dialect, host, credentials) in a centralized, declarative manner. This approach aims to streamline database setup and model management for apeman web applications, reducing boilerplate associated with raw Sequelize initialization and model definition.","status":"active","version":"8.7.4","language":"javascript","source_language":"en","source_url":"https://github.com/apeman-labo/apemandb","tags":["javascript","apeman","database","sequelize"],"install":[{"cmd":"npm install apemandb","lang":"bash","label":"npm"},{"cmd":"yarn add apemandb","lang":"bash","label":"yarn"},{"cmd":"pnpm add apemandb","lang":"bash","label":"pnpm"}],"dependencies":[{"reason":"Core ORM functionality, ApemanDB is a wrapper around it.","package":"sequelize","optional":false},{"reason":"Required for managing environment-specific database configurations.","package":"apemanenv","optional":false},{"reason":"Required for MySQL database dialect support, inferred from database.json example.","package":"mysql2","optional":true},{"reason":"Required for SQLite database dialect support, inferred from database.json example. For Sequelize v6, sqlite3 must be installed manually.","package":"sqlite3","optional":true}],"imports":[{"note":"The primary interaction with ApemanDB is via its `create` factory function, typically consuming configuration from `apemanenv` and a directory of JSON model definitions.","wrong":"import { create } from 'apemandb'; // apemandb primarily uses CommonJS 'require' pattern in examples.","symbol":"create","correct":"const db = require('apemandb').create(envConfig, { modelsDir: './db/models' });"},{"note":"ApemanDB strongly relies on `apemanenv` for loading environment-specific database configuration, as shown in the provided setup guides.","wrong":"import apemanenv from 'apemanenv'; // Examples explicitly use CommonJS `require`.","symbol":"apemanenv","correct":"const apemanenv = require('apemanenv');"},{"note":"After initialization, models are typically accessed via the `models` property of the returned database instance. The `sync` method is used for schema synchronization.","wrong":"await db.User.create(); // Access models via `db.models` property, not directly on the instance.","symbol":"DB Instance (methods)","correct":"await db.sync(); await db.models.User.create({ username: 'test' });"}],"quickstart":{"code":"const path = require('path');\nconst apemanenv = require('apemanenv');\nconst apemandb = require('apemandb');\n\n// 1. Define environment configuration (env/database.json)\n// In a real project, this would be loaded by apemanenv automatically.\n// For quickstart, we'll simulate the structure.\nconst envDir = path.join(__dirname, 'env');\nrequire('fs').mkdirSync(envDir, { recursive: true });\nrequire('fs').writeFileSync(path.join(envDir, 'database.json'), JSON.stringify({\n  \"default\": {\n    \"DIALECT\": \"sqlite\",\n    \"SCHEMA\": \"apeman-demo-web\",\n    \"STORAGE\": \":memory:\"\n  },\n  \"development\": {\n    \"SCHEMA\": \"apeman-demo-web_dev\",\n    \"STORAGE\": \"./tmp/dev-database.db\"\n  },\n  \"test\": {\n    \"DIALECT\": \"sqlite\",\n    \"SCHEMA\": \"apeman-demo-web_test\",\n    \"STORAGE\": \":memory:\"\n  }\n}, null, 2));\n\n// 2. Define a model (db/models/user.json)\nconst modelsDir = path.join(__dirname, 'db', 'models');\nrequire('fs').mkdirSync(modelsDir, { recursive: true });\nrequire('fs').writeFileSync(path.join(modelsDir, 'user.json'), JSON.stringify({\n  \"$name\": \"User\",\n  \"$description\": \"A user model\",\n  \"$attributes\": {\n    \"username\": {\n      \"$type\": \"STRING\",\n      \"$unique\": true\n    },\n    \"introText\": {\n      \"$type\": \"STRING(1024)\",\n      \"$nullable\": true\n    }\n  }\n}, null, 2));\n\nasync function main() {\n  // Load environment variables\n  const envConfig = apemanenv(__dirname); // Simulates env loading from __dirname\n  \n  // Initialize ApemanDB with configuration and models\n  const db = apemandb.create(envConfig, { modelsDir: modelsDir });\n\n  try {\n    // Connect to the database and synchronize models (create tables)\n    await db.sync({ force: true }); // `force: true` drops tables before recreating\n    console.log('Database and tables synchronized!');\n\n    // Create a new user record\n    const newUser = await db.models.User.create({ username: 'john_doe', introText: 'Hello world!' });\n    console.log('Created user:', newUser.toJSON());\n\n    // Find a user\n    const foundUser = await db.models.User.findOne({ where: { username: 'john_doe' } });\n    console.log('Found user:', foundUser.toJSON());\n\n  } catch (error) {\n    console.error('Database operation failed:', error.message);\n  } finally {\n    // Close the database connection if it's not an in-memory SQLite\n    if (db.sequelize.options.dialect !== 'sqlite' || db.sequelize.options.storage !== ':memory:') {\n      await db.sequelize.close();\n      console.log('Database connection closed.');\n    }\n  }\n}\n\nmain();","lang":"javascript","description":"Demonstrates setting up `apemanenv` for database configuration, defining a model using `apemandb`'s JSON schema, and initializing the `apemandb` instance to synchronize schema and perform basic CRUD operations."},"warnings":[{"fix":"Always check the release notes for both `apemandb` and the underlying `sequelize` package when upgrading major versions. Be prepared to adapt to Sequelize's API changes.","message":"ApemanDB is a wrapper around Sequelize. Major version updates in Sequelize (e.g., from v6 to v7) can introduce breaking changes that ApemanDB may not fully abstract or document, requiring users to consult Sequelize's migration guides for underlying changes.","severity":"breaking","affected_versions":">=1.0"},{"fix":"Ensure `env/database.json` and `env/index.js` follow the structure prescribed by `apemanenv` and `apemandb` documentation. Verify environment variable loading if applicable.","message":"ApemanDB is tightly coupled with `apemanenv` for database configuration. Deviations from the expected `apemanenv` structure for `database.json` or its loading mechanism will result in connection failures or unexpected behavior.","severity":"gotcha","affected_versions":">=1.0"},{"fix":"Install the appropriate database driver package (e.g., `npm install mysql2`) corresponding to the `DIALECT` specified in your `database.json`.","message":"Database drivers (e.g., `mysql2`, `sqlite3`, `pg`) are peer dependencies of Sequelize and must be installed separately based on the chosen dialect in `database.json`. Failing to install the correct driver for your specified dialect will lead to runtime errors.","severity":"gotcha","affected_versions":">=1.0"},{"fix":"Understand the JSON schema limitations. For advanced Sequelize features not exposed via the JSON model definition, you might need to extend the database instance post-initialization or consider alternative solutions if full Sequelize flexibility is paramount.","message":"Model definitions are exclusively handled via JSON files. This approach, while simplifying common use cases, can limit direct programmatic control over Sequelize's full feature set (e.g., custom instance methods, hooks) compared to defining models directly in JavaScript/TypeScript.","severity":"gotcha","affected_versions":">=1.0"}],"env_vars":null,"last_verified":"2026-04-22T00:00:00.000Z","next_check":"2026-07-21T00:00:00.000Z","problems":[{"fix":"Install the correct driver (e.g., `npm install sqlite3` or `npm install mysql2`) for your chosen database, and ensure the `DIALECT` property is correctly set in `env/database.json`.","cause":"Missing database driver package or incorrect 'DIALECT' in database.json.","error":"Dialect needs to be explicitly defined. If you are using SQLite, install 'sqlite3' package."},{"fix":"Verify that your database server (e.g., MySQL, PostgreSQL) is running and accessible. Double-check `HOST`, `PORT`, `USERNAME`, and `PASSWORD` in your `env/database.json`.","cause":"The database server is not running, or the host/port/credentials in `database.json` are incorrect, preventing a connection.","error":"Error: connect ECONNREFUSED 127.0.0.1:3306"},{"fix":"Ensure the `modelsDir` path is absolute and correctly points to your model definition directory. Verify that JSON model files are valid and present in that directory.","cause":"The `modelsDir` path provided to `apemandb.create` is incorrect, or the JSON model file (e.g., `user.json`) is malformed or missing.","error":"TypeError: Cannot read properties of undefined (reading 'User')"}],"ecosystem":"npm"}