this code hijacked from https://github.com/masuidrive/node-mysql/blob/master/lib/mysql/pack.js
176711
function calc_null_bitmap(values) {
    var val = 0, len = 0, bitmap = [];
    values.map(function(v) {
        val += (v == null || v == undefined ? 1 << len : 0);
        len += 1;

        if(len == 8) {
          bitmap.push(val);
          len = val = 0;
        }
        return val;
    });

    if(len > 0) {
      bitmap.push(val);
    }

    var packed = []
    bitmap.forEach(function(entry, i, bitmap) {
      packed[i] = pack.pack("C*", entry)
    })

    return packed
}
1225310
async function build() {
  console.time('Packager');

  let requires = [];
  let esmExportString = '';
  let cjsExportString = '';

  try {
    if (!fs.existsSync(DIST_PATH)) fs.mkdirSync(DIST_PATH);
    fs.writeFileSync(ROLLUP_INPUT_FILE, '');
    fs.writeFileSync(TEST_MODULE_FILE, '');

    // All the snippets that are Node.js-based and will break in a browser
    // environment
    const nodeSnippets = fs
      .readFileSync('tag_database', 'utf8')
      .split('\n')
      .filter(v => v.search(/:.*node/g) !== -1)
      .map(v => v.slice(0, v.indexOf(':')));

    const snippets = fs.readdirSync(SNIPPETS_PATH);
    const archivedSnippets = fs
      .readdirSync(SNIPPETS_ARCHIVE_PATH)
      .filter(v => v !== 'README.md');

    snippets.forEach(snippet => {
      const rawSnippetString = getRawSnippetString(SNIPPETS_PATH, snippet);
      const snippetName = snippet.replace('.md', '');
      let code = getCode(rawSnippetString);
      if (nodeSnippets.includes(snippetName)) {
        requires.push(code.match(/const.*=.*require\(([^\)]*)\);/g));
        code = code.replace(/const.*=.*require\(([^\)]*)\);/g, '');
      }
      esmExportString += `export ${code}`;
      cjsExportString += code;
    });
    archivedSnippets.forEach(snippet => {
      const rawSnippetString = getRawSnippetString(
        SNIPPETS_ARCHIVE_PATH,
        snippet
      );
      cjsExportString += getCode(rawSnippetString);
    });

    requires = [
      ...new Set(
        requires
          .filter(Boolean)
          .map(v =>
            v[0].replace(
              'require(',
              'typeof require !== "undefined" && require('
            )
          )
      )
    ].join('\n');

    fs.writeFileSync(ROLLUP_INPUT_FILE, `${requires}\n\n${esmExportString}`);

    const testExports = `module.exports = {${[...snippets, ...archivedSnippets]
      .map(v => v.replace('.md', ''))
      .join(',')}}`;

    fs.writeFileSync(
      TEST_MODULE_FILE,
      `${requires}\n\n${cjsExportString}\n\n${testExports}`
    );

    // Check Travis builds - Will skip builds on Travis if not CRON/API
    if (util.isTravisCI() && util.isNotTravisCronOrAPI()) {
      fs.unlink(ROLLUP_INPUT_FILE);
      console.log(
        `${chalk.green(
          'NOBUILD'
        )} Module build terminated, not a cron job or a custom build!`
      );
      console.timeEnd('Packager');
      process.exit(0);
    }

    await doRollup();

    // Clean up the temporary input file Rollup used for building the module
    fs.unlink(ROLLUP_INPUT_FILE);

    console.log(`${chalk.green('SUCCESS!')} Snippet module built!`);
    console.timeEnd('Packager');
  } catch (err) {
    console.log(`${chalk.red('ERROR!')} During module creation: ${err}`);
    process.exit(1);
  }
}
715230
function prepareBatchInsertSql(tableName, toInserts, options, needArgs) {
  options = options || {};
  var returnFields = options.fields || [];

  var insertsCount = toInserts.length;
  var oneElem = toInserts[0];
  var sql = 'insert into "' + tableName + '"(';
  var fieldClause = '';
  var valueClause = ' values';
  var args = null;
  if (needArgs) args = [];
  var fieldList = Object.keys(oneElem);
  var fieldNameCount = fieldList.length;
  var elemKeyIndex = 1;
  fieldList.forEach(function (f) {
    let endSymbol = ',';
    if (fieldNameCount == elemKeyIndex) endSymbol = ')';
    fieldClause += '"' + f + '"' + endSymbol;
    elemKeyIndex++;
  });

  for (var i = 0; i < insertsCount; i++) {
    var toInsert = toInserts[i];
    var keyCount = Object.keys(toInsert).length;
    if (keyCount != fieldNameCount) throw new Error('prepareBatchInsertSql:one element\'s key count:' + keyCount + ' not equal first element:' + fieldNameCount);
    var keyIndex = 1;
    fieldList.forEach(function (f) {
      let endSymbol = ',';
      if (keyIndex == 1) valueClause += '(';
      if (keyIndex == keyCount) endSymbol = ')';
      var val = toInsert[f];
      var valType = typeof val;
      if (valType == 'string' || valType == 'object') {
        if (valType == 'object') val = JSON.stringify(val);
        valueClause += '$' + (args.length + 1) + endSymbol;
        args.push(val);
      } else if (valType == 'number' || valType == 'boolean') {
        valueClause += val + endSymbol;
      } else {
        console.error('tableName:', tableName, " toInserts:", JSON.stringify(toInserts), " f:", f, " valType:", valType);
        throw new Error('prepareBatchInsertSql:filed:' + f + ',invalid value type, must be one of them:string,number');
      }
      keyIndex++;
    });

    if (i < (insertsCount - 1)) {
      valueClause += ',';
    }
  }
  sql = sql + fieldClause + valueClause;
  if (returnFields) sql += fieldsToReturningClause(returnFields);
  return { sql: sql, args: needArgs ? args : [] };
}
807413
function bundleApp(codeList, ns, domload, compile, before, npmTree, o) {
  var l = []
    , usedBuiltIns = npmTree._builtIns
    , len = 0;
  delete npmTree._builtIns;

  // 1. construct the global namespace object
  l.push("window." + ns + " = {data:{}, path:{}};");

  // 2. attach path code to the namespace object so that require.js can efficiently resolve paths
  l.push('\n// include npm::path');
  var pathCode = read(join(builtInDir, 'path.posix.js'));
  l.push('(function (exports) {\n ' + pathCode + '\n}(window.' + ns + '.path));');

  // 3. pull in serialized data
  Object.keys(o.data).forEach(function (name) {
    return l.push(ns + ".data." + name + " = " + o.data[name] + ";");
  });

  // 4. attach require code
  var config = {
    namespace : ns
  , domains   : Object.keys(o.domains) // TODO: remove npm from here
  , arbiters  : o.arbiters
  , logging   : o.logLevel
  , npmTree   : npmTree
  , builtIns  : builtIns
  , slash     : '/' //TODO: figure out if different types can coexist, if so, determine in resolver, and on client
  };

  l.push(anonWrap(read(join(dir, 'require.js'))
    .replace(/VERSION/, JSON.parse(read(join(dir, '..', 'package.json'))).version)
    .replace(/REQUIRECONFIG/, JSON.stringify(config))
  ));

  // 5. include CommonJS compatible code in the order they have to be defined
  var defineWrap = function (exportName, domain, code) {
    return ns + ".define('" + exportName + "','" + domain + "',function (require, module, exports) {\n" + code + "\n});";
  };

  // 6. harvest function splits code into app and non-app code and defineWraps
  var harvest = function (onlyMain) {
    codeList.forEach(function (pair) {
      var dom = pair[0]
        , file = pair[1]
        , basename = file.split('.')[0];
      if ((dom === 'app') !== onlyMain) {
        return;
      }
      var code = before(compile(join(o.domains[dom], file)));
      l.push(defineWrap(basename, dom, code));
    });
  };

  // 7.a) include required builtIns
  l.push("\n// node builtins\n");
  len = l.length;
  usedBuiltIns.forEach(function (b) {
    if (b === 'path') { // already included
      return;
    }
    l.push(defineWrap(b, 'npm', read(join(builtInDir, b + '.js'))));
  });
  if (l.length === len) {
    l.pop();
  }

  // 7.b) include modules not on the app domain
  l.push("\n// shared code\n");
  len = l.length;
  harvest(false);
  if (l.length === len) {
    l.pop();
  }

  // 7.c) include modules on the app domain, and wait for domloader if set
  l.push("\n// app code - safety wrapped\n\n");
  domload(harvest(true));

  // 8. use a closure to encapsulate the private internal data and APIs
  return anonWrap(l.join('\n'));
}
936558
function(table)
    {
        var moduleName = this.moduleName = table.tableName;
        this.append('module.exports = ' + moduleName +
            ' = require(\'typedef\')');
        this.addBreak(2);
        this.addDisclaimer();
        this.addBreak();
        if (table.description) this.addComment(table.description||'');
        this.append('.class(\'' + moduleName + '\') .define({');
        this.addBreak(2);

        var _this = this;
        var primary;

	    var processedFields = [];
        table.fields.forEach(function(field, n) {
	        if (processedFields.indexOf(field.name) >= 0) {
		        return;
	        }
	        processedFields.push(field.name);
            var name   = field.name;
            var type   = field.type.toLowerCase();

            // dont add that weird shit
            if (name.indexOf('.') != -1) {
                return;
            }

            if (n) _this.append(',\n\n');

            if (type == 'long' || type == 'double' || type == 'integer')
                type = 'number';

            if (type == 'date')
                type = 'datetime';

            // Id as number, assume its primary
            if (name == 'Id' && type == 'number') {
                type = 'primary__' + type;
                primary = name;
            }

            _this.append('    __static__field__' + type + '__');

            field.access.forEach(function(ac) {
                _this.append(ac + '__');
            });

            _this.append(name + ':\n        \'' + name + '\'');

        });

        if (!primary)
            console.log(('No presumed primary key found for ' + moduleName).yellow);

        this.addBreak(2);
        this.append('});');
    }
