psql etiketine sahip kayıtlar gösteriliyor. Tüm kayıtları göster
psql etiketine sahip kayıtlar gösteriliyor. Tüm kayıtları göster

28 Şubat 2023 Salı

psql - PostgreSQL Interactive Terminal Meta Commands

Giriş
Kabuk açıldıktan sonra komut çalıştırmak içindir.

Genel
\l (List) ile veri tabanları listelenir
\c  (Connect) dbname ile veri tabanına bağlanılır
\d (Describe) ile tablo yapısı incelenebilir
\dt (Describe Tables) ile tablolar listelenir
\di (Describe Index) ile indeksler listelenir

\q - quit
Kabuktan çıkmak içindir

\c [database] veya \connect [database] seçeneği - Connect to a different database
Bir veri tabanına bağlanır. Kısa hali \c şeklindedir.
Örnek
payment isimli bir veri tabanı olsun. Şöyle yaparız. Bu komuttan sonra prompt'un veri tabanı ismi olduğu görülebilir.
postgre#\c payment
You are not connected to database 'payment' as "...".
payment#
Örnek
Şöyle yaparız. Burada postgres veri tabanına bağlıydık. \c ile myjhipsterplanet veri tabanına bağlandık. Ayrıca hangi kullanıcı olarak bağlandığımızı da gösteriyor.
postgres=# \c myjhipsterplanet 
You are now connected to database "myjhipsterplanet" as user "mypostgresqldumpplanet".
Örnek
Şöyle yaparız.
\connect springbootjpa
Örnek
Şöyle yaparız
> \c pg_dev

> CREATE TABLE mini_ticker (...);
\copy
Örnek
Şöyle yaparız
psql -h "$host" -U postgres -d demo 
  -c "\copy (SELECT row_to_json(t) FROM ( $query ) t) To STDOUT" 
>> metrics/query-output.log
Örnek
Şöyle yaparız. admission tablosuna csv dosyasındaki satırları kopyalar
\copy admission FROM '/home/data/admit_1.csv' DELIMITER ',' CSV HEADER

\d [table] seçeneği -  Describe a table structure
Describe anlamına gelir. Tablonun sütunlarını gösterir. 
Örnek
Şöyle yaparız
> CREATE TABLE grades(id SERIAL NOT NULL, g INT NOT NULL);
> CREATE INDEX grades_index ON grades(g);

> \d grades;
                            Table "public.grades"
 Column |  Type   | Collation | Nullable |              Default               
--------+---------+-----------+----------+------------------------------------
 id     | integer |           | not null | nextval('grades_id_seq'::regclass)
 g      | integer |           | not null | 
Indexes:
    "grades_index" btree (g)
Örnek
Şöyle yaparız
demodb=# \dt
                 List of relations
 Schema |         Name          | Type  |  Owner   
--------+-----------------------+-------+----------
 public | flyway_schema_history | table | postgres
 public | tenant                | table | postgres
(2 rows)

demodb=# \d tenant
                      Table "public.tenant"
 Column |          Type          | Collation | Nullable | Default 
--------+------------------------+-----------+----------+---------
 id     | uuid                   |           | not null | 
 name   | character varying(100) |           | not null | 
Indexes:
    "tenant_pkey" PRIMARY KEY, btree (id)
\df - List functions
Örnek ver

\di seçeneği
Describe Index anlamına gelir. İndeksleri gösterir
Örnek
Şöyle yaparız
# \di+
                                        List of relations
 Schema | Name  | Type  |  Owner   | Table | Persistence | Access method |  Size   | Description
--------+-------+-------+----------+-------+-------------+---------------+---------+-------------
 public | a_idx | index | postgres | t1    | permanent   | btree         | 6712 kB |
(1 row)
Sonra şöyle yaparız. Böylece index dosyasının ismini öğreniriz.
# select pg_relation_filepath('a_idx');
 pg_relation_filepath
----------------------
 base/16699/16723
