Info:
su means, switch user or substitute user
sudo means, super user do
to use sudo command, related user must be defined in sudoers file
$ su -
(switch user to root then executes all /etc/profile, .profile and .bashrc files by root)
$ su
(switch user to root user then executes only .bashrc file by root)
$ sudo su -
(switch user to root then executes all /etc/profile, .profile and .bashrc files by root if current user defined in sudoers file)
$ sudo su
(switch user to root then executes only .bashrc file by root if current user defined in sudoers file)
Ref: https://ozsoyler.blogspot.com/2016/09/how-to-gain-root-access-without_15.html
Wednesday, 19 December 2018
Thursday, 1 November 2018
How to change timezone?
-> Determine your timezone
# cd /usr/share/zoneinfo
# tzselect
e.g.
Europe/Istanbul
-> Remove current localtime soft link
# rm /etc/localtime
-> Define your localtime soft link as new
# ln -s /usr/share/zoneinfo/Europe/Istanbul /etc/localtime
-> Check your latest timezone setting
# timedatectl
# cd /usr/share/zoneinfo
# tzselect
e.g.
Europe/Istanbul
-> Remove current localtime soft link
# rm /etc/localtime
-> Define your localtime soft link as new
# ln -s /usr/share/zoneinfo/Europe/Istanbul /etc/localtime
-> Check your latest timezone setting
# timedatectl
Wednesday, 31 October 2018
How to connect into local VM via SSH?
* Set a new Port Forwarding Rule in Network Settings
Step 1: Settings -> Network -> Adapter 1 -> Advanced -> Adapter Type -> "Paravirtualized network adapter (virtio-net)" -> OK
Step 2: Settings -> Network -> Adapter 1 -> Advanced -> Keep it as "NAT" -> Click "Port Forwarding" -> Define a Rule -> OK
e.g.
Name Protocol Host Port Guest Port
SSH TCP 1022 22
SSH Connection Host/Port Settings:
Host: 127.0.0.1
Port: 1022
Step 1: Settings -> Network -> Adapter 1 -> Advanced -> Adapter Type -> "Paravirtualized network adapter (virtio-net)" -> OK
Step 2: Settings -> Network -> Adapter 1 -> Advanced -> Keep it as "NAT" -> Click "Port Forwarding" -> Define a Rule -> OK
e.g.
Name Protocol Host Port Guest Port
SSH TCP 1022 22
SSH Connection Host/Port Settings:
Host: 127.0.0.1
Port: 1022
Labels:
linux,
oracle virtual box,
ssh,
virtual machine,
vm
WSREP "Failed to open channel" solution
Error
ERROR WSREP "Failed to open channel 'my_mariadb_cluster'"
Detailed Error
WSREP: gcs/src/gcs.cpp:gcs_open():1458: Failed to open channel 'my_mariadb_cluster' at 'gcomm://10.10.10.10,10.10.10.11': -110 (Connection timed out)
Solution
On the first node: (e.g. node-1)
-> Stop mariadb service if it hangs
# systemctl stop mariadb.service
-> Make sure "safe_to_bootstrap" value is "1"
# cat /var/lib/mysql/grastate.dat
safe_to_bootstrap: 1
-> Run following command for starting cluster as new
# galera_new_cluster
-> mariadb service should be started automatically
# systemctl status mariadb.service
-> note wsrep_last_committed number by looking system table
# mysql -u root -p
> show status like 'wsrep_%';
-> note uuid number
# cat /var/lib/mysql/grastate.dat
On the second node: (e.g. node-2)
-> Stop mariadb service if it hangs
# systemctl stop mariadb.service
-> uuid and seqno (wsrep_last_committed) should be same with node-1
# vi /var/lib/mysql/grastate.dat
uuid: 0000
seqno: 100
-> start mariadb service
# systemctl start mariadb.service
ERROR WSREP "Failed to open channel 'my_mariadb_cluster'"
Detailed Error
WSREP: gcs/src/gcs.cpp:gcs_open():1458: Failed to open channel 'my_mariadb_cluster' at 'gcomm://10.10.10.10,10.10.10.11': -110 (Connection timed out)
Solution
On the first node: (e.g. node-1)
-> Stop mariadb service if it hangs
# systemctl stop mariadb.service
-> Make sure "safe_to_bootstrap" value is "1"
# cat /var/lib/mysql/grastate.dat
safe_to_bootstrap: 1
-> Run following command for starting cluster as new
# galera_new_cluster
-> mariadb service should be started automatically
# systemctl status mariadb.service
-> note wsrep_last_committed number by looking system table
# mysql -u root -p
> show status like 'wsrep_%';
-> note uuid number
# cat /var/lib/mysql/grastate.dat
On the second node: (e.g. node-2)
-> Stop mariadb service if it hangs
# systemctl stop mariadb.service
-> uuid and seqno (wsrep_last_committed) should be same with node-1
# vi /var/lib/mysql/grastate.dat
uuid: 0000
seqno: 100
-> start mariadb service
# systemctl start mariadb.service
Labels:
galera cluster,
mariadb,
WSREP
Monday, 8 October 2018
How to find/follow postgresql server logs?
-> Check log level from config file
# cat /var/lib/pgsql/data/postgresql.conf
e.g.
log_min_messages= 'ERROR' (default value)
(options; DEBUG5, DEBUG4, DEBUG3, DEBUG2, DEBUG1, INFO, NOTICE, WARNING, ERROR, LOG, FATAL, and PANIC)
-> Determine log directory name (via postgres user)
$ psql
postgres=# show log_directory;
e.g. pg_log
-> Determine data directory name (via postgres user)
$ psql
postgres=# show data_directory;
e.g. /var/lib/pgsql/data
-> Determine log file name (via postgres user)
$ psql
postgres=# show log_filename;
e.g. postgresql-%a.log (%a will be "day" of the week)
e.g. postgresql-%a-%H.log (%H will be "hour" of the day)
-> Check log rotation age of the log files
postgres=# show log_rotation_age;
e.g. 1d (1d means one day)
* The database system generate log files daily
e.g. 1h (1h means one hour)
* The database system generate log files hourly
Eventually, the log path could be like this;
e.g.
# ls /var/lib/pgsql/data/pg_log/postgresql-Mon.log
# ls /var/lib/pgsql/data/pg_log/postgresql-Mon-07.log
-> To follow the logs by tail
e.g.
# tail -100f /var/lib/pgsql/data/pg_log/postgresql-Mon.log
# tail -100f /var/lib/pgsql/data/pg_log/postgresql-Mon-07.log
Ref: https://www.postgresql.org/docs/9.5/static/runtime-config-logging.html
# cat /var/lib/pgsql/data/postgresql.conf
e.g.
log_min_messages= 'ERROR' (default value)
(options; DEBUG5, DEBUG4, DEBUG3, DEBUG2, DEBUG1, INFO, NOTICE, WARNING, ERROR, LOG, FATAL, and PANIC)
-> Determine log directory name (via postgres user)
$ psql
postgres=# show log_directory;
e.g. pg_log
-> Determine data directory name (via postgres user)
$ psql
postgres=# show data_directory;
e.g. /var/lib/pgsql/data
-> Determine log file name (via postgres user)
$ psql
postgres=# show log_filename;
e.g. postgresql-%a.log (%a will be "day" of the week)
e.g. postgresql-%a-%H.log (%H will be "hour" of the day)
-> Check log rotation age of the log files
postgres=# show log_rotation_age;
e.g. 1d (1d means one day)
* The database system generate log files daily
e.g. 1h (1h means one hour)
* The database system generate log files hourly
e.g.
# ls /var/lib/pgsql/data/pg_log/postgresql-Mon.log
# ls /var/lib/pgsql/data/pg_log/postgresql-Mon-07.log
-> To follow the logs by tail
e.g.
# tail -100f /var/lib/pgsql/data/pg_log/postgresql-Mon.log
# tail -100f /var/lib/pgsql/data/pg_log/postgresql-Mon-07.log
Ref: https://www.postgresql.org/docs/9.5/static/runtime-config-logging.html
Labels:
database,
log,
postgresql
Thursday, 4 October 2018
How to setup/configure/use mailx for Office365 account?
-> Update the OS
# yum -y update
or (y -> yes)
# yum update
-> Install mailx
# yum install -y mailx
-> Define soft link to use "email" the command
# ln -s /bin/mailx /bin/email
-> Prepare config file
# vi /etc/mail.rc
set smtp=outlook.office365.com
set smtp-auth-user=alper@alper.com
set smtp-auth-password=alper123
set ssl-verify=ignore
set nss-config-dir=/etc/pki/nssdb/
set smtp-use-starttls
set from="alper@alper.com(Alper Ozsoyler)"
-> Try to send an email to yourself
# echo "Your message is my message!" | email -v -s "Message Subject is Bla Bla" alper@alper.com
Ref: https://gist.github.com/ilkereroglu/aa6c868153d1c5d57cd8
# yum -y update
or (y -> yes)
# yum update
-> Install mailx
# yum install -y mailx
-> Define soft link to use "email" the command
# ln -s /bin/mailx /bin/email
-> Prepare config file
# vi /etc/mail.rc
set smtp=outlook.office365.com
set smtp-auth-user=alper@alper.com
set smtp-auth-password=alper123
set ssl-verify=ignore
set nss-config-dir=/etc/pki/nssdb/
set smtp-use-starttls
set from="alper@alper.com(Alper Ozsoyler)"
-> Try to send an email to yourself
# echo "Your message is my message!" | email -v -s "Message Subject is Bla Bla" alper@alper.com
Ref: https://gist.github.com/ilkereroglu/aa6c868153d1c5d57cd8
How to solve "restarting/pending pod repeatedly" problem?
-> Check the pods status
e.g.
# kubectl get pods --all-namespaces
NAMESPACE NAME READY STATUS
kube-system coredns-78fcdf6894-6ggkk 0/1 Pending
kube-system coredns-78fcdf6894-tm52r 0/1 Pending
-> Check the deployments
# kubectl get deployment --all-namespaces
NAMESPACE NAME DESIRED CURRENT UP-TO-DATE AVAILABLE
kube-system coredns 2 2 2 0
-> Needs to remove the deployments related to pod and service
e.g.
# kubectl delete deployment coredns -n kube-system
deployment.extensions "coredns" deleted
e.g.
# kubectl get pods --all-namespaces
NAMESPACE NAME READY STATUS
kube-system coredns-78fcdf6894-6ggkk 0/1 Pending
kube-system coredns-78fcdf6894-tm52r 0/1 Pending
-> Check the deployments
# kubectl get deployment --all-namespaces
NAMESPACE NAME DESIRED CURRENT UP-TO-DATE AVAILABLE
kube-system coredns 2 2 2 0
-> Needs to remove the deployments related to pod and service
e.g.
# kubectl delete deployment coredns -n kube-system
deployment.extensions "coredns" deleted
Labels:
deployment,
kubernetes,
linux,
pod
Tuesday, 2 October 2018
How to enable Hyper-V in Windows 10?
Press Windows key -> Type "Turn Windows features on or off" then click it -> Select "Hyper-V" check box then click "OK" -> Restart PC -> Done!
Labels:
hyper-v,
windows,
windows 10
Tuesday, 18 September 2018
How to install/configure/enable NTP service?
-> Install ntp service
# yum install ntp
-> Once NTP server pool zones are taking
e.g. check from https://www.pool.ntp.org/zone/europe
-> Add specific pool zones into config file if they are not existed
# vi /etc/ntp.conf
server 0.europe.pool.ntp.org
-> Enable service
# systemctl enable ntpd
-> Run service
# systemctl start ntpd
-> Lastly, check the service and the settings
# yum install ntp
e.g. check from https://www.pool.ntp.org/zone/europe
-> Add specific pool zones into config file if they are not existed
# vi /etc/ntp.conf
server 0.europe.pool.ntp.org
-> Enable service
# systemctl enable ntpd
-> Run service
# systemctl start ntpd
-> Lastly, check the service and the settings
# timedatectl
Thursday, 9 August 2018
How to check linux operating system info?
-> show kernel version and other info
# uname -a
-> show machine info
# hostnamectl
-> show specific release version
# rpm --query centos-release
# uname -a
-> show machine info
# hostnamectl
-> show specific release version
# rpm --query centos-release
How to check available yum packages?
e.g. install/update ansible by yum
-> Go to repo path
# cd /etc/yum.repos.d/
-> Add source paths into repo file to be able to install ansible
# vi epel.repo
[epel]
name=Extra Packages for Enterprise Linux 7 - $basearch
#baseurl=http://download.fedoraproject.org/pub/epel/7/$basearch
metalink=https://mirrors.fedoraproject.org/metalink?repo=epel-7&arch=$basearch
failovermethod=priority
enabled=1
gpgcheck=1
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-EPEL-7
[epel-debuginfo]
name=Extra Packages for Enterprise Linux 7 - $basearch - Debug
#baseurl=http://download.fedoraproject.org/pub/epel/7/$basearch/debug
metalink=https://mirrors.fedoraproject.org/metalink?repo=epel-debug-7&arch=$basearch
failovermethod=priority
enabled=0
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-EPEL-7
gpgcheck=1
[epel-source]
name=Extra Packages for Enterprise Linux 7 - $basearch - Source
#baseurl=http://download.fedoraproject.org/pub/epel/7/SRPMS
metalink=https://mirrors.fedoraproject.org/metalink?repo=epel-source-7&arch=$basearch
failovermethod=priority
enabled=0
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-EPEL-7
gpgcheck=1
-> Search yum package
# yum search ansible
-> Check available yum package
# yum list available | grep ansible
-> Check available all yum packages with its duplicates
# yum list available --showduplicates | grep ansible
-> Install ansible
# yum install ansible
-> Download only yum package
# yum install ansible --downloadonly --downloaddir=/root
-> Check available yum packages for upgrade
# yum check-updates | grep ansible
-> Update ansible
# yum update ansible
-> Check yum history
# yum history list
-> Go to repo path
# cd /etc/yum.repos.d/
-> Add source paths into repo file to be able to install ansible
# vi epel.repo
[epel]
name=Extra Packages for Enterprise Linux 7 - $basearch
#baseurl=http://download.fedoraproject.org/pub/epel/7/$basearch
metalink=https://mirrors.fedoraproject.org/metalink?repo=epel-7&arch=$basearch
failovermethod=priority
enabled=1
gpgcheck=1
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-EPEL-7
[epel-debuginfo]
name=Extra Packages for Enterprise Linux 7 - $basearch - Debug
#baseurl=http://download.fedoraproject.org/pub/epel/7/$basearch/debug
metalink=https://mirrors.fedoraproject.org/metalink?repo=epel-debug-7&arch=$basearch
failovermethod=priority
enabled=0
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-EPEL-7
gpgcheck=1
[epel-source]
name=Extra Packages for Enterprise Linux 7 - $basearch - Source
#baseurl=http://download.fedoraproject.org/pub/epel/7/SRPMS
metalink=https://mirrors.fedoraproject.org/metalink?repo=epel-source-7&arch=$basearch
failovermethod=priority
enabled=0
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-EPEL-7
gpgcheck=1
-> Search yum package
# yum search ansible
-> Check available yum package
# yum list available | grep ansible
-> Check available all yum packages with its duplicates
# yum list available --showduplicates | grep ansible
# yum install ansible
-> Download only yum package
# yum install ansible --downloadonly --downloaddir=/root
-> Check available yum packages for upgrade
# yum check-updates | grep ansible
-> Update ansible
# yum update ansible
-> Check yum history
# yum history list
How to install/configure/run ansible?
-> Set hostname
# hostnamectl set-hostname ansible_host
-> Add remote hosts into /etc/hosts file
# vi /etc/hosts
10.10.10.2 remote_host_2
10.10.10.3 remote_host_3
-> Generate ssh key without passphase
# ssh-keygen
-> Install ssh key into remote servers
# ssh-copy-id remote_host_2
# ssh-copy-id remote_host_3
-> Install ansible rpm packages
# yum install ansible
-> Add remote hosts as nodes into /etc/ansible/hosts file
# vi /etc/ansible/hosts
[remote_hosts]
remote_host_2
remote_host_3
-> Prepare an ansible playbook in /etc/ansible/
# vi my_very_first_playbook.yml
# example playbook
- name: Run the role for me
hosts: remote_hosts
roles:
- example-role
-> Prepare a role for the playbook in /etc/ansible/roles/example-role/
# vi main.yml
- name: checking Command Scheduler service
service:
name=crond.service
state=started
-> Run the playbook in /etc/ansible/
# ansible-playbook my_very_first_playbook.yml
or
# ansible-playbook -i hosts my_very_first_playbook.yml
(i -> inventory, its default location is /etc/ansible/hosts)
-> To check the ansible logs
# tail -f /var/log/ansible.log
# hostnamectl set-hostname ansible_host
-> Add remote hosts into /etc/hosts file
# vi /etc/hosts
10.10.10.2 remote_host_2
10.10.10.3 remote_host_3
-> Generate ssh key without passphase
# ssh-keygen
-> Install ssh key into remote servers
# ssh-copy-id remote_host_2
# ssh-copy-id remote_host_3
-> Install ansible rpm packages
# yum install ansible
-> Add remote hosts as nodes into /etc/ansible/hosts file
# vi /etc/ansible/hosts
[remote_hosts]
remote_host_2
remote_host_3
-> Prepare an ansible playbook in /etc/ansible/
# vi my_very_first_playbook.yml
# example playbook
- name: Run the role for me
hosts: remote_hosts
roles:
- example-role
-> Prepare a role for the playbook in /etc/ansible/roles/example-role/
# vi main.yml
- name: checking Command Scheduler service
service:
name=crond.service
state=started
-> Run the playbook in /etc/ansible/
# ansible-playbook my_very_first_playbook.yml
or
# ansible-playbook -i hosts my_very_first_playbook.yml
(i -> inventory, its default location is /etc/ansible/hosts)
-> To check the ansible logs
# tail -f /var/log/ansible.log
Labels:
ansible,
installation,
log
Tuesday, 7 August 2018
usage of "run_once: true" option
If you want to run only once a specific task during all playbook execution, you may add "run_once: true" option into your task to do this.
e.g. example task
- name: prompt for directory name
run_once: true
pause:
prompt: "Please enter directory name: "
register: input_dir_name
- name: show input
debug:
msg="{{ input_dir_name.user_input }}"
e.g. example task
- name: prompt for directory name
run_once: true
pause:
prompt: "Please enter directory name: "
register: input_dir_name
- name: show input
debug:
msg="{{ input_dir_name.user_input }}"
Monday, 30 July 2018
How to know last login info on the system?
-> show all records
$ last
-> show all records page by page
$ last | more
-> show first 10 records
$ last | head
-> show first 100 records
$ last | head -100
-> show last 10 records
$ last | tail -10
-> show last 100 records
$ last | tail -100
$ last
-> show all records page by page
$ last | more
-> show first 10 records
$ last | head
-> show first 100 records
$ last | head -100
-> show last 10 records
$ last | tail -10
-> show last 100 records
$ last | tail -100
Wednesday, 18 July 2018
How to change service name?
e.g.
current service name: postgresql.service
desired service name: postgresql-9.1.service
Run following commands to change service name;
Step 1: Stop current service
# systemctl stop postgresql.service
# systemctl daemon-reload
Step 2: Change service name
# cd /usr/lib/systemd/system
# mv postgresql.service postgresql-9.1.service
Step 3: Start and enable new service
# systemctl start postgresql-9.1.service
# systemctl enable postgresql-9.1.service
Step 4: Check service status:
# systemctl status postgresql-9.1.service
Step 5: Make sure that service runs properly
# journalctl -u postgresql-9.1.service
current service name: postgresql.service
desired service name: postgresql-9.1.service
Run following commands to change service name;
Step 1: Stop current service
# systemctl stop postgresql.service
# systemctl daemon-reload
Step 2: Change service name
# cd /usr/lib/systemd/system
# mv postgresql.service postgresql-9.1.service
Step 3: Start and enable new service
# systemctl start postgresql-9.1.service
# systemctl enable postgresql-9.1.service
Step 4: Check service status:
# systemctl status postgresql-9.1.service
Step 5: Make sure that service runs properly
# journalctl -u postgresql-9.1.service
Labels:
centos,
journal,
linux,
postgresql
Friday, 13 July 2018
How to solve remote connection error cause of iptables/firewalld service?
Case
Machine A(192.168.1.2) wants to connect on Machine B(192.168.1.5) by database port.
Action
In Machine A;
# su - postgres
$ psql -h 192.168.1.5 -d alper -U alper -p 5433
Error
psql: could not connect to server: No route to host
Is the server running on host "192.168.1.5" and accepting
TCP/IP connections on port 5433?
Solution
In Machine B;
For iptables service:
# iptables -I INPUT -p tcp --dport 5433 -j ACCEPT
# iptables-save
For firewalld service:
# firewall-cmd --zone=public --add-port=5433/tcp --permanent
Machine A(192.168.1.2) wants to connect on Machine B(192.168.1.5) by database port.
Action
In Machine A;
# su - postgres
$ psql -h 192.168.1.5 -d alper -U alper -p 5433
Error
psql: could not connect to server: No route to host
Is the server running on host "192.168.1.5" and accepting
TCP/IP connections on port 5433?
Solution
In Machine B;
For iptables service:
# iptables -I INPUT -p tcp --dport 5433 -j ACCEPT
# iptables-save
For firewalld service:
# firewall-cmd --zone=public --add-port=5433/tcp --permanent
# firewall-cmd --reload
Check
In Machine A;
In Machine A;
# nc -vz 192.168.1.5 5433
Ncat: Connected to 192.168.1.5:5433
How to solve database module error?
Action
# ansible-playbook -i myhosts example.yml -v
Error
TASK [example role : example task] *******************
fatal: [local]: FAILED! => {"changed": false, "msg": "The MySQL-python module is required."}
Solution
# yum install MySQL-python
The other solutions related to database tasks:
# yum install python-redis (Redisdb)
# yum install python-psycopg2 (PostgreSQL)
Check it for up to date list of database modules:
https://docs.ansible.com/ansible/latest/modules/list_of_database_modules.html
# ansible-playbook -i myhosts example.yml -v
Error
TASK [example role : example task] *******************
fatal: [local]: FAILED! => {"changed": false, "msg": "The MySQL-python module is required."}
Solution
# yum install MySQL-python
The other solutions related to database tasks:
# yum install python-redis (Redisdb)
# yum install python-psycopg2 (PostgreSQL)
Check it for up to date list of database modules:
https://docs.ansible.com/ansible/latest/modules/list_of_database_modules.html
Friday, 6 July 2018
How to prevent sleep mode on laptop when lid closes?
Press Window Key then type "Power Options" and click on it -> Click "Choose what closing the lid does" -> Set "When I close the lid" to "Do nothing" -> Click "Save changes" -> Done!
Labels:
laptop,
sleep mode,
windows,
windows 10
Friday, 29 June 2018
How to run a SQL query/statement in a task?
You are able to run a SQL query/statement with "echo" command by shell module for the ansible task.
# an example task for sql query/statement
- name: set default schema for user
shell: echo "ALTER ROLE alper SET SEARCH_PATH TO myschema" | psql
become: yes
become_user: postgres
# an example task for sql query/statement
- name: set default schema for user
shell: echo "ALTER ROLE alper SET SEARCH_PATH TO myschema" | psql
become: yes
become_user: postgres
Labels:
ansible,
postgresql,
role,
schema
benefit of "gather_facts: no" setting
If you do not need any facts for your variables, you can run your playbook more fast via gather_facts setting.
For this, just add following setting in your playbook:
# example playbook
- name: Run the role for me
hosts: my_nodes
gather_facts: no
roles:
- example-role
For this, just add following setting in your playbook:
# example playbook
- name: Run the role for me
hosts: my_nodes
gather_facts: no
roles:
- example-role
Labels:
ansible,
gather_facts
Friday, 18 May 2018
"database "example" is being accessed by other users" solution
Action
postgres=# drop database example;
Error
ERROR: database "example" is being accessed by other users
DETAIL: There is 1 other session using the database.
Solution
Run following sql code;
postgres=#
SELECT pg_terminate_backend(pg_stat_activity.pid) FROM pg_stat_activity WHERE pg_stat_activity.datname = 'example' AND pid <> pg_backend_pid();
All sessions should be terminated where belong to "example" database except backend sessions.
Lastly, try to drop it again.
postgres=# drop database example;
Error
ERROR: database "example" is being accessed by other users
DETAIL: There is 1 other session using the database.
Solution
Run following sql code;
postgres=#
SELECT pg_terminate_backend(pg_stat_activity.pid) FROM pg_stat_activity WHERE pg_stat_activity.datname = 'example' AND pid <> pg_backend_pid();
All sessions should be terminated where belong to "example" database except backend sessions.
Lastly, try to drop it again.
Labels:
error,
postgresql
Sunday, 6 May 2018
How to backup database in XE?
It is very simple to backup your database in Oracle XE with already prepared .bat file quickly.
Steps;
Press Windows Key -> Type "Backup Database" -> Click "Backup Database" link -> .bat file "Backup.bat" runs -> Follow the steps -> Done
Finally, check the backup path;
...\oracle\fast_recovery_area\XE
Steps;
Press Windows Key -> Type "Backup Database" -> Click "Backup Database" link -> .bat file "Backup.bat" runs -> Follow the steps -> Done
Finally, check the backup path;
...\oracle\fast_recovery_area\XE
Friday, 27 April 2018
e.g. truncate table cascade
Preparation of Test Data
test=#
create table employees (id integer, name varchar, department_id integer);
test=#
create table departments (id int, department_name varchar);
test=#
ALTER TABLE DEPARTMENTS
ADD CONSTRAINT DEPT_PK
PRIMARY KEY (ID);
test=#
ALTER TABLE EMPLOYEES
ADD CONSTRAINT EMP_DEPT_FK
FOREIGN KEY (DEPARTMENT_ID)
REFERENCES DEPARTMENTS(ID);
test=#
insert into departments
values (1,'IT');
test=#
insert into departments
values (2,'Sales');
test=#
insert into departments
values (3,'Marketing');
test=#
insert into employees
values (1,'John',1);
test=#
insert into employees
values (2,'Alex',1);
test=#
insert into employees
values (3,'Guru',2);
test=#
insert into employees
values (4,'Maximus',3);
test=#
commit;
Data Check
-- select all rows of parent table
test=#
select * from departments;
-- select all rows of child table
test=#
select * from employees;
Action
-- by using truncate table cascade, parent table and child table data will be removed.
test=#
truncate table departments cascade;
Last Data Check
-- select all rows of parent table
test=#
select * from departments;
-- select all rows of child table
test=#
select * from employees;
Info: In Oracle 12c, you are able to use "cascade" clause with "truncate table" statement as well.
test=#
create table employees (id integer, name varchar, department_id integer);
test=#
create table departments (id int, department_name varchar);
test=#
ALTER TABLE DEPARTMENTS
ADD CONSTRAINT DEPT_PK
PRIMARY KEY (ID);
test=#
ALTER TABLE EMPLOYEES
ADD CONSTRAINT EMP_DEPT_FK
FOREIGN KEY (DEPARTMENT_ID)
REFERENCES DEPARTMENTS(ID);
test=#
insert into departments
values (1,'IT');
test=#
insert into departments
values (2,'Sales');
test=#
insert into departments
values (3,'Marketing');
test=#
insert into employees
values (1,'John',1);
test=#
insert into employees
values (2,'Alex',1);
test=#
insert into employees
values (3,'Guru',2);
test=#
insert into employees
values (4,'Maximus',3);
test=#
commit;
Data Check
-- select all rows of parent table
test=#
select * from departments;
-- select all rows of child table
test=#
select * from employees;
Action
-- by using truncate table cascade, parent table and child table data will be removed.
test=#
truncate table departments cascade;
Last Data Check
-- select all rows of parent table
test=#
select * from departments;
-- select all rows of child table
test=#
select * from employees;
Info: In Oracle 12c, you are able to use "cascade" clause with "truncate table" statement as well.
Labels:
oracle,
postgresql,
truncate table cascade
Thursday, 26 April 2018
e.g. fetching JSON data
Preparation of Test Data
test=#
create table T_JSON_DATA (id INTEGER, body JSON);
test=#
insert into T_JSON_DATA
values (1, '{ "name":"John", "age":30, "city":"New York" }');
test=#
insert into T_JSON_DATA
values (2, '{ "name":"Alex", "age":25, "city":"China" }');
test=#
insert into T_JSON_DATA
values (3, '{ "name":"Guru", "age":21, "city":"Russia" }');
test=#
insert into T_JSON_DATA
values (4, '{ "name":"Maximus", "age":25, "city":"Somewhere" }');
test=# commit;
Examples for populating test data
test=#
select * from T_JSON_DATA;
-- to retrieve specific field data
test=#
select body->>'name' from T_JSON_DATA;
-- with aliases
test=#
select body->'name' AS NAME, body->'city' AS CITY from T_JSON_DATA;
-- use with where clause
test=#
select body->'name' AS NAME, body->'city' AS CITY from T_JSON_DATA where id = 1;
test=#
create table T_JSON_DATA (id INTEGER, body JSON);
test=#
insert into T_JSON_DATA
values (1, '{ "name":"John", "age":30, "city":"New York" }');
test=#
insert into T_JSON_DATA
values (2, '{ "name":"Alex", "age":25, "city":"China" }');
test=#
insert into T_JSON_DATA
values (3, '{ "name":"Guru", "age":21, "city":"Russia" }');
test=#
insert into T_JSON_DATA
values (4, '{ "name":"Maximus", "age":25, "city":"Somewhere" }');
test=# commit;
Examples for populating test data
test=#
select * from T_JSON_DATA;
-- to retrieve specific field data
test=#
select body->>'name' from T_JSON_DATA;
-- with aliases
test=#
select body->'name' AS NAME, body->'city' AS CITY from T_JSON_DATA;
-- use with where clause
test=#
select body->'name' AS NAME, body->'city' AS CITY from T_JSON_DATA where id = 1;
Labels:
json,
postgresql
Wednesday, 25 April 2018
ORA-02292 solution
Preparation
-- Insert test data into DEPARTMENT and EMPLOYEES tables.
SQL>
INSERT INTO DEPARTMENTS
VALUES (280,'New Department',100,1700);
SQL>
INSERT INTO EMPLOYEES
VALUES (207,'John','Mathew','JMATHEW','111.111.111',TO_DATE('25.04.2018','DD.MM.YYYY'),'IT_PROG',10000,0.5,100,280);
SQL>
INSERT INTO EMPLOYEES
VALUES (208,'Jim','Parker','JPARKER','111.111.111',TO_DATE('25.05.2018','DD.MM.YYYY'),'IT_PROG',20000,0.6,100,280);
SQL>
INSERT INTO EMPLOYEES
VALUES (209,'Sophia','Ran','SRAN','111.111.111',TO_DATE('25.06.2018','DD.MM.YYYY'),'IT_PROG',30000,0.7,100,280);
SQL>
INSERT INTO EMPLOYEES
VALUES (210,'Wendi','Blake','WBLAKE','111.111.111',TO_DATE('25.07.2018','DD.MM.YYYY'),'IT_PROG',40000,0.8,100,280);
SQL>
COMMIT;
Action
SQL>
DELETE FROM DEPARTMENTS
WHERE DEPARTMENT_ID = 280;
Error
ORA-02292: integrity constraint (HR.EMP_DEPT_FK) violated - child record found
Solution
-- Find referencial integrity constraint between DEPARTMENT and EMPLOYEES tables for this error.
SQL>
SELECT *
FROM ALL_CONSTRAINTS
WHERE TABLE_NAME IN ('EMPLOYEES', 'DEPARTMENTS') AND CONSTRAINT_TYPE = 'R';
-- Drop constraint
SQL>
ALTER TABLE EMPLOYEES DROP CONSTRAINT EMP_DEPT_FK;
-- Re-define constraint with "ON DELETE CASCADE" option
SQL>
ALTER TABLE EMPLOYEES
ADD CONSTRAINT EMP_DEPT_FK
FOREIGN KEY (DEPARTMENT_ID)
REFERENCES DEPARTMENTS(DEPARTMENT_ID)
ON DELETE CASCADE;
-- Try again
SQL>
DELETE FROM DEPARTMENTS
WHERE DEPARTMENT_ID = 280;
SQL>
COMMIT;
-- Insert test data into DEPARTMENT and EMPLOYEES tables.
SQL>
INSERT INTO DEPARTMENTS
VALUES (280,'New Department',100,1700);
SQL>
INSERT INTO EMPLOYEES
VALUES (207,'John','Mathew','JMATHEW','111.111.111',TO_DATE('25.04.2018','DD.MM.YYYY'),'IT_PROG',10000,0.5,100,280);
SQL>
INSERT INTO EMPLOYEES
VALUES (208,'Jim','Parker','JPARKER','111.111.111',TO_DATE('25.05.2018','DD.MM.YYYY'),'IT_PROG',20000,0.6,100,280);
SQL>
INSERT INTO EMPLOYEES
VALUES (209,'Sophia','Ran','SRAN','111.111.111',TO_DATE('25.06.2018','DD.MM.YYYY'),'IT_PROG',30000,0.7,100,280);
SQL>
INSERT INTO EMPLOYEES
VALUES (210,'Wendi','Blake','WBLAKE','111.111.111',TO_DATE('25.07.2018','DD.MM.YYYY'),'IT_PROG',40000,0.8,100,280);
SQL>
COMMIT;
Action
SQL>
DELETE FROM DEPARTMENTS
WHERE DEPARTMENT_ID = 280;
Error
ORA-02292: integrity constraint (HR.EMP_DEPT_FK) violated - child record found
Solution
-- Find referencial integrity constraint between DEPARTMENT and EMPLOYEES tables for this error.
SQL>
SELECT *
FROM ALL_CONSTRAINTS
WHERE TABLE_NAME IN ('EMPLOYEES', 'DEPARTMENTS') AND CONSTRAINT_TYPE = 'R';
-- Drop constraint
SQL>
ALTER TABLE EMPLOYEES DROP CONSTRAINT EMP_DEPT_FK;
-- Re-define constraint with "ON DELETE CASCADE" option
SQL>
ALTER TABLE EMPLOYEES
ADD CONSTRAINT EMP_DEPT_FK
FOREIGN KEY (DEPARTMENT_ID)
REFERENCES DEPARTMENTS(DEPARTMENT_ID)
ON DELETE CASCADE;
-- Try again
SQL>
DELETE FROM DEPARTMENTS
WHERE DEPARTMENT_ID = 280;
SQL>
COMMIT;
Labels:
constraint,
ON DELETE CASCADE,
ORA-02292,
oracle
Thursday, 19 April 2018
e.g. count and distinct aggregate functions
examples; count (1) - count(*) - count(column_name) - count(distinct (column_name))
e.g. count aggregate function
SQL>
SELECT
COUNT(*)
FROM
employees;
COUNT(*)
----------
107
SQL>
SELECT
COUNT(1)
FROM
employees;
COUNT(*)
----------
107
SQL>
SELECT
COUNT(commission_pct)
FROM
employees;
COUNT(COMMISSION_PCT)
---------------------
35
Info: COUNT(1) and COUNT(*) calculate all rows even all columns data are NULL. However, COUNT(COLUMN_NAME) ignores NULL data.
e.g. distinct aggregate function
SQL>
SELECT
distinct(commission_pct)
FROM
employees;
COMMISSION_PCT
--------------
NULL
,15
,35
,4
,3
,2
,25
,1
8 rows selected.
Info: DISTINCT(COLUMN_NAME) function uses not to see duplicated rows and also it shows NULL column if it exists.
e.g. both of count and distinct aggregate functions
SQL>
SELECT
COUNT(DISTINCT(commıssıon_pct) )
FROM
employees;
COUNT(DISTINCT(COMMISSION_PCT))
-------------------------------
7
Info: count(column_name) ignores NULL values, even if distinct function is used.
e.g. count aggregate function
SQL>
SELECT
COUNT(*)
FROM
employees;
COUNT(*)
----------
107
SQL>
SELECT
COUNT(1)
FROM
employees;
COUNT(*)
----------
107
SQL>
SELECT
COUNT(commission_pct)
FROM
employees;
COUNT(COMMISSION_PCT)
---------------------
35
Info: COUNT(1) and COUNT(*) calculate all rows even all columns data are NULL. However, COUNT(COLUMN_NAME) ignores NULL data.
e.g. distinct aggregate function
SQL>
SELECT
distinct(commission_pct)
FROM
employees;
COMMISSION_PCT
--------------
NULL
,15
,35
,4
,3
,2
,25
,1
8 rows selected.
Info: DISTINCT(COLUMN_NAME) function uses not to see duplicated rows and also it shows NULL column if it exists.
e.g. both of count and distinct aggregate functions
SQL>
SELECT
COUNT(DISTINCT(commıssıon_pct) )
FROM
employees;
COUNT(DISTINCT(COMMISSION_PCT))
-------------------------------
7
Info: count(column_name) ignores NULL values, even if distinct function is used.
Labels:
aggregate function,
count,
distinct,
oracle
Wednesday, 11 April 2018
ORA-02449 solution
Preparation
SQL>
CREATE TABLESPACE EXAMPLE_TS DATAFILE
'C:\ORACLEXE_XE\APP\ORACLE\ORADATA\XE\example_01.dbf' SIZE 512K REUSE
LOGGING
ONLINE
EXTENT MANAGEMENT LOCAL AUTOALLOCATE
BLOCKSIZE 8K
SEGMENT SPACE MANAGEMENT AUTO
FLASHBACK ON;
SQL>
CREATE TABLESPACE EXAMPLE_TS_2 DATAFILE
'C:\ORACLEXE_XE\APP\ORACLE\ORADATA\XE\example_02.dbf' SIZE 512K REUSE
LOGGING
ONLINE
EXTENT MANAGEMENT LOCAL AUTOALLOCATE
BLOCKSIZE 8K
SEGMENT SPACE MANAGEMENT AUTO
FLASHBACK ON;
SQL>
CREATE TABLE T_EXAMPLE (ID NUMBER)
TABLESPACE EXAMPLE_TS;
SQL>
CREATE TABLE T_EXAMPLE_CHILD (ID NUMBER, FID NUMBER)
TABLESPACE EXAMPLE_TS_2;
SQL>
ALTER TABLE T_EXAMPLE
ADD CONSTRAINT ID_EXAMPLE_PK
PRIMARY KEY (ID);
SQL>
ALTER TABLE T_EXAMPLE_CHILD
ADD CONSTRAINT FID_EXAMPLE_FK
FOREIGN KEY (FID)
REFERENCES T_EXAMPLE (ID);
Action
SQL>
DROP TABLESPACE EXAMPLE_TS;
Error
ORA-01549: tablespace not empty, use INCLUDING CONTENTS option
Next Action
SQL>
DROP TABLESPACE EXAMPLE_TS INCLUDING CONTENTS AND DATAFILES;
Next Error
SQL>
ORA-02449: unique/primary keys in table referenced by foreign keys
Solid Solution
SQL>
DROP TABLESPACE EXAMPLE_TS INCLUDING CONTENTS AND DATAFILES CASCADE CONSTRAINTS;
SQL>
CREATE TABLESPACE EXAMPLE_TS DATAFILE
'C:\ORACLEXE_XE\APP\ORACLE\ORADATA\XE\example_01.dbf' SIZE 512K REUSE
LOGGING
ONLINE
EXTENT MANAGEMENT LOCAL AUTOALLOCATE
BLOCKSIZE 8K
SEGMENT SPACE MANAGEMENT AUTO
FLASHBACK ON;
SQL>
CREATE TABLESPACE EXAMPLE_TS_2 DATAFILE
'C:\ORACLEXE_XE\APP\ORACLE\ORADATA\XE\example_02.dbf' SIZE 512K REUSE
LOGGING
ONLINE
EXTENT MANAGEMENT LOCAL AUTOALLOCATE
BLOCKSIZE 8K
SEGMENT SPACE MANAGEMENT AUTO
FLASHBACK ON;
SQL>
CREATE TABLE T_EXAMPLE (ID NUMBER)
TABLESPACE EXAMPLE_TS;
SQL>
CREATE TABLE T_EXAMPLE_CHILD (ID NUMBER, FID NUMBER)
TABLESPACE EXAMPLE_TS_2;
SQL>
ALTER TABLE T_EXAMPLE
ADD CONSTRAINT ID_EXAMPLE_PK
PRIMARY KEY (ID);
SQL>
ALTER TABLE T_EXAMPLE_CHILD
ADD CONSTRAINT FID_EXAMPLE_FK
FOREIGN KEY (FID)
REFERENCES T_EXAMPLE (ID);
Action
SQL>
DROP TABLESPACE EXAMPLE_TS;
Error
ORA-01549: tablespace not empty, use INCLUDING CONTENTS option
Next Action
SQL>
DROP TABLESPACE EXAMPLE_TS INCLUDING CONTENTS AND DATAFILES;
Next Error
SQL>
ORA-02449: unique/primary keys in table referenced by foreign keys
Solid Solution
SQL>
DROP TABLESPACE EXAMPLE_TS INCLUDING CONTENTS AND DATAFILES CASCADE CONSTRAINTS;
Labels:
ORA-01549,
ORA-02449,
oracle,
tablespace
ORA-01549 solution
Preparation
SQL>
CREATE TABLESPACE EXAMPLE_TS DATAFILE
'C:\ORACLE_XE\APP\ORACLE\ORADATA\XE\example_01.dbf' SIZE 512K REUSE
LOGGING
ONLINE
EXTENT MANAGEMENT LOCAL AUTOALLOCATE
BLOCKSIZE 8K
SEGMENT SPACE MANAGEMENT AUTO
FLASHBACK ON;
SQL>
CREATE TABLE T_EXAMPLE (ID NUMBER)
TABLESPACE EXAMPLE_TS;
Action
SQL>
DROP TABLESPACE EXAMPLE_TS;
Error
ORA-01549: tablespace not empty, use INCLUDING CONTENTS option
Solution
SQL>
DROP TABLESPACE EXAMPLE_TS INCLUDING CONTENTS AND DATAFILES;
SQL>
CREATE TABLESPACE EXAMPLE_TS DATAFILE
'C:\ORACLE_XE\APP\ORACLE\ORADATA\XE\example_01.dbf' SIZE 512K REUSE
LOGGING
ONLINE
EXTENT MANAGEMENT LOCAL AUTOALLOCATE
BLOCKSIZE 8K
SEGMENT SPACE MANAGEMENT AUTO
FLASHBACK ON;
SQL>
CREATE TABLE T_EXAMPLE (ID NUMBER)
TABLESPACE EXAMPLE_TS;
Action
SQL>
DROP TABLESPACE EXAMPLE_TS;
Error
ORA-01549: tablespace not empty, use INCLUDING CONTENTS option
Solution
SQL>
DROP TABLESPACE EXAMPLE_TS INCLUDING CONTENTS AND DATAFILES;
Labels:
ORA-01549,
oracle,
tablespace
Monday, 9 April 2018
e.g. pivot clause
Preparation
* Define column names for pivot table
SQL>
SELECT LISTAGG (
'''' || JOB_ID || '''' || ' AS ' || '"' || JOB_TITLE || '"' || ', ')
WITHIN GROUP (ORDER BY JOB_TITLE)
FROM JOBS;
Pivot example
* Show that how many jobs are set to persons according to department names.
SQL>
SELECT *
FROM (SELECT JOB_ID, DEPARTMENT_NAME
FROM EMPLOYEES A, DEPARTMENTS B
WHERE A.DEPARTMENT_ID = B.DEPARTMENT_ID) PIVOT (
COUNT (JOB_ID)
FOR JOB_ID
IN ('AD_VP' AS "ADMIN",
'FI_ACCOUNT' AS "Accountant",
'AC_MGR' AS "Accounting Manager",
'AD_ASST' AS "Administration Assistant",
'FI_MGR' AS "Finance Manager",
'HR_REP' AS "Human Resources Representative",
'MK_MAN' AS "Marketing Manager",
'MK_REP' AS "Marketing Representative",
'AD_PRES' AS "Presidentt",
'IT_PROG' AS "Programmer",
'AC_ACCOUNT' AS "Public Accountant",
'PR_REP' AS "Public Relations Represent.",
'PU_CLERK' AS "Purchasing Clerk",
'PU_MAN' AS "Purchasing Manager",
'SA_MAN' AS "Sales Manager",
'SA_REP' AS "Sales Representative",
'SH_CLERK' AS "Shipping Clerk",
'ST_CLERK' AS "Stock Clerk",
'ST_MAN' AS "Stock Manager"))
ORDER BY DEPARTMENT_NAME DESC;
* Define column names for pivot table
SQL>
SELECT LISTAGG (
'''' || JOB_ID || '''' || ' AS ' || '"' || JOB_TITLE || '"' || ', ')
WITHIN GROUP (ORDER BY JOB_TITLE)
FROM JOBS;
Pivot example
* Show that how many jobs are set to persons according to department names.
SQL>
SELECT *
FROM (SELECT JOB_ID, DEPARTMENT_NAME
FROM EMPLOYEES A, DEPARTMENTS B
WHERE A.DEPARTMENT_ID = B.DEPARTMENT_ID) PIVOT (
COUNT (JOB_ID)
FOR JOB_ID
IN ('AD_VP' AS "ADMIN",
'FI_ACCOUNT' AS "Accountant",
'AC_MGR' AS "Accounting Manager",
'AD_ASST' AS "Administration Assistant",
'FI_MGR' AS "Finance Manager",
'HR_REP' AS "Human Resources Representative",
'MK_MAN' AS "Marketing Manager",
'MK_REP' AS "Marketing Representative",
'AD_PRES' AS "Presidentt",
'IT_PROG' AS "Programmer",
'AC_ACCOUNT' AS "Public Accountant",
'PR_REP' AS "Public Relations Represent.",
'PU_CLERK' AS "Purchasing Clerk",
'PU_MAN' AS "Purchasing Manager",
'SA_MAN' AS "Sales Manager",
'SA_REP' AS "Sales Representative",
'SH_CLERK' AS "Shipping Clerk",
'ST_CLERK' AS "Stock Clerk",
'ST_MAN' AS "Stock Manager"))
ORDER BY DEPARTMENT_NAME DESC;
Labels:
oracle,
pivot clause,
pivot table
Subscribe to:
Posts (Atom)