One place for hosting & domains

      Logical

      Understanding Comparison and Logical Operators in JavaScript


      Introduction

      The field of computer science has many foundations in mathematical logic. If you have a familiarity with logic, you know that it involves truth tables, Boolean algebra, and comparisons to determine equality or difference.

      The JavaScript programming language uses operators to evaluate statements that can aid in control flow within programming.

      In this tutorial, we’ll go over logical operators. These are commonly used with conditional statements, and the if, else, and else if keywords, as well as the ternary operator. If you are interested in learning more about conditional statements first, refer to How To Write Conditional Statements in JavaScript.

      Comparison Operators

      In JavaScript, there are a number of comparison operators that you can use to evaluate whether given values are different or equal, as well as if a value is greater than or less than another. Often, these operators are used with stored values in variables.

      Comparison operators all return a Boolean (logical) value of true or false.

      The table below summarizes the comparison operators available in JavaScript.

      OperatorWhat it means
      ==Equal to
      !=Not equal to
      ===Strictly equal to with no type conversion
      ! ==Strictly unequal to with no type conversion
      >Greater than
      >=Greater than or equal to
      <Less than
      <=Less than or equal to

      Let’s go into each operator in detail.

      Equality

      The equality operator measures whether values on either side of the operator are equal.

      Let’s consider the following:

      let x = 3;
      
      x == 3;
      

      Because 3 is equivalent to 3, the output received will be the Boolean value of true.

      Output

      true

      If we instead test whether x is equal to another integer, we’ll receive output stating that the statement is validated to be false.

      let x = 3;
      
      x == 5;
      

      Output

      false

      With this equivalency expression, you can also test other data types such as strings and Booleans.

      We’ll use a string example below.

      let shark = 'sammy';
      
      shark == 'sammy';
      shark == 'taylor';
      

      Output

      true false

      In the first instance, the expression returned true because the strings were equivalent. In the second instance, of shark == 'taylor', the expression returned false because the strings were not equal.

      Worth noting, is that the == operator is not a strict equivalency, so you can mix numbers and strings that evaluate to being equivalent. Consider the following example.

      let x = 3;
      
      x == '3';
      

      Even though the first line uses a number data type, and the second line tests x against a string data type, both values equal 3, and the output you will receive indicates that the expression is true.

      Output

      true

      Because this operator is not strict about data type, it can support users entering strings instead of numbers, for example. There is no need to convert data types to test equivalency.

      There are many cases where you may use comparison operators like the == operator. You may want to test equivalency when grading a test, for example. That way you can validate whether a given answer is correct or not.

      let answer = 10;
      let response = prompt("What is 5 + 5?");
      
      if (answer == response) {
        console.log("You're correct!");
      }
      

      Here, if the student enters 10 in response to the question when prompted, they will receive the feedback that they are correct.

      There are many potential applications of comparison operators in JavaScript, and they will help you control the flow of your program.

      Now that you have a foundation with a few examples for ==, we’ll be a bit briefer going forward.

      Inequality

      The != operator tests inequality, to determine whether the values on either side of the operator are not equal.

      Let’s consider an example.

      let y = 8;
      
      y != 9;
      

      For this example, 8 does not equal 9, so the expression will be evaluated to be true:

      Output

      true

      For a statement of inequality to be considered false, the two values on either side would need to actually be equal, as in the following.

      let y = 8;
      
      y != 8
      

      Output

      false

      In this second example, the two values on either side of the operator are equal, so the expression is not true.

      Identity

      The === operator determines whether two values are both of equal value and of equal type. This is also known as a strict equality operator. This means you cannot mix number and string data types.

      Here’s an example:

      let z = 4;
      
      z === 4;
      
      z === '4'; 
      

      We’ll receive the following output.

      Output

      true false

      The example indicates that z is strictly equal to 4 (as it is assigned the numeric value of 4), but that it is not strictly equal to the string '4'.

      Because this operator is strict, you will need to keep in mind that you may need to convert user-entered data from one data type to another, for instance, when working with the identity operator. This may help you keep data types consistent throughout your program.

      Non Identity

      Like ===, the operator !== evaluates a strict inequality, which considers both the value and the type of the operands on either side of the operator.

      We’ll review the following examples.

      let a = 18;
      
      a !== 18;
      
      a !== '18';
      
      a !== 29;
      

      The output for the above will be as follows.

      Output

      false true true

      In this example, since a does strictly equal 18, the first expression evaluates to false as we are testing inequality. In the next two examples, a is determined to be unequal to the string '18' and the number 29, so those two expressions evaluate to true (since they are not equal).

      Greater than

      The greater than symbol in JavaScript may be familiar to you from math: >. This evaluates whether one value (on the left side of the expression) is greater than another value (on the right side of the expression).

      Like the == operator above, the greater than operator is not strict, and therefore will allow you to mix strings and numbers.

      Let’s consider the following examples.

      let f = 72;
      
      f > 80;
      
      f > '30';
      

      We’ll receive the following output:

      Output

      false true

      In the first instance, 72 is less than 80, so the first expression evaluates to false. In the second instance, 72 is in fact greater than '30', and the operator does not care that the number is a string, so the expression evaluates to true.

      Greater than or equal

      Similarly, the operator for greater than or equal to will evaluate whether one operand meets the threshold of the other. This operator is typed as >= a kind of compound between greater than (>) and the equal sign (=).

      Our examples:

      let g = 102;
      
      g >= 90;
      
      g >= 103;
      

      Output

      true false

      Because 102 is a larger number than 90, it is considered to be greater than or equal to 90. Because 102 is less than 103, it is false to state that 102 >= 103. If either 90 or 103 were a string data type, the expressions would also evaluate the same.

      Less than

      The less than operator appears as the mirror version of the greater than operator: <.

      Consider the following examples as a demonstration.

      let w = 1066;
      
      w < 476;
      
      w < 1945;
      

      Output

      false true

      Here, 1066 is greater than 476, so the expression evaluates to false. However, 1066 is less than 1945, so the second statement evaluates to true. Again, the 476 or 1945 values could also be strings.

      Less than or equal

      The opposite of greater than or equal, the less than or equal operator — <= — will evaluate whether the value on the left side of the operator is less than or equal to the value on the right side.

      Here are a few examples.

      let p = 2001;
      
      p <= 1968;
      
      p <= 2001;
      
      p <= 2020;
      

      Output

      false true true

      The first expression evaluates to false because 2001 is not less than or equal to 1968. In the second expression, because the variable and 2001 are equal values, the output is true. In the third expression, the output is also true because 2001 is less than 2020. Again, these values could also be represented as strings, as in '2001', and would evaluate in the same manner.

      Note: Be sure not to confuse the less than or equal operator (<=) with the arrow function (=>) in JavaScript. Learn more about arrow functions in our tutorial Understanding Arrow Functions in JavaScript.

      To understand how these comparison operators can work together in a program, refer to our grades.js example in our How To Write Conditional Statements in JavaScript tutorial.

      Logical Operators

      In JavaScript, there are three logical operators, which connect two or more programming statements to return a true (also called “truthy”) or false (“falsy”) value. These are most often used with Boolean (logical) types, but can be applied to values of any data type.

      These logical operators are summarized in the table below.

      OperatorSyntaxDescription
      AND&&Returns true if both operands are true
      OR||Returns true if either operand is true
      NOT!Returns true if operand is false

      Let’s review each of these operators in more detail.

      AND

      The AND operator is represented by two ampersands — && — it will return true if the operands to the left and right evaluate to be true.

      For example, with AND we can check if something is both high quality and has a low price.

      // High quality and low price are true
      const highQuality = true;
      const lowPrice = true;
      
      (highQuality && lowPrice);
      

      Output

      true

      Since both variables evaluate to be true, the AND operation within the parentheses returns true. If either one of the variables were initialized as false, the && expression would evaluate to false.

      OR

      The OR operator is represented by two pipes — || — it will return true if one of the operands is true.

      In this example, we’ll check if something is either highQuality or lowPrice.

      // Only low price is true
      const highQuality = false;
      const lowPrice = true;
      
      (highQuality || lowPrice);
      

      Output

      true

      Since one of the two conditions (highQuality or lowPrice) was true, the whole operation returns true. This would only evaluate to false if both conditions were false.

      NOT

      The NOT operator is represented by an exclamation point — ! — it will return true if the operand is set to false, and vice versa.

      const highQuality = true;
      
      !(highQuality);
      

      Output

      false

      In the above statement, highQuality has the value of true. With the NOT operator, we are checking to see if hiqhQuality evaluates to false. If it were false, the output would return true, but since it is true, the output returns false.

      The NOT operator is a bit tricky to understand at first. The important part to remember is that NOT checks whether something evaluates to be false.

      Conclusion

      Logical operators are the building blocks of flow control in JavaScript programming. Using these operators effectively will help you develop programs that evaluate statements and move to the next stage based on whether a statement is true or false.

      To continue learning more about JavaScript, check out our How To Code in JavaScript series, and our JavaScript tag.



      Source link

      How To Set Up Logical Replication with PostgreSQL 10 on Ubuntu 18.04


      Introduction

      When setting up an application for production, it’s often useful to have multiple copies of your database in place. The process of keeping database copies in sync is called replication. Replication can provide high-availability horizontal scaling for high volumes of simultaneous read operations, along with reduced read latencies. It also allows for peer-to-peer replication between geographically distributed database servers.

      PostgreSQL is an open-source object-relational database system that is highly extensible and compliant with ACID (Atomicity, Consistency, Isolation, Durability) and the SQL standard. Version 10.0 of PostgreSQL introduced support for logical replication, in addition to physical replication. In a logical replication scheme, high-level write operations are streamed from a master database server into one or more replica database servers. In a physical replication scheme, binary write operations are instead streamed from master to replica, producing a byte-for-byte exact copy of the original content. In cases where you would like to target a particular subset of data, such as off-load reporting, patching, or upgrading, logical replication can offer speed and flexibility.

      In this tutorial, you will configure logical replication with PostgreSQL 10 on two Ubuntu 18.04 servers, with one server acting as the master and the other as the replica. By the end of the tutorial you will be able to replicate data from the master server to the replica using logical replication.

      Prerequisites

      To follow this tutorial, you will need:

      Step 1 — Configuring PostgreSQL for Logical Replication

      There are several configuration settings you will need to modify to enable logical replication between your servers. First, you’ll configure Postgres to listen on the private network interface instead of the public one, as exposing data over the public network is a security risk. Then you’ll configure the appropriate settings to allow replication to db-replica.

      On db-master, open /etc/postgresql/10/main/postgresql.conf, the main server configuration file:

      • sudo nano /etc/postgresql/10/main/postgresql.conf

      Find the following line:

      /etc/postgresql/10/main/postgresql.conf

      ...
      #listen_addresses = 'localhost'         # what IP address(es) to listen on;
      ...
      

      Uncomment it by removing the #, and add your db_master_private_ip_address to enable connections on the private network:

      Note: In this step and the steps that follow, make sure to use the private IP addresses of your servers, and not their public IPs. Exposing a database server to the public internet is a considerable security risk.

      /etc/postgresql/10/main/postgresql.conf

      ...
      listen_addresses = 'localhost, db_master_private_ip_address'
      ...
      

      This makes db-master listen for incoming connections on the private network in addition to the loopback interface.

      Next, find the following line:

      /etc/postgresql/10/main/postgresql.conf

      ...
      #wal_level = replica                    # minimal, replica, or logical
      ...
      

      Uncomment it, and change it to set the PostgreSQL Write Ahead Log (WAL) level to logical. This increases the volume of entries in the log, adding the necessary information for extracting discrepancies or changes to particular data sets:

      /etc/postgresql/10/main/postgresql.conf

      ...
      wal_level = logical
      ...
      

      The entries on this log will be consumed by the replica server, allowing for the replication of the high-level write operations from the master.

      Save the file and close it.

      Next, let’s edit /etc/postgresql/10/main/pg_hba.conf, the file that controls allowed hosts, authentication, and access to databases:

      • sudo nano /etc/postgresql/10/main/pg_hba.conf

      After the last line, let’s add a line to allow incoming network connections from db-replica. We’ll use db-replica‘s private IP address, and specify that connections are allowed from all users and databases:

      /etc/postgresql/10/main/pg_hba.conf

      ...
      # TYPE      DATABASE        USER            ADDRESS                               METHOD
      ...
      host         all            all             db_replica_private_ip_address/32      md5
      

      Incoming network connections will now be allowed from db-replica, authenticated by a password hash (md5).

      Save the file and close it.

      Next, let’s set our firewall rules to allow traffic from db-replica to port 5432 on db-master:

      • sudo ufw allow from db_replica_private_ip_address to any port 5432

      Finally, restart the PostgreSQL server for the changes to take effect:

      • sudo systemctl restart postgresql

      With your configuration set to allow logical replication, you can now move on to creating a database, user role, and table.

      Step 2 — Setting Up a Database, User Role, and Table

      To test the functionality of your replication settings, let’s create a database, table, and user role. You will create an example database with a sample table, which you can then use to test logical replication between your servers. You will also create a dedicated user and assign them privileges over both the database and the table.

      First, open the psql prompt as the postgres user with the following command on both db-master and db-replica:

      Create a new database called example on both hosts:

      Note: The final ; in these commands is required. On interactive sessions, PostgreSQL will not execute SQL commands until you terminate them with a semicolon. Meta-commands (those starting with a backslash, like q and c) directly control the psql client itself, and are therefore exempt from this rule. For more on meta-commands and the psql client, please refer to the PostgreSQL documentation.

      Using the connect meta-command, connect to the databases you just created on each host:

      Create a new table called widgets with arbitrary fields on both hosts:

      • CREATE TABLE widgets
      • (
      • id SERIAL,
      • name TEXT,
      • price DECIMAL,
      • CONSTRAINT widgets_pkey PRIMARY KEY (id)
      • );
      • CREATE TABLE widgets
      • (
      • id SERIAL,
      • name TEXT,
      • price DECIMAL,
      • CONSTRAINT widgets_pkey PRIMARY KEY (id)
      • );

      The table on db-replica does not need to be identical to its db-master counterpart. However, it must contain every single column present on the table at db-master. Additional columns must not have NOT NULL or other constraints. If they do, replication will fail.

      On db-master, let's create a new user role with the REPLICATION option and a login password. The REPLICATION attribute must be assigned to any role used for replication. We will call our user sammy, but you can replace this with your own username. Make sure to also replace my_password with your own secure password:

      • CREATE ROLE sammy WITH REPLICATION LOGIN PASSWORD 'my_password';

      Make a note of your password, as you will use it later on db-replica to set up replication.

      Still on db-master, grant full privileges on the example database to the user role you just created:

      • GRANT ALL PRIVILEGES ON DATABASE example TO sammy;

      Next, grant privileges on all of the tables contained in the database to your user:

      • GRANT ALL PRIVILEGES ON ALL TABLES IN SCHEMA public TO sammy;

      The public schema is a default schema in each database into which tables are automatically placed.

      With these privileges set, you can now move on to making the tables in your example database available for replication.

      Step 3 — Setting Up a Publication

      Publications are the mechanism that PostgreSQL uses to make tables available for replication. The database server will keep track internally of the connection and replication status of any replica servers associated with a given publication. On db-master, you will create a publication, my_publication, that will function as a master copy of the data that will be sent to your subscribers — in our case, db-replica.

      On db-master, create a publication called my_publication:

      • CREATE PUBLICATION my_publication;

      Add the widgets table you created previously to it:

      • ALTER PUBLICATION my_publication ADD TABLE widgets;

      With your publication in place, you can now add a subscriber that will pull data from it.

      Step 4 — Creating a Subscription

      Subscriptions are used by PostgreSQL to connect to existing publications. A publication can have many subscriptions across different replica servers, and replica servers can also have their own publications with subscribers. To access the data from the table you created on db-master, you will need to create a subscription to the publication you created in the previous step, my_publication.

      On db-replica, let's create a subscription called my_subscription. The CREATE SUBSCRIPTION command will name the subscription, while the CONNECTION parameter will define the connection string to the publisher. This string will include the master server's connection details and login credentials, including the username and password you defined earlier, along with the name of the example database. Once again, remember to use db-master's private IP address, and replace my_password with your own password:

      • CREATE SUBSCRIPTION my_subscription CONNECTION 'host=db_master_private_ip_address port=5432 password=my_password user=sammy dbname=example' PUBLICATION my_publication;

      You will see the following output confirming the subscription:

      Output

      NOTICE: created replication slot "my_subscription" on publisher CREATE SUBSCRIPTION

      Upon creating a subscription, PostgreSQL will automatically sync any pre-existing data from the master to the replica. In our case there is no data to sync since the widgets table is empty, but this is a useful feature when adding new subscriptions to an existing database.

      With a subscription in place, let's test the setup by adding some demo data to the widgets table.

      Step 5 — Testing and Troubleshooting

      To test replication between our master and replica, let's add some data to the widgets table and verify that it replicates correctly.

      On db-master, insert the following data on the widgets table:

      • INSERT INTO widgets (name, price) VALUES ('Hammer', 4.50), ('Coffee Mug', 6.20), ('Cupholder', 3.80);

      On db-replica, run the following query to fetch all the entries on this table:

      You should now see:

      Output

      id | name | price ----+------------+------- 1 | Hammer | 4.50 2 | Coffee Mug | 6.20 3 | Cupholder | 3.80 (3 rows)

      Success! The entries have been successfully replicated from db-master to db-replica. From now on, all INSERT, UPDATE, and DELETE queries will be replicated across servers unidirectionally.

      One thing to note about write queries on replica servers is that they are not replicated back to the master server. PostgreSQL currently has limited support for resolving conflicts when the data between servers diverges. If there is a conflict, the replication will stop and PostgreSQL will wait until the issue is manually fixed by the database administrator. For that reason, most applications will direct all write operations to the master server, and distribute reads among available replica servers.

      You can now exit the psql prompt on both servers:

      Now that you have finished testing your setup, you can add and replicate data on your own.

      Troubleshooting

      If replication doesn't seem to be working, a good first step is checking the PostgreSQL log on db-replica for any possible errors:

      • tail /var/log/postgresql/postgresql-10-main.log

      Here are some common problems that can prevent replication from working:

      • Private networking is not enabled on both servers, or the servers are on different networks;
      • db-master is not configured to listen for connections on the correct private network IP;
      • The Write Ahead Log level on db-master is incorrectly configured (it must be set to logical);
      • db-master is not configured to accept incoming connections from the correct db-replica private IP address;
      • A firewall like UFW is blocking incoming PostgreSQL connections on port 5432;
      • There are mismatched table names or fields between db-master and db-replica;
      • The sammy database role is missing the required permissions to access the example database on db-master;
      • The sammy database role is missing the REPLICATION option on db-master;
      • The sammy database role is missing the required permissions to access the widgets table on db-master;
      • The table wasn't added to the publication on db-master.

      After resolving the existing problem(s), replication should take place automatically. If it doesn't, use following command to remove the existing subscription before recreating it:

      • DROP SUBSCRIPTION my_subscription;

      Conclusion

      In this tutorial you've successfully installed PostgreSQL 10 on two Ubuntu 18.04 servers and configured logical replication between them.

      You now have the required knowledge to experiment with horizontal read scaling, high availability, and the geographical distribution of your PostgreSQL database by adding additional replica servers.

      To learn more about logical replication in PostgreSQL 10, you can read the chapter on the topic on the official PostgreSQL documentation, as well as the manual entries on the CREATE PUBLICATION and CREATE SUBSCRIPTION commands.



      Source link