Featured – DebugEverything https://blog.debugeverything.com A new way to learn programming Fri, 06 Oct 2023 01:48:01 +0000 en-US hourly 1 https://wordpress.org/?v=7.1.4 https://blog.debugeverything.com/wp-content/uploads/2021/04/cropped-DE_white-32x32.png Featured – DebugEverything https://blog.debugeverything.com 32 32 Understanding MySQL: DBMS, SQL and MySQL Workbench https://blog.debugeverything.com/mysql-is-not-a-database/ https://blog.debugeverything.com/mysql-is-not-a-database/#comments Tue, 21 Sep 2021 14:20:24 +0000 https://blog.debugeverything.com/?p=2321 What is MySQL? And what is a database? 🤔

We will answer both answers in this post.

What is MySQL?

Ok we already know what MySQL is not, it is not a database.

MySQL is a relational database management system. 🤯

Okay, now we need to define what a database management system is.

What is a Database Management System (DBMS)?

A Database Management System (DBMS) is software designed to store, retrieve, define, and manage data or data structure in a database.

Data in DBMS is stored in database objects called tables. A table is a collection of related data entries and consists of columns and rows.

Users of this system are given tools to perform various types of operations on the table structures or on the data.

A DBMS acts mainly as an interface between the end user and the database, managing both the data and the database structure in order to facilitate data organisation and manipulation.

Some examples of DBMS include MySQL, PostgreSQL, Microsoft Access, SQL Server and Oracle.

What is a database?

A database is an organised collection of data, typically stored electronically in a digital system in table forms.

In this post we are considering only relational databases, but there is another category of database, called non-relational databases, like MongoDB, you can better understand the difference between relational and non-relational databases here.

A database is usually controlled by a database management system (DBMS). Together, the data the DBMS and associated applications are referred to as a database system, often shortened to just database.

Data, within the most common types of databases currently in operation, is typically modeled in rows and columns in a series of tables to make data processing and querying efficient.

The data can then be easily retrieved, managed, modified, updated, controlled, and organised. Most databases use SQL to write and query data.

What is the difference between a database and an Excel spreadsheet?

Databases and Excel spreadsheets are both convenient ways to store information. The main differences between the two are:

  • How data is stored and manipulated
  • Who can access the data
  • How much data can be stored

The spreadsheets were originally created for one user, or for a small number of users who do not need to do a lot of manipulation on the data.

Databases, on the other hand, are designed to hold much larger collections of information. Databases allow multiple users at the same time to manage and query the data quickly and securely, using logic and a more complex language.

What is SQL?

SQL (Structured Query Language) is the standard language for querying and manipulating relational databases.

Yes, SQL is a programming language. It offers loops, logic directives, variables, and so on.

But rather than being a programming language for building websites, applications, or software, SQL is a language focused on storing, retrieving, and manipulating data in databases.

Here are some examples of SQL commands:

SELECT * FROM table_name WHERE column_name='...';
CREATE TABLE table_name (COLUMN_NAME DATATYPES[,....]);  
ALTER TABLE table_name ADD column_name COLUMN-definition; 
DROP TABLE table_name;  
TRUNCATE TABLE table_name;  

What can you do with SQL?

  • SQL can execute queries on a database
  • SQL can retrieve data from a database
  • SQL can insert records into a database
  • SQL can update records in a database
  • SQL can delete records from a database
  • SQL can create new databases
  • SQL can create new tables in a database
  • SQL can set permissions on tables, procedures, and views

How do SQL and DBMS relate to each other?

DBMS is a database management system. And SQL is the language used to communicate with the data in a DBMS.

Or, in simple terms:

DBMS is a book and SQL is the language being used in the book. Want to read or write in the book? Use SQL.

MySQL Workbench

MySQL Workbench is a visual database design tool that integrates the development, administration, design, creation and maintenance of SQL databases into a single integrated development environment (IDE) for the MySQL database system.

MySQL Workbench provides a set of tools to improve the performance of MySQL applications, provides a visual platform to manage MySQL environments and gain better visibility into databases, also provides visual tools to create, execute, and optimize SQL queries.

There many other tools like that, at some level, it turns out to be your preference to choose one to go with. Some good options are TablePlus and Sequel Pro if you use Mac, otherwise MySql workbench will do the job.

