@function initModels

assign mysql clients to models and sync models

@param {object} config

@returns {Promise}
350610
function initModels (config) {
    // iterate over models
    return Promise.each(_.values(config.models), model => {
        // if model does not have a mysql client then add from app config
        if (model.mysqlClient === null) {
            // get mysql client for model
            var mysql = config.mysql[model.name] || config.mysql.default
            // require database
            assert.ok(mysql, 'mysql client not found for model '+model.name)
            // set database for model
            model.mysql(mysql)
        }
        // if model does not have redis add
        if (!defined(model.cache)) {
            // get redis client for model
            var redis = config.redis[model.name] || config.redis.default
            // redis is optional
            if (defined(redis)) {
                model.redis(redis)
            }
        }
        // sync model unless NO_SYNC env flag set
        if (!process.env.NO_SYNC) {
            return model.sync()
        }
    })
}
347859
function loadModel(modelSpecPath, name) {
  return plugin.myrmex.fire('beforeModelLoad', modelSpecPath, name)
  .spread(() => {
    // Because we use require() to get the spec, it could either be a JSON file
    // or the content exported by a node module
    // But because require() caches the content it loads, we clone the result to avoid bugs
    // if the function is called twice
    const modelSpec = _.cloneDeep(require(modelSpecPath));

    // Lasy loading because the plugin has to be registered in a Myrmex instance before requiring ./model
    const Model = require('./model');
    return Promise.resolve(new Model(name, modelSpec));
  })
  .then(model => {
    // This event allows to inject code to alter the model specification
    return plugin.myrmex.fire('afterModelLoad', model);
  })
  .spread((model) => {
    return Promise.resolve(model);
  });
}
865060
function MySQL(client, conSettings) {
    'use strict';
    this.name = 'mysql';
    this._models = {};
    this.log = console.log;
    this.client = client;
    this.settings = conSettings;
}
1194622
function(callback) {
            var toInit = ['config', 'logger'];
            loader.loadServices(path.resolve(serverRoot, 'services'));
            injectDependencies(loader);

            loader.init(toInit, function(err) {
                callback(err);
            });
        }
