Autore Topic: [Risolto] PostgreSQL come creare un nuovo database  (Letto 1274 volte)

Offline Gianluigi

  • Moderatore globale
  • Senatore Gambero
  • *****
  • Post: 4.152
  • Tonno verde
    • Mostra profilo
[Risolto] PostgreSQL come creare un nuovo database
« il: 02 Settembre 2019, 13:29:06 »
Stavo creando un database di prova postgresql per verificarne i passaggi.
Purtroppo devo aver combinato un pasticcio in quanto alla verifica finale ottengo questi risultati, vale a dire che, se capisco bene, invece di aver popolato il nuovo database "rubinettofelice" ho popolato direttamente il template1.

Questo è quanto mi viene restituito dal terminale:

Codice: [Seleziona]
~$ psql -U postgres
Password for user postgres:
psql (11.5 (Ubuntu 11.5-0ubuntu0.19.04.1))
Type "help" for help.

postgres=# \l

      Name       |   Owner   | Encoding |   Collate   |    Ctype    |   Access privileges   
-----------------+-----------+----------+-------------+-------------+-----------------------
 postgres        | postgres  | UTF8     | it_IT.UTF-8 | it_IT.UTF-8 |
 rubinettofelice | gianluigi | UTF8     | it_IT.UTF-8 | it_IT.UTF-8 |
 template0       | postgres  | UTF8     | it_IT.UTF-8 | it_IT.UTF-8 | =c/postgres          +
                 |           |          |             |             | postgres=CTc/postgres
 template1       | postgres  | UTF8     | it_IT.UTF-8 | it_IT.UTF-8 | =c/postgres          +
                 |           |          |             |             | postgres=CTc/postgres
(4 rows)

postgres=# \du
                                   List of roles
 Role name |                         Attributes                         | Member of
-----------+------------------------------------------------------------+-----------
 gianluigi | Create role, Create DB                                     | {}
 postgres  | Superuser, Create role, Create DB, Replication, Bypass RLS | {}

postgres=# \c rubinettofelice
You are now connected to database "rubinettofelice" as user "postgres".
rubinettofelice=# \d
Did not find any relations.  <<===================================================== SIGH!

rubinettofelice=# \dn
  List of schemas
  Name  |  Owner   
--------+----------
 public | postgres
(1 row)

rubinettofelice=# \c template1
You are now connected to database "template1" as user "postgres".
template1=# \d
                 List of relations
 Schema |       Name        |   Type   |   Owner   
--------+-------------------+----------+-----------
 public | fipart            | table    | gianluigi
 public | tagent            | table    | gianluigi
 public | tagent_idagen_seq | sequence | gianluigi
 public | tfilms            | table    | gianluigi
 public | tfilms_idfilm_seq | sequence | gianluigi
 public | tst_fi            | table    | gianluigi
 public | tstars            | table    | gianluigi
 public | tstars_idstar_seq | sequence | gianluigi
(8 rows)

Io ho creato il database da terminale con questi passaggi.

Prima ho creato l'utente gianluigi:

Codice: [Seleziona]
~$ psql -U postgres -d template1
Password for user postgres:
psql sql (11.5 (Ubuntu 11.5-0ubuntu0.19.04.1))
Type "help" for help.

template1=# CREATE ROLE gianluigi WITH CREATEDB CREATEROLE LOGIN ENCRYPTED PASSWORD 'miapassword';
CREATE ROLE

Poi ho creato il nuovo database "rubinettofelice":

Codice: [Seleziona]
~$ psql -U test -d template1
Password for user test:
psql sql (11.5 (Ubuntu 11.5-0ubuntu0.19.04.1))
Type "help" for help.

template1=> CREATE DATABASE rubinettofelice WITH OWNER=gianluigi TEMPLATE= template1 ENCODING='utf-8';
CREATE DATABASE

A questo punto ha creato un progetto Gambas con un modulo (MBase.module):

Codice: [Seleziona]
' Gambas module file


Private $hConn As New Connection

Public Sub OpenDB(DBType As String, DBHost As String, DBName As String, UserName As String, UserPassword As String)

  $hConn.Close()
  $hConn.Type = Lower(DBType)
  $hConn.Host = DBHost
  '$hConn.Name = ""
  $hConn.Login = UserName
  $hConn.Password = UserPassword
  '$hConn.Port = "5432"

  $hConn.Open()

  If $hConn.Databases.Exist(DBName) Then
    MakeTable()
  Else
    Error.Raise(("Database not found.\n\nAre you sure that the database exist?"))
  Endif
 
  $hConn.Close()
Catch
  Message.Error(Error.Text & "\n\n" & Error.Where)
  FMain.Close()
 
End

Public Sub CloseDB()
 
  $hConn.Close()
 
End

