Search posterous

Search all posts and users. Type a name, type a favorite song title, whatever! See what comes up.
  

More posterous blogs











More recommended blogs »

Here are posterous posts filed under postgresql...

Stargazers says...

Tänään tuli vastaan tapaus jossa piti hakea tietokannasta SQL-kysellä
kaikkein yleisimmin esiintyvä arvo tietyssä taulun sarakkeessa.
Ei ollut varmaankaan aikaisemmin ollut tarvetta moiselle kyselylle,
mutta lopulta googlen kautta vastauksen löysin.

SELECT haluttu_kentta, count(*) FROM taulu GROUP BY haluttu_kentta
ORDER BY count(*) DESC;

Ei loppujen lopuksi siis mitään rakettitiedettä ollut tämäkään.

Filed under: PostgreSQL

Alex says...

I think its new in PostgreSQL 8.4, there is a new field type called citext, which stands for case insensitive text.  Currently on Ubuntu 9.10 its in the PostgreSQL contrib package, which often serves as a testbed for features before they are adopted into PostgreSQL proper.

Using citext ensures that all comparisons are case insensitive, which includes referential integrity on inserts, updates and deletes, and SQL queries for lookups for example, which I think will work well for those fields that should always be compared case insensitive.

Although citext (and probably many other modules) are not listed on the contrib page, they are included, you can see them in the complete file list.

Steps to install on Ubuntu 9.10 (Karmic Koala):

# Install the contrib package
sudo apt-get install postgresql-contrib-8.4
# Add the citext module to a database of your choice
psql [username] -d [databaseName] -f /usr/share/postgresql/8.4/contrib/citext.sql

Where in this case /usr/share/postgresql/8.4 is the PostgreSQL SHARE_DIR folder.

Now you can use the field citext instead of text.  If you'd like to use citext on Ubuntu 9.04 Jaunty (which only includes PostgreSQL 8.3), then check out Mark's post about installing PostgreSQL 8.4 on Ubuntu 9.04.

Filed under: postgresql

Diego says...

Your life of Ruby + Java is going to be fun and painful. I hope this will get you started quickly so you can move on to the more annoying stuff. (JRuby is still amazing though. JVM is also quite lovely from what I've read.)

Required: Make sure you have a Java VM and Postgresql setup.

Download JRuby 1.3.1. (Archived. Already built.):
http://kenai.com/projects/jruby/pages/Home

Extract the contents.

Go to that folder:
cd jruby-1.3.1

Check everything is ok:
bin/jruby -v

Now do:
bin/jruby -S gem install sequel

Now go to: http://jdbc.postgresql.org/download.html
Download a driver (.jar file) where it says "Current Version."

Remember the location.

Now to test if it works:

# FILE NAME:  quick_start.rb
require 'rubygems'

require '/Path/To/Driver/postgres-..-..jdbc4.jar' # Put the path/filename of the driver you downloaded.

require 'sequel'

host = 'localhost'
db_name = 'my-database' # <=== Change this.
user = 'my-username' # <=== Change this.
pass = 'my-password' # <=== Change this.
DB = Sequel.connect( "jdbc:postgresql://%s/%s?user=%s&password=%s" % [ host, db_name, user, pass] )

my_table = :schema_info # <=== Change this.

puts DB[ my_table ].all.inspect

Now do:
bin/jruby ~/Path/To/quick_start.rb

If it works, you can go and properly install and integrate JRuby into your system: http://kenai.com/projects/jruby/pages/Home
(Go to:  "JRuby Basics" > "Getting Started")
There is also: "JRuby Basics" > "Walkthroughs and Tutorials"

COMMON MISTAKES:

  • The equlivalent of "gem install" is "jruby -S gem" (with a capital 'S')
  • Write a proper Sequel connection string: jdbc:postgresql://HOST/DB?user=USER&password=PASS
    Notice how it differs from other connections strings in regular Ruby + Sequel.
    More info. on Sequel + JRuby + connection strings: http://sequel.rubyforge.org/rdoc/classes/Sequel/JDBC.html
  • An alternative to downloading the .jar/jdbc driver for postgresql is to install the JDBC-Postgresql gem:
    bin/jruby -S gem install jdbc-postgres
    (It uses a slightly older JDBC driver. It's compatiable for Postgresql 8.2).

Eventually, I gave up JRuby for Ruby Enterprise Edition. http://www.rubyenterpriseedition.com/

Filed under: postgresql

Daniele says...

After this comment to a my question, im thinking if is better using 1 database with X schemas or viceversa.

My situation: im developing a web-app where, when people do register, i create (actually) a database (no, its not a social network: everyone must have access to his own data and never see the data of the other user).

Thats the way i used for the previus verison of my application (that is still running on mysql): throught the plesk api, for every registration i do:

  1. Create a database user with limited privileges;
  2. Create a database that can be accessed just by the previous created user and the superuser (for maintenance)
  3. Populate the db

Now, i'll need to do the same with posrtgresql (the project is getting mature and mysql.. dont fulfill all the needes)

I need to have all the databases/schemas backups indipendent: pg_dump works perfectly in both ways, the same for the users that can be configured to access just 1 schema or 1 database.

So, assuming you are more experienced potsgres users than me, what do you think is the best solution for my situation, and why?

There will be performance differences using $x db instead of $x schemas? And what solution will be better to mantein in future (reliability)?

Every help and suggestion is really appreciated.

Edit: i almost forgot: all of my databases/schemas will allways have the same structure!

Edit2: For the backups issue (using pg_dump), is maybe better using 1 db and many schemas, dumping all the schemas at once: recovering will be quite simple loading the main dump in a dev machine and then dump and restore just the schema needed: there is 1 additional step, but dumping all the schema seem faster then dumpin them one by one.

p.s: sorry if i forgot some 'W' char in the text, my keyboard suffer that button ;)

edit|close|delete|flag
 
 
"all of my databases/schemas will ever have the same structure!" do you mean they all have the same structure? Or never? – Osama ALASSIRY 17 hours ago
Sorry, yes, they all have the same structure forever: if i change one, i'll change all of them ;) – DaNieL 16 hours ago 

4 Answers

vote up 1 vote down
check

A PostgreSQL "schema" is roughly the same as a MySQL "database". Having many databases on a PostgreSQL installation can get problematic; having many schemas will work with no trouble. So you definitely want to go with one database and multiple schemas within that database.

link

1
 
This. Postgres doesn't allow you to query across databases, which can be pretty annoying. – matt b 3 hours ago

Great, i havent thought the possibility to query another schema without changing database or changing the connection. that's all, i'll go for 1 db and many schemas. Thanks guys! – DaNieL 25 mins ago 
add comment

vote up 0 vote down
check

I would say, go with multiple databases AND multiple schemas :)