581742
function unzipNodeTarball(next) {
        var onError = function(err) {
          console.log(err.stack);
          _log('error', 'failed to extract the node source');
          process.exit(1);
        };

        if (isWin) {
          _log('extracting the node source [node-tar.gz]');

          // tar-stream method w/ gunzip-maybe
          var read = fs.createReadStream(nodeFilePath);
          var extract = tarstream.extract();
          var basedir = nodeFileDir;

          if (!fs.existsSync(nodeFileDir)) {
            fs.mkdirSync(nodeFileDir);
          }

          extract.on('entry', function(header, stream, callback) {
            // header is the tar header
            // stream is the content body (might be an empty stream)
            // call next when you are done with this entry

            var absolutepath = path.join(basedir, header.name);
            if (header.type === 'directory') {
              // handle directories.
              // console.log('dir:', header.name);
              fs.mkdirSync(absolutepath);
              return callback();
            } else if (header.type === 'file') {
              // handle files
              // console.log('file:', header.name);
            } else {
              console.log(header.type + ':', header.name);
              _log('warn', 'unhandled type in tar extraction, skipping');
              return callback();
            }

            var write = fs.createWriteStream(absolutepath);

            stream.pipe(write);

            write.on('close', function() {
              return callback();
            });

            stream.on('error', function(err) {
              return onError(err);
            });

            write.on('error', function(err) {
              return onError(err);
            });

            stream.resume(); // just auto drain the stream
          });

          extract.on('finish', function() {
            _log('extraction finished');
            return next();
          });

          read.pipe(gunzip()).pipe(extract);
        } else {
          _log('extracting the node source [native tar]');

          var cmd = ['tar', '-xf', nodeFilePath, '-C', nodeFileDir];
          _log(cmd.join(' '));

          var tar = spawn(cmd.shift(), cmd);
          tar.stdout.pipe(process.stdout);
          tar.stderr.pipe(process.stderr);

          tar.on('close', function() {
            return next();
          });
          tar.on('error', onError);
        }
      }