Private Sub MakeTable()

  Dim hTable As Table

  $hConn.Begin

  If Not $hConn.Tables.Exist("tstars") Then
    hTable = $hConn.Tables.Add("tstars")
 
    hTable.Fields.Add("idstar", db.Serial)
    hTable.Fields.Add("stname", db.String, 40)
    hTable.Fields.Add("stsurn", db.String, 40)
    hTable.Fields.Add("stheig", db.Integer)
    hTable.Fields.Add("stweig", db.Integer)
    hTable.Fields.Add("stbirt", db.Date)
    hTable.Fields.Add("sttele", db.String, 13)
    hTable.Fields.Add("idagen", db.integer)
    hTable.Fields.Add("stimag", db.Blob)
    hTable.PrimaryKey = ["idstar"]
    hTable.Update

  Endif
 
  If Not $hConn.Tables.Exist("tagent") Then
    hTable = $hConn.Tables.Add("tagent")

    hTable.Fields.Add("idagen", db.Serial)
    hTable.Fields.Add("agname", db.String, 40)
    hTable.Fields.Add("agsurn", db.String, 40)
    hTable.Fields.Add("agaddr", db.string, 80)
    hTable.Fields.Add("agcity", db.string, 40)
    hTable.Fields.Add("agstat", db.string, 40)
    hTable.Fields.Add("agcoun", db.string, 40)
    hTable.Fields.Add("agpost", db.string, 10)
    hTable.Fields.Add("agtele", db.String, 13)
    hTable.Fields.Add("agmail", db.String, 30)
    hTable.Fields.Add("agwebs", db.String, 30)
    hTable.PrimaryKey = ["idagen"]
    hTable.Update
  Endif

  If Not $hConn.Tables.Exist("tfilms") Then
    hTable = $hConn.Tables.Add("tfilms")

    hTable.Fields.Add("idfilm", db.Serial)
    hTable.Fields.Add("finame", db.String, 100)
    hTable.Fields.Add("fiyear", db.Date)
    hTable.Fields.Add("fiprod", db.string, 100)
    hTable.Fields.Add("fiboxo", db.Float)
    hTable.PrimaryKey = ["idfilm"]
    hTable.Update
  Endif

  If Not $hConn.Tables.Exist("tst_fi") Then
    hTable = $hConn.Tables.Add("tst_fi")

    hTable.Fields.Add("idstar", db.Integer)
    hTable.Fields.Add("idfilm", db.Integer)
    hTable.Fields.Add("sfpart", db.String, 20, "ND")
    'hTable.Indexes.Add("x_stfi", ["idstar", "idfilm"])
    hTable.Update
  Endif

  If Not $hConn.Tables.Exist("fipart") Then
    hTable = $hConn.Tables.Add("fipart")

    hTable.Fields.Add("paname", db.String, 10)
    hTable.Update
  Endif

  $hConn.Commit
Catch
  $hConn.Rollback
  CloseDB()
  Debug Error.Where, Error.Text, Error.Code

End

E una finestra nella quale  apro una finestra di connessione che crea qualcosa di simile e fa partire il codice del modulo:

Codice: [Seleziona]
MBase.OpenDB("postgresql", "localhost", "rubinettofelice", "gianluigi", "miapassword")

Qualcuno può aiutarmi a capire dove ho commesso l'errore?

Grazie  :ciao:
« Ultima modifica: 05 Settembre 2019, 10:47:34 da Gianluigi »
nuoto in attesa del bacio di una principessa che mi trasformi in un gambero azzurro

Offline Berserker79

  • Grande Gambero
  • ***
  • Post: 201
    • Mostra profilo
Re:PostgreSQL come creare un nuovo database
« Risposta #1 il: 02 Settembre 2019, 16:35:22 »
Ciao, se non sbaglio, quando effettui la connessione al server, non specifichi il db a cui collegarsi,
quindi è possibile che ti venga associato un db di default per l'utente con cui effettui il login.
Successivamente fai il test se esiste il tuo db, e se esiste lanci la routine di creazione delle tabelle, solo che non vedo il codice in cui gli indichi di utilizzare il tuo db,
quindi il db di riferimento rimane quello al momento del login.
Ciao.

Offline Gianluigi

  • Moderatore globale
  • Senatore Gambero
  • *****
  • Post: 4.152
  • Tonno verde
    • Mostra profilo
Re:PostgreSQL come creare un nuovo database
« Risposta #2 il: 02 Settembre 2019, 16:47:04 »
 :ciao: Berserker79,

buona intuizione, penso che tu abbia ragione.  :ok:
Creerò una nuova VBox, lascerò questa per vedere se qualcuno sa come si ripristina tempate1.
Non ho ancora pensato a googlare su questo argomento...

Grazie
nuoto in attesa del bacio di una principessa che mi trasformi in un gambero azzurro

Offline Gianluigi

  • Moderatore globale
  • Senatore Gambero
  • *****
  • Post: 4.152
  • Tonno verde
    • Mostra profilo
Re:PostgreSQL come creare un nuovo database
« Risposta #3 il: 02 Settembre 2019, 17:42:20 »
Il primo step è fatto, template1 è ripristinato *.
Questi sono i comandi:
Codice: [Seleziona]
~$ psql -U postgres -d template1
Password for user postgres:
psql (11.5 (Ubuntu 11.5-0ubuntu0.19.04.1))
Type "help" for help.