705681
function initRoutes (config, route) {
    // create express router for route
    route.router = express.Router({
        caseSensitive: true,
        strict: true,
    })
    // initialize routes depth first so that explicit nested paths come
    // before wildcard paths and are handled correctly by express router
    _.each(route.routes, (subRoute, path) => {
        // get router for sub route
        var router = initRoutes(config, subRoute)
        // bind route for path
        route.router.use('/'+path+'/', router)
    })
    // clear model if no properties are set
    if (_.keys(route.model).length === 0) {
        route.model = undefined
    }
    // clear controller if no properties are set
    if (_.keys(route.controller).length === 0) {
        route.controller = undefined
    }
    // instantiate ImmutableCoreModel
    if (defined(route.model)) {
        route.model = new ImmutableCoreModel(route.model)
        // add model to app register
        config.models[route.model.name] = route.model
    }
    // if model is not set use model for this node
    if (defined(route.controller) && !defined(route.controller.model)) {
        route.controller.model = route.model
    }
    // instantiate ImmutableCoreController - this will create default controllers
    // for model
    var controller = route.controller = new ImmutableCoreController(route.controller)
    // get all templates then remove those that have controllers
    var bareTemplates = _.cloneDeep(route.templates)
    // iterate over paths
    _.each(controller.paths, path => {
        // iterate over http methods for path
        _.each(path, methods => {
            // iterate over handlers for different roles
            _.each(methods, spec => {
                // role can be specific or default to all
                var role = spec.role || 'all'
                // template can be specified or take from method name
                var template = spec.template || spec.methodName
                // template name exists locally
                if (defined(route.templates[template])) {
                    // if there is a template for the controllers role then remove
                    // it from the list of unused templates
                    if (defined(bareTemplates[template].role[role])) {
                        delete bareTemplates[template].role[role]
                    }
                    // otherwise if there is a template for all roles then assign
                    // it to this controller so that another controller for the
                    // all role will not be created to serve the template
                    else if (defined(bareTemplates[template].role['all'])) {
                        delete bareTemplates[template].role['all']
                    }
                }
            })
        })
    })
    // set to true if any controllers addded
    var added = false
    // create paths for any templates without controllers
    _.each(bareTemplates, (template, templateName) => {
        // iterate over any templates for roles that have not been used
        _.each(template.role, (templatePath, role) => {
            // get path from template name with index becoming /
            var path = templateName === 'index' ? '/' : '/'+templateName
            // create entry for path in controller if not yet defined
            if (!controller.paths[path]) {
                controller.paths[path] = {}
            }
            // create entry for method if not yet defined
            if (!controller.paths[path]['get']) {
                controller.paths[path]['get'] = []
            }
            // add spec for template to controller
            controller.paths[path]['get'].push({
                role: role,
                template: templatePath,
            })
        })
    })
    // if controllers were added then need to reorder controllers
    if (added) {
        controller.orderControllers()
    }
    // get list of path names
    var pathNames = _.keys(controller.paths)
    // sort path names so that static names go above onces with placeholders
    var sortedPathNames = pathNames.sort(sortPlaceholdersLower)
    // create routes for controller paths
    _.each(sortedPathNames, path => {
        var methods = controller.paths[path]
        // add route for each method
        _.each(methods, (spec, method) => {
            // create ImmutableAppPresenter instance
            var presenter = new ImmutableAppPresenter({
                config: config,
                method: method,
                module: module,
                path: path,
                route: route,
                spec: spec,
            })
            // middleware for route
            var routeMiddleware = []
            // iterate over spec(s) for different roles
            _.each(spec, roleSpec => {
                // if spec has middleware add to router
                _.each(roleSpec.middleware, middleware => {
                    routeMiddleware.push(middleware)
                })
            })
            // add presenter as final middleware
            routeMiddleware.push(presenter)
            // add path to router with method
            route.router[method](path, routeMiddleware)
        })
    })
    // return router so it can be bound to parent
    return route.router
}
1156160
public function initModels( $config = [] ) {

		// Detect Category - Used only by dynamic calls
		if( $this->categoryParam ) {

			$this->category = $this->model;
			$this->model	= null;
		}

		// Detect Tag - Used only by dynamic calls
		if( $this->tagParam ) {

			$this->tag		= $this->model;
			$this->model	= null;
		}

		// Detect Author - Used only by dynamic calls
		if( $this->authorParam ) {

			$this->author	= $this->model;
			$this->model	= null;
		}

		// Find models for search page
		if( $this->pagination ) {

			if( empty( $this->dataProvider ) ) {

				// Check Category
				if( empty( $this->category ) && isset( $this->categorySlug ) && isset( $this->categoryType ) ) {

					$categoryService	= Yii::$app->factory->get( 'categoryService' );
					$this->category		= $categoryService->getBySlugType( $this->categorySlug, $this->categoryType );
				}

				// Check Tag
				if( empty( $this->tag ) && isset( $this->tagSlug ) && isset( $this->tagType ) ) {

					$tagService		= Yii::$app->factory->get( 'tagService' );
					$this->tag		= $tagService->getBySlugType( $this->tagSlug, $this->tagType );
				}

				// Category
				if( isset( $this->category ) ) {

					$this->initCategoryModels();
				}
				// Tag
				else if( isset( $this->tag ) ) {

					$this->initTagModels();
				}
				// Author
				else if( isset( $this->author ) ) {

					$this->initAuthorModels();
				}
				// Page
				else {

					$this->initPageModels();
				}
			}

			$this->modelPage = $this->dataProvider->getModels();
		}
		// Find models for popular, recent and related widgets
		else {

			switch( $this->widget ) {

				// Featured
				case 'featured': {

					$this->initFeatured();

					break;
				}
				// Recent
				case 'recent': {

					$this->initRecent();

					break;
				}
				// Popular
				case 'popular': {

					$this->initPopular();

					break;
				}
				// Author
				case 'author': {

					$this->initAuthor( $this->author );

					break;
				}
				// Related
				case 'related': {

					$this->initAuthor( $this->model->creator );

					break;
				}
				// Similar
				case 'similar': {

					$this->initSimilar();

					break;
				}
			}
		}
	}