Schemas in postgres are a lot like packages in Oracle, in case you are familiar with those. Databases are meant to differentiate between entire sets of data, while schemas are more like data entities.

For instance, you could have one database for an entire application with the schemas "UserManagement", "LongTermStorage" and so on. "UserManagement" would then contain the "User" table, as well as all stored procedures, triggers, sequences etc. that are needed for the user management.

Databases are entire programs, schemas are components.

link|flag


... and so i'll have 1 database, with inside the schemas: $customer1_user_schema, $customer2_user_schema, $customer3_user_schema, $customer1_documents_schema, $customer2_documents_schema, $customer3_documents_schema? Mh... dont seem a reliable way... and what about performance? And what about the code of my application (will be php and python)? so many schemas.. – DaNieL 15 hours ago 
add comment

vote up 0 vote down
check

A number of schemas should be more lightweight than a number of databases, although I cannot find a reference which confirms this.

But if you really want to keep things very separate (instead of refactoring the web application so that a "costomer" column is added to your tables), you may still want to use separate databases: I assert that you can more easily make restores of a particular customer's database this way -- without disturbing the other customers.

link|flag

add comment

vote up 0 vote down
check

Definitely, i'll go for the 1-db-many-schemas approach. This let me to dump all the database but restore just 1 very easly, in many ways:

  1. Dump the db (all the schema), load the dump in a new db, dump just the schema i need, and restore back in main db
  2. Dump the schema separately, one by one (but i think the machine ill suffer more this way.. and im aspecting like 500 schemas!)

Otherwise, googlin around iv'se seen that there is no auto-procedure to duplicate a schema (using one as a template), but many suggest this way:

  1. Create a template-schema
  2. When need to duplicate, rename it with new name
  3. Dump it
  4. Rename it back
  5. Restore the dump
  6. The magis is done.

I've written 2 rows in python to do that, hope thay can help someone (in-2-seconds-written-code, dont use it in production):

import os
import sys
import pg

#Take the ne shcema name from the second cmd arguments (the first is the filename)

newSchema = sys.argv[1]

