11 Eylül 2019 Çarşamba

CREATE OR REPLACE FUNCTION

Giriş
Söz dizimi şöyle
CREATE OR REPLACE FUNCTION function_name(parameter_type parameter_name, ...)
RETURNS return_type AS $$
BEGIN
  -- Function logic
END;
$$ LANGUAGE plpgsql;
1. Scalar Functions
Açıklaması şöyle
Scalar functions are user-defined functions that return a single value. They can take one or more input parameters and execute SQL statements. 
Örnek
Şöyle yaparız.
CREATE FUNCTION myfunction(arg1 INTEGER, arg2 TEXT) RETURNS INTEGER
AS $$
DECLARE result INTEGER;
BEGIN
  SELECT COUNT(*) INTO result FROM mytable WHERE mycolumn = arg2;
  RETURN result * arg1;
END;
$$ LANGUAGE plpgsql;
Örnek
Şöyle yaparız
-- Create a simple function that returns the sum of two integers
CREATE OR REPLACE FUNCTION add_two_numbers(a INT, b INT) RETURNS INT AS $$
BEGIN
  RETURN a + b;
END;
$$ LANGUAGE plpgsql;

-- Call the function
SELECT add_two_numbers(5, 7); -- Returns 12
Açıklaması şöyle
In the above example, we create a function add_two_numbers that takes two integers as input parameters and returns their sum. We use the CREATE FUNCTION statement with the RETURNS keyword to specify the return type.
Örnek
Şöyle yaparız. Verilen parametreleri tabloya ekler
CREATE OR REPLACE FUNCTION MyInsert(balance NUMERIC(19), id VARCHAR(250)) RETURNS VOID
AS
  $BODY$
    BEGIN
      INSERT INTO balance(balance, invoice_items_id) VALUES (balance , id);
    END;
  $BODY$
  LANGUAGE 'plpgsql' VOLATILE
  COST 100;
2. Table-Valued Functions
Açıklaması şöyle
Table-valued functions return a set of rows as a result. You can think of them as producing a virtual table.
Örnek
Şöyle yaparız
-- Create a table-valued function that returns all employees in a department
CREATE OR REPLACE FUNCTION get_employees_in_department(dept_id INT) 
RETURNS TABLE(id INT, name TEXT) AS $$
BEGIN
  RETURN QUERY SELECT employee_id, employee_name 
  FROM employees WHERE department_id = dept_id;
END;
$$ LANGUAGE plpgsql;

-- Call the function
-- Returns all employees in department 101
SELECT * FROM get_employees_in_department(101); 
Açıklaması şöyle
In this example, we create a function get_employees_in_department that takes a department ID as input and returns a table of employees in that department. We use the RETURNS TABLE clause to specify the return type.
3. Aggregation Functions
Açıklaması şöyle
Aggregation functions are used to perform operations on sets of values and return a single result. PostgreSQL allows you to create custom aggregation functions to suit your specific needs.
Örnek
Şöyle yaparız
-- Create an aggregation function that calculates the median
  
CREATE OR REPLACE FUNCTION median_accumulator(sfunc INTERNAL, stype INTERNAL,
  finalfunc INTERNAL)
RETURNS internal STRICT
LANGUAGE C;

-- Define the final function
CREATE OR REPLACE FUNCTION median_finalfunc(internal) RETURNS double precision
LANGUAGE sql IMMUTABLE STRICT AS $$
  SELECT CASE
    WHEN $1 IS NULL THEN NULL
    ELSE (percentile_cont(0.5) WITHIN GROUP (ORDER BY $1))
  END;
$$;

-- Create an aggregate that uses the function
CREATE AGGREGATE median(double precision) (
  SFUNC = median_accumulator,
  STYPE = internal,
  FINALFUNC = median_finalfunc
);
Açıklaması şöyle
In this example, we create a custom aggregation function for calculating the median of a set of values. Custom aggregations give you the flexibility to extend PostgreSQL’s built-in aggregation functions.

9 Eylül 2019 Pazartesi

ANY OPERATOR

Giriş
ANY ve IN Operatörleri arasında fark var.

Örnek
Elimizde vehicle tablosu olsun.
veh_id |             vehicle_types              
-------+---------------------------------------
    1  | {"byd_tang","volt","viper","laferrari"} 
    2  | {"volt","viper"}                        
    3  | {"byd_tang","sonata","jaguarxf"}        
    4  | {"swift","teslax","mirai"}              
    5  | {"volt","viper"}                        
    6  | {"viper","ferrariff","bmwi8","viper"}   
    7  | {"ferrariff","viper","viper","volt"}  
