1.0.0 • Published 4 years ago

db-terminal v1.0.0

Weekly downloads
5
License
ISC
Repository
github
Last release
4 years ago

db-terminal

Write the same javascript code to execute CRUD operations on various regular and NoSQL databases. The module currently supports PostgreSQL, MySQL and MongoDB. But, there is an intention to include more databases.

To see a highlight of what can be achieved with this module, let us try to select all students who are named John from students table. For this, we write the following statements.

PostgreSQL and MySQL:	select * from students where name='John';
	
MongoDB:              db.students.find({ name: "John" })

To perform the same activity on any of the databases via this module, we use the following code:

			db.select({
				"table": "students",
				"where": "name='John'"
			});

Installation

Using npm

$ npm install db-terminal --save

Using yarn

$ yarn add db-terminal

Usage

To use this module, follow the procedures below:

  1. Import: const terminal = require('db-terminal');
  2. Instantiate the desired database:

    	const name = "postgresql"; // or "mysql" for MySQL, "mongodb" for MongoDB database
    	const db = terminal(name);  
  3. Call the available functions The following functions can be called on the db instance created above. Calling any of these functions except the connect function is optional.

    • connect (required)
    • create
    • insert
    • select
    • update
    • delete
    • query
    • close (recommended)

    In addition to the above functions, the db instance has also the following property.

    • commands

The description of the above functions and command property is given below. Although collection is the appropriate term which describes a collection of data in NoSQL databases, the term table will be used for both of them. The properties of the arguments for each function are also explained where parameters within square brackets are optional. In addition, all the callback functions are called according to Node.js standard where err is passed as the first argument and response data, if any, is passed as the second argument.

🔷 connect(config :object , callback :function):

This function is used to create a connection with the preferred database.

PropertyTypeDescription
hoststringThe ip address of the machine hosting the database. If not given, its value with be set to localhost.
portnumberThe port number which the database server listens to.
userstringThe user name to which the database is associated.
passwordstringA password to authenticate the user.
databasestringThe name of the database which the user wants to operate on.
keepAlivenumberThe number of milliseconds to keep the database active without a timeout. If not given, its value will be set to 10000.

Example

			const config = {
				"host": "localhost",
				"port": 5432,
				"user": "postgres",
				"password": "abc123",
				"database": "postgres"  
			};

			db.connect(config, (err, res) => {
				if (err) {
					console.log("Error occured.");
					return;
				}
				console.log("Connection successful.");
			});

🔷 create(params :object , callback :function):

This function is used to create a database or a table.

* - feature not supported in MongoDB

* - feature not supported in MongoDB

Example (database creation)

			const params = {
				"database": "mydb",
				"connlimit": 100,
			};

			db.create(params, (err, res) => {
				if (err) {
					console.log("Error occured.");
					return;
				}
				console.log("Database created.");
			});

Example (table creation)

			const params = {
				"table": "customers",
				"fields": ["id", "name", "email", "address"],
				"dataTypes": ["int", "varchar", "varchar", "text"],
					// 'address' field doesn't have constraint
				"constraints": ["NOT NULL", "NOT NULL", "NOT NULL", null],  
				"primaryKey": ["id"]
			};

			db.create(params, (err, res) => {
				if (err) {
					console.log("Error occured.");
					return;
				}
				console.log("Table created.");
			});

🔷 insert(params :object , callback :function):

This function is used to insert a row(s) or a column(s) into a table.

PropertyTypeDescription
tablestringThe name of the table to insert a data into.
item"row", "column"The type of entity to be inserted. Use row to insert a row and column to insert a column.
fieldsarrayThe names of the fields (column names) for which the data will be inserted.
dataTypes *arrayAn array of data type(s) of the the field(s) (columns) to be inserted. The order of the elements should correspond to the order of the fields property described above.
defaultsarrayAn array of default values of the the field(s) (columns) to be inserted. The order of the elements should correspond to the order of the fields property described above.
constraints *arrayAn array of string constraints of the the field(s) (columns) to be inserted. The order of the elements should correspond to the order of the fields property described above. If a field doesn't have a constraint, put its corresponding value in this property to be null. ​