1289023
function Base64lib(){

var b64chars
    = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';

var b64charcodes = function(){
    var a = [];
    var codeA = 'A'.charCodeAt(0);
    var codea = 'a'.charCodeAt(0);
    var code0 = '0'.charCodeAt(0);
    for (var i = 0; i < 26; i ++) a.push(codeA + i);
    for (var i = 0; i < 26; i ++) a.push(codea + i);
    for (var i = 0; i < 10; i ++) a.push(code0 + i);
    a.push('+'.charCodeAt(0));
    a.push('/'.charCodeAt(0));
    return a;
}();

var b64tab = function(bin){
    var t = {};
    for (var i = 0, l = bin.length; i < l; i++) t[bin.charAt(i)] = i;
    return t;
}(b64chars);

var stringToArray = function(s){
    var a = [];
    for (var i = 0, l = s.length; i < l; i ++) a[i] = s.charCodeAt(i);
    return a;
};

this.convertUTF8ArrayToBase64 = function(bin){
    var padlen = 0;
    while (bin.length % 3){
        bin.push(0);
        padlen++;
    };
    var b64 = [];
    for (var i = 0, l = bin.length; i < l; i += 3){
        var c0 = bin[i], c1 = bin[i+1], c2 = bin[i+2];
        if (c0 >= 256 || c1 >= 256 || c2 >= 256)
            throw 'unsupported character found';
        var n = (c0 << 16) | (c1 << 8) | c2;
        b64.push(
            b64charcodes[ n >>> 18],
            b64charcodes[(n >>> 12) & 63],
            b64charcodes[(n >>>  6) & 63],
            b64charcodes[ n         & 63]
        );
    }
    while (padlen--) b64[b64.length - padlen - 1] = '='.charCodeAt(0);
    return String.fromCharCode.apply(String, b64);
};

var convertBase64ToUTF8Array = function(b64){
    b64 = b64.replace(/[^A-Za-z0-9+\/]+/g, '');
    var bin = [];
    var padlen = b64.length % 4;
    for (var i = 0, l = b64.length; i < l; i += 4){
        var n = ((b64tab[b64.charAt(i  )] || 0) << 18)
            |   ((b64tab[b64.charAt(i+1)] || 0) << 12)
            |   ((b64tab[b64.charAt(i+2)] || 0) <<  6)
            |   ((b64tab[b64.charAt(i+3)] || 0));
        bin.push(
            (  n >> 16 ),
            ( (n >>  8) & 0xff ),
            (  n        & 0xff )
        );
    }
    bin.length -= [0,0,2,1][padlen];
    return bin;
};

var convertUTF16ArrayToUTF8Array = function(uni){
    var bin = [];
    for (var i = 0, l = uni.length; i < l; i++){
        var n = uni[i];
        if (n < 0x80)
            bin.push(n);
        else if (n < 0x800)
            bin.push(
                0xc0 | (n >>>  6),
                0x80 | (n & 0x3f));
        else
            bin.push(
                0xe0 | ((n >>> 12) & 0x0f),
                0x80 | ((n >>>  6) & 0x3f),
                0x80 |  (n         & 0x3f));
    }
    return bin;
};

var convertUTF8ArrayToUTF16Array = function(bin){
    var uni = [];
    for (var i = 0, l = bin.length; i < l; i++){
        var c0 = bin[i];
        if    (c0 < 0x80){
            uni.push(c0);
        }else{
            var c1 = bin[++i];
            if (c0 < 0xe0){
                uni.push(((c0 & 0x1f) << 6) | (c1 & 0x3f));
            }else{
                var c2 = bin[++i];
                uni.push(
                       ((c0 & 0x0f) << 12) | ((c1 & 0x3f) << 6) | (c2 & 0x3f)
                );
            }
        }
    }
    return uni;
};

var convertUTF8StringToBase64 = function(bin){
    return convertUTF8ArrayToBase64(stringToArray(bin));
};

this.convertBase64ToUTF8String = function(b64){
    return String.fromCharCode.apply(String, convertBase64ToUTF8Array(b64));
};

var convertUTF8StringToUTF16Array = function(bin){
    return convertUTF8ArrayToUTF16Array(stringToArray(bin));
};

var convertUTF8ArrayToUTF16String = function(bin){
    return String.fromCharCode.apply(String, convertUTF8ArrayToUTF16Array(bin));
};

var convertUTF8StringToUTF16String = function(bin){
    return String.fromCharCode.apply(String, convertUTF8ArrayToUTF16Array(stringToArray(bin)));
};

var convertUTF16StringToUTF8Array = function(uni){
    return convertUTF16ArrayToUTF8Array(stringToArray(uni));
};

var convertUTF16ArrayToUTF8String = function(uni){
    return String.fromCharCode.apply(String, convertUTF16ArrayToUTF8Array(uni));
};

var convertUTF16StringToUTF8String = function(uni){
    return String.fromCharCode.apply(String, convertUTF16ArrayToUTF8Array(stringToArray(uni)));
};

}
1142971
function(sql, val, callback) {
  let qry = (typeof sql === 'object') ? sql : mysql.format(sql, val);
  if (!callback && typeof val === 'function') callback = val; // Handle 2 parm scenario

  _pool.getConnection((err, conn) => {
    _pool.query(qry, (err, items, fields) => {
      if (err) return callback(err);

      conn.release();

      callback(err, items);
    });
  });
}
849194
function(db) {
		var methods_uuid = uuid();
		debug.assert(methods_uuid).is('uuid');

		return db.query('CREATE SEQUENCE methods_seq')
			.query(['CREATE TABLE IF NOT EXISTS methods (',
					"	id uuid PRIMARY KEY NOT NULL default uuid_generate_v5('"+methods_uuid+"', nextval('methods_seq'::regclass)::text),",
					'	types_id uuid REFERENCES types,',
					'	type text NOT NULL,',
					'	name text NOT NULL,',
					'	body text NOT NULL,',
					'	meta json NOT NULL,',
					'	active BOOLEAN DEFAULT TRUE,',
					'	created timestamptz NOT NULL default now(),',
					'	modified timestamptz NOT NULL default now(),',
					'	CONSTRAINT active_not_false CHECK(active != false)',
					')'
				].join('\n'))
			.query('ALTER SEQUENCE methods_seq OWNED BY methods.id')
			.query('CREATE INDEX methods_types_id ON methods (types_id)')
			.query('CREATE INDEX methods_types_id_name ON methods (types_id,name)')
			.query('CREATE INDEX methods_type ON methods (type)')
			.query('CREATE INDEX methods_type_name ON methods (type,name)')
			.query('CREATE UNIQUE INDEX ON methods USING btree(types_id, name, active nulls LAST);')
			.query('CREATE TRIGGER methods_modified BEFORE UPDATE ON methods FOR EACH ROW EXECUTE PROCEDURE moddatetime (modified)')
			.query(
				[
	'CREATE OR REPLACE FUNCTION ensure_only_one_active_row_trigger()',
	'RETURNS trigger',
	'AS $function$',
	'BEGIN',
	  // Disable the currently enabled row
	"  IF (TG_OP = 'UPDATE') THEN",
	     // Nothing to do if updating the row currently enabled'
	"    IF (OLD.active = true AND OLD.name = NEW.name) THEN",
	'      RETURN NEW;',
	'    END IF;',
	"    EXECUTE format('UPDATE %I.%I SET active = null WHERE active = true AND name = %L;', TG_TABLE_SCHEMA, TG_TABLE_NAME, OLD.name);",
	"    IF (OLD.name != NEW.name) THEN",
	"      EXECUTE format('UPDATE %I.%I SET active = null WHERE active = true AND name = %L;', TG_TABLE_SCHEMA, TG_TABLE_NAME, NEW.name);",
	'    END IF;',
	'  ELSE',
	"    EXECUTE format('UPDATE %I.%I SET active = null WHERE active = true AND name = %L;', TG_TABLE_SCHEMA, TG_TABLE_NAME, NEW.name);",
	'  END IF;',
	   // Enable new row
	'  NEW.active := true;',
	'  RETURN NEW;',
	'END;',
	'$function$',
	'LANGUAGE plpgsql'
				].join('\n')
			)
			.query('CREATE TRIGGER methods_only_one_active_row'+
				' BEFORE INSERT OR UPDATE OF active ON methods'+
				' FOR EACH ROW WHEN (NEW.active = true)'+
				' EXECUTE PROCEDURE ensure_only_one_active_row_trigger()'
			);
	}
