16 Aralık 2020 Çarşamba

PostGIS ST_DISTANCE

Giriş
İmzası şöyle
ST_Distance(geometry g1, geometry g2);
Örnek
İki nokta arasındaki mesafeyi şöyle buluruz.
SELECT ST_Distance(ST_GeomFromText('POINT(27.185425 88.124582)',4326),
 ST_GeomFromText('POINT(27.1854258 88.124500)', 4326));
Örnek
Tabloya yeni bir sütun ekleyelim ve index koyalım
ALTER TABLE clients_details_locations ADD COLUMN geom geometry(Point, 4326);

UPDATE clients_details_locations 
   SET geom = ST_SetSRID(ST_MakePoint(longitude , latitude), 4326);

CREATE INDEX clients_details_locations_geom_idx  ON clients_details_locations 
  USING GIST (geom);
Bir noktaya en yakın noktaları bulmak için şöyle yaparız
SELECT ... order by st_distance(geom,client_point)


PostGIS Extension

Giriş 
Açıklaması şöyle
PostGIS is the spatial database extension for PostgreSQL. It has over 300 different built-ins and functions to make it easier to work with spatial data.
PostgreSQL bir sürü şeyi daha destekliyor. Açıklaması şöyle
- OLTP (Online Transaction Processing)
We can use PostgreSQL for CRUD (Create-Read-Update-Delete) operations.
- OLAP (Online Analytical Processing)
We can use PostgreSQL for analytical processing. PostgreSQL is based on 𝐇𝐓𝐀𝐏 (Hybrid transactional/analytical processing) architecture, so it can handle both OLTP and OLAP well.
- FDW (Foreign Data Wrapper)
A FDW is an extension available in PostgreSQL that allows us to access a table or schema in one database from another.
- Streaming
PipelineDB is a PostgreSQL extension for high-performance time-series aggregation, designed to power real-time reporting and analytics applications.
- Geospatial
PostGIS is a spatial database extender for PostgreSQL object-relational database. It adds support for geographic objects, allowing location queries to be run in SQL.
- Time Series
Timescale extends PostgreSQL for time series and analytics. For example, developers can combine relentless streams of financial and tick data with other business data to build new apps and uncover unique insights.
- Distributed Tables
CitusData scales Postgres by distributing data & queries. 

Şeklen şöyle


Spatial Data Nedir?
Açıklaması şöyle. Konum bilgisi taşıyan veridir.
Spatial Data, often referred to as geospatial data, is any data that contains information about a specific location. In layman's terms, spatial data is data about location.
Spatial Data Types Nedir?
Açıklaması şöyle
The two primary spatial data types are Geometric and Geographic data.

Geographic data is data that can be mapped to a sphere (the sphere in question is usually planet earth). Geographic data typically refers to longitude and latitude related to the location of an object on earth. GPS data is a good example of geographic data.

Geometric data is data that can be mapped to a two-dimensional flat surface. A good example of geometric data would be the floor plan of a building.
Açıklaması şöyle
PostgreSQL natively supports NoSQL as well as a rich set of data types, including Numeric Types, Boolean Type, Network Address, Bit String Types, Arrays, Composite Types, Object Identifier Types, Pseudo-Types, and even Geometric Types like Points, Line Segments, Boxes, Paths, Polygons, and Circles. It also supports JSON, hstore, and XML, and users can even add new types using the CREATE TYPE command. Postgres also supports a lot of SQL syntaxes, such as common table expressions, Windows functions, and table inheritance.
PostGIS Kurulumunu Kontrol Etmek
Şu iki komuttan birisini çalıştırırız
SELECT PostGIS_version(); SELECT PostGIS_full_version();
Eğer kurulu değilse çıktı olarak Türkçe şunu alırız
HATA: postgis_full_version() fonksiyonu mevcut değildir
İngilizcesi şöyle
ERROR:  function postgis_full_version() does not exist
Diğer
Bazı diğer yazılar şöyle
ST_MakePointST_MakeValid
 

7 Aralık 2020 Pazartesi

LIKE

Giriş
Eğer Tam eşitlik kontrolü yapmak istiyorsak "=" kullanırız

Örnek
Şöyle yaparız
WHERE description = 'FPS'
LIKE
Örnek
Şöyle yaparız
WHERE description LIKE '%FPS'

3 Aralık 2020 Perşembe

CROSS JOIN