template1=# select * from pg_database;
template1=# UPDATE pg_database SET datallowconn = TRUE WHERE datname = 'template0';
UPDATE 1
template1=# \c template0
You are now connected to database "template0" as user "postgres".
template0=# UPDATE pg_database SET datistemplate = FALSE WHERE datname = 'template1';
UPDATE 1
template0=# drop database template1;
DROP DATABASE
template0=# create database template1 with template = template0;
CREATE DATABASE
template0=# UPDATE pg_database SET datistemplate = TRUE WHERE datname = 'template1';
UPDATE 1
template0=# \c template1
You are now connected to database "template1" as user "postgres".
template1=# UPDATE pg_database SET datallowconn = FALSE WHERE datname = 'template0';
UPDATE 1
template1=# \d
Did not find any relations.

 :ciao:

* Mi ero dimenticato di segnalare la guida che ho seguito, rimedio:
https://wiki.postgresql.org/wiki/Adventures_in_PostgreSQL,_Episode_1
« Ultima modifica: 03 Settembre 2019, 14:44:43 da Gianluigi »
nuoto in attesa del bacio di una principessa che mi trasformi in un gambero azzurro

Offline Gianluigi

  • Moderatore globale
  • Senatore Gambero
  • *****
  • Post: 4.152
  • Tonno verde
    • Mostra profilo
Re:PostgreSQL come creare un nuovo database
« Risposta #4 il: 02 Settembre 2019, 18:21:29 »
Ciao Berserker79,  :D

avevi ragione  :ok: ho aggiunto alla stringa di connessione le voci che avevo commentato, vale a dire che adesso è così:
Codice: [Seleziona]
  $hConn.Close()
  $hConn.Type = Lower(DBType)
  $hConn.Host = DBHost
  $hConn.Name = DBName
  $hConn.Login = UserName
  $hConn.Password = UserPassword
  $hConn.Port = "5432"
l'unico dubbio era su connection.port ma lo ha digerito bene.
Poi ho controllato:
Codice: [Seleziona]
~$ psql -U gianluigi -d template1
Password for user gianluigi:
psql (11.5 (Ubuntu 11.5-0ubuntu0.19.04.1))
Type "help" for help.

template1=> \c rubinettofelice
You are now connected to database "rubinettofelice" as user "gianluigi".
rubinettofelice=> \d
                 List of relations
 Schema |       Name        |   Type   |   Owner   
--------+-------------------+----------+-----------
 public | fipart            | table    | gianluigi
 public | tagent            | table    | gianluigi
 public | tagent_idagen_seq | sequence | gianluigi
 public | tfilms            | table    | gianluigi
 public | tfilms_idfilm_seq | sequence | gianluigi
 public | tst_fi            | table    | gianluigi
 public | tstars            | table    | gianluigi
 public | tstars_idstar_seq | sequence | gianluigi
(8 rows)

rubinettofelice=> \dn
  List of schemas
  Name  |  Owner   
--------+----------
 public | postgres
(1 row)
 
e con il comando rubinettofelice-> \d+ tstars posso vedere la tabella nel dettaglio.

 :-*

nuoto in attesa del bacio di una principessa che mi trasformi in un gambero azzurro

Offline dregi

  • Gambero
  • **
  • Post: 85
  • Non possum tuis usque tandem abutere patientiae?
    • Mostra profilo
Re:PostgreSQL come creare un nuovo database
« Risposta #5 il: 02 Settembre 2019, 22:15:07 »
Certamente fare ciò che devi da terminale, aumenta l'autostima  :)  ,ma anche la comodità vuole la sua parte  ;)  Perchè non installi DBeaver, io lo sto usando, è comodissimo, anche se per la verità, quando ho dovuto trasformare ID in auto-incrementante, ho dovuto agire su terminale.

Offline Gianluigi

  • Moderatore globale
  • Senatore Gambero
  • *****
  • Post: 4.152
  • Tonno verde
    • Mostra profilo
Re:PostgreSQL come creare un nuovo database
« Risposta #6 il: 03 Settembre 2019, 12:13:27 »
Certamente fare ciò che devi da terminale, aumenta l'autostima  :)  ,ma anche la comodità vuole la sua parte  ;)  ...

Se parliamo di comodità in Linux, allora dobbiamo parlare di Terminale.
Linux non è Windows, è basato sul terminale e poi ci sono le interfacce grafiche (0, 1), quando cerchi aiuto per qualcosa che non funziona lo troverai facilmente ma quasi esclusivamente, per non dire esclusivamente, con comandi da terminale.
Prima ti abitui al terminale e meglio vivrai le esperienze con questo OS.

Quindi l'autostima non c'entra nulla e poi da terminale ho creato solamente il nuovo (con il solito nome) database vuoto come ben descritto nella guida di sotema, tutto il resto (anche l'errore) l'ho fatto con Gambas.  :-\

(0) https://it.wikipedia.org/wiki/Interfaccia_grafica
(1) https://www.giuseppefava.com/10-desktop-manager-linux/

 :ciao:
« Ultima modifica: 03 Settembre 2019, 12:17:13 da Gianluigi »
nuoto in attesa del bacio di una principessa che mi trasformi in un gambero azzurro