Gathering detailed insights and metrics for loopback-connector-mysql
Gathering detailed insights and metrics for loopback-connector-mysql
Gathering detailed insights and metrics for loopback-connector-mysql
Gathering detailed insights and metrics for loopback-connector-mysql
npm install loopback-connector-mysql
Module System
Min. Node Version
Typescript Support
Node Version
NPM Version
125 Stars
740 Commits
183 Forks
45 Watching
23 Branches
56 Contributors
Updated on 26 Nov 2024
JavaScript (98.14%)
Shell (1.86%)
Cumulative downloads
Total Downloads
Last day
-31.6%
1,162
Compared to previous day
Last week
-22.5%
6,024
Compared to previous week
Last month
11.9%
29,800
Compared to previous month
Last year
-18.5%
342,018
Compared to previous year
MySQL is a popular open-source relational database
management system (RDBMS). The loopback-connector-mysql
module provides the
MySQL connector module for the LoopBack framework.
In your application root directory, enter this command to install the connector:
1npm install loopback-connector-mysql --save
Note: Since loopback-connector-mysql
v7.x.x, this MySQL connector has dropped support for MySQL 5.7 and requires MySQL 8.0+.
This installs the module from npm and adds it as a dependency to the
application's package.json
file.
If you create a MySQL data source using the data source generator as described
below, you don't have to do this, since the generator will run npm install
for
you.
For LoopBack 4 users, use the LoopBack 4
Command-line interface
to generate a DataSource with MySQL connector to your LB4 application. Run
lb4 datasource
, it
will prompt for configurations such as host, post, etc. that are required to
connect to a MySQL database.
After setting it up, the configuration can be found under
src/datasources/<DataSourceName>.datasource.ts
, which would look like this:
1const config = { 2 name: 'db', 3 connector: 'mysql', 4 url: '', 5 host: 'localhost', 6 port: 3306, 7 user: 'user', 8 password: 'pass', 9 database: 'testdb', 10};
Use
the Data source generator to
add a MySQL data source to your application.
The generator will prompt for the database server hostname, port, and other
settings required to connect to a MySQL database. It will also run the
npm install
command above for you.
The entry in the application's /server/datasources.json
will look like this:
1"mydb": { 2 "name": "mydb", 3 "connector": "mysql", 4 "host": "myserver", 5 "port": 3306, 6 "database": "mydb", 7 "password": "mypassword", 8 "user": "admin" 9 }
Edit <DataSourceName>.datasources.ts
to add any other additional properties
that you require.
Property | Type | Description |
---|---|---|
collation | String | Determines the charset for the connection. Default is utf8_general_ci. |
connector | String | Connector name, either “loopback-connector-mysql” or “mysql”. |
connectionLimit | Number | The maximum number of connections to create at once. Default is 10. |
database | String | Database name |
debug | Boolean | If true, turn on verbose mode to debug database queries and lifecycle. |
host | String | Database host name |
password | String | Password to connect to database |
port | Number | Database TCP port |
socketPath | String | The path to a unix domain socket to connect to. When used host and port are ignored. |
supportBigNumbers | Boolean | Enable this option to deal with big numbers (BIGINT and DECIMAL columns) in the database. Default is false. |
timeZone | String | The timezone used to store local dates. Default is ‘local’. |
url | String | Connection URL of form mysql://user:password@host/db . Overrides other connection settings. |
username | String | Username to connect to database |
allowExtendedOperators | Boolean | Set to true to enable MySQL-specific operators
such as match . Learn more in
Extended operators below.
|
NOTE: In addition to these properties, you can use additional parameters
supported by node-mysql
.
See LoopBack 4 types (or LoopBack 3 types) for details on LoopBack's data types.
LoopBack Type | MySQL Type |
---|---|
String/JSON | VARCHAR |
Text | TEXT |
Number | INT |
Date | DATETIME |
Boolean | TINYINT(1) |
GeoPoint object | POINT |
Custom Enum type (See Enum below) | ENUM |
MySQL Type | LoopBack Type |
---|---|
CHAR | String |
BIT(1) CHAR(1) TINYINT(1) | Boolean |
VARCHAR TINYTEXT MEDIUMTEXT LONGTEXT TEXT ENUM SET | String |
TINYBLOB MEDIUMBLOB LONGBLOB BLOB BINARY VARBINARY BIT | Node.js Buffer object |
TINYINT SMALLINT INT MEDIUMINT YEAR FLOAT DOUBLE NUMERIC DECIMAL |
Number For NUMERIC and DECIMAL, see Fixed-point exact value types |
DATE TIMESTAMP DATETIME | Date |
NOTE as of v3.0.0 of MySQL Connector, the following flags were introduced:
treatCHAR1AsString
default false
- treats CHAR(1) as a String instead of a
BooleantreatBIT1AsBit
default true
- treats BIT(1) as a Boolean instead of a
BinarytreatTINYINT1AsTinyInt
default true
- treats TINYINT(1) as a Boolean
instead of a NumberExcept the common database-specific properties we introduce in How LoopBack Models Map To Database Tables/Collections, the following are more detailed examples and MySQL-specific settings.
Besides the basic LoopBack types, as we introduced above, you can also specify additional MySQL-specific properties for a LoopBack model. It would be mapped to the database.
Use the mysql.<property>
in the model definition or the property definition to
configure the table/column definition.
For example, the following settings would allow you to have custom table name
(Custom_User
) and column name (custom_id
and custom_name
). Such mapping is
useful when you'd like to have different table/column names from the model:
{% include code-caption.html content="user.model.ts" %}
1@model({ 2 settings: { mysql: { schema: 'testdb', table: 'Custom_User'} }, 3}) 4export class User extends Entity { 5 @property({ 6 type: 'number', 7 required: true, 8 id: true, 9 mysql: { 10 columnName: 'custom_id', 11 }, 12 }) 13 id: number; 14 15 @property({ 16 type: 'string', 17 mysql: { 18 columnName: 'custom_name', 19 }, 20 }) 21 name?: string;
1{ 2 "name": "User", 3 "options": { 4 "mysql": { 5 "schema": "testdb", 6 "table": "Custom_User" 7 } 8 }, 9 "properties": { 10 "id": { 11 "type": "Number", 12 "required": true, 13 "mysql": { 14 "columnName": "custom_id", 15 } 16 }, 17 "name": { 18 "type": "String", 19 "mysql": { 20 "columnName": "custom_name", 21 } 22 }, 23 } 24}
Except the names, you can also use the dataType column/property attribute to specify what MySQL column type to use. The following MySQL type-dataType combinations are supported:
The following examples will be in LoopBack 4 style, but it's the same if you
provide mysql.<property>
to the LB3 property definition.
For Float and Double data types, use the precision
and scale
options to
specify custom precision. Default is (16,8).
1@property({ 2 type: 'Number', 3 mysql: { 4 dataType: 'float', 5 precision: 20, 6 scale: 4 7 } 8}) 9price: Number;
For Decimal and Numeric types, use the precision
and scale
options to
specify custom precision. Default is (9,2). These aren't likely to function as
true fixed-point.
1@property({ 2 type: 'Number', 3 mysql: { 4 dataType: 'decimal', 5 precision: 12, 6 scale: 8 7 } 8}) 9price: Number;
Convert String / DataSource.Text / DataSource.JSON to the following MySQL types:
1@property({ 2 type: 'String', 3 mysql: { 4 dataType: 'char', 5 dataLength: 24 // limits the property length 6 }, 7}) 8userName: String;
Convert JSON Date types to datetime or timestamp.
1@property({ 2 type: 'Date', 3 mysql: { 4 dataType: 'timestamp', 5 }, 6}) 7startTime: Date;
See the Model ENUM property for details.
Use the default
and dataType
properties to have MySQL handle setting column DEFAULT
value.
1@property({ 2 type: 'String', 3 mysql: { 4 dataType: 'varchar', 5 default: 'pending' 6 } 7}) 8status: String; 9 10@property({ 11 type: 'Number', 12 mysql: { 13 dataType: 'int', 14 default: 42 15 } 16}) 17maxDays: Number; 18 19@property({ 20 type: 'boolean', 21 mysql: { 22 dataType: 'tinyint', 23 default: 1 24 } 25}) 26isDone: Boolean;
For the date or timestamp types use CURRENT_TIMESTAMP
or now
.
1@property({ 2 type: 'Date', 3 mysql: { 4 dataType: 'datetime', 5 default: 'CURRENT_TIMESTAMP' 6 } 7}) 8last_modified: Date;
NOTE: The following column types do NOT supported MySQL Default Values:
MySQL connector supports the following MySQL-specific operators:
match
Please note extended operators are disabled by default, you must enable
them at datasource level or model level by setting allowExtendedOperators
to
true
.match
The match
operator allows you to perform a full text search using the MATCH() .. AGAINST() operator in MySQL.
Three different modes of the MATCH
clause are also available in the form of operators -
matchbool
for Boolean Full Text Searchmatchnl
for Natural Language Full Text Searchmatchqe
for Full-Text Searches with Query Expansionmatchnlqe
for Full-Text Searches with Query Expansion with the IN NATURAL LANGUAGE MODE WITH QUERY EXPANSION
modifier.By default, the match
operator works in Natural Language mode.
Note The fields you are querying must be setup with a FULLTEXT
index to perform full text search on them.
Assuming a model such as this:
1@model({ 2 settings: { 3 allowExtendedOperators: true, 4 } 5}) 6class Post { 7 @property({ 8 type: 'string', 9 mysql: { 10 index: { 11 kind: 'FULLTEXT' 12 } 13 }, 14 }) 15 content: string; 16}
You can query the content field as follows:
1const posts = await postRepository.find({ 2 where: { 3 { 4 content: {match: 'someString'}, 5 } 6 } 7});
The MySQL connector supports model discovery that enables you to create LoopBack models based on an existing database schema. Once you defined your datasource:
lb4 discover
to
discover models.The MySQL connector also supports auto-migration that enables you to create a
database schema from LoopBack models. For example, based on the following model,
the auto-migration method would create/alter existing Customer
table in the
database. Table Customer
would have two columns: name
and id
, where id
is also the primary key that has auto_increment
set as it has definition of
type: 'Number'
and generated: true
:
1@model() 2export class Customer extends Entity { 3 @property({ 4 id: true, 5 type: 'Number', 6 generated: true, 7 }) 8 id: number; 9 10 @property({ 11 type: 'string', 12 }) 13 name: string; 14}
Moreover, additional MySQL-specific properties mentioned in the Data mapping properties section work with auto-migration as well.
For now LoopBack MySQL connector only supports auto-generated id
(generated: true
) for integer type as for MySQL, the default id type is
integer. If you'd like to use other types such as string (uuid) as the id
type, you can:
defaultFn: uuid
.1 @property({ 2 id: true, 3 type: 'string' 4 defaultFn: 'uuidv4', 5 // generated: true, -> not needed 6 }) 7 id: string;
1 @property({ 2 id: true, 3 type: 'string' 4 generated: true, // to indicate the value generates by the db 5 useDefaultIdType: false, // needed 6 }) 7 id: string;
Foreign key constraints can be defined in the model definition.
Note: The order of table creation is important. A referenced table must
exist before creating a foreign key constraint. The order can be specified
using the optional SchemaMigrationOptions
argument of migrateSchema
:
await app.migrateSchema({
models: [ 'Customer', 'Order' ]
});
Define your models and the foreign key constraints as follows:
{% include code-caption.html content="customer.model.ts" %}
1@model() 2export class Customer extends Entity { 3 @property({ 4 id: true, 5 type: 'Number', 6 generated: true, 7 }) 8 id: number; 9 10 @property({ 11 type: 'string', 12 }) 13 name: string; 14}
order.model.ts
:
1@model({ 2 settings: { 3 foreignKeys: { 4 fk_order_customerId: { 5 name: 'fk_order_customerId', 6 entity: 'Customer', 7 entityKey: 'id', 8 foreignKey: 'customerId', 9 }, 10 }, 11 }) 12export class Order extends Entity { 13 @property({ 14 id: true, 15 type: 'Number', 16 generated: true 17 }) 18 id: number; 19 20 @property({ 21 type: 'string' 22 }) 23 name: string; 24 25 @property({ 26 type: 'Number' 27 }) 28 customerId: number; 29}
1({ 2 "name": "Customer", 3 "options": { 4 "idInjection": false 5 }, 6 "properties": { 7 "id": { 8 "type": "Number", 9 "id": 1 10 }, 11 "name": { 12 "type": "String", 13 "required": false 14 } 15 } 16}, 17{ 18 "name": "Order", 19 "options": { 20 "idInjection": false, 21 "foreignKeys": { 22 "fk_order_customerId": { 23 "name": "fk_order_customerId", 24 "entity": "Customer", 25 "entityKey": "id", 26 "foreignKey": "customerId" 27 } 28 } 29 }, 30 "properties": { 31 "id": { 32 "type": "Number" 33 "id": 1 34 }, 35 "customerId": { 36 "type": "Number" 37 }, 38 "description": { 39 "type": "String", 40 "required": false 41 } 42 } 43})
MySQL handles the foreign key integrity by the referential action specified by
ON UPDATE
and ON DELETE
. You can specify which referential actions the
foreign key follows in the model definition upon auto-migrate or auto-update
operation. Both onDelete
and onUpdate
default to restrict
.
Take the example we showed above, let's add the referential action to the
foreign key customerId
:
1@model({ 2 settings: { 3 foreignKeys: { 4 fk_order_customerId: { 5 name: 'fk_order_customerId', 6 entity: 'Customer', 7 entityKey: 'id', 8 foreignKey: 'customerId', 9 onUpdate: 'restrict', // restrict|cascade|set null|no action|set default 10 onDelete: 'cascade' // restrict|cascade|set null|no action|set default 11 }, 12 }, 13 }) 14export class Order extends Entity { 15...
model-definiton.json
1{ 2 "name": "Customer", 3 "options": { 4 "idInjection": false 5 }, 6 "properties": { 7 "id": { 8 "type": "Number", 9 "id": 1 10 }, 11 "name": { 12 "type": "String", 13 "required": false 14 } 15 } 16}, 17{ 18 "name": "Order", 19 "options": { 20 "idInjection": false, 21 "foreignKeys": { 22 "fk_order_customerId": { 23 "name": "fk_order_customerId", 24 "entity": "Customer", 25 "entityKey": "id", 26 "foreignKey": "customerId", 27 "onUpdate": "restrict", 28 "onDelete": "cascade" 29 } 30 } 31 }, 32 "properties": { 33 "id": { 34 "type": "Number" 35 "id": 1 36 }, 37 "customerId": { 38 "type": "Number" 39 }, 40 "description": { 41 "type": "String", 42 "required": false 43 } 44 } 45}
boot-script.js
1module.exports = function (app) { 2 var mysqlDs = app.dataSources.mysqlDS; 3 var Book = app.models.Order; 4 var Author = app.models.Customer; 5 6 // first autoupdate the `Customer` model to avoid foreign key constraint failure 7 mysqlDs.autoupdate('Customer', function (err) { 8 if (err) throw err; 9 console.log('\nAutoupdated table `Customer`.'); 10 11 mysqlDs.autoupdate('Order', function (err) { 12 if (err) throw err; 13 console.log('\nAutoupdated table `Order`.'); 14 // at this point the database table `Order` should have one foreign key `customerId` integrated 15 }); 16 }); 17};
Prior to loopback-connector-mysql@5.x
, MySQL connector was saving and loading
GeoPoint properties from the MySQL database in reverse. MySQL expects values to
be POINT(X, Y)
or POINT(lng, lat)
, but the connector was saving them in the
opposite order(i.e. POINT(lat,lng)
).
Use the geopoint
type to achieve so:
1 @property({ 2 type: 'geopoint' 3 }) 4 name: GeoPoint;
If you have an application with a model that has a GeoPoint property using previous versions of this connector, you can migrate your models using the following programmatic approach:
NOTE Please back up the database tables that have your application data before performing any of the steps.
server/boot/
directory with the following:1'use strict'; 2module.exports = function (app) { 3 function findAndUpdate() { 4 var teashop = app.models.teashop; 5 //find all instances of the model we'd like to migrate 6 teashop.find({}, function (err, teashops) { 7 teashops.forEach(function (teashopInstance) { 8 //what we fetch back from the db is wrong, so need to revert it here 9 var newLocation = { 10 lng: teashopInstance.location.lat, 11 lat: teashopInstance.location.lng, 12 }; 13 //only update the GeoPoint property for the model 14 teashopInstance.updateAttribute('location', newLocation, function ( 15 err, 16 inst, 17 ) { 18 if (err) console.log('update attribute failed', err); 19 else console.log('updateAttribute successful'); 20 }); 21 }); 22 }); 23 } 24 25 findAndUpdate(); 26};
node .
For the above example, the model definition is as follows:
1{ 2 "name": "teashop", 3 "base": "PersistedModel", 4 "idInjection": true, 5 "options": { 6 "validateUpsert": true 7 }, 8 "properties": { 9 "name": { 10 "type": "string", 11 "default": "storename" 12 }, 13 "location": { 14 "type": "geopoint" 15 } 16 }, 17 "validations": [], 18 "relations": {}, 19 "acls": [], 20 "methods": {} 21}
If you have a local or remote MySQL instance and would like to use that to run the test suite, use the following command:
1MYSQL_HOST=<HOST> MYSQL_PORT=<PORT> MYSQL_USER=<USER> MYSQL_PASSWORD=<PASSWORD> MYSQL_DATABASE=<DATABASE> CI=true npm test
1SET MYSQL_HOST=<HOST> SET MYSQL_PORT=<PORT> SET MYSQL_USER=<USER> SET MYSQL_PASSWORD=<PASSWORD> SET MYSQL_DATABASE=<DATABASE> SET CI=true npm test
If you do not have a local MySQL instance, you can also run the test suite with very minimal requirements.
1source setup.sh <HOST> <PORT> <USER> <PASSWORD> <DATABASE>
where <HOST>
, <PORT>
, <USER>
, <PASSWORD>
and <DATABASE>
are optional
parameters. The default values are localhost
, 3306
, root
, pass
and
testdb
respectively.
1npm test
No vulnerabilities found.
No security vulnerabilities found.