#Temp folder for the dumps
dumpFile
= '/test/dumps/' + str(newSchema) + '.sql'

#Settings
db_name
= 'db_name'
db_user
= 'db_user'

db_pass = 'db_pass'
schema_as_template
= 'schema_name'


#Connection
pgConnect
= pg.connect(dbname= db_name, host='localhost', user= db_user, passwd= db_pass)

#Rename schema with the new name
pgConnect
.query("ALTER SCHEMA " + schema_as_template + " RENAME TO " + str(newSchema))

#Dump it
command
= 'export PGPASSWORD="' + db_pass + '" && pg_dump -U ' + db_user + ' -n ' + str(newSchema) + ' ' + db_name + ' > ' + dumpFile

os.system(command)
#Rename back with its default name

pgConnect.query("ALTER SCHEMA " + str(newSchema) + " RENAME TO " + schema_as_template)

#Restore the previus dump to create the new schema
restore
= 'export PGPASSWORD="' + db_pass + '" && psql -U ' + db_user + ' -d ' + db_name + ' < ' + dumpFile

os.system(restore)
#Want to delete the dump file?

os.remove(dumpFile)
#Close connection

pgConnect.close()

Filed under: Postgresql

Daniele says...

http://explain.depesz.com/
Copy'n'paste your query plan, it will highligth all the 'bad steps'.

Dont know how does this works withour knowing the database structure, data-types and indexes, but.. its not bad

Filed under: Postgresql

Daniele says...

Prima si crea al tabella 'madre' (main), dichiarando tutti i campi normalmente, con tutte le primary key, serial, etc...
Le sequenze e i vincoli vengono create automaticamente da postgres (presi dalle dichiarazioni delle colonne).
Solitamente non serve mettere indici sulla tabella madre, ma solo sulle figlie.
 
CREATE TABLE main (...);

Poi si dichiara la tabella 'figlia', SENZA LE COLONNE EREDITATE, ma al massimo con le colonne aggiuntive che la tabella MADRE non deve avere.
 
CREATE TABLE child () INHERITS (main);

Si aggiunge la primary key sulla tabella figlia, in questo modo 'eredita' anche la sequenza di default (per il campo id serial)

ALTER TABLE child ADD PRIMARY KEY(id)

Se si hanno più tabelle figlie, e alcuni campi devono essere univoci (anche visti dalla tabella madre), è possibile mettere dei vincoli sulla tabella madre.. ma solitamente indici e vincoli vanno messi solo sulle tabelle figlie:

CREATE INDEX $index_name ON child USING btree (field)
Poi, via via con le Foreign key (quando necessarie):

ALTER TABLE child ADD FOREIGN KEY ($field) REFERENCES other_table($field) ON DELETE SET NULL

Filed under: Postgresql

Daniele says...

Description

This tutorial is about howto installing PostgreSQL on Debian Server.

Installing PostgreSQL

apt-get update
apt-get install pgsql

Create Language

Example plpgsql

su postgres
createlang plpgsql template1
exit

Change authentication method

We need to edit file pg_hba.conf to change authentification method for accessing PostgreSQL database.

cp /etc/postgresql/pg_hba.conf /etc/postgresql/pg_hba.confbak
vi /etc/postgresql/pg_hba.conf

Find this section

# TYPE  DATABASE  USER  IP-ADDRESS  IP-MASK  METHOD
# Database administrative login by UNIX sockets
local all postgres ident sameuser
#
# All other connections by UNIX sockets
local all all ident sameuser

#
# All IPv4 connections from localhost
host all all 127.0.0.1 255.255.255.255 ident sameuser
#
# All IPv6 localhost connections
host all all ::1 ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff ident sameuser

host all all ::ffff:127.0.0.1/128 ident sameuser
#
# reject all other connection attempts
host all all 0.0.0.0 0.0.0.0 reject

Edit that section to

# TYPE  DATABASE  USER  IP-ADDRESS  IP-MASK  METHOD
# Database administrative login by UNIX sockets
local all postgres ident sameuser
#
# All other connections by UNIX sockets
local all all password

#
# All IPv4 connections from localhost
host all all 127.0.0.1 255.255.255.255 password
#
# All IPv6 localhost connections
host all all ::1 ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff password
host all all ::ffff:127.0.0.1/128 password

#
# reject all other connection attempts
host all all 0.0.0.0 0.0.0.0 reject

Restart PostgreSQL Server

/etc/init.d/postgresql restart

