19 Ocak 2020 Pazar

Two Phase Commit (2PC)- Distributed Transaction İçindir

Giriş
Distributed Transaction Management için 7 farklı çözüm var. Bunlar şöyle
1. Two-phase commit/XA
2. SAGA
3. TCC (Try, Confirm, Cancel)
4. Local Messaging
5. Transactional Messaging
6. Best-effort Notification
7. Seata-AT

Local Messaging ve Transactional Messaging
Transaction destekleyen ve persistent olan mesaj kuyruğu (message queue) kullanarak gerçekleştirilir.

XA ve JTA İlişkisi
XA standardın ismi. X/Open organizasyonu tarafından yönetiliyor. Açıklaması şöyle
XA is a specification for distributed transactions proposed by the X/Open organization. The XA specification mainly defines the interface between a (global) Transaction Manager (TM) and a (local) Resource Manager (RM). Local databases such as mysql play the RM role in the XA specification.
JTA ise Java gerçekleştirimi. Açıklaması şöyle
Two-phase commit(2PC) is a blocking protocol used to guarantee that all the transactions are succeeded or failed together in a distributed transaction.

The XA standard is a specification for the 2PC distributed transactions. JTA includes standard API for XA. JTA-compliant application servers support XA out-of-the-box. But all the resources have to be deployed to a single JTA platform to run 2PC. 
XA Bileşenleri
İki tane bileşen var. 
1. Transaction Manager 
2. Resource Manager
3. Application Program - Bu aslında bileşen sayılmayabilir
 Açıklaması şöyle
The XA specification mainly defines the interface between a (global) Transaction Manager (TM) and a (local) Resource Manager (RM). Local databases such as mysql play the RM role in the XA specification.
Two Phase Commit Gerçekleştirimi
İki tane yöntem var.
1. 2PC destekleyen veri tabanı kullanmak
2. Distributed Transaction Manager kullanmak
Açıklaması şöyle. Distributed Transaction Manager olarak Atomikos kullanılabilir
Database Management Systems
Many database management systems, such as Oracle, MySQL, and PostgreSQL, provide support for 2PC out-of-the-box. 

Distributed Transaction Managers
Distributed transaction managers, such as JBoss Transactions, provide support for 2PC and can be used to manage transactions across multiple nodes. When using a distributed transaction manager, you can use 2PC by configuring the transaction manager to use 2PC as the transaction management mechanism.

Hangi Veri Tabanları XA Destekler
 Açıklaması şöyle
At present, almost all mainstream databases support XA transactions, including mysql, oracle, sql-server, postgres
Hangi Durumlarda Kullanılır
Strong Consistency (linearizability) gerekiyorsa kullanılır. 

Özellikle
1. Database Replication Varsa
2. Farklı Sistemler Varsa

Açıklaması şöyle
Other than the above database replication scenario for scalability, 2PC is also used when executing transactions between different types of systems such as database servers and message brokers. However, we generally avoid 2PC because of increased lock contention in distributed participants, which leads to poor performance, and hinders scalability. 
Akış Nasıldır?
Şeklen şöyle

Açıklaması şöyle
- Prepare: The participant is asked to check if its data operation can be performed and provide a promise to the transaction coordinator that later on if required, it can commit the operation or rollback. This is done for all the participants. 

- Commit: If all the participants said okay in the prepare phase, each participant is given a commit operation to commit the earlier mentioned operation. At this point, the participant cannot deny the operation, due to the promise given to the transaction coordinator earlier. If any of the participants earlier denied their local data operation due to any reason, the coordinate will send rollback commands to all the participants. 
Örnek
Şeklen şöyle


Voting Aşaması
Eğer tüm sistemler evet cevabını veriyorsa veri bitmiş olarak kabul edilir. Bu aşamaya voting denilir.

Klasik Coordinator Kullanımı
Açıklaması şöyle.
- The Coordinator service asks all the participants if they are ready to commit the transaction. They can reply with a yes or no. Note that if a single service replies with a no ( or a timeout or any other error), the full transaction is automatically canceled.

- If all the participants have answered yes, the Coordinator sends the Commit command to them and waits for the final ack.
Bu yöntemin dezavantajları şöyle.
- First of all, it comes with an intrinsic performance penalty as we're putting all the actors on hold multiple times waiting for an answer. - Secondly, in some cases, it may be possible that other transactions triggered in between are paused until the whole process completes.
- If the Coordinator fails for some reason at the beginning of Phase 2, all the other services are left hanging in a limbo-state.
Coordinator Olmadan Kullanımı
Örneğin kaynağı burası.

1. Two Phase Commit Kullanılmazsa
Bu yöntemin kullanılmadığı şöyle bir senaryo olsun.

Veri tabanına bir işlem yaptıktan sonra commit'lemeden REST çağrısı yapıp çağrı sonucuna göre rollback veya commit yapalım.

