Download PostgreSQL File

Document related concepts

IMDb wikipedia , lookup

Microsoft SQL Server wikipedia , lookup

Concurrency control wikipedia , lookup

Open Database Connectivity wikipedia , lookup

Microsoft Jet Database Engine wikipedia , lookup

SQL wikipedia , lookup

Entity–attribute–value model wikipedia , lookup

Database wikipedia , lookup

PL/SQL wikipedia , lookup

Extensible Storage Engine wikipedia , lookup

Clusterpoint wikipedia , lookup

Relational model wikipedia , lookup

Database model wikipedia , lookup

Transcript
Struktur Data
PostreSQL 9.2
Pengenalan PostgreSQL
PostgreSQL
• PostgreSQL is a powerful, open source object-relational
database system.
• More than 15 years of active development and a proven
architecture that has earned it a strong reputation for
reliability, data integrity, and correctness.
• Based on POSTGRES, Version 4.2, developed at the
University of California at Berkeley Computer Science
Department.
Feature
• complex queries
• foreign keys
• triggers
• views
• transactional integrity
• Multi-version concurrency control
• point in time recovery
• tablespaces
• asynchronous replication
• nested transactions (savepoints)
• online/hot backups
• a sophisticated query planner/optimizer
• write ahead logging for fault tolerance
• PostGIS
Limitation
Limit
Value
Maximum Database Size
Unlimited
Maximum Table Size
32 TB
Maximum Row Size
1.6 TB
Maximum Field Size
1 GB
Maximum Rows per Table
Unlimited
Maximum Columns per Table
250 - 1600 depending on column types
Maximum Indexes per Table
Unlimited
Advantages
• Extensible
•
•
•
•
•
•
•
•
•
•
data types
functions
operators
aggregate functions
index methods
procedural languages
Cross Platform
Designed for high volume environments
GUI database design and administration tools
Free..!
Cross Platform Distribution
• BSD
• FreeBSD
• OpenBSD
• Linux
•
•
•
•
•
RedHat/CentOS/Fedora/Scientific families Linux
Debian GNU/Linux
Ubuntu Linux
SuSE and OpenSuSE
Other Linux
• Mac OS X
• Solaris
• Windows
• Source Code
GiST
• GiST (Generalized Search Tree) indexing
• advanced system which brings together a wide array of
different sorting and searching algorithms
• B-tree, B+-tree, R-tree, partial sum trees, ranked B+-trees and
many others.
• provides an interface which allows both the creation of
custom data types as well as extensible query methods with
which to search them.
• flexibility to specify what you store, how you store it, and the
ability to define new ways to search through
• Foundation for many public projects that use
PostgreSQL
• OpenFTS
• PostGIS
OpenFTS
• OpenFTS (Open Source Full Text Search engine) is
an advanced PostgreSQL-based search engine that
provides online indexing of data and relevance
ranking for database searching.
• Close integration with database allows use of
metadata to restrict search results.
PostGIS
• PostGIS adds support for geographic objects to
the PostgreSQL object-relational database.
• PostgreSQL used as a backend spatial database for
geographic information systems (GIS).
• Like ESRI's SDE or Oracle's Spatial extension.
• PostGIS follows the OpenGIS "Simple Features
Specification for SQL" and has been certified as
compliant with the "Types and Functions" profile.
• PostGIS is open source spatial database technology.
Instalasi
• …..
PgAdmin III
SQL Shell
Referensi SQL
• http://www.postgresql.org/docs/9.2/static/index.h
tml
RDBMS
• A Relational database management system
(RDBMS) is a database management system
(DBMS) that is based on the relational model as
introduced by E. F. Codd
• Data stored in tables
• Column  Field
• Row  Data
Normalization
• Eliminating redundant data, for example, storing
the same data in more than one tables.
• Ensuring data dependencies make sense.
• Normalization form
• First Normal Form (1NF)
• Second Normal Form (2NF)
• Third Normal Form (3NF)
SQL
• SQL is structured Query Language which is a computer
language for storing, manipulating and retrieving data
stored in relational database.
• Standard language for Relation Database System.
• All relational database management systems uses SQL as
standard database language
• Also they are using different dialects, Such as:
• MS SQL Server using T-SQL,
• Oracle using PL/SQL,
• MS Access version of SQL is called JET SQL (native format )etc
Query Process
SQL Commands:
• DDL - Data Definition Language:
• Statement yang digunakan untuk membangun atau
memodifikasi struktur table atau objek lainnya dalam
database.
• DML - Data Manipulation Language:
• Statement yang digunakan untuk memanipulasi data
• DCL - Data Control Language:
• Statement yang digunakan untuk menciptakan roles,
permission dan melakukan control akses dalam database
• DQL - Data Query Language:
• Statement untuk mengambil data.
PgSQL ROLE
ROLE
• User untuk database
• Administrasi ROLE
• Menciptakan
• Menghapus
• Mengubah
Mengelola Role
• Menciptakan Role
• CREATE ROLE <name>;
• Menghapus Role
• DROP ROLE <name>;
• Melihat Role
• SELECT rolname FROM pg_roles;
Atribute Role
• LOGIN
• SUPERUSER
• CREATEDB
• CREATEROLE
• REPLICATION LOGIN
• PASSWORD password'
Mengubah Role
• ALTER ROLE <name> [ [ WITH ] option [ ... ] ]
• ALTER ROLE <name> RENAME TO <new_name>
• Options
SUPERUSER | NOSUPERUSER
| CREATEDB | NOCREATEDB
| CREATEROLE | NOCREATEROLE
| CREATEUSER | NOCREATEUSER
| INHERIT | NOINHERIT
| LOGIN | NOLOGIN
| REPLICATION | NOREPLICATION
| CONNECTION LIMIT connlimit
| [ ENCRYPTED | UNENCRYPTED ] PASSWORD 'password'
| VALID UNTIL 'timestamp'
Administrasi Database
Mengelola Database
• Menampilkan db
• SELECT datname FROM pg_database
• Menciptakan db
• CREATE DATABASE <dbname>
• CREATE DATABASE <dbname> OWNER <rolename>;
Mengelola Database
• Menggunakan db
• \connect<dbname>
• \c <dbname>
• Menghapus db
• DROP DATABASE <dbname>
Manajemen Tabel
Manajemen Tabel
• Menampilkan
• Menciptakan
• Menghapus
• Mengubah
• Mendeskripsikan
Struktur Table
• Data disimpan dalam table
• Column  Data Field
• Row  Data/Fakta
• Column memiliki data type
• Data disimpan sesuai data type column tersebut.
Data Type
•
•
•
•
•
•
•
•
•
Numeric
Monetary
Character
Binary Data Type
Date/Time
Boolean
Enumerated Type
Geometric
Network Address Type
•
•
•
•
•
•
•
•
•
•
Bit String
Text Search Type
UUID
XML
JSON
Array
Composite
Range Type
Object Identifier
Pseudo Type
Numeric Type
Name
smallint
integer
Storage Size
2 bytes
4 bytes
Description
small-range integer
typical choice for integer
bigint
8 bytes
large-range integer
decimal
variable
user-specified precision,
exact
numeric
variable
user-specified precision,
exact
real
double precision
4 bytes
8 bytes
smallserial
2 bytes
serial
4 bytes
bigserial
8 bytes
variable-precision, inexact
variable-precision, inexact
small autoincrementing
integer
autoincrementing integer
large autoincrementing
integer
Range
-32768 to +32767
-2147483648 to +2147483647
-9223372036854775808 to
9223372036854775807
up to 131072 digits before the decimal
point; up to 16383 digits after the decimal
point
up to 131072 digits before the decimal
point; up to 16383 digits after the decimal
point
6 decimal digits precision
15 decimal digits precision
1 to 32767
1 to 2147483647
1 to 9223372036854775807
Character Type
Name
Description
character varying(n), varchar(n)
variable-length with limit
character(n), char(n)
fixed-length, blank padded
text
variable unlimited length
Date/Time Type
Name
Storage Size
Description
Low Value
High Value
Resolution
8 bytes
both date and
time (no time
zone)
4713 BC
294276 AD
1 microsecond / 14
digits
timestamp [ (p) ]
with time zone
8 bytes
both date and
time, with time
zone
4713 BC
294276 AD
1 microsecond / 14
digits
date
4 bytes
date (no time of
day)
4713 BC
5874897 AD
1 day
time [ (p) ] [ without
time zone ]
8 bytes
time of day (no
date)
00:00:00
24:00:00
1 microsecond / 14
digits
time [ (p) ] with time
12 bytes
zone
times of day
only, with time
zone
00:00:00+1459
24:00:00-1459
1 microsecond / 14
digits
interval [ fields ] [ (p)
12 bytes
]
time interval
-178000000
years
178000000
years
1 microsecond / 14
digits
timestamp [ (p) ] [
without time zone ]
Boolean
Name
Storage Size
Description
boolean
1 byte
state of true or false
Enumerated Type
CREATE TYPE mood AS ENUM ('sad', 'ok', 'happy');
CREATE TABLE person (
name text,
current_mood mood
);
INSERT INTO person VALUES ('Moe', 'happy');
SELECT * FROM person WHERE current_mood = 'happy';
name | current_mood
------+-------------Moe | happy
Geometric
Name
Storage Size
Representation
Description
point
16 bytes
Point on a plane
(x,y)
line
32 bytes
Infinite line (not
((x1,y1),(x2,y2))
fully implemented)
lseg
32 bytes
Finite line segment ((x1,y1),(x2,y2))
box
32 bytes
Rectangular box
((x1,y1),(x2,y2))
path
16+16n bytes
Closed path
(similar to
polygon)
((x1,y1),...)
path
16+16n bytes
Open path
[(x1,y1),...]
polygon
40+16n bytes
Polygon (similar to
closed path)
((x1,y1),...)
circle
24 bytes
Circle
<(x,y),r> (center
point and radius)
Administrasi Table
• Menampilkan Table
• SELECT table_name FROM information_schema.tables
WHERE table_schema = 'public';
Menciptakan Tabel
CREATE TABLE weather (
city
varchar(80),
temp_lo
int,
-- low temperature
temp_hi
int,
-- high temperature
prcp
real,
-- precipitation
date
date
);
Menghapus Tabel
• DROP TABLE <tablename>;
Mengubah Tabel
• ALTER TABLE <tablename> RENAME TO
<newname>;
Mengubah Tabel
• Add Column
• ALTER TABLE products ADD COLUMN description text CHECK
(description <> '');
• Remove Column
• ALTER TABLE products DROP COLUMN description CASCADE;
• Rename Column
• ALTER TABLE products RENAME COLUMN product_no TO
product_number;
• Change Data Type
• ALTER TABLE products ALTER COLUMN price TYPE
numeric(10,2);
Tabel mahasiswa UNAND
• Nama
varchar(100)
• NIM
varchar(10)
• Fakultas varchar(32)
• Jurusan varchar(32)
• Jenis Kelamin
Boolean/varchar(1)
• Tempat Lahir
varchar(32)
• Tanggal Lahir
date
Constraint & Default Value
• Default Value
• ALTER TABLE products ALTER COLUMN price SET
DEFAULT 7.77;
• Adding Constraint
• ALTER TABLE products ADD CHECK (name <> '');
• ALTER TABLE products ADD CONSTRAINT some_name
UNIQUE (product_no);
• ALTER TABLE products ADD FOREIGN KEY
(product_group_id) REFERENCES product_groups;
• Removing Constraint
• ALTER TABLE products DROP CONSTRAINT some_name;
Constraints
• Check Constraints
• CHECK(<condition>)
• Not-Null Constraints
• NOT NULL
• Unique Constraints
• UNIQUE
• Primary Keys
• PRIMARY KEY
• Foreign Keys
• REFERENCES <tablename>(<columnname>)
• Exclusion Constraints
• EXCLUDE USING gist (c WITH &&)
Deskripsi Tabel
• SELECT column_name FROM
information_schema.columns WHERE table_name
=‘<table>‘;
Manipulasi Data
Insert Data
INSERT INTO <tablename> VALUES (<val1>, <val2>,…)
INSERT INTO <tablename>
(<col1>, <col2>, …)
VALUES
(<val1>, <val2>, …)
Update Data
• UPDATE <tablename> SET <column_name> =
<new_value> WHERE <condition>
Delete Data
• DELETE FROM <tablename>
• DELETE FROM <tablename> WHERE condition
Query Data
SELECT * FROM <tablename>;
SELECT [ ALL | DISTINCT [ ON ( expression [, ...] ) ] ]
* | expression [ [ AS ] output_name ] [, ...]
[ FROM from_item [, ...] ]
[ WHERE condition ]
[ GROUP BY expression [, ...] ]
[ HAVING condition [, ...] ]
[ WINDOW window_name AS ( window_definition ) [, ...] ]
[ { UNION | INTERSECT | EXCEPT } [ ALL | DISTINCT ] select ]
[ ORDER BY expression [ ASC | DESC | USING operator ] [ NULLS { FIRST | LAST } ] [, ...] ]
[ LIMIT { count | ALL } ]
[ OFFSET start [ ROW | ROWS ] ]
[ FETCH { FIRST | NEXT } [ count ] { ROW | ROWS } ONLY ]
[ FOR { UPDATE | SHARE } [ OF table_name [, ...] ] [ NOWAIT ] [...] ]
Query Data (FROM)
• Basic Form
• FROM <table_reference>
• Table Join
• Cross Join
• Qualified Join
•
•
•
•
Inner Join
Left join
Right Join
Full Join
Query Data (WHERE)
• SELECT * FROM <tablename> WHERE <condition>
Query Data
• HAVING
• GROUP BY
• LIMIT
• OFFSET
TUGAS
• Buat tabel (query table)
• Barang
• Penjualan
• Detil Penjualan
• Query
• Insert barang (5 contoh barang)
• Insert data penjualan dan detil penjualan (3)
• Menampilkan 1 data penjualan berikut dengan detil
barang yang dibeli
• Menampilkan total penjualan dalam satu hari (rupiah).
• Menampilkan barang yang memiliki stok < 5 buah
Fitur Lanjutan PgSQL
View
CREATE VIEW myview AS
SELECT city, temp_lo, temp_hi, prcp, date, location
FROM weather, cities
WHERE city = name;
SELECT * FROM myview;
Table Relation
CREATE TABLE cities (
city varchar(80) primary key,
location point
);
CREATE TABLE weather (
city varchar(80) REFERENCES cities(city) on delete
cascade,
temp_lo int,
temp_hi int,
prcp real,
date date );
Foreign Keys
• ON DELETE
• ON UPDATE
•
•
•
•
•
NO ACTION
RESTRICT
CASCADE
SET NULL
SET DEFAULT
Transactions
• The essential point of a transaction is that it
bundles multiple steps into a single, all-or-nothing
operation
Transactions
BEGIN
UPDATE accounts SET balance = balance - 100.00
WHERE name = 'Alice';
UPDATE accounts SET balance = balance + 100.00
WHERE name = 'Bob';
COMMIT
Transactions
BEGIN;
UPDATE accounts SET balance = balance - 100.00
WHERE name = 'Alice';
SAVEPOINT my_savepoint;
UPDATE accounts SET balance = balance + 100.00
WHERE name = 'Bob';
-- oops ... forget that and use Wally's account
ROLLBACK TO my_savepoint;
UPDATE accounts SET balance = balance + 100.00
WHERE name = 'Wally';
COMMIT;
Window Function
SELECT depname, empno, salary, avg(salary) OVER (PARTITION BY depname) FROM
empsalary;
depname | empno | salary | avg
--------+-------+--------+----------------------develop |
11
|
5200 | 5020.0000000000000000
develop |
7
|
4200 | 5020.0000000000000000
develop |
9
|
4500 | 5020.0000000000000000
develop |
8
|
6000 | 5020.0000000000000000
develop |
10
|
5200 | 5020.0000000000000000
personnel |
5
|
3500 | 3700.0000000000000000
personnel |
2
|
3900 | 3700.0000000000000000
sales
|
3
|
4800 | 4866.6666666666666667
sales
|
1
|
5000 | 4866.6666666666666667
sales
|
4
|
4800 | 4866.6666666666666667
(10 rows)
Inheritance
CREATE TABLE cities (
name text,
population real,
altitude int -- (in ft)
);
CREATE TABLE capitals (
state char(2)
) INHERITS (cities);
Inheritance
• SELECT name, altitude FROM cities WHERE altitude
> 500;
• SELECT name, altitude FROM ONLY cities WHERE
altitude > 500;
Tugas
• Buatlah database sederhana untuk sebuah
perpustakaan jurusan. Database tersebut harus
bisa.
• Mengelola data anggota dan koleksi
• Mengelola data transaksi peminjaman
• Memberikan laporan
•
•
•
•
•
Jumlah total koleksi
5 mahasiswa peminjam terbanyak/bulan
10 Buku yang paling sering dipinjam/bulan
Total Peminjaman koleksi/bulan
Total mahasiswa yang meminjam/bulan
PHP & PgSQL
Pendahuluan
• PgSQL merupakan RDBMS
• Aplikasi membutuhkan database
• Aplikasi dibangun dengan menggunakan bahasa
pemograman
• PHP…
<HTML>
• Hyper Text Markup Language.
• HTML bukan bahasa pemrograman, HTML adalah
suatu markup language.
• Suatu markup language berupa serangkaian markup
tags.
• HTML menggunakan markup tags untuk
mendeskripsikan halaman web.
• Dibantu CSS
HTML Tags
• HTML Tags
• HTML markup tag biasa disebut HTML tag.
• HTML tags berupa keywords oleh tanda kurung
• Exp : <html> <b> <strong> <h1> <title>
• HTML tags biasanya dipakai berpasangan
• Start tags - end tags / opening tags - closing tags.
• Tag memiliki attribute
• HTML Document
• HTML document mendeskripsikan suatu web pages.
• HTML documents berisi HTML tags dan plain text atau
text biasa.
HTML Tags : example
Standar HTML
• HTML 4.01 (1999)
• http://www.w3.org/TR/html401/
• HTML 5
• http://www.w3.org/TR/html5/
• Apa bedanya ??
• http://www.w3.org/TR/html5-diff/
Pengenalan PHP
• PHP
•
•
•
•
•
•
•
•
open-source server-side scripting language
designed for Web development
embedded into an HTML source document
interpreted by a PHP processor module
command-line interface capability
can be deployed on most Web servers
free of charge.
Created by Rasmurf Lerdorf
Why PHP?
• Multiplatform
• Kompatibel dengan kebanyakan web server
• Support database yang luas
• PHP is free
• Mudah dipelajari
Overview PHP
• Script PHP harus berada dalam tag <?php …. ?>
• Variable dalam PHP
• Diawali dengan $
• Dynamic type
• Operator dalam PHP
• As usual
• Commenting…
Overview
• Basic
• Output
• echo
• printf
• Input?
• …..
Control Program
• Pemilihan Kondisi
• If
• If … else
• If … else if … else
• Perulangan
• Do while
• While do
• For loop
Function
PHP & PgSQL
Tugas – tidak dikumpul
• Instalasi PgSQL
• Instalasi Apache & PHP
• Pelajari PHP
• Buat aplikasi CRUD data mahasiswa
Tabel Mahasiswa
• Nim
varchar(10)
• Nama
varchar(32)
• Jurusan varchar(32), enum
• Fakultas varchar(32), enum
• Tempatlahir
varchar(32)
• TanggalLahir
date
Aplikasi Sederhana
Data Koleksi Perpustakaan
• Buat sebuah aplikasi sederhana untuk mengelola data
koleksi perpustakaan.
•
•
•
•
Buat database (tabel koleksi, anggota, peminjaman)
Tentukan field
Buat aplikasi CRUD (Create Read Update Delete) untuk koleksi
Buat laporan :
• Statistik :
• Total Koleksi
• Total Anggota
• Total peminjaman/bulan
• Kumpulkan pada saat UAS