Connecting the parts

To understand how all these pieces are connected, take a look at the image below.

]]>
https://blog.debugeverything.com/mysql-is-not-a-database/feed/ 1
Laravel Request Lifecycle: the best starting point for learning Laravel https://blog.debugeverything.com/laravel-request-lifecycle/ https://blog.debugeverything.com/laravel-request-lifecycle/#comments Wed, 30 Jun 2021 10:42:56 +0000 https://blog.debugeverything.com/?p=2153 Laravel, as you may be aware, is a powerful framework, and the Laravel request lifecycle is the best place to start when you want to learn more about the framework itself. I’ll describe what occurs between an HTTP request to your application and the response. An in-depth examination of the request lifecycle will aid our understanding of the Laravel structure.

Autoloader, kernel, Service Providers, Dispatch Request, and Router are just a few of the terms used in the Laravel Request Lifecycle. Once you have a thorough understanding of all of the terms, you will be more confident and at ease with the framework, and you will be able to extend various features in any way you see fit.

Laravel Request Lifecycle Overview

The public/index.php file serves as the entry point for all requests to a Laravel application. This file serves as the start point for the remainder of your framework to be loaded.

Laravel Request Lifecycle Starting point

The file loads the composer-generated autoloader definition before retrieving the Laravel application instance from bootstrap/app.php.

Laravel’s initial action is to build an instance of the application/Service Container.

Http/Console Kernels

During the Laravel request lifecycle, the incoming request is sent to either the Http Kernel or the Console Kernel, depending on the kind of request.

Laravel Request Lifecycle Kernels

The Http kernel extends the Illuminate\Foundation\Http\Kernel class, which defines an array of bootstrappers that will be run before the request is executed.

These bootstrappers configures for you, right away:

  • Error handling
  • Logging
  • Detect the application environment
  • Perform tasks that will be run before the request is executed

The HTTP kernel (app\HttpKernel.php) also defines a list of HTTP middleware through which all requests must pass before being handled by the application.

This middleware handles reading and writing the HTTP session, identifying whether the app is in maintenance mode, validating the CSRF token, and many other tasks.

The method signature for the HTTP Kernel’s handle() method is quite simple: it receives a Request and returns a Response.

    /**
     * Handle an incoming HTTP request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function handle($request)
    {
        // It does other things here

        return $response;
    }

Consider the Kernel to be a large black box that contains your entire application. It will return HTTP Responses if you feed it HTTP Requests.

Services Providers

One of the most important Kernels bootstrapping actions during the Laravel request lifecycle is loading the Service Providers for the app.

Laravel Request Lifecycle Service Providers

All the services providers for the application are configured in the config\app.php configuration files provider’s array.

'providers' => [

        /*
         * Laravel Framework Service Providers...
         */
        Illuminate\Auth\AuthServiceProvider::class,
        Illuminate\Broadcasting\BroadcastServiceProvider::class,
        Illuminate\Bus\BusServiceProvider::class,
        Illuminate\Cache\CacheServiceProvider::class,
        ...
        App\Providers\RouteServiceProvider::class,
    ],

Laravel iterate through the list of providers and instantiate each of them. After instantiating the providers, the register() method will be called on all the providers. Then, once all of the providers have been registered, the boot() method will be called for each provider.

Provider has its own lifecycle, will look something like this:

Instantiate providers -> register providers -> boot providers

The Service providers in the Laravel request lifecycle are in charge of bootstrapping all of the framework’s key elements, such as:

  • Database
  • Queue
  • Validation
  • Routing Components

Essentially every major feature offered by Laravel is bootstrapped and configured by a service provider.

Service providers are the most important aspect of the Laravel request lifecycle bootstrap process because they bootstrap and configure so many features provided by the framework.

Routing

One of the most important bootstrapped Service Providers in your application is the App\Providers\RouteServiceProvider. This Service Provider loads the route files contained within your application’s routes directory.

Laravel Request Lifecycle Routing

Once the application has been bootstrapped and all Service Providers have been registered, the Request will be handed off to the router for dispatching. The route will dispatch the request to a route or controller, as well as run any route-specific middleware.