668194
public function exec($config = array(), &$models = array())
    {
        $this->result = array();
        $this->current = 0;
        $count = 0;
        $this->init($config);
        $offset = $config['start'];
        $size = $config['size'];
        $total = 0;
        if ($header = $this->getCore()->next()) {
            $this->current++;
            while ($next = $this->getCore()->next()) {
                if ($offset && $size) {
                    if ($total >= $offset && $total < ($offset + $size)) {
                        $total++;
                    } else {
                        continue;
                    }
                }
                if (implode('', $next) != '') {
                    $modelSource = null;
                    $model = $this->build($header, $next, $modelSource);
                    if ($model instanceof Model) {
                        if ($model && $model->valid() && $model->save(true)) {
                            if ($this->callback) {
                                call_user_func($this->callback, $model, $modelSource);
                            }
                            $models[] = $model;
                            $this->result[$this->current] = $model;
                            $count++;
                        }
                    }
                }
                $this->current++;
            }
            return $count;
        }

        return false;
    }
770393
function initModelList (args) {
    var controller = this
    var model = this.model
    // make sure args is object
    args = requireValidOptionalObject(args)
    // make sure list is defined
    args.list = requireValidOptionalObject(args.list)
    // make sure query args are object
    var queryArgs = requireValidOptionalObject(args.list.query)
    // create title from name
    var title = model.title+' Records'
    // create new form instance configured to submit from list page
    if (controller.form && _.get(args, 'list.form') !== false) {
        var form = controller.form.newInstance({
            action: './?redirect=./',
        })
    }
    // get role
    var role = args.defaultRole || 'all'
    // build fields for table view
    this.fields = buildFields(model, args.list && args.list.fields)
    // index inputs
    var input = {
        // included deleted records
        deleted: 'query.deleted',
        // limit - overrides value in query if any
        limit: 'query.limit',
        // offset - overrides value in query if any
        offset: 'query.offset',
        // column to sort by
        orderColumn: 'query.orderColumn',
        // direction to sort in
        orderDirection: 'query.orderDirection',
        // free-form search string
        search: 'query.search',
        // list of columns to select
        select: 'query.select',
        // json encoded where arguments
        where: 'query.where',
    }
    // if model has an original id column then add to query options
    if (model.columnName('originalId')) {
        input.originalId = 'query.originalId'
    }
    // add extra columns as query param options
    _.each(model.extraColumns, (spec, name) => {
        // only add column if it has index
        if (!spec.index && !spec.unique) {
            return
        }
        // do not overwrite core inputs
        if (input[name]) {
            return
        }
        // add column to inputs
        input[name] = 'query.'+name
    })
    // links to display at top of page
    var links
    // use links from list view
    if (Array.isArray(args.list.links)) {
        links = args.list.links
    }
    // use global controller links
    else if (Array.isArray(args.links)) {
        links = args.links
    }
    // set default links
    else {
        links = [
            {href: './new', title: 'Create New'},
        ]
    }
    // create path if it does not exist
    if (!this.paths['/']) {
        this.paths['/'] = {}
    }
    // add list handler for GET on /
    this.paths['/'].get = [
        {
            before: function (args) {
                // load records
                return beforeList(controller, args, _.cloneDeep(controller.fields), title, form, links, queryArgs)
            },
            input: input,
            method: function (args) {
                return args.json
                    ? _.pick(args, ['records', 'result'])
                    : _.pick(args, ['clear', 'fields', 'form', 'links', 'pager', 'query', 'records', 'result', 'title'])
            },
            methodName: 'list',
            role: role,
        },
    ]
}
1320345
public function init($config = [])
    {
        $this->__init_database();

        $this->_db_name = (string)(($db = $config['session_db_name']) ? $db : $config['db_name']);

        if (!($this->db instanceof MysqlDb)) {
            return false;
        }

        // check if the sql table does exist
        $sql         = (string)"SELECT COUNT(`session_id`) FROM `{$this->_db_name}`.`user_session`";
        $session_res = $this->db->query((string)$sql);
        // if not try to create the session table
        if ($session_res === false) {
            $sql = (string)"CREATE TABLE `{$this->_db_name}`.`user_session` (
                    `session_id` varchar(100) NOT NULL default '',
                    `session_data` LONGTEXT NOT NULL,
                    `expires` int(11) NOT NULL default '0',
                    `created` DATETIME,
                    `updated` DATETIME,
                     PRIMARY KEY (`session_id`)
                    ) ENGINE=InnoDB Collate=utf8_general_ci";

            return $this->db->query((string)$sql);
        }

        return true;
    }