663692
function unwrapAst (ast, prefix, suffix) {
  let fake_code = `${prefix}\nlet ${LONG_AND_WEIRED_STRING}\n${suffix}`
  let fake_ast = babylon.parse(fake_code, {
    sourceType: 'module'
  })

  let selected_node
  let selected_index
  traverse(fake_ast, {
    enter: function (node, parent) {
      // removes the loc info of fake ast
      if (node.loc) {
        node.loc = null
      }

      if (node.type !== 'BlockStatement') {
        return
      }

      // find the index of LONG_AND_WEIRED_STRING
      let index = node.body.findIndex(n => {
        if (node.type !== 'VariableDeclaration') {
          return
        }

        if (
          access(n, [
            'declarations', 0,
            'id',
            'name'
          ]) === LONG_AND_WEIRED_STRING
        ) {
          return true
        }
      })

      if (!~index) {
        return
      }

      selected_node = node
      selected_index = index
    }
  })

  if (selected_node) {
    selected_node.body.splice(selected_index, 1)
    selected_node.body.push(...ast.program.body)
  }

  return fake_ast
}
457165
function EasyMySQL(config)
{
	this.debug = config.error_debug || false;

	if(db)
		db.configure(config);
}
1201780
function (backend) {

    backend.Debug (4, "MySQL creating connection [%s]", backend.uid);
    backend.base = mysql.createConnection(backend.opts);
    backend.count ++;
      
    // register event for asynchronous server errors
    backend.base.on('error', function(err) {
        backend.Debug (1, "MySQL server error=[%s]", err);
        // Sever was restarted or network connection was lost let restart connection
        if(err.code === 'PROTOCOL_CONNECTION_LOST') {
             backend.Debug (4, "MySQL connection lost [%s/%d] automatic connect retry in 10s]", backend.uid, backend.count);
             setTimeout(function () {CreateConnection (backend);}, MYSQL_RECONNECT_TIMER);  
             
        } else { 
            throw err;  // server variable configures this)
        };
    });
    
    // force an initial connectiion at object construction time
    backend.base.connect (function(err) {
        if (err) {
             backend.Debug (4, "MySQL connection fail [%s/%d] automatic connect retry in 10s]", backend.uid, backend.count);
             setTimeout(function () {CreateConnection (backend);}, MYSQL_RECONNECT_TIMER);  
            
        } else {
            backend.Debug (5,"MySQL Connect Done [%s]",  backend.uid);
        }
    });
}
1182940
async function build() {
    const clientConfig = await webpackConfig({target: 'web', env: 'prod'});
    const serverConfig = await webpackConfig({target: 'node', env: 'prod'});

    return new Promise((resolve, reject) => {
        console.log('Compiling client...');

        // eslint-disable-next-line consistent-return
        webpack(clientConfig, (clientError, clientStats) => {
            if (clientError) {
                return reject(clientError);
            }

            const clientMessages = formatWebpackMessages(clientStats.toJson({}, true));
            if (clientMessages.errors.length) {
                return reject(new Error(clientMessages.errors.join('\n\n')));
            }

            if (
                process.env.CI &&
                (typeof process.env.CI !== 'string' || process.env.CI.toLowerCase() !== 'false') &&
                clientMessages.warnings.length
            ) {
                console.log(
                    chalk.yellow(
                        '\nTreating warnings as errors because process.env.CI = true.\n' +
                            'Most CI servers set it automatically.\n'
                    )
                );
                return reject(new Error(clientMessages.warnings.join('\n\n')));
            }

            console.log(chalk.green('Compiled client successfully.'), '\n');
            console.log('Compiling server...');
            webpack(serverConfig, (serverError, serverStats) => {
                if (serverError) {
                    return reject(serverError);
                }

                const serverMessages = formatWebpackMessages(serverStats.toJson({}, true));
                if (serverMessages.errors.length) {
                    return reject(new Error(serverMessages.errors.join('\n\n')));
                }

                if (
                    process.env.CI &&
                    (typeof process.env.CI !== 'string' || process.env.CI.toLowerCase() !== 'false') &&
                    serverMessages.warnings.length
                ) {
                    console.log(
                        chalk.yellow(
                            '\nTreating warnings as errors because process.env.CI = true.\n' +
                                'Most CI servers set it automatically.\n'
                        )
                    );
                    return reject(new Error(serverMessages.warnings.join('\n\n')));
                }

                console.log(chalk.green('Compiled server successfully.'), '\n');
                return resolve({
                    stats: clientStats,
                    warnings: Object.assign({}, clientMessages.warnings, serverMessages.warnings),
                });
            });
        });
    });
}
1109364
function (model) {
              return Token.create({
                code: Token.generateCode(),
                expire: Token.defaultExpire(),
                ownerId: model.id
              }).then(function (data) {
                return data;
              }).catch(function (err) {
                res.database(err)
              });
            }