(1 row)
Sonra şöyle yaparız. Böylece verinin saklandığı dizinin yolunu öğreniriz.
# show data_directory;
          data_directory
-----------------------------------
 /home/postgres/pgdata/data
(1 row)
Yani index dosyası burada /home/postgres/pgdata/data/base/16699/16723
Teyit etmek için şöyle yaparız
# \! ls /home/postgres/pgdata/data/base/16699/16723
/home/postgres/pgdata/data/base/16699/16723
\dn - List schemas
Örnek ver

\dt seçeneği - List tables in the current database
Describe Tables anlamına gelir. Tabloları gösterir
Örnek
Şöyle yaparız
adv=> \dt
                    List of relations
 Schema |              Name              | Type  | Owner
--------+--------------------------------+-------+-------
 adv    | cfr_history_log                | table | adv
...
\du seçeneği - List users and their roles
Describe Users anlamına gelir. Kullanıcıları gösterir

\dx seçeneği - List extensions
Örnek
Şöyle yaparız
partitioning_test=# \dx
                                            List of installed extensions
        Name        | Version |   Schema   |                              Description
--------------------+---------+------------+------------------------------------------------------------------------
 bloom              | 1.0     | public     | bloom access method - signature file based index
 citext             | 1.6     | public     | data type for case-insensitive character strings
 citus              | 13.1-1  | pg_catalog | Citus distributed database
 citus_columnar     | 12.2-1  | pg_catalog | Citus Columnar extension
 hstore             | 1.8     | public     | data type for storing sets of (key, value) pairs
 pg_cron            | 1.6     | pg_catalog | Job scheduler for PostgreSQL
 pg_ivm             | 1.11    | pg_catalog | incremental view maintenance on PostgreSQL
 pg_partman         | 5.2.4   | partman    | Extension to manage partitioned tables by time or ID
 pg_stat_statements | 1.11    | public     | track planning and execution statistics of all SQL statements executed
 pg_trgm            | 1.6     | public     | text similarity measurement and index searching based on trigrams
 pgcrypto           | 1.3     | public     | cryptographic functions
 plpgsql            | 1.0     | pg_catalog | PL/pgSQL procedural language
 postgres_fdw       | 1.1     | public     | foreign-data wrapper for remote PostgreSQL servers
 uuid-ossp          | 1.1     | public     | generate universally unique identifiers (UUIDs)
 vector             | 0.8.0   | public     | vector data type and ivfflat and hnsw access methods
(15 rows)
\i seçeneği
Beliritlen dosyayı çalıştırır. Şöyle yaparız.
\i "C:\Users\myname\some path\query.sql"
\l seçeneği veya \list -  List all databases
Veri tabanlarını listeler

Örnek
Şöyle yaparız. Burada 5 tane veri tabanı var. 
postgres=# \l
                                                            List of databases
          Name          |         Owner          | Encoding |  Collate   |   Ctype    |                 Access privileges                 
------------------------+------------------------+----------+------------+------------+---------------------------------------------------
 myjhipsterplanet       | myjhipsterplanet       | UTF8     | en_US.utf8 | en_US.utf8 | 
 mypostgresqldumpplanet | mypostgresqldumpplanet | UTF8     | en_US.utf8 | en_US.utf8 | 
 postgres               | mypostgresqldumpplanet | UTF8     | en_US.utf8 | en_US.utf8 | 
 template0              | mypostgresqldumpplanet | UTF8     | en_US.utf8 | en_US.utf8 | =c/mypostgresqldumpplanet                        +
                        |                        |          |            |            | mypostgresqldumpplanet=CTc/mypostgresqldumpplanet
 template1              | mypostgresqldumpplanet | UTF8     | en_US.utf8 | en_US.utf8 | =c/mypostgresqldumpplanet                        +
                        |                        |          |            |            | mypostgresqldumpplanet=CTc/mypostgresqldumpplanet

\x seçeneği
Select cümlesi ile gösterilen kayıtları expanded display olarak gösterir. Yani sütunları alt alta yazar

13 Ekim 2019 Pazar