Giriş
Sol tablodaki her bir satır için sağ tablodaki tüm satırları çaprazlar

Örnek - interval
Elimizde şöyle iki tablo olsun
create table employee (
    id int,
    name char(20),
    division_id int
);

create table attendance (
    id int,
    employee_id int,
    activity_type int,
    created_at timestamp
);
attendance değerlerini günlük olarak görmek istersek şöyle yaparız
SELECT
days::date AS created_date, e.* FROM ( SELECT MIN(created_at), MAX(created_at) FROM attendance) AS r(startdate,enddate),
generate_series( startdate::timestamp, enddate::timestamp, interval '1 day') g(days) CROSS JOIN employee e
Çıktı olarak şunu alırız. Burada her created_day için tüm çalışanları (toplam 5 kişi) teker teker yazdı
created_date id name division_id
2020-11-18 1 John    1
2020-11-18 2 Amber   2
2020-11-18 3 Mike    1
2020-11-18 4 Jimmy   1
2020-11-18 5 Kathy   2
2020-11-19 1 John    1
2020-11-19 2 Amber   2
2020-11-19 3 Mike    1
2020-11-19 4 Jimmy   1
2020-11-19 5 Kathy   2

TIMESTAMP metodu

Giriş
Precision verilebilir. Açıklaması şöyle.
Postgres allows you to specify precision(0 to 6) while casting to TIMESTAMP
Örnek 
select (now() at time zone 'utc') normalde şu çıktıyı verir
2020-12-03 09:39:28.992948
Şöyle yaparız
select (now() at time zone 'utc') :: timestamp(3)
Çıktı olarak 972 ile biten şu değeri alırız.
2019-01-29 08:54:28.972
Örnek - String Girdi
Şöyle yaparız.
select timestamp '2012-08-31 01:00:00';
Çıktı olarak şunu alırız
2012-08-31 01:00:00
Çıkartma İşlemi
Açıklaması şöyle.
Subtracting timestamps produces an INTERVAL data type. INTERVALs are a special data type for representing the difference between two TIMESTAMP types. When subtracting timestamps, Postgres will typically give an interval in terms of days, hours, minutes, seconds, without venturing into months. This generally makes life easier, since months are of variable lengths.

11 Kasım 2020 Çarşamba

pg_notify metodu - LISTEN ve NOTIFY

Giriş
Not : Java gerçekleştirimi burada

Açıklaması şöyle
The NOTIFY command sends a notification event together with an optional "payload" string to each client application that has previously executed LISTEN channel for the specified channel name in the current database. Notifications are visible to all users.
Açıklaması şöyle
PostgreSQL has got the LISTEN/NOTIFY commands. Set up a trigger on each table that calls [NOTIFY ‘tableName_changed’]. Any process connected to the database can wait using [LISTEN ‘tableName_changed’].
Örnek
Şöyle yaparız. table_name yerine istediğimiz tablo ismi gelir. Burada kendi trigger metodumuzu belirtiyoruz.
CREATE TRIGGER table_change 
    AFTER INSERT OR UPDATE OR DELETE ON table_name
    FOR EACH ROW EXECUTE PROCEDURE notify_change();
Trigger metodumuz şöyler. pg_notify() çağrısı yapılıyor. Burada değişen tablo ismi TG_TABLE_NAME ile elde edilir.
CREATE OR REPLACE FUNCTION notify_change() RETURNS TRIGGER AS $$
    BEGIN
        SELECT pg_notify('test', TG_TABLE_NAME);
        RETURN NEW;
    END;
$$ LANGUAGE plpgsql;
Örnek
Şöyle yaparız
CREATE TABLE PUBLIC.TBLEXAMPLE
(
  KEY1 CHARACTER VARYING(10) NOT NULL,
  KEY2 CHARACTER VARYING(14) NOT NULL,
  VALUE1 CHARACTER VARYING(20),
  VALUE2 CHARACTER VARYING(20) NOT NULL,
  CONSTRAINT TBLEXAMPLE_PKEY PRIMARY KEY (KEY1, KEY2)
);

CREATE OR REPLACE FUNCTION PUBLIC.NOTIFY() RETURNS TRIGGER AS
$BODY$
BEGIN
  PERFORM pg_notify('myevent', row_to_json(NEW)::text);
  RETURN NEW;
END;
$BODY$
LANGUAGE 'plpgsql' VOLATILE COST 100;


