npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

ndm-schema-generator-mysql

v1.1.23

Published

Tool to generate a database schema object for use with the node-data-mapper project.

Downloads

504

Readme

ndm-schema-generator-mysql

A tool to generate a database schema object for use with the node-data-mapper project.

When using node-data-mapper a database schema object is required to describe how each table and column will be mapped from a tablular format to a normalized format (from rows and columns to JavaScript objects and arrays). Manually creating and maintaining a database schema object is cumbersome and error prone, so it's recommended that the database schema object be generated automatically at application start-up time. After all, the database itself has metadata available that describes the tables, columns, data types, maximum lengths, nullability, etc. Using a generator makes additions and modifications to the database automatic. So if, for example, a column is added to the database, a simple application restart gives the ORM knowledge of the new column. This tool provides a working example that can be used to generate a database schema object, with some useful hooks for aliasing tables and columns and attaching global converters.

Table of Contents

Getting Started

First off, if you're not familiar with node-data-mapper then please read through the Getting Started section.

The below example uses a fictitious bike_shop database. If you would like to run the example included in the example folder (./example/index.js), then first follow the instructions for creating the bike_shop database.

Install ndm-schema-generator-mysql
$ npm install ndm-schema-generator-mysql --save

Generate a Database Schema Object

Example

Below is a quick example of how to generate a database schema object. The example generates the schema object, performs some minor manipulation on the tables and columns, and then prints the results to the console. There are two event handlers--onAddTable and onAddColumn--that are described in further detail below.

'use strict';

const mysql                  = require('mysql');
const ndm                    = require('node-data-mapper');
const schemaGen              = require('ndm-schema-generator-mysql');
const MySQLSchemaGenerator   = schemaGen.MySQLSchemaGenerator;
const infoSchemaDB           = schemaGen.informationSchemaDatabase;
const util                   = require('util');

// Connect to the database.
const con = mysql.createConnection({
  host:     'localhost',
  user:     'example',
  password: 'secret',
  database: 'INFORMATION_SCHEMA'
});

// Create the Datacontext instance for the information_schema database.
const dataContext = new ndm.MySQLDataContext(infoSchemaDB, con);

// Create the MySQLSchemaGenerator instance.
const generator = new MySQLSchemaGenerator(dataContext);

// Handlers for the ADD_TABLE and ADD_COLUMN events.
generator.on('ADD_TABLE',  onAddTable);
generator.on('ADD_COLUMN', onAddColumn);

// Generate the schema.
generator
  .generateSchema('bike_shop')
  .then(schema => console.log(util.inspect(schema, {depth: null})))
  .catch(console.error);

/**
 * The table mapping (mapTo) removes any underscores and uppercases the
 * proceeding character.  Ex: bike_shop_bikes => bikeShopBikes
 * @param {Table} table - An ndm.Table instance with a name property.
 * @return {void}
 */
function onAddTable(table) {
  table.mapTo = table.name.replace(/_[a-z]/g, (c) => c.substr(1).toUpperCase());
}

/**
 * Set up each column.
 * @param {Column} col - An ndm.Column instance with name, mapTo, dataType,
 * columnType, isNullable, maxLength, and isPrimary properties.
 * @param {Table} table - An ndm.Table object with name and mapTo properties.
 * @return {void}
 */
function onAddColumn(col, table) {
  // Add a converter based on the type.
  if (col.dataType === 'bit')
    col.converter = ndm.bitConverter;
}

The generator.generateSchema takes a single dbName parameter, which is a string.

Add Table Event

For each table in the database, an ADD_TABLE event is broadcast, passing along a Table object describing the table. This event allows for defining global mappings for tables. In the example above, tables are defined in the database using snake_case (bike_shops and bike_shop_bikes for example). In JavaScript, however, the most common convention is camelCase. Hence, the tableCB function above take in a table object with a name in snake_case, and modifies it to have a camelCase mapTo (mapping).

Add Column Event

Likewise, for each column in the database an ADD_COLUMN event is broadcast. An event handler can be used to define custom column mappings, or to attached global converters based on data type. In the example above, a bitConverter is attached to all bit-type columns (in reality, this would most likely be attached to columns with a columnType of tinyint(1) as well). At any rate, with the above definition in place every bit-type column in the database will automatically be transformed into a boolean on retrieve, and from a boolean to a bit on save. One could, for example, convert all dates to UTC strings, or perform other system-wide format changes.