* - feature not supported in MongoDB

Example (row insertion)

			const params = {
				"table": "students",
				"item": "row",
				"fields": ["id", "name", "email"],
				"values": [1, "John Doe", "johndoe@provider.com"]
			};

			db.insert(params, (err, res) => {
				if (err) {
					console.log("Error occured.");
					return;
				}
				console.log("Row inserted.");
			});

Example (column insertion)

			const params = {
				"table": "customers",
				"item": "column",
				"fields": ["account no."],
				"dataTypes": ["int"],
				"constraints": ["UNIQUE"],  
			};

			db.insert(params, (err, res) => {
				if (err) {
					console.log("Error occured.");
					return;
				}
				console.log("Column inserted.");
			});

🔷 select(params :object , callback :function):

This function is used to fetch records from a database.

PropertyTypeDescription
tablestringThe name of the table to fetch a data from.
fieldsarrayThe names of the fields (column names) for which the data will be fetched. If not given, data will be brought from all fields.
distinctbooleanSet the value of this property to true to fetch only records which have distinct values.
countstringA field name to determine the number of records in that particular field (column).
avgstringA field name to determine the average of the values in that particular field (column).
maxstringA field name to determine the maximum value in that particular field (column).
minstringA field name to determine the minimum value in that particular field (column).
sumstringA field name to determine the sum of the values in that particular field (column).
wherestringA selector statement to filter the data to be fetched.
likestringA selector which is used to filter all rows where the values of the first element of fields fulfil a certain regular expression specified by this property. For MongoDB, avoid inclding regex symbols in the string.
betweenarrayAn array of two elements (minval, maxval) which is used to select all rows where the values of the first element of fields are between minval and maxval.
inarrayAn array of pre-defined values which is used to select all rows where the values of the first element of fields are among those pre-defined values.
limitnumberThe maximum number of records to fetch.
offsetstringThe number or rows to skip during fetching the results.
innerJoin *stringA table name to make inner join with the table given by table property.
leftJoinstringA table name to make left join with the table given by table property.
fullOuterJoinstringA table name to make full outer join with the table given by table property.
crossJoin *stringA table name to make cross join with the table given by table property.
naturalJoin *stringA table name to make natural join with the table given by table property.
onstringA criteria which specifies on what condition that two tables are joined.
orderBystringA field name to be used to order the records fetched from the database.
order"ASC", "DESC"A propery which describes how the data is ordered while using the orderBy property. Use ASC for an ascending order and DESC for a descending order.
groupBystringA property which specifies based on which field that the results of aggregate operations will be categorized.
union *stringA table name to fetch a data from in combination with the records from the table given bytable property. Note that all the data in the table given by this property will be used for the union.
except *stringA table name with records which must be excluded while fetching records from the table given by table property. Note that all the data in the table given by this property will be used for the exclusion.
intersect *stringA table name with records in which only records contained in this table will be fetched from the table given by table property. Note that all the data in the table given by this property will be used for the intersection.
havingstringA criteria which filters results grouped by the groupBy property.

* - feature not supported in MongoDB

Example

			const params = {
				"table": "items",
				"fields": ["id", "price", "quantity"],
				"where": "price < 100.0",
				"orderBy": "quantity",
				"order": "ASC"
			};

			db.select(params, (err, res) => {
				if (err) {
					console.log("Error occured.");
					return;
				}
				console.log(res);
			});

🔷 update(params :object , callback :function):

This function is used to update existing records in a database.

PropertyTypeDescription
tablestringThe name of the table to update.
fieldsarrayThe names of the fields (column names) for which the data will be updated.
valuesarrayThe new values of the fields to update the table with. Their order should correspond to the order of the field names given in the field property described above.
fromstringThe name of a source table from which the data which is used to update table is obtained.
sourceFieldsarrayThe field names of the source table which correspond with fields for the update. If this property is not specified, the columns given by fields will be used as a substitute. In MongoDB, this field has no effect and the fields in the table and sourceTable should match.
wherestringA condition which specifies which rows should be updated.