psql - PostgreSQL interactive terminal

Giriş
psql için bazı notlar

postgresql Kullanıcısı
Açıklaması şöyle. postgresql kullanıcısı psql komutunu çalıştır
There is a sub-class of non-root users that are often called "system users". Despite what the name suggests, they are ordinary users. They just happen to be created for special purposes like running a particular daemon and owning that daemon's files and directories. e.g. user lp for a printer daemon, ftp for ftpd, postgres for the postgresql database, and many more. They usually have a disabled password and their shell set to /bin/false or /usr/sbin/nologin or similar (user postgres is a notable exception because it's fairly common to su to user postgres to run psql for maintenance tasks).
Dump dosyasını geri yüklemek için şöyle yaparız
psql dbname < infile
Auto Complete
Açıklaması şöyle
Q : Is it possible to make autocomplete working in psql on Windows? As I know from Linux users, they can make use pressing TAB to autocomplete, which is quite handy, I guess.

A : psql's autocompletion comes by virtue of the readline or libedit library, whichever was configured when PostgreSQL was built from source. The Windows binaries were built without that support, most likely because there are no Windows ports of these libraries. If you port either of these libraries to Windows, you can build PostgreSQL from source and enjoy command line completion.
Çıktı
Giriş yaptıktan sonra gösterilen bilgi şöyledir
# psql -U myuser -d mydb -h 127.0.0.1 -p 5432 -W
Password:
psql (13.2 (Debian 13.2-1.pgdg100+1))
SSL connection (protocol: TLSv1.3, cipher: TLS_AES_256_GCM_SHA384, bits: 256,
compression: off) Type "help" for help.
Seçenekler
-c seçeneği
SQL cümlesini verir
Örnek
Şöyle yaparız.
psql mydb myuser -c "update endpoint set endpoint_group_id = 15 where mac_address='a';"
-d/--dbname seçeneği
Bağlanılacak veri tabanı ismini verir.
Örnek
Şöyle yaparız
psql -h localhost -U postgres -d mydb
-f/--file seçeneği
Çalıştırılacak SQL dosyasını belirtir.
Örnek
Şöyle yaparız
psql -U postgres -f /opt/scripts/test_script.sql
-h/--host seçeneği
Bağlanılacak host ismini belirtir. host ismi belirtilmezse localhost kullanılır.

ON_ERROR_STOP seçeneği
Örnek
Şöyle yaparız
psql -v ON_ERROR_STOP=1 --username "$POSTGRES_USER" --dbname "$POSTGRES_DB"
Örnek
Şöyle yaparız
#!/bin/bash
set -e
psql -v ON_ERROR_STOP=1 --username "$POSTGRES_USER" --dbname "$POSTGRES_DB" <<-EOSQL
  create schema test_schema;
  create table test_schema.employee(
          id  SERIAL PRIMARY KEY,
          firstname   TEXT    NOT NULL,
          lastname    TEXT    NOT NULL,
          email       TEXT    not null,
          age         INT     NOT NULL,
          salary         real,
          unique(email)
      );
EOSQL
--set seçeneği
Örnek
SSL ile bağlanmak için şöyle yaparız
psql -h <HOST_NAME> -p 5432 -U <USER_NAME> -W -d <DB_NAME> --set=sslmode=require
-U/--username seçeneği
Bağlantı için kullanılacak kullanıcı ismini belirtir.

-V seçeneği
Şöyle bir çıktı alırız
psql (PostgreSQL) 11.12
-w/--no-password seçeneği
Açıklaması şöyle
Never issue a password prompt. If the server requires password authentication and a password is not available from other sources such as a .pgpass file, the connection attempt will fail. This option can be useful in batch jobs and scripts where no user is present to enter a password.
-W/--password seçeneği
Açıklaması şöyle
Force psql to prompt for a password before connecting to a database, even if the password will not be used.
Şöyle yaparız
psql -h localhost -p 5432 -U postgres -W -d postgres

Meta Commands
Meta Commands yazısına taşıdım