Игорь Олемской — практические заметки по системному администрированию Linux CentOS

Архив тега ‘postgresql’

Django postgresql connect_timeout via environment variable (перепечатка)

Комментариев нет

Recently, I've had to move a postgresql database onto a separate server and split it out from the django application server.

On doing so, we saw intermittent «OperationalError: could not connect to server: Connection timed out».

This was quite obvious that the «connect_timeout» had to be increased to resolve the issue due to the latency introduced by the network. However, psycopg2 database adapter was being used which did not support the «connect_timeout» option to be passed via django.

We were able to work around the issue setting the environmental variable «PGCONNECT_TIMEOUT» so libpq would pick up the connection parameter.

Put the below in «django.wsgi»:

os.environ['PGCONNECT_TIMEOUT'] = '30'

read more

munin-node and postgresql plugins setup (перепечатка)

Комментариев нет

While setting up munin to monitor postgresql, I was getting [DBD::Pg not found, and cannot do psql yet]"" when running `munin-node-configure --suggest | grep postgres`.

I confirmed that the rpm package «perl-DBI-1.52-2.el5» was indeed installed.

However, when I ran a test against the module, it failed with:

# perl -MDBD::Pg -e 1<br />Can't load '/usr/lib64/perl5/vendor_perl/5.8.8/x86_64-linux-thread-multi/auto/DBD/Pg/Pg.so' for module DBD::Pg: libpq.so.4: cannot open shared object file: No such file or directory at /usr/lib64/perl5/5.8.8/x86_64-linux-thread-multi/DynaLoader.pm line 230.<br /> at -e line 0<br />Compilation failed in require.<br />BEGIN failed--compilation aborted.

On checking the library, it returned with «libpq.so.4 => not found»:

# ldd /usr/lib64/perl5/vendor_perl/5.8.8/x86_64-linux-thread-multi/auto/DBD/Pg/Pg.so<br /> linux-vdso.so.1 =>  (0x00007fffb60bb000)<br /> libpq.so.4 => not found<br /> libc.so.6 => /lib64/libc.so.6 (0x00007fa36d2c2000)<br /> /lib64/ld-linux-x86-64.so.2 (0x00007fa36d845000)

Indeed libpq.so.4 was missing since postgresql90-libs was installed which only includes «libpq.so.5».

To get libpq.so.4, «compat-postgresql-libs» package needed to be installed.

Once installed the perl module test passed and I was able to get the munin plugins linked using:

# munin-node-configure --shell | grep postgres | sh

read more

tora-2.1.3 (перепечатка)

Комментариев нет

RPM of new version of TOra — Toolkit For Oracle are available in remi repository for Fedora 10 to 14.

The official site also provides RPM for Fedora 12.
To work, you need RPM Oracle Instant Client.
Pour l'installer, comme toujours :
yum --enablerepo=remi install toraThis tool can be used to manage your Oracle, PostgreSQL and MySQL databases. Despite this software is GPLv2, it can't be included in the official repository because of its link with... Lire tora-2.1.3

tora-2.1.2 (перепечатка)

Комментариев нет

RPM of new version of TOra — Toolkit For Oracle are available in remi repository for Fedora ≥ 9.

The official site also provides RPM for Fedora 12.
To work, you need RPM Oracle Instant Client.
Pour l'installer, comme toujours :
yum --enablerepo=remi install toraThis tool can be used to manage your Oracle, PostgreSQL and MySQL databases. Despite this software is GPLv2, it can't be included in the official repository because of its link with... Lire tora-2.1.2

Adding an administrative user to OS-X via the terminal (перепечатка)

Комментариев нет

So, I tend to do a lot of lower-level stuff on OS-X such as compiling my own PostgreSQL server for development and testing purposes.  One of the things that tends to interrupt the process of actually trying to run postgres is that it cannot change to the postgres user and it cannot run it as root.

In order to accomplish this you could make a user with your System Preferences which I have done in the past, the problem is then every time you log into your computer you’ll see this postgres user for no reason. Ugh, I hate that.  So to work around this you just have to run the following commands in your OS-X terminal to add a group and user for postgres, with the user “home” being the default compilation target directory for PostgreSQL (/usr/local/pgsql)

This is confirmed to work on every version of Leopard and Snow Leopard.

Cheers and enjoy!

PostgreSQL: read-only доступ ко всем таблицам БД

Комментариев нет

Чтобы в PostgreSQL предоставить readonly доступ ко всем созданным к текущему моменту таблицам определенной БД (но за исключением системных таблиц), можно воспользоваться командой:

psql -U postgres -qAt -c "select 'grant select on ' || tablename || ' to username;' from pg_tables where schemaname = 'public'" db_name | psql -U postgres db_name

Где вместо «grant select on» можно указать список доступов, к примеру "grant select, update, insert, delete on ".
Имя супер-пользователя: postgres, название БД, к таблицам которой предоставляется доступ: db_name, название пользователя, которому предоставляется ограниченный доступ: username.

03.12.2009

Написал Игорь Олемской

Рубрики: Мои записи

Теги: , , ,

