<commit_before>var nonObjectCriteriaTypes = { // object to validate types
        string: true,
        number: true,
        boolean: true
    },

    util = require('./util'),
    errors = require('./errors'),
    db = require('./db'),
    Mediator = require('./mediator'),
    Transaction; // fn

/**
 * Sails Transaction allows you to pass specific sails actions through common database connection allowing you to
 * leverage mySQL transactions support.
 *
 * @constructor
 * @param {function} callback - receives `error`, `transaction`
 */
Transaction = function (callback) {
    var connection = null;

    util.extend(this, /** @lends Transaction.prototype */ {
        /**
         * Creates a connection if not already connected.
         *
         * @private
         * @returns {mysql.Connection}
         */
        connect: function (callback) {
            // validate db setup prior to every connection. this ensures nothing goes forward post teardown
            if (!Transaction.db) {
                callback(errors.TRANSACTION_NOT_SETUP);
            }

            if (!connection) {
                Transaction.db.getConnection(function (error, conn) {
                    if (!error) {
                        connection = conn; // save locally
                        Transaction.associateConnection(conn); // assign a transaction id
                    }
                    callback(error, connection);
                });
            }
            else {
                callback(undefined, connection);
            }
        },

        /**
         * Gets the instance of the db connection associated with this transaction. The connection object is sealed off
         * within the Transaction constructor to avoid any sort of integrity loss while the transaction or the actor is
         * moved along the codebase.
         *
         * @private
         * @returns {mysql.Connection}
         */
        connection: function () {
            return connection;
        },

        /**
         * Clears the internal reference of the connection with this transaction
         *
         * @private
         */
        disconnect: function () {
            if (connection) {
                connection = null;
            }
        }
    });

    // if not yet connected, spawn new connection and initiate transaction
    return this.start(callback);
};