1. Eğer REST çağrısı başarılı ancak sonucu bize gelmezse transaction rollback edilir ve veri tutarsız olur
2. Eğer REST çağrısı başarılı ancak bizim commit işlemi başarısız ise veri tutarsız olur

2. İki Transaction Kullanan Two Phase Commit
Daha basit bir yöntem iki transaction kullanmak. Veri önce kendi veri tabanımıza yazılır ancak bitmiş olarak işaretlenmez. Daha sonra REST çağrısı yapılır. Eğer çağrı başarılı ise verimiz bitmiş olarak işaretlenir. Böylece işlem toplam üç transaction'a bölünür. İki tanesi ayrı veri tabanlarında gerçekleşir. Sonuncusu ise voting kabul edilir ve kendi veri tabanımızda gerçekleşir.

Outbox Pattern - Coordinator Olmadan Kullanımı
Açıklaması şöyle. Bu yöntemde tek transaction var ancak veri 2 tabloya yazılıyor.
This pattern provides an effective solution to publish events reliably. The idea of this approach is to have an “Outbox” table in the service’s database. When receiving a request for enrollment, not only an insert into the Student table is done, but a record representing the event is also inserted into the Outbox table. The two database actions are done as part of the same transaction.

An asynchronous process monitors the Outbox table for new entries and if there are any, it publishes the events to the Event Bus. The pattern merely splits the two transactions over different services, increasing reliability.


13 Ocak 2020 Pazartesi

PostGIS ST_Union

Örnek
Şöyle yaparız.
CREATE OR REPLACE VIEW _06_spildevand_vandloeb.drikkevandsledning_dissolve AS
  SELECT ROW_NUMBER() OVER() AS id, 
         ST_Union(the_geom)::GEOMETRY(MULTILINESTRING,25832) AS geom,  -- alias AS geom
         descr 
  FROM   _06_spildevand_vandloeb.ledninger_vand
  GROUP BY
         descr
;

2 Ocak 2020 Perşembe

GROUP BY - Aggregate Function İle Birlikte Kullanılır

Giriş
Açıklaması şöyle. GROUP BY içine SELECT edilen en az bir sütun ismi verilmeli. İstersek daha fazla da verebiliriz.
Each GROUP BY expression must contain at least one column that is not an outer reference
Aggregation Function
Açıklaması şöyle. Yani GROUP BY bir aggregate metod ile birlikte kullanılır. Bunlar SUM(),COUNT(),AVG() olabilir.
The real importance of GROUP BY can be seen when you use it with aggregate functions like SUM(), COUNT()
Açıklaması şöyle.
In most texts, GROUP BY is defined as a way of aggregating records by the specified columns which allow you to perform aggregation functions on non-grouped columns (such as SUM, COUNT, AVG, etc). In other words, the GROUP BY clause’s purpose is to summarize unique combinations of columns values.
Avg Aggregation Function
Örnek
Şöyle yaparız
SELECT department, AVG(salary) AS avg_salary
FROM employees
GROUP BY department;
Çıktısı şöyle
department | avg_salary
-----------------------
Sales      | 65000
Marketing  | 55000
Engineering| 80000
Count Aggregation Function
Count işlemi gruplamadan sonra 
- Tek tablo içinde yapılabilir.
- LEFT JOIN ile yapılabilir

Örnek - Tek Tablo İçinde Count
Şöyle yaparız. Burada GROUP BY içinde SELECT edilen bir sütun için kullanılıyor. COUNT() metodu aggregate olarak kullanılıyor.
SELECT style,COUNT(name) FROM beers GROUP BY style ORDER BY style
Örnek - Tek Tablo İçinde Count
Şöyle yaparız.  Burada GROUP BY içinde SELECT edilen iki sütun için kullanılıyor. COUNT() metodu aggregate olarak kullanılıyor.
SELECT style,brewery_id,COUNT(Name) FROM beers GROUP BY style,brewery_id ORDER BY style
Örnek - LEFT JOIN ile Count
Şöyle yaparız
SELECT products.*, COUNT(sold_products.id) AS total_sold
FROM products
LEFT JOIN sold_products ON sold_products.product_id = product.id
GROUP BY sold_products.product_id

10 Aralık 2019 Salı

CREATE ROLE

Giriş
Kullanıcı bilgilerini değiştirmek için ALTER ROLE kullanılır.

CREATE ROLE ve CREATE USER Farkı Nedir?
Açıklaması şöyle.
In PostgreSQL 9.4 documentation it says: "CREATE USER is now an alias for CREATE ROLE. The only difference is that when the command is spelled CREATE USER, LOGIN is assumed by default, whereas NOLOGIN is assumed when the command is spelled CREATE ROLE."
Açıklaması şöyle. Yani NOLOGIN kullanıcıları grup policy gibi düşünmek gerekir.
According to the description the LOGIN/NOLOGIN attribute determines whether or not a role can be used to connect from a client. A client can be anything from your pgAdmin III to lets say a web application. To test this you might want to create a role with LOGIN attribute and use it instead of your postgres role to connect to your server via pdAdmin III.