CREATE TRIGGER TBLEXAMPLE_AFTER
 AFTER insert or update or delete ON PUBLIC.TBLEXAMPLE
FOR EACH ROW
EXECUTE PROCEDURE PUBLIC.NOTIFY();

1 Kasım 2020 Pazar

Docker ve PostgreSQL

Giriş
Image ismi olarak 
postgres:12
postgres:alpine kullanılabilir

1. docker pull ile İndirmek
PostgreSQL'i indirmek için şöyle yaparız
docker pull postgres
Belli bir PostgreSQL sürümünü indirmek için şöyle yaparız
docker pull postgres:12
Bu işlemden sonra image dosyasını kontrol etmek için şöyle yaparız
docker images
2. docker run ile Veri tabanını Başlatmak
Bazı ortam değişkenleri isimleri şöyle. Bu değişkenler -e seçeneği ile birlikte kullanılırlar

POSTGRES_USER
POSTGRES_PASSWORD
POSTGRES_DB
PGDATA

Ayrıca ilk indirilen postgre her yerden bağlantı kabul etmez. Bu ayarları değiştirmek için pg_hba.conf ve postgresql.conf dosyalarına ayarlar yapmak gerekir

Örnek
PostgreSQL'i çalıştırmak için şöyle yaparız. Burada -v ile bir volume postgre'nin kullanması için mount ediliyor. O an bulunduğumuz dizin yani PWD, postgre açısından /var/lib/postgresql/data dizini oluyor
Burada kullanıcı ismi belirtilmiyor. Dolayısıyla kullanıcı ismi "postgre" olacak ancak şifresi POSTGRES_PASSWORD ile belirtiliyor. Şifre "docker" olacak
docker run --name pg-docker -e POSTGRES_PASSWORD=docker -e POSTGRES_DB=sampledb
  -e PGDATA=/tmp -d -p 5433:5432 -v ${PWD}:/var/lib/postgresql/data postgres:11