162402
function injectModel(name, config, m) {
    const modelConfig = app.think.config('model', undefined, m);
    const cacheConfig = app.think.config('cache', undefined, m);
    config = helper.parseAdapterConfig(modelConfig, config);
    const instance = model(name, config, m);
    instance._cacheConfig = cacheConfig;
    return instance;
  }
469130
function initMongo(config, callback) {
  
  var self = this;
  
  // Set db
  self.db = new Db(config.database, new Server(config.host, config.port, {}), {safe: true});
  
  // Get client
  self.db.open(function(err, client) {
    if (err) throw err;
    else {
      self.client = client;
      client.collectionNames(function(err, names) {
        if (err) throw err;
        else {
          var name = config.database + '.' + config.collection;
          var exists = names.filter(function(col) {
            if (col.name == name) return col; 
          });
          
          // Collection options
          var opts = {capped: true, size: config.logSize};
          if (config.logLimit != null) opts.max = config.logLimit;
          
          if (exists.length === 0) {
            client.createCollection(config.collection, opts, function(err, collection) {
              if (err) throw err;
              else {
                self.collection = collection;
                callback.call(self);
              }
            });
          } else {
            // Get collection
            client.collection(config.collection, function(err, collection) {
              if (err) throw err;
              else {
                self.collection = collection;
                // Get collection options » Check if collection has already been capped
                collection.options(function(err, options) {
                  if (err) {
                    throw err;
                  } else {
                    // Check if collection's options match log requirements
                    var ready = (options.capped === true && options.size === opts.size);
                    if ('max' in opts) ready = (ready && options.max === opts.max);
                    if (!ready) {
                      // Convert collection to capped if it's not match log requirements
                      var cmd = {"convertToCapped": config.collection, size: opts.size};
                      if ('max' in opts) cmd.max = opts.max;
                      client.command(cmd, function(err) {
                        if (err) throw err;
                        else {
                          callback.call(self);
                        }
                      });
                    } else {
                      callback.call(self);
                    }
                  }
                });
              }
            });
          }
        }
      });
    }
  });
}
739269
function (config) {
        this.config = core.extend({
            connection: 'mongodb://localhost/mvcjs',
            options: {}
        }, config);
        this.db = mongoose.connect(this.config.connection, this.config.options);
        logger.info('Mongo.construct:', this.config);
    }
