My Youtube Channel

Please Subscribe

Flag of Nepal

Built in OpenGL

Word Cloud in Python

With masked image

Showing posts with label database. Show all posts
Showing posts with label database. Show all posts

Wednesday, September 11, 2024

Classification of SQL Queries

SQL (Structured Query Language) is a standard language for managing and manipulating databases. SQL is divided into different languages or subcategories based on the type of operation it performs. Here's a classification of SQL languages along with examples of queries:


1. **Data Query Language (DQL)**:

   - **Purpose**: Used to retrieve data from a database.

   - **Key Statement**: `SELECT`


Example:

   SELECT * FROM students;


   In this example, the `SELECT` statement retrieves all rows from the `students` table.


2. **Data Definition Language (DDL)**:

   - **Purpose**: Defines the structure of the database, such as creating, altering, and dropping tables and other database objects.

   - **Key Statements**: `CREATE`, `ALTER`, `DROP`, `TRUNCATE`


 Example 1: `CREATE TABLE`


   CREATE TABLE students (

      student_id INT PRIMARY KEY,

      student_name VARCHAR(100),

      age INT

   );



   This creates a `students` table with columns for `student_id`, `student_name`, and `age`.


 Example 2: `ALTER TABLE`


   ALTER TABLE students ADD COLUMN gender VARCHAR(10);



   This adds a `gender` column to the `students` table.


Example 3: `DROP TABLE`


   DROP TABLE students;



   This statement deletes the `students` table along with all its data.


---


3. **Data Manipulation Language (DML)**:

   - **Purpose**: Used to manipulate data within the database. It covers inserting, updating, and deleting records.

   - **Key Statements**: `INSERT`, `UPDATE`, `DELETE`


Example 1: `INSERT`


   INSERT INTO students (student_id, student_name, age) 

   VALUES (1, 'John Doe', 20);



   This inserts a new record into the `students` table.


Example 2: `UPDATE`

   UPDATE students 

   SET age = 21 

   WHERE student_id = 1;



   This updates the `age` of the student with `student_id` 1 to 21.


Example 3: `DELETE`

   DELETE FROM students WHERE student_id = 1;


   This deletes the record of the student with `student_id` 1 from the `students` table.


4. **Data Control Language (DCL)**:

   - **Purpose**: Used to control access to data in the database, typically through permission management.

   - **Key Statements**: `GRANT`, `REVOKE`


Example 1: `GRANT`


   GRANT SELECT, INSERT ON students TO 'username';



   This grants the user `username` permission to `SELECT` and `INSERT` records in the `students` table.


Example 2: `REVOKE`


   REVOKE INSERT ON students FROM 'username';



   This revokes the `INSERT` permission from the user `username` on the `students` table.


---


5. **Transaction Control Language (TCL)**:

   - **Purpose**: Used to manage transactions in the database. Transactions allow groups of SQL statements to be executed in a way that ensures consistency and atomicity.

   - **Key Statements**: `COMMIT`, `ROLLBACK`, `SAVEPOINT`


 Example 1: `COMMIT`

   COMMIT;


   This commits the current transaction, making all changes made permanent.


 Example 2: `ROLLBACK`

   ```sql

   ROLLBACK;

   ```


   This rolls back the current transaction, undoing all changes since the last `COMMIT`.


 Example 3: `SAVEPOINT`

   SAVEPOINT save1;


   This creates a savepoint named `save1`, which allows partial rollback to this specific point


Classification of SQL Queries:




Each of these languages plays a critical role in working with relational databases, and depending on the specific use case, you would use different combinations of them to interact with your data effectively.

Query to Connect all tables of Sakila Database of MYSQL

select g1.first_name, g1.last_name, g1.film_id, g1.actor_id, g1.title, g1.release_year,

g1.language_id, g1.rating, g1.inventory_id, g1.store_id,

g3.staff_id, g3.staff_firstname, g3.staff_lastname, g3.staff_email, g3.store_id,

g3.address, g3.district, g3.city_id, g3.phone, g3.city, g3.country,

g3.payment_id, g3.rental_id, g3.customer_id, g3.amount, g3.cust_firstname,

g3.cust_lastname, g3.cust_email

from (select tt1.first_name, tt1.last_name, tt1.film_id, tt1.actor_id, tt1.title, tt1.release_year,

tt1.language_id, tt1.rating, tt2.inventory_id, tt2.store_id from (select t1.first_name, t1.last_name, t1.film_id, t1.actor_id, t2.title, t2.release_year,

t2.language_id, t2.rating from (select a.first_name,  a.last_name,

a.actor_id, b.film_id from actor a join film_actor b on a.actor_id=b.actor_id) t1

join film t2 on t1.film_id=t2.film_id) tt1 join inventory tt2 on tt1.film_id=tt2.film_id) g1

join