// Route dispatch
Route::get('/', function () {
    return view('welcome');
});
// Controller dispatch
Route::get('profile', [UserController::class, 'show'])->middleware('auth');

Middleware provide a convenient mechanism for filtering or examining HTTP Requests entering your application.

If the request passes through all of the matched route’s assigned middleware, the route or controller method will be executed and the response will be sent back through the route’s chain of middleware.

Response

And the final step in the Laravel Request Lifecycle, is returning a response. All routes and controllers should provide a response that should be sent back to the user’s browser. Laravel provides several different ways to return responses.

When a route or controller method returns a response, the response will flow back outward through the route’s middleware, allowing the application the opportunity to alter or examine the outgoing response.

Typically, you won’t just be returning simple strings or arrays from your route actions. Instead, you will be returning full Illuminate\Http\Response instances or views.

A Response instance is derived from the Symfony\Component\Http\Foundation\Response class, which provides a number of methods for constructing HTTP responses.

One of the advantages returning a full Response instance, is that you can alter the HTTP status code and headers of the response.

Finally, once the response has passed through the middleware, the HTTP kernel’s handle() method provides the response object, and the index.php file uses the returned response to call the send() method.  The send() method sends the response content to the user’s web browser.

We have completed our journey through the Laravel request lifecycle!

]]>
https://blog.debugeverything.com/laravel-request-lifecycle/feed/ 2
Database Demystified: Relational vs. Non-relational Showdown https://blog.debugeverything.com/database-demystified-relational-vs-non-relational-showdown/ https://blog.debugeverything.com/database-demystified-relational-vs-non-relational-showdown/#comments Thu, 23 Jul 2020 17:12:05 +0000 https://debugeverything.com/?p=1600

By the end of this decade, our digital data universe will grow from 4.4 zettabytes today to about 44 zettabytes, or 44 trillion gigabytes.

OK, so we know you’re here to weigh the technical differences between the relational and non-relational databases. But before we dive in, we need to define some important details. You need to determine what priority scalability represents for your particular model.

To make your data model as accurate as possible, you need to ask the right questions. Otherwise, your solution may not be the most appropriate for your problem. If you already have this well defined, go ahead.

What is a relational database?

A relational database is a digital database based on the relational data model as proposed by E. F. Codd in 1970, an intuitive and direct way to represent data in tables. Relational databases store and provide access to data points that are related to each other.

In a relational database, each table row is a record with a unique identification called a primary key. The table columns contain the data attributes, and each record usually has a value for each attribute, making it easier to establish the relationships between the data. In this example below the Primary Key is the id.

There are several systems you can use to manage relational databases, they are known as Relational Database Management Systems (DBMS). The most popular among them is MySQL, but we also have other options like Oracle Database, Microsoft SQL Server, and IBM DB2.

The vast majority of RDBMS offer the option to use SQL (Structured Query Language) for database query and maintenance.

Types of relationship

One of the advantages of a relational database is that once you have your data kept in clearly defined tables you can connect or relate the data between different tables. In order to identify these relationships, you need to examine the data and have an understanding of the business rules that apply to the data and tables.

When creating relationships, you always work with two tables at a time. One table is called the main table or parent table and the other is the related table or child table.

The three types of relationships you will find in the relational databases are, one-to-one, one-to-many, and many-to-many. The relationships are described below.

  • One-to-one (1…1): Both tables can have only one record on each side of the relationship. Each primary table value refers to only one (or no) record in the related table.
  • One-to-many (1…n): The primary table contains only one record that can relate to none, one, or many records in the related table.
  • Many-to-many (n…n): Each record in both tables can relate to any number of records (or no records) in the other table. Many relationships of type n…n require a third table, known as a link table or associated table, because relational systems cannot directly accommodate the relationship.

What is a non-relational database?

A non-relational database is any database that does not follow the relational model provided by traditional relational database management systems (RDBMS). This category of databases is also known as NoSQL databases.

The most popular being MongoDB, DocumentDB, Cassandra, Couchbase, HBase, Redis, and Neo4j. These databases are generally grouped into four categories: Key-value stores, Graph stores, Column stores, and Document stores.

Types of non-relational database

Key-value stores