441779
function initModelSchema (args) {
    var controller = this
    var model = this.model
    // if model does not have schema do not create schema controller
    if (!model.schemaData) {
        return
    }
    // get accountId column
    var accountIdColumn = model.columnName('accountId') 
    // set role to authenticated if model requires account id
    var role = args.defaultRole || (accountIdColumn && model.columns[accountIdColumn].null === false ? 'authenticated' : 'all')
    // index inputs
    var input = {
        // optionally get schema for action
        action: 'query.action',
        // get full schema including meta data
        meta: 'query.meta',
    }
    // create path if it does not exist
    if (!this.paths['/schema']) {
        this.paths['/schema'] = {}
    }
    // add GET /schema handler
    this.paths['/schema'].get = [
        {
            input: input,
            method: function (args) {
                return schema(controller, args)
            },
            methodName: 'schema',
            role: role,
        }
    ]
}
286643
function initModule (args) {
    debug('new ImmutableCoreModel', args)
    // require object for args
    assert.equal(typeof args, 'object', 'argument must be object')
    // require name for model
    assert.equal(typeof args.name, 'string', 'name required')
    // set model name
    this.name = args.name
    // create title from name
    this.title = changeCase.titleCase(this.name)
    // create path from name
    this.path = changeCase.paramCase(this.name)
    // module name is model name with Model appended
    this.moduleName = args.name+'Model'
    // create new immutable module for model - this will throw error
    // if moduleName is already defined
    this.module = immutable.module(this.moduleName, {})
    // add info to module meta
    this.module.meta.class = 'ImmutableCoreModel'
    this.module.meta.instance = this
    // and model to global registers
    this.global().models[this.name] = this
    // set to true if model is an action for another model
    this.isAction = false
    // parent model for action models
    this.model = undefined
    // controller object will be set when controller created for model
    this.controller = undefined
    // transformation functions keyed by property name
    this.transform = {}
    // get transform functions from args
    _.each(args.transform, (transform, property) => {
        // require function
        assert.equal(typeof transform, 'function', `tranform must be function for ${this.name} ${property}`)
        // set transform function
        this.transform[property] = transform
    })

    /* cache */

    if (defined(args.redis)) {
        this.redis(args.redis)
    }

    /* database */

    // database is now deprecated so this will throw error
    if (defined(args.database)) {
        this.database(args.database)
    }

    /* binaryIds */

    // use setting from env if set
    if (defined(process.env.DEFAULT_BINARY_IDS)) {
        this.binaryIds = process.env.DEFAULT_BINARY_IDS === 'true' || process.env.DEFAULT_BINARY_IDS === '1' ? true : false
    }
    // use binary ids setting for model if set
    else if (defined(args.binaryIds)) {
        this.binaryIds = !!args.binaryIds
    }
    // use global setting
    else {
        this.binaryIds = this.global().defaultBinaryIds
    }

    /* compression */

    // use setting from env
    if (defined(process.env.DEFAULT_COMPRESSION)) {
        this.compression = process.env.DEFAULT_COMPRESSION === 'true' || process.env.DEFAULT_COMPRESSION === '0' ? true : false
    }
    // use compresion setting for model if set
    else if (defined(args.compression)) {
        this.compression = !!args.compression
    }
    // use global setting
    else {
        this.compression = this.global().defaultCompression
    }

    /* insert delayed */

    // use insert delayed setting for model if set
    if (args.insertDelayed !== undefined) {
        this.insertDelayed = args.insertDelayed
    }
    // use global setting
    else if (process.env.DEFAULT_INSERT_DELAYED) {
        this.insertDelayed = process.env.DEFAULT_INSERT_DELAYED === 'true' ? true : false
    }
    // use global setting
    else {
        this.insertDelayed = this.global().insertDelayed
    }

    /* concurrency */

    // use concurrency setting from args if set
    if (parseInt(args.concurrency)) {
        this.concurrency = parseInt(args.concurrency)
    }
    // use global setting
    else {
        this.concurrency = this.global().concurrency
    }

    /* charset */

    // charset to use when creating table - this only applies when mode is
    // first syncd and will not be changed
    this.charset = args.charset || process.env.DEFAULT_CHARSET || this.global().defaultCharset

    /* database engine */

    // database engine to use when creating table - this only applies when model
    // is first syncd and will not be changed
    this.engine = args.engine || process.env.DEFAULT_ENGINE || this.global().defaultEngine

    /* elasticsearch configuration */

    // if elasticsearch is true then client will be set later and is required
    if (args.elasticsearch === true) {
        this.elasticsearchClient = true
    }
    // set elasticsearch client
    else if (args.elasticsearch) {
        this.elasticsearch(args.elasticsearch)
    }
    else {
        this.elasticsearchClient = null
    }
    // retain deleted records - default false
    this.esDeleted = !!args.esDeleted
    // set index name - default to model path
    this.esIndex = args.esIndex || this.path
    // set type selector - if not defined model name will also be used for type
    this.esType = args.esType

    /* mysql */

    if (defined(args.mysql)) {
        this.mysql(args.mysql)
    }
    else {
        this.mysqlClient = null
    }
}
1159277
function(records,config) {
    
    //the hell is this doing here
    this.id = new Date();

    if ( records instanceof Array ) {
        this.records = records;
    } else {
        var dataField = records.data;
        var data = records.datasource;
        this.records =  data[dataField];
    }
    this.config = config;
    if ( this.config ) {
        this.propertyConfigMap = {};
        this.config.cols.forEach( col => {
            this.propertyConfigMap[col.property] = col;
        });
    }

    //indexRecords.call(this);
}
1253884
function create(item, model, data) {
    var serverProps = serverProperties(item, model, data).properties;
    return utils.socketPut(model.io, model.url + '/create/', serverProps).then(function(response) {
        _.merge(serverProps, response);
        return update(item, model, serverProps);
    }).then(function() {
        // Refresh all items that were referenced - some of their properties might change
        return Promise.all(_.map(serverProps.refresh, function(item) {
            return item.refresh();
        }));
    });
}
1237339
function init() {
    var debugFile = path.join(__dirname, 'debug.js');

    if (debug) {
        if (fs.existsSync(debugFile)) { fs.unlinkSync(debugFile); }
        debugFD = fs.openSync(debugFile, 'a');
    }

    getFileList(modelsPath).forEach(defineModel);
    processAllRelations(defineRelation);

    if (debug) {
        fs.closeSync(debugFD);
    }
}