@@ -851,27 +851,62 @@ IBMDB.prototype.buildIndexes = function(model) {
851851 var indexClauses = [ ] ;
852852 var definition = this . getModelDefinition ( model ) ;
853853 var indexes = definition . settings . indexes || { } ;
854+ /*!
855+ This module did not allow to define indexes the "new" way loopback wants to.
856+ - The new way to define indexes in loopback
857+ (https://loopback.io/doc/en/lb3/Model-definition-JSON-file.html#indexes)
858+ "name_key": {
859+ "columns": "name",
860+ "unique": true
861+ }
862+ - The way the module previously accepted indexes:
863+ "name_key": {
864+ "keys" : {
865+ "name": 1
866+ }
867+ }
868+ The module now allows both ways to define the indexes.
869+ */
854870 // Build model level indexes
855871 for ( var index in indexes ) {
856872 var i = indexes [ index ] ;
857873 var statement = new ParameterizedSQL ( 'CREATE' ) ;
858874 if ( i . kind ) {
859875 statement . merge ( i . kind ) ;
860- } else if ( i . unique ) {
876+ } else if ( ( i . options && i . options . unique && i . options . unique === true )
877+ || i . unique ) {
878+ // if index unique indicator is configured
861879 statement . merge ( 'UNIQUE' ) ;
862880 }
863-
864- var columns = i . columns . split ( ',' ) . map ( function ( val ) {
865- return self . escapeName ( val ) ;
866- } ) ;
881+ var indexedColumns = [ ] ;
882+ var columns = '' ;
883+ // if indexes are configured as "keys"
884+ if ( i . keys ) {
885+ // for each field in "keys" object
886+ for ( var key in i . keys ) {
887+ // index in asc order
888+ if ( i . keys [ key ] !== - 1 ) {
889+ indexedColumns . push ( key ) ;
890+ } else {
891+ // index in desc order
892+ indexedColumns . push ( key + ' DESC' ) ;
893+ }
894+ }
895+ }
896+ if ( indexedColumns . length ) {
897+ columns = indexedColumns . join ( ',' ) ;
898+ } else if ( i . columns ) {
899+ columns = i . columns . split ( ',' ) . map ( function ( val ) {
900+ return self . escapeName ( val ) ;
901+ } ) ;
902+ }
867903
868904 statement . merge ( 'INDEX ' + self . escapeName ( index ) + ' ON ' ) ;
869905 statement . merge ( self . schema + '.' + self . tableEscaped ( model ) ) ;
870906 statement . merge ( '(' + columns + ')' ) ;
871907
872908 indexClauses . push ( statement . sql ) ;
873909 }
874-
875910 return indexClauses ;
876911} ;
877912
0 commit comments