As the name suggests, in a key-value database, the data is represented as a collection of pairs of key values. They are also known as associative arrays, organized in rows.

These databases store the data as a hash table with a unique key and pointer to a particular data item. Similar to traditional hash tables, this type of database allows the storage and retrieval of data using keys.

Key-value databases are used whenever data is queried by precise parameters and need to be recovered quickly.

Graph stores

Although key-value databases can handle a large amount of data, they are designed for a high level (low depth) view of the data. Graph databases can maintain a minimum storage size, even with a greater depth of data than other types of databases.

The graph-type NoSQL database was specially developed to handle very large sets of structured, semi-structured, or unstructured data. It helps organizations access, integrate, and analyze data from various sources.

Widely used when it is necessary to analyze data from social networks, for example.

Column stores

A column data storage, also known as DBMS in column, uses columns to store data instead of rows as in the relational model. Both row-based and column-based DBMS use SQL as the query language, but column-based DBMS can offer better performance.

Column store databases use a concept called keyspace. A keyspace is like a schema in the relational model. The keyspace contains all column families (such as tables in the relational model), which contain rows, which contain columns.

Document stores

The document store type database, also called document oriented DBMS, is characterized by its data organization without schemas.

This means that the records do not need to have a uniform structure, that is, different records can have different columns. The value types can be different for each record, the columns can have more than one value (arrays), and the records can have a nested structure.

Documents are usually stored in a structure similar to JSON, which makes life easier for the programmer, and JSON is one of the most common data structures, especially working with Javascript.

What is the difference between relational and non-relational databases?

Relational databases like MySQL, PostgreSQL and SQLite3 represent and store data in tables and queues. Non-relational databases like MongoDB represent data in JSON document collections.

Relational databases use Structured Query Language (SQL), making them a good choice for applications that involve the management of various transactions. The structure of a relational database allows linking information from different tables through the use of foreign keys (or indexes).

Se você estiver lidando com uma quantidade fenomenal de dados, a complexidade do banco de dados relacional e das queries necessárias também vai crescer na mesma proporção. Nessa situação, talvez você precise considerar a possibilidade de utilizar um base de dados não relacional. Uma base de dados não relacional apenas armazena dados sem uma mecânica explícita e estruturada para vincular dados de diferentes tabelas uns aos outros.

If you are dealing with a phenomenal amount of data, the complexity of the relational database and the required queries will also grow in the same proportion. In this situation, you may need to consider using a non-relational database. A non-relational database can store data without an explicit and structured mechanics to link data from different tables to each other.

Disadvantages of relational databases

Although relational databases are great, they come with trade-offs. One of them is ORM Impedance Mismatching, because relational databases were not initially created with OOP languages in mind. The best way to avoid this issue is to create your database schema with referenced integrity. Therefore, when using a relational database with OOP (such as Ruby or Java), you have to think about how to configure your primary and foreign keys, the use of constraints (including deletion and cascading), and how to write your migrations.

Disadvantages of non-relational databases

In non-relational databases like MongoDB, there are no joins like in relational databases. This means you need to perform multiple queries and join the data manually within your code.

Since Mongo does not automatically treat the operations as transactions in the same way as a relational database, you must choose to create a transaction and then check it, commit, or rollback manually.

My suggestion is, analyze the data you will store. Ask the right questions to find out what data model you’ll need. Choosing the programming language to write your application and using a specific database will get your application on the right track.

If you like the article, be sure to comment and share. And so you don’t miss any news here, subscribe to the newsletter and receive exclusive content every week! See you next time!

]]>
https://blog.debugeverything.com/database-demystified-relational-vs-non-relational-showdown/feed/ 4
4 big differences between forEach and map in Javascript https://blog.debugeverything.com/difference-foreach-and-map-in-javascript/ https://blog.debugeverything.com/difference-foreach-and-map-in-javascript/#respond Thu, 02 Jul 2020 09:28:01 +0000 https://debugeverything.com/?p=1534 JavaScript has some methods that help us to iterate through Arrays. The two most used are foreach() and map() in Javascript. But I believe there is a lot of doubt between these two methods.

Because they both do some iteration. So, what’s the difference?

forEach and map in Javascript: Definitions

We will define each method, and where each one fits in, to try to understand better what we can do with each one:

The map() method gets a function as a parameter. This function is invoked for each Array element and, at the end, the method returns a completely new array filled with the results of the given function call.

const numbers = [5, 4, 3, 2, 1]
console.log(numbers.map(element => element * element)) //[ 25, 16, 9, 4, 1 ]

This means that it returns a new array that contains an image of each array element. It will always return the same number of items.

The forEach() method receives a function as an argument and executes it once for each Array element. However, instead of returning a new array as the map() method, it returns undefined.

const numbers = [5, 4, 3, 2, 1]
console.log(numbers.forEach(element => element * element)) //undefined

The method’s return

As you can already see, one of the main differences between forEach and map in Javascript is the return of each method.

The forEach() method returns undefined, while map() returns a new array with the transformed elements.

let numbers = [5, 4, 3, 2, 1]
console.log(numbers.map(element => element * element)) //[ 25, 16, 9, 4, 1 ]
console.log(numbers.forEach(element => element * element)) //undefined

Ability to chain with other methods

The second difference between these methods is the fact that map() is chainable. This means that you can chain other methods (like reduce(), sort(), filter(), and so on), after executing the map() method in an array.

This is something you can’t do with forEach() because, as you can guess, it returns undefined.

let numbers = [5, 4, 3, 2, 1]
const newArrayMap = numbers.map(element => element * element).filter(x => x > 9);
console.log(newArrayMap); //[ 25, 16 ]
const newArrayForEach = numbers.forEach(element => element * element).filter(x => x > 9);
console.log(newArrayForEach) // Cannot read property 'filter' of undefined

Mutability

Mutability means ” Capacity or ability to change.”

A mutable object is an object whose state can be changed after its creation. Regarding mutability, how do the foreach() and map() methods in Javascript behave?

Well, according to the MDN documentation:

forEach() does not modify the array in which it is called. (However, the callback method can do this).

map() does not modify the array in which it is called (although the callback method, if invoked, can do that).

That’s perhaps the most confusing explanation I’ve read in recent months. Let’s clear things up.

When the map() method is called, it returns a completely new Array and does not change the original Array to which it was called. And all the transformation happens in this new Array, that at the beginning it’s a “copy” of the original Array.

The forEach() method does not return anything (undefined). It simply calls a function provided in each element of its array. This call back has permission to change the Array that was called. It means that forEach() does not create a copy of the original Array to interact over it. But also does not return anything, that’s why you don’t see any difference in the original Array.

Notice in the example below that the map() method makes the necessary changes and returns a new Array. To simulate the same effect using forEach() I needed to change the original value.

let numbers = [5, 4, 3, 2, 1]
const newArrayMap = numbers.map(element => element * element);
console.log(newArrayMap); //[ 25, 16, 9, 4, 1 ]
console.log(numbers); //[ 5, 4, 3, 2, 1 ]
const newArrayForEach = numbers.forEach(
   (element, index) =>
      numbers[index] = element * element
);
console.log(numbers) // [ 25, 16, 9, 4, 1 ]

Performance

Although many sites state that the map() method is up to 70% faster than the forEach() method. This is not exactly what I found in my tests.

Actually, I found out the opposite. I tested several scenarios and in none of the tests did the forEach method perform less well. You can check one of the tests here. I believe that if the side effect of changing the original Array is not a problem, the forEach() method fits very well with the proposal of being efficient.

The Bottom line

Which is the best?

That depends on the result you want to get.
forEach() may be preferable when you’re not trying to change the data in your array, but instead want to just do something with it – like save it to a database or just display the data:

let names = ['Elon', 'Jeff', 'Mark'];
names.forEach((name) => {
    console.log(name);
});
// Elon
// Jeff
// Mark

And the map() method may be the best way to change the data because it returns a new Array with the data. And since the return is an Array we can take advantage of this to chain other methods like ( map(), filter(), reduce(), etc.).

let arr = [1, 2, 3, 4, 5];
let arr2 = arr.map(num => num * 2).filter(num => num > 5);
// arr2 = [6, 8, 10

Check out the other Javascript tutorials, and sign up for our newsletter to receive news!

]]>
https://blog.debugeverything.com/difference-foreach-and-map-in-javascript/feed/ 0