Elimizde vehicle_names tablosu olsun
 id |  vehicle_name
  -----+-----------------------
    1  |  byd_tang
    2  |  volt
    3  | viper
    4  | laferrari
    5  | sonata
    6  |  jaguarxf
    7  |  swift
    8  |  teslax
    9  | mirai
    10 | ferrariff
    11 | bmwi8
Birden fazla araçta kullanılan vehicle_name'leri bulmak için şöyle yaparız
SELECT
   vn.id,
   vn.veh_name
FROM vehicle_names vn
INNER JOIN vehicle v
   ON vn. veh_name = ANY (v.veh_types)
GROUP BY
  vn.id,
  vn.veh_name
HAVING
  COUNT(*) > 1;

pg_hba.conf Dosyası - Client Authentication and Access Control

Giriş
Not:  postgresql.conf dosyası da bazı ayarları içerir. postgresql.conf hangi ethernet kartının (network card) dinleneceğini belirtilir.

pg_hba.conf  "Host Based Authentication" anlamına gelir.  Açıklaması şöyle
This file handles client authentication configuration and controls as per doc "which hosts are allowed to connect, how clients are authenticated, which PostgreSQL user names they can use, which databases they can access". You need to edit this file to enable remote connections. The content is self-explanatory in this file.
Sütun Başlıkları
1. Type
2. Database
3. User
4. Address
5. Method
Her satır 7 tane formattan bir tanesine sahip olabilir. Bu formatlar şöyle
local      database  user  auth-method  [auth-options]
host       database  user  address  auth-method  [auth-options]
hostssl    database  user  address  auth-method  [auth-options]
hostnossl  database  user  address  auth-method  [auth-options]
host       database  user  IP-address  IP-mask  auth-method  [auth-options]
hostssl    database  user  IP-address  IP-mask  auth-method  [auth-options]
hostnossl  database  user  IP-address  IP-mask  auth-method  [auth-options]
1. Type Sütunu
local Unix Doman Socket içindir
host IPv4 ve Ipv6 içindir

2. database Sütunu
Açıklaması şöyle
Specifies which database name(s) this record matches. The value all specifies that it matches all databases. The value sameuser specifies that the record matches if the requested database has the same name as the requested user. The valuesamerole specifies that the requested user must be a member of the role with the same name as the requested database. (samegroup is an obsolete but still accepted spelling of samerole.)
3. user Sütunu
Açıklaması şöyle
Specifies which database user name(s) this record matches. The value all specifies that it matches all users.
4. address Sütunu
Açıklaması şöyle
Specifies the client machine address(es) that this record matches. This field can contain either a host name or an IP address range. An IP address range is specified using standard numeric notation for the range’s starting address, then a slash (/) and a CIDR mask length. The mask length indicates the number of high-order bits of the client IP address that must match.
5. auth-method Alanı
Açıklaması şöyle
Specifies the authentication method to use when a connection matches this record. The possible choices are summarized here: https://www.postgresql.org/docs/current/auth-methods.html
Şu değerlerden birini alabilir. Eğer trust ise kullanıcı şifresiz login olur.
trust
reject
md5
password
gss
sspi
krb5
ident
peer
ldap
radius
cert
pam
Örnek
Şöyle yaparız
#Type		DATABASE	USER	ADDRESS	        METHOD
#local is for Unix domain socket connections only
local		all		all			 trust

#IPv4 local connections
host		all		all	127.0.0.1/32     trust

#IPv6 local connections
host		all		all	::1/128	         trust

#Allow replication connections from localhost, by a user with 
#the replication privilege
local		replication	all			 trust
host 		replication	all	127.0.0.1/32     trust
host 		replication	all	::1/128	         trust
Örnek
Şöyle yaparız
# Allow any user from host 192.168.12.10 to connect to database
# "postgres" if the user's password is correctly supplied.
#
# TYPE  DATABASE        USER            ADDRESS                 METHOD
host    postgres        all             192.168.12.10/32        scram-sha-256

Örnek
IPv4 ile her yerden bağlantıya izin vermek için bu dosyanın en altına bir satır ekleriz. Şöyle yaparız
host    all             all             0.0.0.0/0            md5
Örnek
IPv4 ve IPv6 ile her yerden bağlantıya izin vermek için bu dosyanın en altına bir satır ekleriz. Şöyle yaparız
host all all 0.0.0.0/0 md5
host all all ::/0 md5
Örnek
Şöyle yaparız
host replication pglogrepl 127.0.0.1/32 md5