// Add static functions to the Transaction constructor.
util.extend(Transaction, /** @lends Transaction */ {
    /**
     * Mediator allows Model operations to be executed in coherence with a transaction.
     */
    Mediator: Mediator,

    /**
     * Stores all ongoing database connections.
     * @private
     *
     * @type {object<mysql~connection>}
     */
    connections: {},

    /**
     * For first run, the transactions environment needs to be setup. Without that, it is not possible to procure new
     * database connections.
     */
    setup: function (config) {
        // at this stage, the `db` variable should not exist. expecting fresh setup or post teardown setup.
        if (this.db) {
            // @todo - emit wrror event instead of console.log
            console.log('Warn: duplicate setup of connection found in Transactions.setup');
        }
        this.db = db.createSource(config);
    },

    /**
     * This function needs to be called at the end of app-lifecycle to ensure all db connections are closed.
     */
    teardown: function () {
        // just to be sure! clear all items in the connections object. they should be cleared by now
        util.each(this.connections, function (value, prop, conns) {
            try {
                value.release();
            }
            catch (e) { } // nothing to do with error
            delete conns[prop];
        });

        // now execute end on the db. will end pool if pool, or otherwise will execute whatever `end` that has been
        // exposed by db.js
        if (this.db) {
            this.db.end();
            this.db = null;
        }
    },

    /**
     * Update the internal cache to associate a connection with a particular transaction id
     * @private
     *
     * @param {mysql.Connection} connection
     */
    associateConnection: function (connection) {
        if (connection.transactionId && Transaction.connections[connection.transactionId]) {
            throw errors.TRANSACTION_CONNECTION_OVERLAP;
        }

        connection.transactionId = util.uid();
        Transaction.connections[connection.transactionId] = connection;
    },

    /**
     * Update internal cache to disassociate a connection from a transaction id
     * @private<commit_msg>Added support for creating multiple connections during setup of Transaction ORM.<commit_after>var nonObjectCriteriaTypes = { // object to validate types
        string: true,
        number: true,
        boolean: true
    },

    util = require('./util'),
    errors = require('./errors'),
    db = require('./db'),
    Mediator = require('./mediator'),
    Transaction; // fn

/**
 * Sails Transaction allows you to pass specific sails actions through common database connection allowing you to
 * leverage mySQL transactions support.
 *
 * @constructor
 * @param {function} callback - receives `error`, `transaction`
 */
Transaction = function (callback) {
    var connection = null;

    util.extend(this, /** @lends Transaction.prototype */ {
        /**
         * Creates a connection if not already connected.
         *
         * @private
         * @returns {mysql.Connection}
         */
        connect: function (callback) {
            // validate db setup prior to every connection. this ensures nothing goes forward post teardown
            if (!Transaction.sources.primary) {
                callback(errors.TRANSACTION_NOT_SETUP);
            }

            if (!connection) {
                Transaction.sources.primary.getConnection(function (error, conn) {
                    if (!error) {
                        connection = conn; // save locally
                        Transaction.associateConnection(conn); // assign a transaction id
                    }
                    callback(error, connection);
                });
            }
            else {
                callback(undefined, connection);
            }
        },

        /**
         * Gets the instance of the db connection associated with this transaction. The connection object is sealed off
         * within the Transaction constructor to avoid any sort of integrity loss while the transaction or the actor is
         * moved along the codebase.
         *
         * @private
         * @returns {mysql.Connection}
         */
        connection: function () {
            return connection;
        },

        /**
         * Clears the internal reference of the connection with this transaction
         *
         * @private
         */
        disconnect: function () {
            if (connection) {
                connection = null;
            }
        }
    });

    // if not yet connected, spawn new connection and initiate transaction
    return this.start(callback);
};

// Add static functions to the Transaction constructor.
util.extend(Transaction, /** @lends Transaction */ {
    /**
     * Mediator allows Model operations to be executed in coherence with a transaction.
     */
    Mediator: Mediator,

    /**
     * Stores all database sources
     */
    sources: {},

    /**
     * Stores all ongoing database connections.
     * @private
     *
     * @type {object<mysql~connection>}
     */
    connections: {},

    /**
     * For first run, the transactions environment needs to be setup. Without that, it is not possible to procure new
     * database connections.
     */
    setup: function (config) {
        var that = this;

        // at this stage, the `db` variable should not exist. expecting fresh setup or post teardown setup.
        if (this.sources.primary) {
            // @todo - emit wrror event instead of console.log
            console.log('Warn: duplicate setup of connection found in Transactions.setup');
            this.teardown();
        }

        // create connections for read-replicas
        util.each(config.replicas, function (replicaConfig, replicaId) {
            that.sources[replicaId] = db.createSource(util.extend(util.clone(replicaConfig), {
                database: config.database,
                adapter: config.adapter
            }));
        });

        // there should not be a database replica-set named `primary`
        if (this.sources.primary) {
            // @todo - emit wrror event instead of console.log
            console.log('Warn: replica set named "primary" will be overridden by main source. Rename it.');
        }

        // create the primary db
        this.sources.primary = db.createSource(config);
    },

    /**
     * This function needs to be called at the end of app-lifecycle to ensure all db connections are closed.
     */
    teardown: function () {
        // just to be sure! clear all items in the connections object. they should be cleared by now
        util.each(this.connections, function (connection, connectionName, conns) {
            try {
                connection.release();
            }
            catch (e) { } // nothing to do with error
            delete conns[connectionName];
        });

        // now execute end on the db. will end pool if pool, or otherwise will execute whatever `end` that has been
        // exposed by db.js
        util.each(this.sources, function (source, sourceName, sources) {
            try {
                source.end();
            }
            catch (e) { } // nothing to do with error
            delete sources[sourceName];
        });
    },

    /**
     * Update the internal cache to associate a connection with a particular transaction id
     * @private
     *
     * @param {mysql.Connection} connection
     */
    associateConnection: function (connection) {
        if (connection.transactionId && Transaction.connections[connection.transactionId]) {
            throw errors.TRANSACTION_CONNECTION_OVERLAP;
        }

        connection.transactionId = util.uid();
        Transaction.connections[connection.transactionId] = connection;
    },

    /**
     * Update internal cache to disassociate a connection from a transaction id
     * @private
{'fraction_non_alphanumeric': 0.09165145547122683, 'fraction_numerical': 0.0, 'mean_word_length': 1.8567508232711307, 'pattern_counts': {'":': 0, '<': 5, '<?xml version=': 0, '>': 5, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '1957951', 'n_tokens_mistral': 2495, 'n_tokens_neox': 2412, 'n_words': 874}