A role with NOLOGIN attribute can't do this. This type of role can be regarded as an object you can add privileges to. LOGIN roles might then inherit those privileges by adding them as a member. One can think of the whole matter in terms of groups and users being members of groups.

So after all I think this is just another way of expressing what you already said.
Örnek
felix isminde yeni kullanıcı yaratmak için şöyle yaparız.
CREATE ROLE felix;
Örnek
emp4 isminde yeni kullanıcı yaratmak için şöyle yaparız.
CREATE ROLE emp4 WITH LOGIN PASSWORD 'password';
Örnek
felix isminde ve şifresi süreli yeni kullanıcı yaratmak için şöyle yaparız.
CREATE ROLE felix WITH LOGIN PASSWORD 'password' VALID UNTIL '2020-09-30';

Data Type Formatting Functions - TO_DATE

Giriş
Açıklaması şöyle. Yani bir tipi String'e çevirir, veya String'den parse eder.
The PostgreSQL formatting functions provide a powerful set of tools for converting various data types (date/time, integer, floating point, numeric) to formatted strings and for converting from formatted strings to specific data types.
Formatlama için kullanılan metodlar şöyle
to_char(...),to_date(...),to_number(...),to_timestamp(...)
Örnek
Şöyle yaparız.
to_char(to_date(proforma_invoice_date, 'DD/MM/YYYY')), 'Month')

31 Ekim 2019 Perşembe

CREATE INDEX

CREATE INDEX CONCURRENTLY
Açıklaması şöyle
Creating an index is always a resource-intensive operation, so always use the “CONCURRENTLY” parameter so that the creation does not affect the performance of the index source table.
Örnek
Şöyle yaparız
CREATE INDEX CONCURRENTLY index_name ON table_name USING btree (column);

1. Index Tipleri
Index tipleri şöyle
- Balanced Tree (B-Tree)
- Generalized Inverted Index (GIN) : GIN INDEX yazısına taşıdım
- Generalized Inverted Search Tree (GiST)
- Space partitioned GiST (SP-GiST)
- Block Range Indexes (BRIN)

Açıklaması şöyle
You should know your indexes, although 99% of the time, you’re going to use B-Tree indexes, there’s that 1% that can make a huge difference if used right.
Balanced Tree (B-Tree)
Balanced Tree (B-Tree) yazısına taşıdım

Bu index aynı zamanda pattern_ops ile de kullanılabilir. 
- text_pattern_ops : text için
- varchar_pattern_ops : varchar için
- bpchar_pattern_ops : char için

değerlerini alabilir.

text_pattern_ops 
Ne zaman fuzzy search kullanmak gerekir?
Eğer bu iki maddeden birine takılıyorsak pg_trgm Module - Pattern Matching Full Text Search yazısına bakınız. Açıklaması şöyle
The BTree index can only search smaller strings with either direct match or prefix/suffix match with slightly better performance. But in the real world, users often misspell words, and it gets pretty hard to search for them. This is where the fuzzy search capabilities of PostgreSQL come in. They can search strings with similar words and do not have the size limitations of BTree indexes.
1. Eğer Full Text Search Yapıyorsak Takılırız
Şöyle yaparız. Burada prefix/suffix arama yapılmıyor ve index kullanılsa da yavaş olduğu görülecektir.
SELECT
  DISTINCT(event_type)
FROM
  storm_events
WHERE
  event_type ILIKE '%winter%'
2. Eğer Index Yaratamıyorsak Takılırız
B-Tree index 'in büyüklüğü belli bir değeri aşamaz. Şöyle yaparız.
CREATE INDEX anchored_search ON storm_events (event_type text_pattern_ops)
Çıktı olarak şunu alırız
index row size 4144 exceeds btree version 4 maximum 2704 for index "..."
Kullanım 
Örnek - Text Alan + LIKE
Açıklaması şöyle.
The B-Tree index is one of the simplest yet commonly used indexes in the PostgreSQL world. But when it comes to text, it cannot handle searches.
Görmek için şöyle yaparız. Sequential Scan yaptığı görülebilir.
EXPLAIN ANALYZE SELECT
  event_type
FROM
  storm_events
WHERE
  event_type LIKE '%Storm'
Index'i yaratmak için pattern_ops kullanılmalı. Şöyle yaparız
CREATE INDEX anchored_search ON storm_events (event_type text_pattern_ops)
Örnek - Text Alan + REGEX
Şöyle yaparız. S veya H ile başlayan event_type'ları seçer.
SELECT
  DISTINCT(event_type)
FROM
  storm_events
WHERE
  event_type ~ '^(S|H)'
2. Partial Index
Partial Index yazısına taşıdım



29 Ekim 2019 Salı

Array Functions and Operators

İndeks İle Erişme
Şöyle yaparız.
select (array['Cat', 'Dog', 'Horse'])[3];