Create a New Database

Example wordpress

su postgres
createdb -T template1 wordpress
exit

Create a New User

Example: User supriyadisw with password cak3p

su postgres
createuser supriyadisw -P
Enter password for new user: cak3p [enter]
Enter it again: cak3p [enter]
Shall the new user be allowed to create databases? (y/n) y [enter]
Shall the new user be allowed to create more new users? (y/n) n [enter]

CREATE USER
exit

Login to PostgreSQL

pgsql -U supriyadisw wordpress [enter]
Password: cak3p [enter]

Good Luck :D

FROM: http://www.supriyadisw.net

Filed under: Postgresql

divia says...

I really like that clsql will create database tables for me using create-view-from-class. (For some reason I haven't gotten drop-view-from-class to work--it just returns "No Value" and leaves the table intact--but that doesn't really bother, since it's easy enough to drop tables.
 
I do, however, wish that there were an updated-view-from-class command that I could run when I added a slot to a class. Dropping the table myself, then creating it again certainly works, but then I lose my data, which is rarely what I'm going for. Usually, I don't care much, because I can just log into phpPgAdmin and update the table manually. In the past, it hasn't been too hard for me to figure out how to do so. I'm capable of converting hyphens to underscores, and it was always obvious which type to make the table, integer would be integer, float a double precision, string a character varying. I just had a symbol type slot in my object though, and I wasn't sure what that would be.
 
Annoying as it was, I deleted the table and used create-view-from class.

The answer is: clsql converts the symbol type to a "character varying", just as it does with strings. So now I know, and I won't have to go through that again.

Filed under: PostgreSQL

divia says...

This latest chapter in the saga of me trying to getting Weblocks working on my Ubuntu slice took me quite a few hours to figure out.  After configuring my .clsql-test.config file to run just the PostgreSQL tests and running (asdf:oos 'asdf:test-op 'clsql), I kept getting this error:

debugger invoked on a SIMPLE-ERROR in thread #<THREAD "hunchentoot-worker-2" RUNNING {10035C3B11}>:

  Couldn't load foreign library "libpq". (searched CLSQL-SYS:*FOREIGN-LIBRARY-SEARCH-PATHS*)

I remembered having this problem when before, when setting this stuff up on my Mac, but then the solution had been to create a clsql-init.lisp file in /etc that told clsql where the libraries were.  That clsql-init.lisp:

(clsql:push-library-path "/Library/PostgreSQL8/lib/")
(clsql:push-library-path "/usr/local/mysql/lib/")

However, that only worked because the libraries I needed were all in the folder /Library/PostgreSQL8/lib.  Its contents:

divia-melwanis-macbook:~ divia$ cd /Library/PostgreSQL8/lib
divia-melwanis-macbook:lib divia$ ls
libecpg.6.0.dylib libpgtypes.3.0.dylib
libecpg.6.dylib libpgtypes.3.dylib
libecpg.a libpgtypes.a
libecpg.dylib libpgtypes.dylib
libecpg_compat.3.0.dylib libpq.5.1.dylib
libecpg_compat.3.dylib libpq.5.dylib
libecpg_compat.a libpq.a
libecpg_compat.dylib libpq.dylib
libpgport.a postgresql

On my Ubuntu slice, I found the folder /usr/lib/postgresql/8.3, but here's what was in this one:

ascii_and_mic.so utf8_and_euc_cn.so cyrillic_and_mic.so utf8_and_euc_jis_2004.so dict_snowball.so utf8_and_euc_jp.so euc_cn_and_mic.so utf8_and_euc_kr.so euc_jis_2004_and_shift_jis_2004.so utf8_and_euc_tw.so euc_jp_and_sjis.so utf8_and_gb18030.so euc_kr_and_mic.so utf8_and_gbk.so euc_tw_and_big5.so utf8_and_iso8859.so latin2_and_win1250.so utf8_and_iso8859_1.so latin_and_mic.so utf8_and_johab.so plpgsql.so utf8_and_shift_jis_2004.so tsearch2.so utf8_and_sjis.so utf8_and_ascii.so utf8_and_uhc.so utf8_and_big5.so utf8_and_win.so utf8_and_cyrillic.so
 
I tried find / -name "*libpq*", but libpq.a was nowhere to be found anywhere!  I'm really not sure why the "apt-get install postgresql" installation didn't include any of the .dylib or .a files that my installation on the Mac did, and if does to know I'd love to hear an explanation.  In any case, after hours of fruitless googling trying to understand why those libraries were missing, I found this cl-sql-postgresql package, and installed it.  I knew things were going well when I got here:

Configuration file `/etc/clsql-init.lisp'
 ==> File on system created by you or by a script.
 ==> File also in package provided by package maintainer.
   What would you like to do about it ?  Your options are:
    Y or I  : install the package maintainer's version
    N or O  : keep your currently-installed version
      D     : show the differences between the versions
      Z     : background this process to examine the situation
 The default action is to keep your current version.
*** clsql-init.lisp (Y/I/N/O/D/Z) [default=N] ? Y
Installing new version of config file /etc/clsql-init.lisp ...

It worked!  I loaded up clbuild lisp again and the clsql tests ran!

Filed under: PostgreSQL

divia says...

Okay, so probably my terminology exposes how I am not nearly fluent in darcs, but am translating it to svn in my head.  Darcs has tags, patches, and changesets, but not versions, and it has get instead of checkout.   

So far, I've been doing Weblocks development on my Macbook, but I wanted to be able to show what we've been working on to other people, so I decided to set it up on the Slicehost slice I've been paying for and not using for months now.  Mostly, installing everything on Ubuntu was much easier than it had been on OS X, party because I'd done it before, but more because I didn't have to recompile SBCL.  I was basically able to apt-get install everything I needed: sbcl, postgresql, cvs, svn, git, mercurial, darcs, and possibly some things I'm forgetting.  I got clbuild from darcs and did ./clbuild install weblocks prevalence, just as I had done in the past.  I updated my clsql to the clsql-fluid branch, and installed bordeaux-threads.  I got an error saying I needed usocket, and I installed that.  Then, I got this error:

;     SB-INT:SIMPLE-READER-PACKAGE-ERROR at 437 (line 14, column 28) 
on #<SB-SYS:FD-STREAM for "file /home/smee/clbuild/source/weblocks/src/ 
debug-mode.lisp" {100437C231}>: 
;       package "HUNCHENTOOT-MP" not found 
; compilation aborted after 0:00:00 

WARNING: 
   COMPILE-FILE warned while performing #<COMPILE-OP NIL {1002CF3021}> 
on 
   #<CL-SOURCE-FILE "debug-mode" {10029E26C1}>. 

debugger invoked on a ASDF:COMPILE-FAILED in thread #<THREAD "initial 
thread" RUNNING {100266B2E1}>: 
  erred while invoking #<COMPILE-OP NIL {1002CF3021}> on 
  #<CL-SOURCE-FILE "debug-mode" {10029E26C1}> 

basically and didn't know what to do, so I asked the ever-helpful Weblocks google group, and was informed that the current stable version of Weblocks didn't yet work with the latest version of Hunchentoot, which had been just updated, but that it should work if I downgraded my Hunchentoot installation.  This is where, as usual, I ran into some problems.  

It took me a while to actually figure out how to get an old version from a darcs repository.  Here's an example of one of the less helpful bits of darcs documentation I encountered:

How do I go back to an older version of my repository?

Short answer: darcs get --to-match

Long answer: What exactly do you mean by go back to an older version?

http://wiki.darcs.net/DarcsWiki/FrequentlyAskedQuestions#head-e393e169c2c1ab8e991ff19fd0d09d29ce6c23f3

I went here and saw this:

To reproduce the state of a repository `R' as at tag `t', use the command `darcs get -tag t R'. The command `darcs show tags' lists all tags in the current repository.

but got confused when running "darcs show tags" revealed that there were no tags in this repository.  The same page also said:


If you want to get a specific version of a repository, you have a few options. You can either use the --tag--to-patch or --to-match options, or you can use the --context=FILENAME option, which specifies a file containing a context generated with darcs changes --context.


which seemed like it was getting me closer, but which I still got wrong, because I was stuck on the idea of tags. This page was the one that finally made sense to me:

Here's what did end up working:

  1. darcs changes, to see the patch names so as to use them later.  In this case, I saw that it had gone from "version 0.15.7" (the one I wanted) to "version 1.0.0".
  2. darcs unrecord -p 1.0, to remove the most recent patch and go back to the version before that.
  3. darcs revert, for the change made in 2. to actually take effect, with 'a' to revert all changes at once without saying 'y' for each one.

And that did it!  Weblocks is now working on my slice!  As usual with me, the way darcs works seems pretty clear from the documentation after the fact.

Filed under: PostgreSQL