PostgreSQL or Postgres is an object-relational database management system (ORDBMS). Unlike MySQL, PostgreSQL is not controlled by any single company, it is a community developed project. It is a advanced version of the ‘Ingres’ Database project (which is how the project gets the name post-ingres or postgres ).
Postgres is one of the best open-source database alternative which is fully object oriented and transactions compliant. It has stored procedures, multiple views and a huge set of datatypes. Some of the other notable features are as follows.
Objects and Inheritance
Database consists of objects and the database administrators can design custom or user-defined objects for the tables. Inheritance is another feature. Tables can be set to inherit their characteristics from a “parent” table.
Functions
Functions can be used in Postgres. These can be written in the postgres’ own procedural language called ‘PL/pgSQL’ which resembles Oracle’s procedural language ‘PL/SQL’ or any other common scripting languages which support posgtres’ procedural language like PL/Perl, plPHP, PL/Python, PL/Ruby etc. Run the following in the psql client to determine if functions is enabled:
SELECT true FROM pg_catalog.pg_language WHERE lanname = 'plpgsql';
To create user-defined functions we use the CREATE OR REPLACE FUNCTION command. Example:
CREATE OR REPLACE FUNCTION fib ( fib_for integer ) RETURNS integer AS $$ BEGIN IF fib_for < 2 THEN RETURN fib_for; END IF; RETURN fib(fib_for - 2) + fib(fib_for - 1); END; $$ LANGUAGE plpgsql;
Indexes
An index is like a summary of a certain portion of the table. It is an optimization technique which increases speed of accessing records from a database. PostgreSQL supports indexes like Btree, hash etc. User-defined index methods can also be created. Indexes are created on tables with respect to a particular field (based on which there are a number of queries). As an example for a table:
CREATE TABLE name ( id integer, fname varchar lname varchar );
To create an index on table name with respective to the field id (as there are many queries on this table requesting for firstname or lastname from the id provided), we use the index:
CREATE INDEX name_id_index ON name (id);
Triggers
Triggers are events or functions run upon the action of certain SQL statements which modify data in some records. Depending on the kind of modification we can have multiple triggers in a database. Postgres supports multiple triggers written in PL/PgSQL or it’s scripting counterparts like PL/Python. The trigger function must be defined before the trigger can be created. The trigger function must be declared as a function taking no arguments and returning type trigger. CREATE TRIGGER command is used to declare triggers.
Concurrency
PostgreSQL ensures concurrency with the help of MVCC (Multi-Version Concurrency Control), which gives the database user a “snapshot” of the database, allowing changes to be made without being visible to other users until a transaction is committed.
PostgreSQL’s MVCC keeps all of the versions of the data together in the same partition in the same table. By identifying which rows were added by which transactions, which rows were deleted by which transactions, and which transactions have actually committed, it becomes a straightforward check to see which rows are visible for which transactions.
Inorder to accomplish this, Rows of a table are stored in PostgreSQL as a tuple. Two fields of each tuple are xmin and xmax. Xmin is the transaction ID of the transaction that created the tuple. Xmax is the transaction ID of the transaction that deleted it (if any).
Along with the tuples in each table, a record of each transaction and its current state (in progress, committed, aborted) is kept in a universal transaction log.
When data in a table is selected, only those rows that are created and not destroyed are seen. That is, each row’s xmin is observed. If the xmin is a transaction that is in progress or aborted, then the row is invisible. If the xmin is a transaction that has committed, then the xmax is observed. If the xmax is a transaction that is in progress or aborted and not the current transaction, or if there is no xmax at all, then the row is seen. Otherwise, the row is considered as already deleted.
Insertions are straightforward. The transaction that inserts the tuple simply creates it with the xmax blank and the xmin set to its transaction ID. Deletions are also straightforward. The tuple’s xmax is set to the current transaction. Updates are no more than a concurrent insert and delete.
Views
A view is a table which does not exist in the database. It is a virtual table created from fields in various tables and is joined together based on some criteria. Views can be used in place of tables and will accomplish the task same as that of a table. The CREATE VIEW statement is used to accomplish this eg:
CREATE VIEW best_sellers AS SELECT * FROM publishers WHERE demand LIKE 'high';
Foreign Keys
The primary key used in one table which is used to refer to the records in a second table is called the foreign key of the second table.
CREATE TABLE products (
product_no integer PRIMARY KEY,
name text,
price numeric
);
CREATE TABLE orders (
order_id integer PRIMARY KEY,
product_no integer REFERENCES products (product_no),
quantity integer
);
Here product_no is the foreign key in the second table created. The foreign key field may have values which are repeated unlike primary keys.
Files Users and Configuration
The main configuration file of Postgres is postgresql.conf. This can be located in the ‘data’ directory. It may be present either in /var/lib (/var/lib/pgsql/data/postgresql.conf) or /usr/local (/usr/local/pgsql/data/postgresql.conf). Temporary changes to the configurations can be made using postmaster command.
The init script that starts the postgres service is /etc/init.d/postgresql . It runs a number of child processes concurrently. The postgres server process is postmaster. These processes and files associated with PosgreSQL are owned by the user/group postgres. The default port used for database connections is 5432
The user postgres is the PostgreSQL database superuser. We can create a number of super users for the database (this accomplished by the create role command ), however, the default super user is postgres. The postgres user has the privilege to access all the databases and files in the server (Unless the user root is created in postgres as a superuser).
Client Authentication is controlled by the file pg_hba.conf in the data directory, e.g., /var/lib/pgsql/data/pg_hba.conf. (HBA stands for host-based authentication.)
Each record specifies a connection type, a client IP address range (if relevant for the connection type), a database name or names, and the authentication method to be used for connections matching these parameters.A record is typically in one of two forms:
local database authentication-method [ authentication-option ]
host database IP-address IP-mask authentication-method [ authentication-option ]
local : This record pertains to connection attempts over Unix domain sockets.
host : This record pertains to connection attempts over TCP/IP networks.
database : Specifies the database that this record applies to. The value all specifies that it applies to all databases, while the value sameuser identifies the database with the same name as the connecting user.
authentication methods
trust: The connection is allowed unconditionally.
reject: The connection is rejected unconditionally.
password: The client is required to supply a password which is required to match the database password that was set up for the user.
md5: Like the password method, but the password is sent over the wire encrypted using a simple challenge-response protocol.
ident: This method uses the “Identification Protocol” as described in RFC 1413. It may be used to authenticate TCP/IP or Unix domain socket connections, but its reccomended use is for local connections only and not remote connections.
Front-ends
The minimalistic front-end for PostgreSQL is the psql command-line. It can be used to enter SQL queries directly, or execute them from a file. phpPgAdmin is a web-portal used for PostgreSQL administration written in PHP and based on the popular phpMyAdmin. Likewise pgAdmin is a graphical front-end administration tool for PostgreSQL, which has support on multiple platforms. The latest stable version of the same is pgAdmin III.
Some administration related commands
Command to login to psql database mydb as user myuser:
psql -d mydb -U myuser
Command to login to psql database mydb as user myuser on a different host myhost:
psql -h myhost -d mydb -U myuser
If the port the server runs is different we use -p [port number] . Upon entering the psql shell the prompt will show the database name currently being used. In the above example it will show
mydb=> (if logged in as an ordinary user )
mydb=# (if logged in as a super user like postgres)
Create a PostgreSQL user
There are two ways to create a postgres database user. The only user initially allowed to create users is postgres. So one has to switch to this user before creating other users with varying privileges.
1. Creating the user in the shell prompt, with createuser command.
switch to the postgres user with:
su - postgres createuser tom Shall the new role be a superuser? (y/n) n Shall the new role be allowed to create databases? (y/n) y Shall the new role be allowed to create more new roles? (y/n) n
2. Creating the user in the PSQL prompt, with CREATE USER command.
switch to the postgres user with:
su - postgres create user mary with password 'marypass';
Creating and deleting a PostgreSQL Database
There are two way to create databases.
1. Creating database in the PSQL prompt, with createuser command.
CREATE DATABASE db1 WITH OWNER tom;
2. Creating database in the shell prompt, with createdb command.
createdb db2 -O mary
To delete an entire database from within the psql prompt do :
DROP DATABASE db1;
Determining execution time of a query
Turn on timing with
\timing
Now execute the qery:
SELECT * from db1.employees ; Time: 0.065 ms
Calculate postgreSQL database size in disk
SELECT pg_database_size('db1');
to get the values in human readable format
SELECT pg_size_pretty(pg_database_size('db1'));
to calculate postgreSQL table size in disk
SELECT pg_size_pretty(pg_total_relation_size(‘big_table’));
Slash commands used in psql
To list all slash commands and thier purpose. Login to psql and issue to the command \? . Some of the most commonly used slash commands are the following:
| List databases | \l |
| System tables | \dS |
| Types | \dT |
| Functions | \df |
| Operators | \do |
| Aggregates | \da |
| Users | \du |
| Quit from psql | \q |
| Connect to different database db2 | \c db2 |
| Describe Table/index/view/sequence | \d |
The below can be used with a specific table/index/view name for description of the specific table/index/view
| Tables | \dt |
| Indexes | \di |
| Sequences | \ds |
| Views | \dv |
Useful Bash commands
Bash command to list all the postgresql databases:
psql -l #This can be run as a unix user who is also a super user in postgresql
Indirect bash command to list all the postgresl users:
psql -c '\du' #-c is used to run an internal or sql command in psql shell
Backing up and restoring databases
To dump the database to an sql file use the bash command:
pg_dump mydb > db.out
To restore a database from an sql backup file (via bash)
psql -d newdb -f backupdb.out or psql -f backupdb.out newdb
(here the database newdb must be already created and the file backupdb.out must be present in the current directory)
To take the backup of all the Postgres databases in the server:
pg_dumpall > /var/lib/pgsql/backups/dumpall.sql
(Only possible with the postgres or the database superuser )
Resetting database user’s password
To change the password for a database user (say ‘thomas’):
ALTER USER thomas WITH PASSWORD 'newpassword';
This same command can be used to reset the password for the postgresql super user postgres, but in this case, you will have to enable password less login for postgres user by adding the following line to the top of the file pg_hba.conf in the data directory of postgres. Once the password is reset this line can be removed:
local all postgres trust
Next we issue the same command but for the user postgres
ALTER USER postgres WITH PASSWORD 'newpassword';
To create a super user via bash with multiple roles
createuser -sPE mysuperuser
Instead of this we can also use the below psql shell command:
CREATE ROLE mysuperuser2 WITH SUPERUSER CREATEDB CREATEROLE LOGIN ENCRYPTED PASSWORD 'mysuperpass2';
Physical database files in postgres
The files in data/base are named by the oid (Object Identifier) of the database record in
pg_database, like this:
cd /var/lib/pgsql/data/base ls -l total 33 drwx------ 22 postgres postgres 4096 Jul 23 20:06 ./ drwx------ 11 postgres postgres 4096 Aug 1 05:59 ../ drwx------ 2 postgres postgres 4096 Jun 20 09:32 1/ drwx------ 2 postgres postgres 4096 Mar 3 13:36 10792/ drwx------ 2 postgres postgres 4096 Jun 20 15:09 10793/ drwx------ 2 postgres postgres 4096 May 27 01:40 16497/ drwx------ 2 postgres postgres 4096 May 27 01:40 16589/ drwx------ 2 postgres postgres 4096 Jun 20 10:28 16702/ drwx------ 2 postgres postgres 4096 May 27 01:40 16764/ drwx------ 2 postgres postgres 4096 May 27 01:40 16785/ drwx------ 2 postgres postgres 4096 Aug 1 04:37 16786/ drwx------ 2 postgres postgres 4096 Aug 1 04:36 19992/ drwx------ 2 postgres postgres 4096 May 27 01:40 19997/
To obtain the oid, execute the following command in psql prompt
postgres=# select oid,datname from pg_database order by oid; oid | datname ---------+-------------------------- 1 | template1 10792 | template0 10793 | postgres 16497 | gadgetwi_Unable 16589 | vimusicc_filehost 16702 | personea_altissimo 16764 | shopping_businessfinance 16785 | ansonyi_wp2 16786 | ansonyi_wp 19992 | globook_PostgreSQLContinue Reading
This error is shown while removing a domain from plesk panel. When trying to remove the domain for the first time, it will show a success. But on listing the domains again from plesk, we will find the entry for the domain with a cross mark to the left of it hinting that the domain was tried for removal but still, not properly removed
We can verify this. Try adding a new domain of the same name and it will show an error stating that the an entry for the domain already exixts.
So after several tries we find that it is not possible to remove the domain from the plesk interface. So the problem needs to be dealt at the root level. So what is the root of all the entries in plesk? Of course the plesk’s DB ! Here are the steps to follow for the troubleshoot:
1) Since plesk uses different DBs we shall now try to find what DB server it uses.
Go to Start>All Programs>Plesk?Plesk Reconfigurator. In the pop up window obtained, select ‘Switch DB provider’. Note the field for ‘Server Type’. It will show the DB type plesk is currently using. You may find that it supports MySQl,MSSQL and Jet. I shall now continue the article with refernce to Jet DB.
2) Now we have our target clear: editing plesk’s Jet DB to remove all instances of a particular domain. We shall now try to find a frontend GUI tool for editing plesk’s Jet DB tables. I used ‘MDB Viewer Plus’. It is a DB viewer combined and an editor software. You can download the file from:
http://www.alexnolan.net/software/MDBPlus.exe
Then proceed with the installation.
3)Run the program. Navigate to File>Open. Now search for the DB location. It will usually be in %Program Files\Parallels\Plesk\admin\db\psa.mdb. Open the particular db.
4)Open the ‘Query’ from the toolbar. This helps us to execute MSSQL queries from this program. Into the space for query, enter:
SELECT d.name FROM domains d LEFT JOIN dns_zone z ON d.dns_zone_id=z.id WHERE z.id IS NULL;
and click ‘Execute’. It will display the list of domains having missing or inappropriate IDs in psa.mdb.
The meaning and reason for the error is that in the DB file psa.mdb, the ‘dns_zone_id’ record in the table ‘domains’ points to inexistent ‘id’ record in ‘dns_zone’ table for one or several domains. It may happen because of Plesk internal issues, broken database, incomplete domain deletion. We shall verify this now.
5) In the toolbar for the list of tables of the psa.mdb, navigate to the table ‘dns_zone’. You will find multiple entries for the domain in question. Remove the latest entries and then note the ‘id’ record for the particular domain.
6)From the toolbar navugate to the table ‘domains’. Click on the domain in question. Then move the scroll bar below to search for the record(or coloumn ‘dns_zone_id’). Note the this id. You will note that this will be different from the ‘id’ record in step 5. This mismatch had led to the dns zone being NULL for the particular domain.
7)We can verify this by running commnads in ‘Query’ toolbar also. Open ‘Query’ from the toolbar and run the commands:
a. to verify step 5: Select id from [dns_zone] where name=’domainname’
b. to verify step 6: Select dns_zone_id from [domains] where name=’domainname’
We can see the two different id results.
8)So we need to eliminate this mismatch. For that we will need to provide the correct id for the table: ‘domains’. For this we will replace the result of 7)b with 7)a. Run the following command:
UPDATE domains SET dns_zone_id=’dns-zone-id’ WHERE name=’domainname’;
Replace dns-zone-id with the result of 7)a.
The issue is fixed !
If you have logged in as admin, select the domain for which you want to make the change or if as a normal plesk user, select ‘Virtual Directories’ under ‘File’ menu. Below is the screen shot:
In the page that you obtain, you will see ‘Directory Properties’ . See below:
Click on ‘Directory Properties’. The page resulting wil have the options for changing the Directory Index for a domain. See the pic given:
Here you can set the priorities for your index pages.
Continue ReadingIf you are using custom httpHandlers or httpModules, you would need to
run the migration command below.
C:\> %systemroot%\system32\inetsrv\APPCMD.EXE migrate config "domain_name.com/virtual_directory" Successfully migrated section "system.web/httpModules". Successfully migrated section "system.web/httpHandlers".
Now if you are going to migate the web.config inside the WEB_ROOT directory itself and not inside any virtual directory don’t miss a forward slash, / after the domain name.
eg:
C:\> %systemroot%\system32\inetsrv\APPCMD.EXE migrate config "domain_name.com/" Successfully migrated section "system.web/httpModules". Successfully migrated section "system.web/httpHandlers".
Otherwise you may get an error like below,
ERROR ( message:Cannot find APP object with identifier “domainame.com”. )
A good article to refer is available at http://blogs.msdn.com/tmarq/archive/2007/08/30/iis-7-0-asp-net-pipelines-modules-handlers-and-preconditions.aspx
Continue ReadingIssue with one domain not resolving when you are running BIND server.
Suspend and quickly unsuspend the domain works around 20% of situations and if that also fails, we may need to work in the Plesk PSA database. Before you work on this, please make sure that the plesk psa database is backed up.
cd %plesk_bin% cd ..\..\MySQL\bin mysql -u admin -pPASSWORD -P 8306
In most cases, Plesk MySQL server’s admin PASSWORD will be the Plesk password itself. If it isn’t reset the plesk password again, but with “%plesk_bin%\plesksrvclient.exe” -set NEW_PASSWORD_HERE true (true parameter will reset the MySQL admin password as well)
Assuming you are now in the plesk mysql server prompt, follow the below steps in mysql prompt.
mysql> use psa; mysql> select * from dns_zone where name like 'domain_name.com';
In the output shown similar to below, check the status of the zone. I have seen only the values 0 and 2. Not sure whether there is a status value of 1 even.
If DNS for some domain is managed in Plesk Control Panel, the status for this domain in dns_zone table is temporary setting to value 2 (to lock it for any changes) and sets it to 0 value when the transaction is over. If for some reason the transaction is interrupted during DNS managing (Plesk restarts for example) the status field value is not changed to 0 and stays as 2. Domains with that status value are not recorded in named.conf file during any DNS management.
Now check to see whether there is only one such record for the ID shown for the above sql query. Chances are there could be two and if there are two, you should delete the record which is orphan or has no reference back to dns_zone.
mysql> select * from dns_recs where dns_zone_id=`the_id_you_got_from_the_above_mysql_query`;
The results you get should be matching with the DNS_Zone_ID and the domainname in question.
If you see anything else, i.e orphans or else if you don’t see any entries in dns_recs corresponding to the dns_zone_id, delete it.
mysql> delete from dns_zone where id=[wrong_record_id];
And finally update the status from 2 to 0;
mysql> update dns_zone set status=0 where id=[the_dns_zone_id_you_got]
When it’s done update DNS records using dnsmng.exe utility:
cd %plesk_bin% dnsmng.exe update domain.com
Finally there could be a few situations where the entire DNS service is down. Usually the monitoring should detect such situations. However I usually noticed that this happens only when it is the BIND server which is being used as the DNS server software. A switch of the DNS server to Microsoft DNS should fix the issue. You may need to check the versions supported at the release notes available at http://www.parallels.com/products/plesk/docs/ . On my investigation disabling the zone of an internationalized domain name solved the issue with one server though and let us continue using BIND server.
References : http://kb.parallels.com/en/5242
Continue Reading