670550
function executeQuery () {
    return this.model.mysql().query(this.select.sql, this.select.params)
    // decode data
    .then(results => {
        // decode any encoded data columns
        return this.decodeData(results)
    })
    // add custom error handler
    .catch(err => {
        throw this.error('db error', err)
    })
}
20279
function GulpDotaNpc (type) {
  var file = 'npc_' + type + '_custom.txt';
  var headerName = 'DOTA' + type[0].toUpperCase() + type.substr(1);

  function transformFiles (contents, file) {
    // get the string contents of the file so we can easily update it
    var strContent = String(contents);
    var splitPath = file.relative.split(path.sep);
    var needsRename = splitPath.length > 1;
    var abilityName = stripDotTxt(splitPath.join('_'));

    if (needsRename) {
      strContent = strContent.replace('"' + stripDotTxt(splitPath[1]) + '"', '"' + abilityName + '"');
    }
    console.log('Adding', type, abilityName);
    return strContent;
  }

  function addHeader (contents, file) {
    return [
    '"', headerName, '"\n{\n',
    contents,
    '\n\n}'
    ].join('');
  }

  return multipipe(transform(transformFiles), concat(file), transform(addHeader));
}
814325
public function compile()
    {
        $sql = array();

        if (isset($this->select)) {
            $sql[] = 'SELECT ' . implode(',', $this->select);
        }

        if (isset($this->update)) {
            $sql[] = 'UPDATE';
            $sql[] = $this->update['table'];
            $sql[] = 'SET';

            $blocks = array();
            foreach ($this->update['values'] as $key => $value) {
                $blocks[] = $key . ' = ' . $value;
            }

            $sql[] = implode(',', $blocks);
        }

        if (isset($this->delete)) {
            $sql[] = "DELETE ";
        }

        if (isset($this->insert)) {
            $sql[] = 'INSERT INTO';
            $sql[] = $this->insert['table'];

            $fields = array();
            $replaces = array();

            foreach ($this->insert['values'] as $key => $value) {
                $fields[] = '`' . $key . '`';
                $replaces[] = $value;
            }

            $sql[] = '(' . implode(',', $fields) . ')';
            $sql[] = (count($this->insert['values']) > 1) ? 'VALUES' : 'VALUE';
            $sql[] = '(' . implode(',', $replaces) . ')';
        }

        if (isset($this->replace)) {
            $sql[] = 'REPLACE INTO';
            $sql[] = $this->replace['table'];

            $fields = array();
            $replaces = array();

            foreach ($this->replace['values'] as $key => $value) {
                $fields[] = '`' . $key . '`';
                $replaces[] = $value;
            }

            $sql[] = '(' . implode(',', $fields) . ')';
            $sql[] = (count($this->replace['values']) > 1) ? 'VALUES' : 'VALUE';
            $sql[] = '(' . implode(',', $replaces) . ')';
        }

        if (isset($this->from)) {
            $sql[] = 'FROM ' . implode(',', $this->from);
        }

        foreach ($this->where as $index => $where) {

            if (!is_string($where['column'])) {
                throw new \OtherCode\Database\Exceptions\QueryException("The column field is not a string in where clause.");
            }

            if (!is_string($where['operator']) || !in_array($where['operator'], $this->operators)) {
                throw new \OtherCode\Database\Exceptions\QueryException("Invalid operator in where clause.");
            }

            if (gettype($where['value']) == 'string' && $where['quoted'] === true) {
                $where['value'] = '"' . $where['value'] . '"';
            }

            unset($where['quoted']);

            $sentence = ($index == 0) ? "WHERE " : "AND ";
            $sql[] = $sentence . implode(" ", $where);

        }

        if (isset($this->group)) {
            $sql[] = 'GROUP BY ' . $this->group;
        }

        foreach ($this->order as $index => $order) {

            if (!in_array($order[1], array('ASC', 'DESC'))) {
                throw new \OtherCode\Database\Exceptions\QueryException('Invalid order by value, must be ASC or DESC.');
            }

            $sql[] = 'ORDER BY ' . implode(" ", $order);
        }

        if (isset($this->limit)) {
            $sql[] = 'LIMIT ' . implode(" ", $this->limit);
        }

        return trim(implode(" ", $sql));
    }