(select g2.staff_id, g2.staff_firstname, g2.staff_lastname, g2.staff_email, g2.store_id,

g2.address, g2.district, g2.city_id, g2.phone, g2.city, g2.country,

g2.payment_id, g2. rental_id, g2.customer_id, g2.amount, g2.cust_firstname,

g2.cust_lastname, g2.cust_email 

from

(select pppp1.staff_id, pppp1.first_name as staff_firstname, pppp1.last_name as staff_lastname, pppp1.email as staff_email, pppp1.store_id,

pppp1.address, pppp1.district, pppp1.city_id, pppp1.phone, pppp1.city, pppp1.country,

pppp1.payment_id, pppp1. rental_id, pppp1. customer_id, pppp1.amount, pppp2.first_name as cust_firstname,

pppp2.last_name as cust_lastname, pppp2.email as cust_email 

from

(select ppp1.staff_id, ppp1.first_name, ppp1.last_name, ppp1.email, ppp1.store_id,

ppp1.address, ppp1.district, ppp1.city_id, ppp1.phone, ppp1.city, ppp1.country,

ppp2.payment_id, ppp2. rental_id, ppp2. customer_id, ppp2.amount 

from

(select pp1.staff_id, pp1.first_name, pp1.last_name, pp1.email, pp1.address_id, pp1.store_id,

pp1.address, pp1.district, pp1.city_id, pp1.phone, pp1.city, pp1.country_id, pp2.country 

from 

(select p1.staff_id, p1.first_name, p1.last_name, p1.email, p1.address_id, p1.store_id,

p1.address, p1.district, p1.city_id, p1.phone, p2.city, p2.country_id 

from

(select d.staff_id, d.first_name, d.last_name, d.email, d.address_id, d.store_id,

e.address, e.district, e.city_id, e.phone 

from staff d join address e on

d.address_id=e.address_id) p1 join city p2 on p1.city_id=p2.city_id) pp1 join country pp2

on pp1.country_id=pp2.country_id) ppp1 join payment ppp2 on ppp1.staff_id=ppp2.staff_id)pppp1

join customer pppp2 on pppp1.customer_id=pppp2.customer_id) g2) g3

on g1.store_id=g3.store_id;




Thursday, March 21, 2024

What is RMAN (Recovery Manager) in Oracle Database ?

RMAN stands for "Recovery Manager" and it is a key component of the Oracle database management system. RMAN is used for backup and recovery tasks, providing a centralized and efficient mechanism for managing backups, restoring data, and recovering databases in the event of failures.



Here are some key features and functionalities of RMAN:


1. **Backup and Recovery:** RMAN provides a comprehensive solution for backing up Oracle databases, including data files, control files, and archived redo logs. It allows for full backups, incremental backups, and differential backups to minimize backup time and storage requirements. Additionally, RMAN simplifies the process of restoring data in case of media failures, database corruption, or user errors.


2. **Incremental Backup:** RMAN supports incremental backups, which only back up the blocks that have changed since the last backup. This helps to reduce backup times and conserve storage space, especially for large databases with frequent changes.


3. **Block-Level Corruption Detection:** RMAN can detect and repair block-level corruption within the database files during backup or restore operations. This ensures data integrity and helps prevent data loss due to undetected corruption.


4. **Parallelization:** RMAN can parallelize backup and recovery operations, utilizing multiple channels to improve performance and reduce backup and recovery times.


5. **Integration with Oracle Enterprise Manager (OEM):** RMAN is integrated with Oracle Enterprise Manager, providing a graphical user interface (GUI) for managing backup and recovery operations. This allows database administrators to monitor backup jobs, configure backup policies, and perform recovery tasks through a centralized console.


6. **Backup Optimization:** RMAN supports features such as backup compression and backup set encryption to optimize backup storage and enhance data security.


7. **Catalog Database:** RMAN can maintain a recovery catalog database, which serves as a centralized repository for storing backup metadata and RMAN configurations. This enables better management of backups across multiple databases and facilitates disaster recovery scenarios.


Overall, RMAN plays a crucial role in ensuring data availability, integrity, and recoverability for Oracle databases, offering a robust and efficient solution for backup and recovery operations.

Saturday, February 3, 2024

Solved: ERROR 1045 (28000): Access denied for user 'root'@'localhost' (using password: YES)


Follow the given steps to solve the issue. The commands here are for CentOS 8. The solution is same for other OS as well so modify the commands accordingly.

Step 1: After the installation of MYSQL is finished, enable and start mysqld as given below:

sudo systemctl start mysqld

sudo systemctl enable mysqld

Once, done also check the status of the mysqld to verify whether it is running or not:

sudo systemctl status mysqld

Step 2: Find the temporary password and copy it using the following command:

sudo grep 'temporary password' /var/log/mysqld.log

You will see something like this:

 A temporary password is generated for root@localhost: ;ND0#VvB0*Mt

Copy the temporary password.

Step 3: Type the following command:

mysql -u root -p

Step 4: When prompted to enter password, just paste the copied temporary password and yes you are done with your task. 

Step 5: Then you can change the password for root using the command:

sudo mysql_secure_installation



Thursday, February 1, 2024

Steps to install oci8 on centos 8

The following steps is valid for Oracle 11g, you can modify as per your oracle version in a similar fashion.