Foreign keys для ActiveRecord (перепечатка)

Комментариев нет

Делаю очередной проект на Ruby on Rails. Как обычно, в миграциях понадобились foreign keys на уровне БД. Окинул взглядом все плагины, которые смог найти в google и на github.com. Ни один из них не умеет делать FK, используя ActiveRecord::ConnectionAdapters::Table#references и ActiveRecord::ConnectionAdapters::TableDefinition#references.

Поэтому сел и написал свой плагин: active_record_foreign_keys.

Установка:

Rails::Initializer.run do |config|
  ...
  config.gem "active_record_foreign_keys", :source => "http://gemcutter.org"
  ...
end
$ rake gems:install

Использование:

def self.up
  # create reference table
  create_table :users do |t|
  end
  # create referencing table
  create_table :a_examples do |t|
    t.references :user, :foreign_key => true
  end
  # or
  create_table :b_examples do |t|
    t.references :user, :foreign_key => { :o n_update => :cascade, :o n_delete => :restrict }
  end
  # or
  create_table :c_examples do |t|
  end
  add_foreign_key :c_examples, :user_id, :users, :id, :o n_update => :no_action, :o n_delete => :set_null
  # or change existing table
  change_table :d_examples do |t|
    t.references :user, :foreign_key => true
  end
end
def self.down
  # remove constraint
  remove_foreign_key :examples, :user_id, :users, :id
end

Плагин тестировался только под PostgreSQL, но по идее должен работать и под MySQL, и под Sqlite.

Внутреннее устройство реляционных баз данных (перепечатка)

Комментариев нет

Случайно наткнулся на серию статей, ознакомиться с которыми будет полезно, как сисадминам, так и программистам.

  1. Кортежи. Разбор запроса, построение AST, оптимизация AST. Построение плана выполнения
  2. Выполнение плана запроса
  3. Кэширование планов выполнения запроса
  4. Управление оперативной памятью
  1. Типы индексов: B-Tree, R-Tree, GiST, Bitmap, Hash, GIN

CentOS 5: особенности установки memcached и pgbouncer на одной машине

Один комментарий

В этой заметке описано, как установить memcached на ту же машину, где уже запущен pgbouncer (из репозитория pgdg). Сложность в том, что pgbouncer использует более новую версию libevent, чем memcached, в результате чего memcached при установке выдает «transaction failed».

Один из наиболее красивых выходов из ситуации — пересборка SRPM с новой библиотекой libevent, а заодно и новой версией memcached.

В случае, если репозиторий pgdg еще не установлен, его можно инсталировать следующей командой (версию можно выбрать на странице http://yum.pgsqlrpms.org/reporpms/repoview/pgdg-centos.html)

rpm -ihv http://yum.pgsqlrpms.org/reporpms/8.3/pgdg-centos-8.3-6.noarch.rpm

Из репозитория pgdg необходимо установить новый libevent-devel (вместо 83 может быть ваша версия pgdg)

yum --disablerepo=\* --enablerepo=pgdg83 install libevent-devel

Теперь необходимо загрузить srpm memcached (выбрать версию из репозитория можно по адресу: http://download.fedora.redhat.com/pub/epel/5/SRPMS/repoview/memcached.html) и последнюю версию самого memcached

rpm -Uhv http://download.fedora.redhat.com/pub/epel/5/SRPMS/memcached-1.2.5-2.el5.src.rpm
wget http://memcached.googlecode.com/files/memcached-1.2.8.tar.gz -O /usr/src/redhat/SOURCES/memcached-1.2.8.tar.gz

В файле /usr/src/redhat/SPECS/memcached.spec необходимо актуализировать версии memcached и rpm

Version:        1.2.8
Release:        1%{?dist}

Осталось собрать rpm

rpmbuild -bb /usr/src/redhat/SPECS/memcached.spec

В случае, если не хватает каких-то дополнительных библиотек, их можно установить командой «yum install».

Готовые пакеты можно найти в папке /usr/src/redhat/RPMS/

28.05.2009

Написал Игорь Олемской

Ruby 1.9 on Rails: несовместимость кодировок (перепечатка)

Комментариев нет

Я активно начал пробовать завести rails-приложения на ruby 1.9.1. В целом, все неплохо работает, но мелкие косяки бывают. Например, в will_paginate.

Для работы с PostgreSQL пришлось доработать гем postgres. Теперь гем компилируется как под ruby 1.8, так и под ruby 1.9. Кроме того, всем строковым данным, которые возвращает БД, навешивается кодировка из Encoding.external_encoding. Поставить доработанный гем можно командой:

sudo gem install antage-postgres --source=http://gems.github.com/

Исходники гема на гитхабе.

Но я хотел о другом написать. Об ошибке несовместимости кодировок ASCII-8BIT и UTF-8: ActionView::TemplateError (incompatible character encodings: ASCII-8BIT and UTF-8). Такая ошибка появляется при запуске Rails на ruby 1.9.1. В edge-версии rails ошибка все еще не исправлена. Для исправления нужно закинуть monkey-patch в config/initializers/.