migration.js 26.2 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900
// Copyright IBM Corp. 2015,2016. All Rights Reserved.
// Node module: loopback-connector-mysql
// This file is licensed under the MIT License.
// License text available at https://opensource.org/licenses/MIT

'use strict';
var g = require('strong-globalize')();
var async = require('async');
module.exports = mixinMigration;

/*!
 * @param {MySQL} MySQL connector class
 * @param {Object} mysql mysql driver
 */
function mixinMigration(MySQL, mysql) {
  MySQL.prototype.showFields = function(model, cb) {
    var table = this.tableEscaped(model);
    var sql = 'SHOW FIELDS FROM ' + table;
    this.execute(sql, function(err, fields) {
      if (err) {
        return cb(err);
      } else {
        cb(err, fields);
      }
    });
  };

  MySQL.prototype.showIndexes = function(model, cb) {
    var table = this.tableEscaped(model);
    var sql = 'SHOW INDEXES FROM ' + table;
    this.execute(sql, function(err, indexes) {
      if (err) {
        return cb(err);
      } else {
        cb(err, indexes);
      }
    });
  };

   /**
    * Perform autoupdate for the given models
    * @param {String[]} [models] A model name or an array of model names.
    * If not present, apply to all models
    * @param {Function} [cb] The callback function
    */
  MySQL.prototype.autoupdate = function(models, cb) {
    var self = this;
    var foreignKeyStatements = [];

    if ((!cb) && ('function' === typeof models)) {
      cb = models;
      models = undefined;
    }
    // First argument is a model name
    if ('string' === typeof models) {
      models = [models];
    }

    models = models || Object.keys(this._models);

    async.eachSeries(models, function(model, done) {
      if (!(model in self._models)) {
        return process.nextTick(function() {
          done(new Error(g.f('Model not found: %s', model)));
        });
      }

      self.getTableStatus(model, function(err, fields, indexes) {
        self.discoverForeignKeys(self.table(model), {}, function(err, foreignKeys) {
          if (err) console.log('Failed to discover "' + table + '" foreign keys', err);

          if (!err && fields && fields.length) {
            //if we already have a definition, update this table
            self.alterTable(model, fields, indexes, foreignKeys, function(err, result) {
              if (!err) {
                self.addForeignKeys(model, function(err, result) {
                  done(err);
                });
              } else {
                done(err);
              }
            });
          } else {
            //if there is not yet a definition, create this table
            self.createTable(model, function(err) {
              if (!err) {
                self.addForeignKeys(model, function(err, result) {
                  done(err);
                });
              } else {
                done(err);
              }
            });
          }
        });
      });
    }, function(err) {
      return cb(err);
    });
  };

  /*!
   * Create a DB table for the given model
   * @param {string} model Model name
   * @param cb
   */
  MySQL.prototype.createTable = function(model, cb) {
    var metadata = this.getModelDefinition(model).settings[this.name];
    var engine = metadata && metadata.engine;
    var sql = 'CREATE TABLE ' + this.tableEscaped(model) +
      ' (\n  ' + this.buildColumnDefinitions(model) + '\n)';
    if (engine) {
      sql += 'ENGINE=' + engine + '\n';
    }
    this.execute(sql, cb);
  };

  /**
   * Check if the models exist
   * @param {String[]} [models] A model name or an array of model names. If not
   * present, apply to all models
   * @param {Function} [cb] The callback function
   */
  MySQL.prototype.isActual = function(models, cb) {
    var self = this;
    var ok = false;

    if ((!cb) && ('function' === typeof models)) {
      cb = models;
      models = undefined;
    }
    // First argument is a model name
    if ('string' === typeof models) {
      models = [models];
    }

    models = models || Object.keys(this._models);

    async.eachSeries(models, function(model, done) {
      self.getTableStatus(model, function(err, fields, indexes) {
        self.discoverForeignKeys(self.table(model), {}, function(err, foreignKeys) {
          if (err) console.log('Failed to discover "' + table + '" foreign keys', err);

          self.alterTable(model, fields, indexes, foreignKeys, function(err, needAlter) {
            if (err) {
              return done(err);
            } else {
              ok = ok || needAlter;
              done(err);
            }
          }, true);
        });
      });
    }, function(err) {
      cb(err, !ok);
    });
  };

  MySQL.prototype.getColumnsToAdd = function(model, actualFields) {
    var self = this;
    var m = this.getModelDefinition(model);
    var propNames = Object.keys(m.properties).filter(function(name) {
      return !!m.properties[name];
    });
    var sql = [];

    propNames.forEach(function(propName) {
      if (m.properties[propName] && self.id(model, propName)) return;
      var found;
      var colName = expectedColNameForModel(propName, m);
      if (actualFields) {
        actualFields.forEach(function(f) {
          if (f.Field === colName) {
            found = f;
          }
        });
      }
      if (found) {
        actualize(propName, found);
      } else {
        sql.push('ADD COLUMN ' + self.client.escapeId(colName) + ' ' +
          self.buildColumnDefinition(model, propName));
      }
    });

    function actualize(propName, oldSettings) {
      var newSettings = m.properties[propName];
      if (newSettings && changed(newSettings, oldSettings)) {
        var pName = self.columnEscaped(model, propName);
        sql.push('CHANGE COLUMN ' + pName + ' ' + pName + ' ' +
          self.buildColumnDefinition(model, propName));
      }
    }

    function changed(newSettings, oldSettings) {
      if (oldSettings.Null === 'YES') {
        // Used to allow null and does not now.
        if (!self.isNullable(newSettings)) {
          return true;
        }
      }
      if (oldSettings.Null === 'NO') {
        // Did not allow null and now does.
        if (self.isNullable(newSettings)) {
          return true;
        }
      }

      if (oldSettings.Type.toUpperCase() !==
        self.buildColumnType(newSettings).toUpperCase()) {
        return true;
      }
      return false;
    }
    return sql;
  };

  MySQL.prototype.getColumnsToDrop = function(model, actualFields) {
    var self = this;
    var fields = actualFields;
    var sql = [];
    var m = this.getModelDefinition(model);
    var propNames = Object.keys(m.properties).filter(function(name) {
      return !!m.properties[name];
    });
    // drop columns
    if (fields) {
      fields.forEach(function(f) {
        var colNames = propNames.map(function expectedColName(propName) {
          return expectedColNameForModel(propName, m);
        });
        var index = colNames.indexOf(f.Field);
        var propName = index >= 0 ? propNames[index] : f.Field;
        var notFound = !~index;
        if (m.properties[propName] && self.id(model, propName)) return;
        if (notFound || !m.properties[propName]) {
          sql.push('DROP COLUMN ' + self.client.escapeId(f.Field));
        }
      });
    }
    return sql;
  };

  MySQL.prototype.addIndexes = function(model, actualIndexes) {
    var self = this;
    var m = this.getModelDefinition(model);
    var propNames = Object.keys(m.properties).filter(function(name) {
      return !!m.properties[name];
    });
    var indexNames = m.settings.indexes && Object.keys(m.settings.indexes).filter(function(name) {
      return !!m.settings.indexes[name];
    }) || [];
    var sql = [];
    var ai = {};

    if (actualIndexes) {
      actualIndexes.forEach(function(i) {
        var name = i.Key_name;
        if (!ai[name]) {
          ai[name] = {
            info: i,
            columns: [],
          };
        }
        ai[name].columns[i.Seq_in_index - 1] = i.Column_name;
      });
    }
    var aiNames = Object.keys(ai);

    // remove indexes
    aiNames.forEach(function(indexName) {
      if (indexName === 'PRIMARY' ||
        (m.properties[indexName] && self.id(model, indexName))) return;

      if (indexNames.indexOf(indexName) === -1 && !m.properties[indexName] ||
        m.properties[indexName] && !m.properties[indexName].index) {
        sql.push('DROP INDEX ' + self.client.escapeId(indexName));
      } else {
        // first: check single (only type and kind)
        if (m.properties[indexName] && !m.properties[indexName].index) {
          // TODO
          return;
        }
        // second: check multiple indexes
        var orderMatched = true;
        if (indexNames.indexOf(indexName) !== -1) {
          //check if indexes are configured as "columns"
          if (m.settings.indexes[indexName].columns) {
            m.settings.indexes[indexName].columns.split(/,\s*/).forEach(
              function(columnName, i) {
                if (ai[indexName].columns[i] !== columnName) orderMatched = false;
              });
          } else if (m.settings.indexes[indexName].keys) {
            //if indexes are configured as "keys"
            var index = 0;
            for (var key in m.settings.indexes[indexName].keys) {
              var sortOrder = m.settings.indexes[indexName].keys[key];
              if (ai[indexName].columns[index] !== key) {
                orderMatched = false;
                break;
              }
              index++;
            }
            //if number of columns differ between new and old index
            if (index !== ai[indexName].columns.length) {
              orderMatched = false;
            }
          }
        }
        if (!orderMatched) {
          sql.push('DROP INDEX ' + self.client.escapeId(indexName));
          delete ai[indexName];
        }
      }
    });

    // add single-column indexes
    propNames.forEach(function(propName) {
      var i = m.properties[propName].index;
      if (!i) {
        return;
      }
      var found = ai[propName] && ai[propName].info;
      if (!found) {
        var colName = expectedColNameForModel(propName, m);
        var pName = self.client.escapeId(colName);
        var type = '';
        var kind = '';
        if (i.type) {
          type = 'USING ' + i.type;
        }
        if (kind && type) {
          sql.push('ADD ' + kind + ' INDEX ' + pName +
            ' (' + pName + ') ' + type);
        } else {
          if (typeof i === 'object' && i.unique && i.unique === true) {
            kind = 'UNIQUE';
          }
          sql.push('ADD ' + kind + ' INDEX ' + pName + ' ' + type +
            ' (' + pName + ') ');
        }
      }
    });

    // add multi-column indexes
    indexNames.forEach(function(indexName) {
      var i = m.settings.indexes[indexName];
      var found = ai[indexName] && ai[indexName].info;
      if (!found) {
        var iName = self.client.escapeId(indexName);
        var type = '';
        var kind = '';
        if (i.type) {
          type = 'USING ' + i.type;
        }
        if (i.kind) {
          kind = i.kind;
        } else if (i.options && i.options.unique && i.options.unique == true) {
          //if index unique indicator is configured
          kind = 'UNIQUE';
        }

        var indexedColumns = [];
        var columns = '';
        //if indexes are configured as "keys"
        if (i.keys) {
          for (var key in i.keys) {
            if (i.keys[key] !== -1) {
              indexedColumns.push(key);
            } else {
              indexedColumns.push(key + ' DESC ');
            }
          }
        }
        if (indexedColumns.length > 0) {
          columns = indexedColumns.join(',');
        } else if (i.columns) {
          //if indexes are configured as "columns"
          columns = i.columns;
        }
        if (kind && type) {
          sql.push('ADD ' + kind + ' INDEX ' + iName +
            ' (' + columns + ') ' + type);
        } else {
          sql.push('ADD ' + kind + ' INDEX ' + type + ' ' + iName +
            ' (' + columns + ')');
        }
      }
    });
    return sql;
  };

  MySQL.prototype.getForeignKeySQL = function(model, actualFks) {
    var self = this;
    var m = this.getModelDefinition(model);
    var addFksSql = [];

    if (actualFks) {
      var keys = Object.keys(actualFks);
      for (var i = 0; i < keys.length; i++) {
        var constraint = self.buildForeignKeyDefinition(model, keys[i]);

        if (constraint) {
          addFksSql.push('ADD ' + constraint);
        }
      }
    }
    return addFksSql;
  };

  MySQL.prototype.addForeignKeys = function(model, fkSQL, cb) {
    var self = this;
    var m = this.getModelDefinition(model);

    if ((!cb) && ('function' === typeof fkSQL)) {
      cb = fkSQL;
      fkSQL = undefined;
    }

    if (!fkSQL) {
      var newFks = m.settings.foreignKeys;
      if (newFks)
        fkSQL = self.getForeignKeySQL(model, newFks);
    }
    if (fkSQL && fkSQL.length) {
      self.applySqlChanges(model, fkSQL, function(err, result) {
        if (err) cb(err);
        else
          cb(null, result);
      });
    } else cb(null, {});
  };

  MySQL.prototype.dropForeignKeys = function(model, actualFks) {
    var self = this;
    var m = this.getModelDefinition(model);

    var fks = actualFks;
    var sql = [];
    var correctFks = m.settings.foreignKeys || {};

    //drop foreign keys for removed fields
    if (fks && fks.length) {
      var removedFks = [];
      fks.forEach(function(fk) {
        var needsToDrop = false;
        var newFk = correctFks[fk.fkName];
        if (newFk) {
          var fkCol = expectedColNameForModel(newFk.foreignKey, m);
          var fkEntity = self.getModelDefinition(newFk.entity);
          var fkRefKey = expectedColNameForModel(newFk.entityKey, fkEntity);
          var fkRefTable = newFk.entity.name; //TODO check for mysql name
          needsToDrop = fkCol != fk.fkColumnName ||
                        fkRefKey != fk.pkColumnName ||
                        fkRefTable != fk.pkTableName;
        } else {
          needsToDrop = true;
        }

        if (needsToDrop) {
          sql.push('DROP FOREIGN KEY ' + fk.fkName);
          removedFks.push(fk); //keep track that we removed these
        }
      });

      //update out list of existing keys by removing dropped keys
      fks = actualFks.filter(function(k) {
        return removedFks.indexOf(k) == -1;
      });
    }
    return sql;
  };

  MySQL.prototype.getAlterStatement = function(model, statements) {
    return statements.length ?
      'ALTER TABLE ' + this.tableEscaped(model) + ' ' + statements.join(',\n') :
      '';
  };

  MySQL.prototype.alterTable = function(model, actualFields, actualIndexes, actualFks, done, checkOnly) {
    //if this is using an old signature, then grab the correct callback and check boolean
    if ('function' == typeof actualFks && typeof done !== 'function') {
      checkOnly = done || false;
      done = actualFks;
    }
    var self = this;

    var statements = [];

    async.series([
      function(cb) {
        statements = self.getAddModifyColumns(model, actualFields);
        cb();
      },
      function(cb) {
        statements = statements.concat(self.getDropColumns(model, actualFields));
        cb();
      },
      function(cb) {
        statements = statements.concat(self.addIndexes(model, actualIndexes));
        cb();
      },
      function(cb) {
        statements = statements.concat(self.dropForeignKeys(model, actualFks));
        cb();
      },
    ], function(err, result) {
      if (err) done(err);

      //determine if there are column, index, or foreign keys changes (all require update)
      if (statements.length) {
        //get the required alter statements
        var alterStmt = self.getAlterStatement(model, statements);
        var stmtList = [alterStmt];

        //set up an object to pass back all changes, changes that have been run,
        //and foreign key statements that haven't been run
        var retValues = {
          statements: stmtList,
          query: stmtList.join(';'),
        };

        //if we're running in read only mode OR if the only changes are foreign keys additions,
        //then just return the object directly
        if (checkOnly) {
          done(null, true, retValues);
        } else {
          //if there are changes in the alter statement, then execute them and return the object
          self.execute(alterStmt, function(err) {
            done(err, true, retValues);
          });
        }
      } else {
        done();
      }
    });
  };

  MySQL.prototype.buildForeignKeyDefinition = function(model, keyName) {
    var definition = this.getModelDefinition(model);

    var fk = definition.settings.foreignKeys[keyName];
    if (fk) {
      //get the definition of the referenced object
      var fkEntityName = (typeof fk.entity === 'object') ? fk.entity.name : fk.entity;

      //verify that the other model in the same DB
      if (this._models[fkEntityName]) {
        return ' CONSTRAINT ' + this.client.escapeId(fk.name) +
          ' FOREIGN KEY (' + fk.foreignKey + ')' +
          ' REFERENCES ' + this.tableEscaped(fkEntityName) +
          '(' + this.client.escapeId(fk.entityKey) + ')';
      }
    }
    return '';
  };

  MySQL.prototype.buildColumnDefinitions =
    MySQL.prototype.propertiesSQL = function(model) {
      var self = this;

      var pks = this.idNames(model).map(function(i) {
        return self.columnEscaped(model, i);
      });

      var definition = this.getModelDefinition(model);
      var sql = [];
      if (pks.length === 1) {
        var idName = this.idName(model);
        var idProp = this.getModelDefinition(model).properties[idName];
        if (idProp.generated) {
          sql.push(self.columnEscaped(model, idName) +
            ' INT(11) NOT NULL AUTO_INCREMENT PRIMARY KEY');
        } else {
          idProp.nullable = false;
          sql.push(self.columnEscaped(model, idName) + ' ' +
            self.buildColumnDefinition(model, idName) + ' PRIMARY KEY');
        }
      }
      Object.keys(definition.properties).forEach(function(prop) {
        if (self.id(model, prop) && pks.length === 1) {
          return;
        }
        var colName = self.columnEscaped(model, prop);
        sql.push(colName + ' ' + self.buildColumnDefinition(model, prop));
      });
      if (pks.length > 1) {
        sql.push('PRIMARY KEY(' + pks.join(',') + ')');
      }

      var indexes = self.buildIndexes(model);
      indexes.forEach(function(i) {
        sql.push(i);
      });

      return sql.join(',\n  ');
    };

  MySQL.prototype.buildIndex = function(model, property) {
    var prop = this.getModelDefinition(model).properties[property];
    var i = prop && prop.index;
    if (!i) {
      return '';
    }
    var type = '';
    var kind = '';
    if (i.type) {
      type = 'USING ' + i.type;
    }
    if (i.kind) {
      kind = i.kind;
    }
    var columnName = this.columnEscaped(model, property);
    if (kind && type) {
      return (kind + ' INDEX ' + columnName + ' (' + columnName + ') ' + type);
    } else {
      if (typeof i === 'object' && i.unique && i.unique === true) {
        kind = 'UNIQUE';
      }
      return (kind + ' INDEX ' + columnName + ' ' + type + ' (' + columnName + ') ');
    }
  };

  MySQL.prototype.buildIndexes = function(model) {
    var self = this;
    var indexClauses = [];
    var definition = this.getModelDefinition(model);
    var indexes = definition.settings.indexes || {};
    // Build model level indexes
    for (var index in  indexes) {
      var i = indexes[index];
      var type = '';
      var kind = '';
      if (i.type) {
        type = 'USING ' + i.type;
      }
      if (i.kind) {
        //if index uniqueness is configured as "kind"
        kind = i.kind;
      } else if (i.options && i.options.unique && i.options.unique == true) {
        //if index unique indicator is configured
        kind = 'UNIQUE';
      }
      var indexedColumns = [];
      var indexName = this.escapeName(index);
      var columns = '';
      //if indexes are configured as "keys"
      if (i.keys) {
        //for each field in "keys" object
        for (var key in i.keys) {
          if (i.keys[key] !== -1) {
            indexedColumns.push(key);
          } else {
            //mysql does not support index sorting Currently
            //but mysql has added DESC keyword for future support
            indexedColumns.push(key + ' DESC ');
          }
        }
      }
      if (indexedColumns.length) {
        columns = indexedColumns.join(',');
      } else if (i.columns) {
        columns = i.columns;
      }
      if (columns.length) {
        if (kind && type) {
          indexClauses.push(kind + ' INDEX ' +
          indexName + ' (' + columns + ') ' + type);
        } else {
          indexClauses.push(kind + ' INDEX ' + type +
          ' ' + indexName + ' (' + columns + ')');
        }
      }
    }
    // Define index for each of the properties
    for (var p in definition.properties) {
      var propIndex = self.buildIndex(model, p);
      if (propIndex) {
        indexClauses.push(propIndex);
      }
    }
    return indexClauses;
  };

  MySQL.prototype.buildColumnDefinition = function(model, prop) {
    var p = this.getModelDefinition(model).properties[prop];
    var line = this.columnDataType(model, prop) + ' ' +
      (this.isNullable(p) ? 'NULL' : 'NOT NULL');
    return line;
  };

  MySQL.prototype.buildColumnType = function buildColumnType(propertyDefinition) {
    var dt = '';
    var p = propertyDefinition;
    switch (p.type.name) {
      default:
      case 'JSON':
      case 'Object':
      case 'Any':
      case 'Text':
        dt = columnType(p, 'TEXT');
        dt = stringOptionsByType(p, dt);
        break;
      case 'String':
        dt = columnType(p, 'VARCHAR');
        dt = stringOptionsByType(p, dt);
        break;
      case 'Number':
        dt = columnType(p, 'INT');
        dt = numericOptionsByType(p, dt);
        break;
      case 'Date':
        dt = columnType(p, 'DATETIME'); // Currently doesn't need options.
        break;
      case 'Boolean':
        dt = 'TINYINT(1)';
        break;
      case 'Point':
      case 'GeoPoint':
        dt = 'POINT';
        break;
      case 'Enum':
        dt = 'ENUM(' + p.type._string + ')';
        dt = stringOptions(p, dt); // Enum columns can have charset/collation.
        break;
    }
    return dt;
  };

  function columnType(p, defaultType) {
    var dt = defaultType;
    if (p.dataType) {
      dt = String(p.dataType);
    }
    return dt;
  }

  function stringOptionsByType(p, columnType) {
    switch (columnType.toLowerCase()) {
      default:
      case 'varchar':
        // The maximum length for an ID column is 1000 bytes
        // The maximum row size is 64K
        var len = p.length || p.limit ||
          ((p.type !== String) ? 4096 : p.id || p.index ? 255 : 512);
        columnType += '(' + len + ')';
        break;
      case 'char':
        len = p.length || p.limit || 255;
        columnType += '(' + len + ')';
        break;

      case 'text':
      case 'tinytext':
      case 'mediumtext':
      case 'longtext':

        break;
    }
    columnType = stringOptions(p, columnType);
    return columnType;
  }

  function stringOptions(p, columnType) {
    if (p.charset) {
      columnType += ' CHARACTER SET ' + p.charset;
    }
    if (p.collation) {
      columnType += ' COLLATE ' + p.collation;
    }
    return columnType;
  }

  function numericOptionsByType(p, columnType) {
    switch (columnType.toLowerCase()) {
      default:
      case 'tinyint':
      case 'smallint':
      case 'mediumint':
      case 'int':
      case 'integer':
      case 'bigint':
        columnType = integerOptions(p, columnType);
        break;

      case 'decimal':
      case 'numeric':
        columnType = fixedPointOptions(p, columnType);
        break;

      case 'float':
      case 'double':
        columnType = floatingPointOptions(p, columnType);
        break;
    }
    columnType = unsigned(p, columnType);
    return columnType;
  }

  function floatingPointOptions(p, columnType) {
    var precision = 16;
    var scale = 8;
    if (p.precision) {
      precision = Number(p.precision);
    }
    if (p.scale) {
      scale = Number(p.scale);
    }
    if (p.precision && p.scale) {
      columnType += '(' + precision + ',' + scale + ')';
    } else if (p.precision) {
      columnType += '(' + precision + ')';
    }
    return columnType;
  }

  /*  @TODO: Change fixed point to use an arbitrary precision arithmetic library.     */
  /*  Currently fixed point will lose precision because it's turned to non-fixed in   */
  /*  JS. Also, defaulting column to (9,2) and not allowing non-specified 'DECIMAL'   */
  /*  declaration which would default to DECIMAL(10,0). Instead defaulting to (9,2).  */
  function fixedPointOptions(p, columnType) {
    var precision = 9;
    var scale = 2;
    if (p.precision) {
      precision = Number(p.precision);
    }
    if (p.scale) {
      scale = Number(p.scale);
    }
    columnType += '(' + precision + ',' + scale + ')';
    return columnType;
  }

  function integerOptions(p, columnType) {
    var tmp = 0;
    if (p.display || p.limit) {
      tmp = Number(p.display || p.limit);
    }
    if (tmp > 0) {
      columnType += '(' + tmp + ')';
    } else if (p.unsigned) {
      switch (columnType.toLowerCase()) {
        default:
        case 'int':
          columnType += '(10)';
          break;
        case 'mediumint':
          columnType += '(8)';
          break;
        case 'smallint':
          columnType += '(5)';
          break;
        case 'tinyint':
          columnType += '(3)';
          break;
        case 'bigint':
          columnType += '(20)';
          break;
      }
    } else {
      switch (columnType.toLowerCase()) {
        default:
        case 'int':
          columnType += '(11)';
          break;
        case 'mediumint':
          columnType += '(9)';
          break;
        case 'smallint':
          columnType += '(6)';
          break;
        case 'tinyint':
          columnType += '(4)';
          break;
        case 'bigint':
          columnType += '(20)';
          break;
      }
    }
    return columnType;
  }

  function unsigned(p, columnType) {
    if (p.unsigned) {
      columnType += ' UNSIGNED';
    }
    return columnType;
  }
  function expectedColNameForModel(propName, modelToCheck) {
    var mysql = modelToCheck.properties[propName].mysql;
    if (typeof mysql === 'undefined') {
      return propName;
    }
    var colName = mysql.columnName;
    if (typeof colName === 'undefined') {
      return propName;
    }
    return colName;
  }
}