1. Install the Oracle Instant Client:

   - Download the Oracle Instant Client RPM packages for your architecture from the Oracle website (https://www.oracle.com/database/technologies/instant-client/linux-x86-64-downloads.html). You'll need  oracle-instantclient-basic ,  oracle-instantclient-devel and oracle-instantclient-sqlplus packages.

   - Transfer the downloaded RPM packages to your CentOS 8 system if you downloaded them on a different machine.

Note: for centos, it is better to download “.rpm” file rather than “.zip”

2. Install the Oracle Instant Client RPM packages:

Go to the directory where you downloaded the oracle instant-client files and install those files:

Let’s take example for version oracle instant-client 11.2,

sudo dnf install oracle-instantclient11.2-basic-11.2.0.4.0-1.x86_64.rpm 

sudo dnf install oracle-instantclient11.2-devel-11.2.0.4.0-1.x86_64

sudo dnf install oracle-instantclient11.2-sqlplus-11.2.0.4.0-1.x86_64

To verify whether the Oracle Instant Client "devel" package is installed on your CentOS system, you can use the package management tool rpm or dnf. Here's how you can check for the presence of the Oracle Instant Client devel package:

Using ‘rpm’:

rpm -qa | grep oracle-instantclient-devel

Using ‘dnf’:

dnf list installed | grep oracle-instantclient-devel

 

3. Verify the ORACLE_HOME environment variable:

echo $ORACLE_HOME

Ensure that the ORACLE_HOME environment variable is set correctly and points to the location where you installed the Oracle Instant Client. If it's not set correctly, you can set it as follows:

export ORACLE_HOME=/path/to/instant/client

During the installation process, you may be prompted to provide the path to the Oracle Instant Client library. If prompted, enter the correct path:

Enter the path: instantclient,/usr/lib/oracle/19.20/client64/lib

 

4. Set the environment variables required for OCI8 and PHP:

 

$ export ORACLE_HOME=/usr/lib/oracle/11.2/client64

$ export LD_LIBRARY_PATH=/usr/lib/oracle/11.2/client64/lib

sudo ldconfig

Once you are done with above steps, the environment is set for oci8 installation, follow the bellows steps now,

5. Stop Apache and uninstall older version of OCI8 if any (stopping Apache is very important):

 service httpd stop

 pecl uninstall oci8

 

6. Install php-pear and php devel:

 sudo yum install php-pear php-devel

 pear download pecl/oci8

7. The next commands depend on the version of oci8 downloaded above.

$ tar xvzf oci8-2.2.0.tgz

$ cd oci8-2.2.0/

$ phpize

$ export PHP_DTRACE=yes

$ sudo dnf install libnsl

$ sudo dnf install epel-release

$ setenforce 0

 

8. Make sure of the instantclient path below... mine was version 11.2 so it was located in this folder... Also make note some tutorials ask for the ORACLE_HOME folder which theoretically is /usr/lib/oracle/11.2/client64 but if its instantclient then put the lib folder underneath it (worked for me at least:)

$ ./configure --with-oci8=instantclient,/usr/lib/oracle/12.2/client64/lib/

$ make

$ make install

$ sudo pecl install oci8-3.3.0 instantclient,$ORACLE_HOME/lib

$ sudo systemctl restart httpd

$ sudo systemctl restart php-fpm

$ sudo systemctl restart mysqld 

9. NOW an .so file built in: /usr/lib64/php/modules/oci8.so

10. check whether oci8 has been successfully installed or not:

php -m | grep oci8

The steps may not be needed in most of the cases. If indeed, it is required in your case go through these steps as well (though it is suggested to first try running before implementing the below steps):

# THIS STEP NOT NEEDED if SELinux disabled on your server/box, but if SELinux is enabled run: setsebool -P httpd_execmem 1

# NOW add:   extension=oci8.so    at the bottom of your php.ini file (probably in /etc/php.ini)

# Add extension_dir=/usr/lib64/php/modules/


Tuesday, January 30, 2024

Defining and differentiating Super key and Candidate Key based on two properties

Candidate keys and super keys are concepts in relational database theory that relate to the uniqueness and irreducibility of attributes within a table's schema.

1. **Super Key**:

   - A super key is a set of one or more attributes (columns) that uniquely identifies each tuple (row) within a table.

   - It may contain more attributes than necessary to uniquely identify tuples.

   - A super key must satisfy the uniqueness property, meaning no two tuples in the table can have the same combination of values for the attributes in the super key.

   - Super keys can be minimal (irreducible) or non-minimal (reducible).


2. **Candidate Key**:

   - A candidate key is a minimal super key, meaning it is a super key with the fewest possible attributes.

   - It uniquely identifies each tuple in the table.

   - If any attribute is removed from a candidate key, it loses its uniqueness property.

   - Each candidate key within a table is unique, meaning no two candidate keys contain the same set of attributes.


Now, let's delve deeper into the uniqueness and irreducibility properties that differentiate between candidate keys and super keys:


- **Uniqueness**:

  - Both candidate keys and super keys must guarantee uniqueness.

  - However, candidate keys provide the strongest form of uniqueness because they are minimal and cannot be further reduced without losing the uniqueness property.

  - Super keys, on the other hand, may contain redundant attributes that do not contribute to uniqueness, but they still ensure that each tuple in the table is uniquely identifiable.


- **Irreducibility**:

  - Irreducibility refers to the inability to remove any attribute from a key without losing its unique identification property.

  - Candidate keys are by definition irreducible because they are minimal super keys.

  - Super keys, while they can also provide uniqueness, may include additional attributes that are not strictly necessary for uniquely identifying tuples. Removing these attributes may still preserve uniqueness, making them reducible.


In summary, while both candidate keys and super keys ensure uniqueness, candidate keys are distinguished by their irreducibility, as they represent the smallest set of attributes necessary to uniquely identify each tuple in a table. Super keys, while also ensuring uniqueness, may contain redundant attributes and are not necessarily minimal.


Understanding with example:

Let's consider a simple table representing employees in a company:


**Employee Table:**


| EmployeeID | Name      | Department | Salary |

|------------|-----------|------------|--------|

| 1          | John      | HR         | 50000  |

| 2          | Jane      | IT         | 60000  |

| 3          | Alice     | IT         | 55000  |

| 4          | Bob       | Sales      | 48000  |


**1. Uniqueness:**


- **Candidate Key Example:**

  In this table, the attribute `EmployeeID` serves as a candidate key because it uniquely identifies each employee. No two employees have the same `EmployeeID`.

  Candidate Key: `{EmployeeID}`


- **Super Key Example:**

  A super key could be the combination of `EmployeeID` and `Name`. This combination uniquely identifies each employee, making it a super key. However, it's not minimal because `EmployeeID` alone is sufficient.

  Super Key: `{EmployeeID, Name}`


**2. Irreducibility:**


- **Irreducible Candidate Key Example:**

  `EmployeeID` is an irreducible candidate key because removing any attribute from it would violate uniqueness. If you remove `EmployeeID`, you can't uniquely identify employees anymore.

  Candidate Key: `{EmployeeID}`


- **Reducible Super Key Example:**

  Let's consider the super key `{EmployeeID, Department}`. While it uniquely identifies each tuple, `Department` is not necessary for uniqueness. Removing `Department` still leaves us with a unique identifier.

  Super Key (Reducible): `{EmployeeID, Department}`


In summary, `EmployeeID` serves as both a candidate key and an example of irreducibility. Meanwhile, combinations like `{EmployeeID, Name}` represent super keys but are not minimal due to the inclusion of non-essential attributes.

Tuesday, September 26, 2023

Immutable backup and how it is achieved ?

An immutable backup refers to a type of data backup that cannot be modified, altered, or deleted once it has been created. The term "immutable" implies that the data is protected from any changes, intentional or accidental, for a specified period of time or until certain conditions are met. This concept is commonly used in data protection and disaster recovery strategies to ensure the integrity and availability of critical data.


Here are some key characteristics and benefits of immutable backups:


1. Data Integrity: Immutable backups are designed to prevent data tampering, corruption, or deletion. This helps maintain the integrity of the backed-up data, ensuring that it remains unchanged and reliable for recovery purposes.


2. Ransomware Protection: Immutable backups are an effective defense against ransomware attacks. Since ransomware typically tries to encrypt or delete data, having immutable backups ensures that attackers cannot alter or delete the backup copies, making it possible to restore the data to a clean state.


3. Compliance Requirements: Some industries and regulatory bodies require organizations to maintain immutable backups as part of their compliance and data retention policies. Immutable backups can help organizations meet these requirements by providing a secure and unmodifiable data repository.


4. Legal and Audit Purposes: Immutable backups can be used as evidence in legal proceedings or audits, as they demonstrate that the data has not been altered or tampered with since the backup was created.


5. Data Recovery: In the event of data loss or system failures, immutable backups can be relied upon for data recovery. They provide a reliable source for restoring data to its previous state.


6. Retention Periods: Immutable backups often have predefined retention periods during which the data cannot be deleted or modified. Once the retention period expires, the data may become mutable or can be deleted according to the organization's policies.


Immutable backups are achieved through a combination of technology, policies, and best practices aimed at ensuring that data cannot be modified, altered, or deleted once it has been backed up. Here are some common methods and strategies for achieving immutable backups:


1. **Write Once Read Many (WORM) Storage**: WORM storage systems are designed


to allow data to be written once and read many times. Once data is written to a WORM storage device, it cannot be overwritten, modified, or deleted, making it an ideal choice for immutable backups.


2. **Versioning**: Implementing versioning mechanisms within a backup system allows multiple copies of a file or data to be retained. Each version is immutable, meaning it cannot be altered or deleted. This ensures that previous versions of data can be restored if needed.


3. **Data Encryption**: Encrypting backup data can help protect it from unauthorized access and tampering. Even if an attacker gains access to the backup storage, they won't be able to modify the data without the encryption keys.


4. **Access Controls and Authentication**: Implement strict access controls and authentication mechanisms to prevent unauthorized personnel from making changes to backup data.


5. **Retention Policies**: Establish clear retention policies that define how long backup data should be kept in its immutable state. Once the retention period expires, the data may become mutable or can be deleted based on organizational policies.


6. **Auditing and Monitoring**: Regularly audit and monitor backup systems to detect any unusual activities or attempts to tamper with the data. Log and track all actions related to backup data.


7. **Backup Replication**: Create multiple copies of backups and store them in geographically diverse locations. This ensures redundancy and protects against both data loss and the risk of a single copy being compromised.


8. **Offline or Air-Gapped Backups**: Keep some backup copies completely offline or air-gapped from the network. This makes it nearly impossible for cyberattacks to reach the backup data.


9. **Immutable Backup Solutions**: Some backup solutions and cloud providers offer built-in features for creating immutable backups. These solutions often provide a secure and automated way to achieve immutability.


10. **Regular Testing and Recovery Drills**: Periodically test the restoration process from immutable backups to ensure that the data can be successfully recovered when needed.


11. **Legal and Compliance Compliance**: Ensure that your immutable backup strategy aligns with legal and compliance requirements specific to your industry and region.


The exact implementation of immutable backups can vary depending on the organization's needs, available technologies, and budget. It's crucial to assess the specific requirements and risks associated with your data and design an immutable backup strategy accordingly. Additionally, maintaining documentation and regular reviews of your backup strategy can help ensure its effectiveness over time.

Tuesday, August 22, 2023

Physical IP Vs Virtual IP Vs SCAN IP (with Examples)

Physical IP, Virtual IP, and SCAN IP are terms often used in the context of networking and IT infrastructure. Let's break down the differences between these concepts:


1. Physical IP (Internet Protocol):

A physical IP address is a unique numerical label assigned to each device (like computers, routers, servers, etc.) connected to a network. It serves as an identifier that helps in routing data packets to the correct destination. Physical IP addresses are associated with the hardware of the device and are typically static, meaning they don't change frequently.


2. Virtual IP (VIP):

A virtual IP address is an IP address that is not associated with a specific physical device, but rather with a service or a group of devices that provide redundancy or load balancing. Virtual IPs are often used to ensure high availability and fault tolerance in server clusters. When a client requests a service, the virtual IP redirects the request to one of the available physical servers in the cluster, helping to distribute the workload evenly and providing redundancy in case one server fails.


3. SCAN IP (Single Client Access Name):

SCAN IP is a concept used in Oracle Real Application Clusters (RAC), which is a technology that allows multiple servers to work together as a single system to provide high availability and scalability for databases. SCAN IP provides a single DNS entry for clients to connect to the database cluster. This single DNS entry resolves to multiple IP addresses (usually three) that are associated with different nodes in the RAC cluster. This helps distribute the database client connections across the nodes and simplifies connection management.


In summary:

- Physical IP addresses are unique identifiers assigned to individual devices on a network.

- Virtual IP addresses are used for load balancing and high availability, directing client requests to a group of devices.

- SCAN IP is specific to Oracle RAC, providing a single DNS entry that resolves to multiple IP addresses for load distribution and easier client connection management to the database cluster.



Examples to make it more clear:


1. **Physical IP Address**:

Imagine you have a small office network with three computers: Computer A, Computer B, and Computer C. Each of these computers has a physical IP address assigned to it.


- Computer A: IP Address - 192.168.1.2

- Computer B: IP Address - 192.168.1.3

- Computer C: IP Address - 192.168.1.4


These IP addresses uniquely identify each computer on the network. When data packets need to be sent from one computer to another, they use these IP addresses to ensure the packets reach the correct destination.


2. **Virtual IP Address (VIP)**:

Let's say you have a web application that runs on a cluster of servers to handle incoming user requests. To ensure that the workload is distributed evenly and to provide fault tolerance, you set up a virtual IP address for the cluster. This IP address isn't tied to any specific physical server but rather represents the entire cluster.


- Virtual IP Address: 10.0.0.100


You have three physical servers in your cluster:


- Server 1: IP Address - 10.0.0.101

- Server 2: IP Address - 10.0.0.102

- Server 3: IP Address - 10.0.0.103


When a user tries to access your web application using the virtual IP address (10.0.0.100), the load balancer associated with that VIP will distribute the incoming request to one of the physical servers (e.g., Server 1). If Server 1 becomes overloaded or experiences issues, the load balancer can redirect traffic to Server 2 or Server 3, ensuring the application remains available.


3. **SCAN IP (Single Client Access Name)**:

Consider a scenario where you're using Oracle Real Application Clusters (RAC) to manage a database that serves a large number of clients. In this setup, you can use SCAN IP to simplify client connections.


You have an Oracle RAC cluster with three nodes:


- Node 1: IP Address - 192.168.1.10

- Node 2: IP Address - 192.168.1.11

- Node 3: IP Address - 192.168.1.12


With SCAN IP, you have a single DNS entry:


- SCAN IP Address: scan.mydatabase.com


When clients want to connect to the Oracle database, they use the SCAN IP address (scan.mydatabase.com). Behind the scenes, the DNS resolution for this SCAN IP results in the three node IP addresses. This simplifies client connection setup and load distribution, as clients don't need to know the individual node addresses.


So, if a client connects to scan.mydatabase.com, the DNS system resolves this to one of the three IP addresses (e.g., 192.168.1.10), enabling the client to communicate with one of the nodes in the Oracle RAC cluster.


In summary, these concepts highlight how IP addressing can be used to manage and optimize network resources, distribute workloads, and simplify client connections in various scenarios.

Saturday, August 5, 2023

Uninstall MariaDB completely along with its dependencies from the Centos

 To uninstall MariaDB on CentOS 8, you can use the `yum` package manager. Follow these steps to uninstall MariaDB:


1. **Stop the MariaDB service**:

   Before uninstalling, it's better to stop the MariaDB service to avoid any issues. Open a terminal and run the following command:

   sudo systemctl stop mariadb


2. **Remove the MariaDB packages**:

   Once the service is stopped, you can proceed to remove the MariaDB packages using `yum`:

   sudo yum remove mariadb-server mariadb-client


3. **Remove data and configuration files (optional)**:

   By default, the package manager may not remove the MariaDB data and configuration files. If you want to remove them as well, run the following commands:

   sudo rm -rf /var/lib/mysql

   sudo rm -rf /etc/my.cnf


   Please be cautious while running the `rm` command, as it permanently deletes the files and directories.


4. **Clean up dependencies (optional)**:

   You can also clean up any unused dependencies to free up disk space:

   sudo yum autoremove


That's it! MariaDB should now be uninstalled from your CentOS 8 system. Before performing these steps, make sure to back up any important databases to prevent data loss.

Install MariaDB on Centos

 To install MariaDB on CentOS 8, follow these steps:


1. Update the system packages:

   Before installing any software, it's a good idea to update your system to ensure you have the latest packages. Open a terminal or SSH into your CentOS 8 server and run the following commands:

   sudo dnf clean all

   sudo dnf update


2. Install MariaDB server:

CentOS 8 uses the DNF package manager, so you can easily install MariaDB by running the following command:

   sudo dnf install mariadb-server


3. Start and enable the MariaDB service:

   After the installation is complete, start the MariaDB service and enable it to start on boot using the following commands:

   sudo systemctl start mariadb

   sudo systemctl enable mariadb


4. Secure the MariaDB installation:

   By default, MariaDB is not configured with a root password, and it is recommended to set a root password for security. You can run the following command to secure your installation:

   sudo mysql_secure_installation

   This command will prompt you to set the root password, remove anonymous users, disallow root login remotely, and remove the test database. You can choose 'Y' or 'N' based on your preferences and requirements.


5. Verify the installation:

   To check if MariaDB is running and to verify its version, you can use the following command:

   sudo systemctl status mariadb

   mysql --version


That's it! MariaDB is now installed and running on your CentOS 8 system. You can interact with the database using the `mysql` command-line client or other tools like phpMyAdmin if you have a web server installed.

Solved: MariaDB failed to start with error message "job for mairadb.service failed because the control process exited with error code"

Here are some steps you can follow to resolve the issue:


1. **Check for Running Processes**: As the logs indicate, another process is already using port 3306. You can verify this by running the following command:

   sudo netstat -tulnp | grep 3306


 The command will show you the process ID (PID) of the process using port 3306. Make a note of the PID.

for example,

[root@Pinrecovery ~]# sudo netstat -tulnp | grep 3306

tcp6       0      0 :::3306                 :::*                    LISTEN      110920/mysqld


Here, the process id is: 110920


2. **Stop the Conflicting Process**: Once you identify the PID of the process using port 3306, you can stop it using the `kill` command. Replace `<PID>` with the actual PID you obtained in the previous step:

   sudo kill <PID>


3. **Start MariaDB**: After stopping the conflicting process, try starting the MariaDB service again:

   sudo systemctl start mariadb


4. **Check SELinux**: If you're still having issues with starting MariaDB, ensure that SELinux is not causing any problems. Temporarily disable SELinux to see if it resolves the issue:

   sudo setenforce 0

   However, keep in mind that disabling SELinux is not recommended for security reasons. If SELinux is causing the issue, you should investigate and configure SELinux policies appropriately.


5. **Verify Configuration**: Double-check your MariaDB configuration files (`/etc/my.cnf` or `/etc/mysql/my.cnf`) for any incorrect settings. Ensure that there are no duplicate configurations or conflicts with other services.


6. **Check Hardware/Software Issues**: If the problem persists, investigate for any potential hardware or software issues on your system that might be affecting MariaDB's ability to start.


After attempting the above steps, try starting the MariaDB service again. If the issue persists, review the error messages carefully to understand the root cause, and if needed, seek further assistance from the MariaDB community or forums.

Solution for "error 1045: access denied for user 'root'@'localhost' (using password: no)"

The error message "1045: Access denied for user 'root'@'localhost' (using password: no)" indicates that you are trying to connect to the MariaDB database server as the 'root' user without providing a password, but the server is expecting one.

Here are some steps to troubleshoot and resolve the issue:

1. Check your password:

   Ensure that you are using the correct password for the 'root' user. By default, MariaDB sets an empty password for the 'root' user during installation. If you have set a password and forgotten it, you might need to reset it.


2. Provide the password in your PHP script:

   If you have set a password for the 'root' user, you need to provide it when connecting to the database using `mysqli`. Update your PHP script to include the correct password:


   <?php

   $servername = "localhost";

   $username = "root";

   $password = "your_root_password"; // Update this with the actual password

   $dbname = "your_database";


   // Create connection

   $conn = new mysqli($servername, $username, $password, $dbname);


   // Check connection

   if ($conn->connect_error) {

       die("Connection failed: " . $conn->connect_error);

   }


   echo "Connected successfully";


   // Close connection

   $conn->close();

   ?>



3. Verify MariaDB service status:

   Make sure the MariaDB service is running on your CentOS 8 system. You can check the status using the following command:

   sudo systemctl status mariadb


   If it's not running, start the service:

   sudo systemctl start mariadb


4. Check MariaDB user privileges:

   It's possible that the 'root' user does not have the necessary privileges to connect from 'localhost'. Log in to the MariaDB server as the root user:

   sudo mysql -u root


   Once logged in, check the user privileges:

   MariaDB [(none)]> SELECT user, host FROM mysql.user;

 Make sure there is an entry for 'root' user with 'localhost' as the host. If it's not there, you can add it:


   MariaDB [(none)]> CREATE USER 'root'@'localhost' IDENTIFIED BY 'your_root_password';

   MariaDB [(none)]> GRANT ALL PRIVILEGES ON *.* TO 'root'@'localhost' WITH GRANT OPTION;

   MariaDB [(none)]> FLUSH PRIVILEGES;

 

   Remember to replace `'your_root_password'` with the actual password you want to set.


5. Firewall considerations:

   Ensure that there are no firewall rules blocking the connection to the MariaDB server on localhost.

After performing these steps, try running your PHP script again. It should connect to the MariaDB server without the access denied error.


If you still encounter issues with access denied, here are a few things to check:


1. Verify the MariaDB root password:

   If you are unable to log in as the root user using the correct password, it's possible that the password is incorrect. You can try resetting the root password following these steps:


   - Stop the MariaDB service:

   sudo systemctl stop mariadb

 

   - Start the MariaDB server without permission checks:

   sudo mysqld_safe --skip-grant-tables &


   - Connect to the MariaDB server as the root user:

   mysql -u root

 

   - Update the root user's password:

   USE mysql;

   UPDATE user SET password = PASSWORD('new_password') WHERE User = 'root';

   FLUSH PRIVILEGES;


   Replace `'new_password'` with your desired new password.


   - Exit the MariaDB prompt:

   EXIT;


   - Stop the MariaDB server:

   sudo pkill mysqld_safe


   - Start the MariaDB service again:

   sudo systemctl start mariadb


2. Check for other potential login issues:

   It's possible that there are other issues causing the access denied error. For example, the 'root' user might not be allowed to connect from 'localhost'. Make sure you have the correct host specified in your PHP script (e.g., `'localhost'`).


3. Verify PHP configuration:

   Ensure that you are using the correct PHP configuration (`php.ini`) and that it is loading the `mysqli` extension properly.


Will "mysqli" extension work for MariaDB database?

Yes, `mysqli` can work with MariaDB in PHP. The `mysqli` extension stands for "MySQL Improved" and is designed to work with both MySQL and MariaDB databases. MariaDB is a fork of MySQL, so they share a lot of similarities and are largely compatible with each other.

When you use the `mysqli` extension in PHP, you can connect to both MySQL and MariaDB databases using the same functions and methods. This is because the `mysqli` extension provides an improved and more feature-rich API for accessing MySQL and MariaDB databases in PHP.

Here's a simple example of connecting to a MariaDB database using `mysqli` in PHP:


<?php

$servername = "localhost";

$username = "your_username";

$password = "your_password";

$dbname = "your_database";


// Create connection

$conn = new mysqli($servername, $username, $password, $dbname);


// Check connection

if ($conn->connect_error) {

    die("Connection failed: " . $conn->connect_error);

}


echo "Connected successfully";


// Close connection

$conn->close();

?>


Remember to replace `your_username`, `your_password`, and `your_database` with your actual database credentials.

So, whether you are working with MySQL or MariaDB, you can use `mysqli` in PHP to interact with the database effectively.

Install oci8 on centos 8

 Install oci8 on centos 8

 

Now that you have the necessary tools and libraries installed, you can proceed with the next steps to install the OCI8 extension for PHP on CentOS 8:

 

1. Install the Oracle Instant Client:

   - Download the Oracle Instant Client RPM packages for your architecture from the Oracle website (https://www.oracle.com/database/technologies/instant-client/linux-x86-64-downloads.html). You'll need  oracle-instantclient-basic ,  oracle-instantclient-devel and oracle-instantclient-sqlplus packages.

   - Transfer the downloaded RPM packages to your CentOS 8 system if you downloaded them on a different machine.

Note: for centos, it is better to download “.rpm” file rather than “.zip”

2. Install the Oracle Instant Client RPM packages:

Go to the directory where you downloaded the oracle instant-client files and install those files:

Let’s take example for version oracle instant-client 11.2,

sudo dnf install oracle-instantclient11.2-basic-11.2.0.4.0-1.x86_64.rpm  

sudo dnf install oracle-instantclient11.2-devel-11.2.0.4.0-1.x86_64

sudo dnf install oracle-instantclient11.2-sqlplus-11.2.0.4.0-1.x86_64

To verify whether the Oracle Instant Client "devel" package is installed on your CentOS system, you can use the package management tool rpm or dnf. Here's how you can check for the presence of the Oracle Instant Client devel package:

Using ‘rpm’:

rpm -qa | grep oracle-instantclient-devel

Using ‘dnf’:

dnf list installed | grep oracle-instantclient-devel

 

3. Verify the ORACLE_HOME environment variable:

echo $ORACLE_HOME

Ensure that the ORACLE_HOME environment variable is set correctly and points to the location where you installed the Oracle Instant Client. If it's not set correctly, you can set it as follows:

export ORACLE_HOME=/path/to/instant/client

During the installation process, you may be prompted to provide the path to the Oracle Instant Client library. If prompted, enter the correct path:

Enter the path: instantclient,/usr/lib/oracle/19.20/client64/lib

 

 

 

4. Set the environment variables required for OCI8 and PHP:

 

echo 'export ORACLE_HOME=/usr/lib/oracle/19.12/client64' | sudo tee -a /etc/profile.d/oracle.sh

echo 'export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/usr/lib/oracle/19.12/client64/lib' | sudo tee -a /etc/profile.d/oracle.sh

sudo ldconfig

Once you are done with above steps, the environment is set for oci8 installation, follow the bellows steps now,

5. Stop Apache and uninstall older version of OCI8 if any (stopping Apache is very important):

 service httpd stop

 pecl uninstall oci8

 

6. Install php-pear and php devel:

 sudo yum install php-pear php-devel

 pear download pecl/oci8

7. The next commands depend on the version of oci8 downloaded above.

$ tar xvzf oci8-2.2.0.tgz

$ cd oci8-2.2.0/

$ phpize

$ export PHP_DTRACE=yes

 

 

8. Make sure of the instantclient path below... mine was version 11.2 so it was located in this folder... Also make note some tutorials ask for the ORACLE_HOME folder which theoretically is /usr/lib/oracle/11.2/client64 but if its instantclient then put the lib folder underneath it (worked for me at least:)

$ ./configure --with-oci8=instantclient,/usr/lib/oracle/12.2/client64/lib/

$ make

$ make install

 

9. NOW an .so file built in: /usr/lib64/php/modules/oci8.so

10. check whether oci8 has been successfully installed or not:

php -m | grep oci8

11. sudo service httpd restart

The steps may not be needed in most of the cases. If indeed, it is required in your case go through these steps as well (though it is suggested to first try running before implementing the below steps):

# THIS STEP NOT NEEDED if SELinux disabled on your server/box, but if SELinux is enabled run: setsebool -P httpd_execmem 1

# NOW add:   extension=oci8.so    at the bottom of your php.ini file (probably in /etc/php.ini)

# Add extension_dir=/usr/lib64/php/modules/

Tuesday, July 25, 2023

What is Archive logs in Oracle database?

An archive log is a term commonly used in the context of database management systems, particularly with relation to Oracle Database.


In a database system, the archive log refers to a copy of a redo log file that has been filled with data and then archived (backed up) to a storage location, such as a separate disk or tape. The redo log files store a record of changes made to the database, and these changes are essential for recovering the database in the event of a failure or for performing certain types of backups (e.g., hot backups).


Here's a brief overview of how archive logs work in Oracle Database:


1. Redo Log Files: When changes are made to the database, they are first written to the redo log files in a circular fashion. These files are crucial for maintaining a record of all transactions that modify the database.


2. Log Switch: Once a redo log file is filled with data, a log switch occurs, and the database starts writing to a new redo log file. The filled redo log file is now ready for archiving.


3. Archiving: The filled redo log file is copied (archived) to a separate location known as the archive log destination. This process ensures that a copy of the redo log is preserved even after a log switch, which helps in data recovery and backup operations.


4. Backup and Recovery: By regularly archiving the redo logs, database administrators can use them to recover the database to a specific point in time in case of a system failure or data corruption. Additionally, archive logs are necessary for performing consistent backups while the database remains operational (hot backups).


It's essential to manage archive logs properly to avoid running out of disk space and to ensure database recoverability. Administrators often set up proper archiving policies and regularly back up archived logs to free up space and safeguard critical data.

Saturday, June 3, 2023

Differences between Datafile and Tablespace



 

Datafile

Tablespace

Definition

Physical file used by the DBMS to store data

Logical storage container within a database

Purpose

Stores actual data, indexes, and other database objects

Provides a logical organization and management structure for storing and accessing data

Location

Resides on a storage device (e.g., hard drive, SAN)

Exists within the database

Managed by

Operating system

Database management system

Unit of storage

Individual file

Collection of one or more datafiles

Allocation

Datafiles are allocated to tablespaces

Tables, indexes, and other database objects are allocated space within tablespaces

Administrative control

File-level management

Logical-level management

Separation

Represents physical storage

Provides a logical grouping of data

Usage

Accessed by the DBMS for reading and writing data

Used by the DBMS to organize and manage data