|
|
 |
LXXXIV. Funzioni PostgreSQLIntroduzione
Il database PostgreSQL è un prodotto OpenSource ed è disponibile gratuitamente.
Postgres, sviluppato originariamente nel Dipartimento di Informatica dell'Università di
Berkeley, ha anticipato molti dei concetti su oggetti e relazioni che ora
stanno diventando disponibili in alcuni database commerciali. Postgres fornisce
supporto per il linguaggio SQL/92/SQL99, transazioni, integrità referenziale,
stored procedures ed estensibilità dei tipi. PostgreSQL è un discendente open source
dell'originario codice di Berkeley.
Requisiti
Per utilizzare il supporto a PostgreSQL, occorre PostgreSQL 6.5 o
versioni più recenti. PostgreSQL 7.0 o successivi permettono di abilitare tutte le funzionalità
di questo modulo. PostgreSQL ammette molte codifiche di carattere, tra cui
la codifica multibyte. La versione corrente e maggiori
informazioni su PostgreSQL sono disponibili su
http://www.postgresql.org/ e
http://techdocs.postgresql.org/.
Installazione
In order to enable PostgreSQL support,
--with-pgsql[=DIR] is required when you compile
PHP. DIR is the PostgreSQL base install directory, defaults to
/usr/local/pgsql. If shared object module is
available, PostgreSQL module may be loaded using
extension directive in php.ini or
dl()
function.
Configurazione di Runtime
Il comportamento di queste funzioni è influenzato dalle impostazioni di php.ini.
Tabella 1. PostgreSQL configuration options | Name | Default | Changeable |
|---|
| pgsql.allow_persistent | "1" | PHP_INI_SYSTEM | | pgsql.max_persistent | "-1" | PHP_INI_SYSTEM | | pgsql.max_links | "-1" | PHP_INI_SYSTEM | | pgsql.auto_reset_persistent | "0" | PHP_INI_SYSTEM | | pgsql.ignore_notice | "0" | PHP_INI_ALL | | pgsql.log_notice | "0" | PHP_INI_ALL |
For further details and definition of the PHP_INI_* constants see
ini_set().
Breve descrizione dei parametri
di configurazione.
- pgsql.allow_persistent
boolean
Whether to allow persistent Postgres connections.
- pgsql.max_persistent
integer
The maximum number of persistent Postgres connections per
process.
- pgsql.max_links
integer
The maximum number of Postgres connections per process,
including persistent connections.
- pgsql.auto_reset_persistent
integer
Detect broken persistent links with pg_pconnect().
Needs a little overhead.
- pgsql.ignore_notice
integer
Whether or not to ignore PostgreSQL backend notices.
- pgsql.log_notice
integer
Whether or not to log PostgreSQL backends notice messages. The PHP
directive
pgsql.ignore_notice must be off in order to log notice
messages.
Utilizzo e suggerimenti| Attenzione |
L'utilizzo del modulo PostgreSQL con PHP 4.0.6 non è raccomandato a causa
di un bug nella gestione dei messaggi. Si usi PHP 4.1.0 o successivi.
|
| Attenzione |
I nomi delle funzioni relative a PostgreSQL verranno cambiate a partire dalla versione 4.2.0 per
conformarsi agli standard di sviluppo attuali. La maggior parte dei nuovi nomi avrà
underscore aggiuntivi, per esempio pg_lo_open(). Alcune funzioni verranno rinominate
per dare consistenza. Per esempio pg_exec() diventerà
pg_query(). I vecchi nomi potranno essere usati nella versione 4.2.0 e in alcune versioni
successive alla 4.2.0, ma potranno essere cancellati in futuro.
Tabella 2. Nomi di funzione cambiati
La vecchia sintassi di pg_connect()/pg_pconnect()
sarà deprecata per supportare, in futuro, connessioni asincrone.
Si usi una stringa di connessione con pg_connect() e
pg_pconnect().
|
Non tutte le funzioni sono supportate su tutte le architetture. Dipende dalla versione
di libpq (L'interfaccia Client C per PostgreSQL) e da come libpq è
compilato. Se c'è una funzione mancante, libpq non supporta
la feature richiesta per quella funzione.
È importante usare versioni di libpq più recenti rispetto al Server
PostgreSQL al quale ci si vuole collegare. Se si usa una versione di libpq più vecchia rispetto
al Server PostgreSQL al quale ci si vuole collegare, si andrà probabilmente incontro a problemi.
Fin dalla versione 6.3 (03/02/1998) PostgreSQL usa gli unix domain socket
di default. La porta TCP, di default, NON verrà aperta. La tabella
sottostante descrive queste nuove possibilità di connessione. Questo
socket può essere trovato in /tmp/.s.PGSQL.5432.
Questa opzione può venire abilitata con la flag '-i' da
postmaster e il suo significato è: "ascolta i
socket TCP/IP così come gli Unix domain socket".
Tabella 3. Postmaster e PHP | Postmaster | PHP | Status |
|---|
| postmaster & | pg_connect("dbname=NomeMioDatabase"); | OK | | postmaster -i & | pg_connect("dbname=NomeMioDatabase"); | OK | | postmaster & | pg_connect("host=localhost dbname=NomeMioDatabase"); |
Unable to connect to PostgreSQL server: connectDB() failed:
Is the postmaster running and accepting TCP/IP (with -i)
connection at 'localhost' on port '5432'? in
/path/to/file.php on line 20.
| | postmaster -i & | pg_connect("host=localhost dbname=NomeMioDatabase"); | OK |
Si può stabilire una connessione al server PostgreSQL usando le
seguenti coppie di valori impostate nella stringa di comando: $conn =
pg_connect("host=IlMioHost port=LaMiaPorta tty=myTTY options=LeMieOpzioni
dbname=IlMioDB user=IlMioUtente password=LaMiaPassword ");
L'uso della sintassi in uso precedentemente:
$conn = pg_connect ("host", "port", "options", "tty", "dbname")
è deprecato.
Le variabili d'ambiente modificano il comportamento server/client di
PostgreSQL. Per esempio, il modulo PostgreSQL si baserà sulla variabile
PGHOST quando il nome dell'host è omesso nella stringa di
connessione. Le variabili d'ambiente riconosciute sono diverse da versione
a versione. Consultare il Manuale del Programmatore PostgreSQL (libpq -
Variabili d'Ambiente) per ulteriori dettagli.
Assicurarsi di aver impostato le variabili d'ambiente per l'utente appropriato. Usare
$_ENV o getenv() per controllare
quali variabili d'ambiente sono disponibili al processo corrente.
Esempio 1. Impostazione dei parametri di default PGHOST=pgsql.example.com
PGPORT=7890
PGDATABASE=web-system
PGUSER=web-user
PGPASSWORD=segreta
PGDATESTYLE=ISO
PGTZ=JST
PGCLIENTENCODING=EUC-JP
export PGHOST PGPORT PGDATABASE PGUSER PGPASSWORD PGDATESTYLE PGTZ PGCLIENTENCODING |
|
Costanti predefinite
Queste costanti sono definite da questa estensione e
sono disponibili solo se l'estensione è stata compilata
nel PHP o se è stata caricata dinamicamente a runtime.
Esempi
A partire da PostgreSQL 7.1.0, il tipo di dato text ha 1GB come dimensione
massima. Nelle versioni più vecchie di PostgreSQL il tipo di dato text è limitato dalla dimensione
del block. (Default 8KB. Massimo 32KB, specificato al momento della compilazione)
Per usare l'interfaccia large object (lo), è necessario includerla entro
un blocco di una transazione. Un blocco di transazione inizia con un
comando SQL BEGIN e se la
transazione è stata valida, termina con COMMIT o
END. Se la transazione fallisce, essa
deve venire chiusa con ROLLBACK o
ABORT.
Esempio 2. Utilizzare Large Objects |
<?php
$database = pg_connect ("dbname=jacarta");
pg_query ($database, "begin");
$oid = pg_lo_create ($database);
echo "$oid\n";
$handle = pg_lo_open ($database, $oid, "w");
echo "$handle\n";
pg_lo_write ($handle, "dati large object");
pg_lo_close ($handle);
pg_query ($database, "commit");
?>
|
|
Non chiudere la risorsa di connessione prima di aver chiuso la risorsa
large object.
add a note
User Contributed Notes
Funzioni PostgreSQL
17-Mar-2004 11:50
I wrote some code that converts Postgres arrays to PHP arrays. I haven't done too much testing, but it seems to do the job for me.
/**
* A quick and dirty array grabber for postgres arrays. Not
* tested very well.
* @returns A PHP array.
**/
function toArray($pgArray){
if(strlen($pgArray) == 0){
return;
}
elseif($this->getChar($pgArray) == "," or $this->getChar($pgArray) == " "){
return $this->toArray(substr($pgArray, 1));
}
elseif($this->getChar($pgArray) == "{"){
//find the end of the array
$depth = 1;
for($i=1; $depth>0 && $i<strlen($pgArray); $i++){
if($this->getChar($pgArray, $i) == '\\'){
//skip escape chars
$i++;
next;
}
if($this->getChar($pgArray, $i) == "{"){
$depth++;
next;
}
if($this->getChar($pgArray, $i) == "}"){
$depth--;
next;
}
}
$arrayEnd = $i;
$first = substr($pgArray, 1, $arrayEnd - 2);
$second = substr($pgArray, $arrayEnd);
if($second == ""){
return $this->toArray($first);
}
$r[] = $this->toArray($first);
$r[] = $this->toArray($second);
return $r;
}
elseif($this->getChar($pgArray) == "\""){
//a quoted item
$depth = 1;
for($i=1; $depth && $i<strlen($pgArray); $i++){
if($this->getChar($pgArray, $i) == "\\"){
$i++;
next;
}
if($this->getChar($pgArray, $i) == "\""){
$depth--;
next;
}
}
$arrayEnd = $i;
$r[] = substr($pgArray, 1, $arrayEnd - 2);
$r = array_merge($r,
$this->toArray(substr($pgArray, $arrayEnd + 1)));
return $r;
}
else{
//an unquoted item
$depth = 1;
for($i=1; $depth && $i<strlen($pgArray); $i++){
if($this->getChar($pgArray, $i) == "\\"){
$i++;
next;
}
if($this->getChar($pgArray, $i) == ","){
$depth--;
next;
}
}
$arrayEnd = $i;
if($arrayEnd == strlen($pgArray)){
$r[] = $pgArray;
}
else{
$r[] = substr($pgArray, 0, $arrayEnd-1);
}
$r = array_merge($r,$this->toArray(substr($pgArray,
$arrayEnd)));
return $r;
}
}
function getChar($string, $pos=0){
return substr($string, $pos, 1);
}
fmonteiro11 at hotmail dot com
15-Jan-2004 04:50
daniel at bichara dot com dot br
30-Dec-2002 11:04
Running RedHat Linux and Apache with suexec enabled you must include pgsql.so on each .php file using dl("pgsql.so") and remove "extension=pgsql.so" from php.ini, otherwise Apache (httpd) will not start.
anonymous at unknown dot com
29-Nov-2002 03:50
I just wanted to add to my previous post I've got the system up and running.
Environment: Windows XP, Apache 1.3.23, Php 4.3 RC2, PostGreSQL beta4 native windows build
Installation was fairly easy:
1. read the readme.txt
2. edit the setenv.bat as described in readme
3. run 'initdb'
all execs are in /bin
help is accessed like <command> --help
4. Start the psql deamon - you may want to create a batch file like
'D:\postgres_beta4\bin\postmaster -h localhost -D D:/postgres_beta4/data'
--deamon should be up and running now--
You can login into a shell from a console like
'psql -h localhost -d <username>'
You must load the postgresql extension by editing the php.ini and restarting apache in order to access psql with php.
And one final not: when running
$dbconn = pg_connect ("host=localhost port=5432 dbname=$dbname user=$user");
remember that $user and or $dbname is CASESENSITIVE.
Oh yeah, I created the data dir manually - don't know whether that was necessary
Grtz Vargo
anonymous at unknown dot com
29-Nov-2002 12:01
amk at eight13 dot com
27-Nov-2002 05:36
The list of postgresql function name changes is missing pg_errormessage being changed to pg_last_error.
swm at php dot net
22-Aug-2002 02:49
mystran at wasteland dot pp dot htv dot fi
04-Feb-2002 01:46
Nice to know fact that I didn't find documented here.
PHP will return values of PostgreSQL boolean datatype as single character strings "t" and "f", not PHP true and false.
[Editor's Note]
't' or 'f' is valid boolean expression for PostgreSQL.
All values from PostgreSQL are strings, since PostgreSQL integer, float may be much larger than PHP's native int, double can handle. PostgreSQL array is not supported.
saberit at home dot com
15-Sep-2001 08:11
I tried compiling PHP from source with PostgreSQL support (./configure --with-pgsql=/usr/local/pgsql) and ran into a bunch of problems when trying to 'make'. The problem was that some of the PostgreSQL headers were not installed by default when I installed PostgreSQL from source. When installing PostgreSQL make sure you 'make install-all-headers' after you 'make install'.
hubert at hubertmuller dot com
09-Jul-2001 10:36
The best way to find the separated list of tables, sequences, keys etc is:
SELECT relname FROM pg_class WHERE relkind='<value>' AND relname !~ '^pg_';
<value> takes:
i for keys,
r for relations,
S for sequences
Note that all tables names that begins with 'pg_' are PostgreSQL internal tables (this explain why I use AND relname !~ '^pg_' condition).
passion at monkey dot org
28-Jun-2001 12:53
!spamcraig at ahdore dot com
15-Apr-2001 07:11
If you want to extract data from select statements, you need to store the result index, and then apply pg_result to that value. Basically, do this
$resultIdx = pg_query ($database, "select * from tablename");
$mySelect = pg_fetch_result($resultIdx, 0, 0); // gets column 0 of tuple 0
echo("My select: [".$mySelect."]");
I'm new to php and had to do some fiddling around to work this out. It's reasonably elementary, but not demonstrated by the examples on these pages. Hopefully it will come in useful to someone else.
jdb30 at cornell.edu
06-Dec-2000 06:08
bleach at chek dot com
02-Mar-2000 06:36
If you want to see all the objects in a database, you can find that information in the pg_class table. <BR>
SELECT * FROM pg_class;<BR>
Now this is going to be kind of long and complex, to see how psql command handles the \d and other things. use the syntax. psql -E <Database>, ie psql -E mydatabase <BR>
What this will do is show the SQL command used for everything. So when you type a \d or something, it shows the SQL query used for the result.
| |