Skip to content

Commit

Permalink
feat: query to fetch unique columns
Browse files Browse the repository at this point in the history
Signed-off-by: Muhammad Aaqil <[email protected]>
  • Loading branch information
aaqilniz committed Jan 26, 2025
1 parent 3596be1 commit b55e736
Show file tree
Hide file tree
Showing 3 changed files with 40 additions and 1 deletion.
23 changes: 23 additions & 0 deletions lib/discovery.js
Original file line number Diff line number Diff line change
Expand Up @@ -301,6 +301,29 @@ function mixinDiscovery(MySQL, mysql) {
return sql;
};

/**
* Discover unique keys for a given table
* @param {String} table The table name
* @param {Object} options The options for discovery
*/

/*!
* Retrieves a list of column names that have unique key index
* @param schema
* @param table
* @returns {string}
*/
MySQL.prototype.buildQueryUniqueKeys = function(schema, table) {
const sql = 'SELECT Column_name AS "columnName",' +
' table_schema AS "owner",' +
' table_name AS "tableName"' +
' FROM Information_schema.statistics' +
' WHERE Table_schema = ' + mysql.escape(schema) +
' AND Table_name = ' + mysql.escape(table) +
' AND Non_unique = 0 AND Index_name <> \'PRIMARY\';';
return sql;
};

/**
* Discover foreign keys that reference to the primary key of this table
* @param {String} table The table name
Expand Down
15 changes: 15 additions & 0 deletions test/mysql.discover.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -283,6 +283,21 @@ describe('Discover LDL schema from a table', function() {
});
});

describe('Discover unique properties', function() {
let schema;
before(function(done) {
db.discoverSchema('CUSTOMER', {owner: 'STRONGLOOP'}, function(err, schema_) {
schema = schema_;
done(err);
});
});
it('should validate unique key for customer', function() {
assert.ok(/STRONGLOOP/i.test(schema.options.mysql.schema));
assert.strictEqual(schema.options.mysql.table, 'CUSTOMER');
assert.strictEqual(schema.properties.email.index.unique, true);
});
});

describe('Discover and handle enum', function() {
let schema;
before(function(done) {
Expand Down
3 changes: 2 additions & 1 deletion test/schema.sql
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,8 @@ CREATE TABLE `CUSTOMER` (
PRIMARY KEY (`ID`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;

ALTER TABLE `CUSTOMER`
ADD COLUMN `email` VARCHAR(100) UNIQUE;
--
-- Dumping data for table `CUSTOMER`
--
Expand Down

0 comments on commit b55e736

Please sign in to comment.