Example

			const params = {
				"table": "employees",
				"fields": ["salary"],
				"values": [2000],
				"where": "department = 'frontend'",
			};

			db.update(params, (err, res) => {
				if (err) {
					console.log("Error occured.");
					return;
				}
				console.log(res);
			});

🔷 delete(params :object , callback :function):

This function is used to delete databases, tables, columns or rows.

PropertyTypeDescription
databasestringThe name of the database to delete. No error will be thrown if the database doesn't exist.
item"database"A property which describes the entity to delete.
PropertyTypeDescription
tablestringThe name of the table to delete or truncate.
item"table"A property which describes the entity to delete.
truncatebooleanSet the value to true to truncate the table instead of deleting it.
PropertyTypeDescription
tablestringThe table name to delete a column(s) from.
item"column"A property which describes the entity to delete.
fieldsarrayThe field name(s) (column name(s)) to be deleted. An error will be thrown if the column doesn't exist.
PropertyTypeDescription
tablestringThe table name to delete a row(s) from.
item"row"A property which describes the entity to delete.
fieldsarrayThe field name(s) to be used to select the rows which will be deleted.
using *stringThe name of a reference table which is referenced with where condition and used to delete selected rows in table.
wherestringA selector which is used to delete all rows which pass a comparison stated by this property.
likestringA selector which is used to delete all rows in which the values of the first element of fields fulfil a certain regular expression specified by this property.
betweenarrayAn array of two elements (minval, maxval) which is used to delete all rows where the values of the first element of fields are between minval and maxval.
inarrayAn array of pre-defined values which is used to delete all rows where the values of the first element of fields are among those pre-defined values.

* - feature not supported in MongoDB

Example (database deletion)

			db.delete({"database": "items", item: "database"}, (err, res) => {
				if (err) {
					console.log("Error occured.");
					return;
				}
				console.log("Database deleted");
			});

Example (table truncation)

			const params = {
				"table": "customers",
				"item": "table",
				"truncate": true
			};

			db.delete(params, (err, res) => {
				if (err) {
					console.log("Error occured.");
					return;
				}
				console.log("Table truncated");
			});

Example (column deletion)

			const params = {
				"table": "items",
				"item": "column",
				"fields": ["price"]
			};

			db.delete(params, (err, res) => {
				if (err) {
					console.log("Error occured.");
					return;
				}
				console.log("Column 'price' deleted");
			});

Example (row deletion)

			const params = {
				"table": "users",
				"item": "row",
				"fields": ["date"],
				"in": ["02/15/2020", "02/16/2020"]
			};

			db.delete(params, (err, res) => {
				if (err) {
					console.log("Error occured.");
					return;
				}
				console.log("Rows deleted");
			});

🔷 query(document :string | | object , callback :function):

Example (PostgreSQL and MySQL)

			const sql = "select id from students except select ineligible_ids from programming";
			db.query(sql, (err, res) => {
				if (err) {
					console.log("Error occured.");
					return;
				}
				console.log(res);
			});

Example (MongoDB)

			const doc = { 
				find: "items", 
				$db: "sales", 
				projection: { _id: 0, price: 1, quantity: 1 }, 
				sort: { price: -1} 
			};

			db.query(doc, (err, res) => {
				if (err) {
					console.log("Error occured.");
					return;
				}
				console.log(res);
			});

🔷 close():

Example (MySQL or PostgreSQL)

			db.query("select * from customers", (err, res) => {
				if (err) {
					console.log("Error occured.");
					return;
				}
				console.log(res);
				db.close();
			});

🔷 commands:

Example

			db.commands.forEach((command) => {
				console.log(command); // logs each command
			});	

A sample command output for the above code may look like:

			{ sql:
			  	'UPDATE customers SET email = 'abc@def.com' , name = 'John Doe' WHERE id = 213',
			  nosql:
			    { 
			    	update: 'customers',
			      '$db': 'mydb',
			      ordered: false,
			      updates: [{ 
			        q: { id: 213 },  
			        u: { '$set': { email: 'abc@def.com', name: 'John Doe' } },
							upsert: true,
							multi: true 
						}] 
			   	} 
			 }

Issues or suggestions?

If you have any issues or if you want to suggest something, you can write it here.