Açıklaması şöyle
Container data is gone once it is stopped and this is useful for certain situations (e.g. if you are running some database/integration testing and want to get rid of test data then it's great). But if we want to persist data generated by the Postgres instance running inside a container beyond the container’s lifecycle, we need to map a local mount point as a data volume to an appropriate path inside the container.
Örnek
Şöyle yaparız. Burada image ismi olarak postgres:alpine kullanılıyor. Daha sonra veri tabanına kabul açılıyor
docker run \
--name postgres-spring \ -e POSTGRES_PASSWORD=password \ -d \ -p 5432:5432 \ postgres:alpine docker exec -it postgres-spring bin/bash > psql veya > psql -U postgres
Örnek
Şöyle yaparız. Burada Linux ve Windows arasındaki çoklu satır farkı görülebilir. Linux'ta \ karakteri kullanılır, Windows'ta ^ karakteri kullanılır.
#Linux
$ docker run --rm \
--name ewallet-db \
-e POSTGRES_DB=ewalletdb \
-e POSTGRES_USER=ewallet \
-e POSTGRES_PASSWORD=xxxxxxxxxx \
-e PGDATA=/var/lib/postgresql/data/pgdata \
-v "$PWD/ewalletdb-data:/var/lib/postgresql/data" \
-p 5432:5432 \
postgres:14

#Windows
docker run --rm ^
--name ewallet-db ^
-e POSTGRES_DB=ewalletdb ^
-e POSTGRES_USER=ewallet^
-e POSTGRES_PASSWORD=xxxxxxxxxx ^
-e PGDATA=/var/lib/postgresql/data/pgdata ^
-v “%cd%\ewalletdb-data:/var/lib/postgresql/data” ^
-p 5432:5432 ^
postgres:14
Bağlanmak için şöyle yaparız
psql -h 127.0.0.1 -U ewallet ewalletdb
Örnek
Şöyle yaparız. Burada Debezium için hazır hale getiriliyor.
docker run -d --name postgres -e POSTGRES_PASSWORD=postgres \
  -p 5432:5432 postgres -c wal_level=logical
Örnek
Şöyle yaparız
docker run -d -p 5432:5432 
  --rm \
  -e POSTGRES_PASSWORD=postgres \
  -e PGDATA=/var/lib/postgresql/data/pgdata \
  -v /home/user/postgres/data:/var/lib/postgresql/data \
  --name postgres \
  postgres
3. docker exe ile SQL Çalıştırmak
Örnek
Şöyle yaparız. Burada container ismi pg_docker. Çalıştırılacak komut psql ve parametreleri
docker exec -it pg-docker psql -U postgres -c "CREATE DATABASE testdb;"
Örnek
Şöyle yaparız. Burada container ismi pg_docker. Çalıştırılacak komut psql ve parametreleri
docker exec -it pg-docker psql -U postgres -f /opt/scripts/test_script.sql
Örnek
Yine bash açarak dockerized postgresql data dosyalarına bakmak için şöyle yaparız. Burada docker'a geçince prompt'un $ karakterinden root@xyx şeklinde değiştiği görülebilir.
$ docker exec -it my-postgres-db-container bash
root@c7d61efe2a5d:/# cd /var/lib/postgresql/data/
root@c7d61efe2a5d:/var/lib/postgresql/data# ls -lh
total 56K
drwx------. 7 postgres postgres   71 Apr  5  2018 base
drwx------. 2 postgres postgres 4.0K Nov  2 02:42 global
drwx------. 2 postgres postgres   18 Dec 27  2017 pg_clog
drwx------. 2 postgres postgres    6 Dec 27  2017 pg_commit_ts
drwx------. 2 postgres postgres    6 Dec 27  2017 pg_dynshmem
-rw-------. 1 postgres postgres 4.4K Dec 27  2017 pg_hba.conf
-rw-------. 1 postgres postgres 1.6K Dec 27  2017 pg_ident.conf
drwx------. 4 postgres postgres   39 Dec 27  2017 pg_logical
drwx------. 4 postgres postgres   36 Dec 27  2017 pg_multixact
drwx------. 2 postgres postgres   18 Nov  2 02:42 pg_notify
drwx------. 2 postgres postgres    6 Dec 27  2017 pg_replslot
drwx------. 2 postgres postgres    6 Dec 27  2017 pg_serial
drwx------. 2 postgres postgres    6 Dec 27  2017 pg_snapshots
drwx------. 2 postgres postgres    6 Sep 16 21:15 pg_stat
drwx------. 2 postgres postgres   63 Nov  8 02:41 pg_stat_tmp
drwx------. 2 postgres postgres   18 Oct 24  2018 pg_subtrans
drwx------. 2 postgres postgres    6 Dec 27  2017 pg_tblspc
drwx------. 2 postgres postgres    6 Dec 27  2017 pg_twophase
-rw-------. 1 postgres postgres    4 Dec 27  2017 PG_VERSION
drwx------. 3 postgres postgres   92 Dec 20  2018 pg_xlog
-rw-------. 1 postgres postgres   88 Dec 27  2017 postgresql.auto.conf
-rw-------. 1 postgres postgres  21K Dec 27  2017 postgresql.conf
-rw-------. 1 postgres postgres   37 Nov  2 02:42 postmaster.opts
-rw-------. 1 postgres postgres   85 Nov  2 02:42 postmaster.pid
4. Veri tabanını Doldurarak Çalıştırmak

Örnek
Elimizde şöyle bir DockerFile olsun
FROM postgre:11
LABEL author="Jawad Hasan"

ENV POSTGRES_PASSWORD sasa
ENV POSTGRES_DB sampledb

COPY dbscriptOrder/ /docker-entrypoint-initdb.d/
dbscriptOrder/ dizininde ismi rakam ile başlayan iki tane dosya olsun
2-createtable
3-insertdata
docker imajı için şöyle yaparız
docker image build -t postgresbasic .
Daha sonra docker'ı doldurulmuş veri tabanı ile başlatmak için şöyle yaparız
docker run --name pg-docker -e PGDATA=/tmp -d -p 5433:5432
-v ${PWD}:/var/lib/postgresql/data postgresbasic
Örnek
Elimizde şöyle bir DockerFile olsun. Burada veri tabanı ayar dosyaları da yeni image içine dahil ediliyor.
FROM postgres:12
ADD pg_hba.conf /var/lib/postgresql/data/
ADD postgresql.conf /var/lib/postgresql/data/
COPY init.sql /docker-entrypoint-initdb.d/
Yeni image build edip çalıştırmak için şöyle yaparız
docker build --t medium/database:latest .

docker run --rm -e POSTGRES_PASSWORD=P@ssword1
-v /opt/workspace/nerdcode/docker/data/medium:/var/lib/postgresql/data:rw
-p 5432:5432 medium/database:latest