PostgreSQL Database: PG::ConnectionBad: FATAL: Peer authentication failed for user

If, when working on a Linux machine of the Ubuntu flavor and setting up a PostgreSQL 9.3 database, you run into the error ‘PG::ConnectionBad: FATAL: Peer authentication failed for user’ when trying to connect to a database from a web application (Rails, PHP, Node, etc.), you are more than likely running into local socket connection permissions within PostgreSQL. The most common fix for this error in a development or staging environment is to loosen the local permissions up a bit.

How To:
1. locate the file ‘/etc/postgresql/9.3/main/pg_hba.conf’ and open it using sudo (sudo nano /etc/postgresql/9.3/main/pg_hba.conf)
2. scroll down through the file (almost to the bottom) until you find the section that starts with ‘# Database administrative login by Unix domain socket
3. directly below that you will find ‘local all all peer’ change it to ‘local all all trust’
4. save and close the file
5. restart the PostgreSQL server (sudo service postgresql restart)

SQL: Reseeding the Identity Column

If you have reference tables containing list data used to populate drop downs and selection controls in your UI, you may run into instances where you need to clear and repopulate these tables with updated data. But at the same time you may need to maintain the identity numbers when the table is repopulated to make sure that references from other tables remain correct. To accomplish this you need to make sure that your SQL scripts reset the table’s identity column back to 0 so that when the table is repopulated the first entry begins with 1 rather than 32. Here is an example:

DELETE FROM [UsState]
GO

DBCC CHECKIDENT('UsState', RESEED, 0)
GO

INSERT INTO [UsState] VALUES ('Alabama', 'AL');
INSERT INTO [UsState] VALUES ('Alaska', 'AK');
INSERT INTO [UsState] VALUES ('Arizona', 'AZ');
INSERT INTO [UsState] VALUES ('Arkansas', 'AR');

SQL: For Each Loop

Easy way to loop through records in a table.

declare @cursor cursor, @customerID int

set @cursor = cursor for select CustomerId from StoreUpdates

open @cursor

while 1=1

begin

fetch from @cursor into @customerID

if @@fetch_status 0

break

update Stores set Name = (select StoreName from StoreUpdates where CustomerId = @customerID) where CustomerId = @customerID;

end