lunes, 26 de junio de 2017

jueves, 25 de mayo de 2017

Postgres dblink - Consultando tablas de otra base de datos

With PostgreSQL 9.1 or later, installation of additional modules has been simplified. Registered extensions (including dblink) can be installed with CREATE EXTENSION:

CREATE EXTENSION dblink;

Run once per database. Or run it in the standard system database template1 to add it to every newly created DB automatically. Details in the manual.


Ejemplo:

select t.*
 from dblink('host=localhost dbname=bd user=postgres password=secret', 
                    'select id, name from table')
  as t(id int, name varchar)
 where id < 100
 order by id desc


Mas ejemplos:

http://www.postgresonline.com/journal/archives/44-Using-DbLink-to-access-other-PostgreSQL-Databases-and-Servers.html

martes, 23 de mayo de 2017

pgFormatter - Formateando query

http://sqlformat.darold.net/

This SQL formatter/beautifier supports keywords from SQL-92, SQL-99, SQL-2003, SQL-2008, SQL-2011 and PostgreSQL specifics keywords. May works with any other databases too.

Interesante... nice ;)

Links:

    Website: http://sqlformat.darold.net/
    Download: http://sourceforge.net/projects/pgformatter/
    Development: https://github.com/darold/pgFormatter
    Changelog: https://github.com/darold/pgFormatter/blob/master/ChangeLog

Emparejamiento difuso - Fuzzy Matching Algorithms To the Rescue

Levenshtein is a great algorithm to detect typos in a search query. It operates based on how distant one search term is from another term. Starting with the “source” word, it counts the number of operations (additions, subtractions, substitutions) it takes to arrive at the “destination” word. This make the Levenshtein algorithm particularly good at catching seach typos, and uncommon spellings.
(https://mrfrosti.com/2011/08/22/fuzzy-matching-in-postgresql-with-nicknames/)

Previamente habilitar la extensión:

CREATE EXTENSION fuzzystrmatch;

Ejemplo:

SELECT levenshtein('iden', 'idem');

Ejemplo: comparando el campo NOMBRE de dos tablas:

SELECT a.nombre1, b.nombre2, levenshtein(a.nombre1, b.nombre2) as leven
from tabla1 a, tabla2 b
where 
and levenshtein(a.nombre_com, b.nombre_c_1) >=  0
order by leven

links relacionados:

https://www.postgresql.org/docs/9.3/static/functions-matching.html
https://www.laurivan.com/fuzzy-string-matching-in-postgresql/
https://www.rdegges.com/2013/easy-fuzzy-text-searching-with-postgresql/

martes, 25 de abril de 2017

Vim - mínimo

Search & replace: 
:11,15s/old/new/gc         with c_onfirmation in a range
:%s/old/new                    all
:21,$
:.,$                                    current line
:.,+100

Ciertos caracteres especiales (/ & ! . ^ * $ \ ?) tienen un significado particular en el proceso de búsqueda, y por lo tanto deben especificarse de un modo especial cuando están incluidos en el string a buscar, precediéndolos por la barra hacia atrás (\).

Read  oother file:
:r  ~/home/ric/file.txt
:r! sed -n 7,15p ~/home/ric/file.txt              (block)

Indent/ Unindent:
gg=G                all
in mode insert   CTRL-T   indent
                          CTRL-D   unindent
in mode normal  >>    <<     line current

Indent bloques:
v    marcar bloque - visual mode
<    indenta izq,   > derecha


Borrar/copiar/pegar:
dgg      del cursor al principio
dG                        al final
3dd      3 líneas

3yy      copiar 3 líneas
p           debajo de la línea  P arriba

Modo columna:
CTRL-V

Bloques - copiar/pegar
mb    - en inicio de bloque marca con el nombre b (ejm)
y'b     - al final de bloque   (d para borrar)
luego con p  ó  P en la ubicación deseada

Bloques - copiar/pegar con número de línea
:7,10y           (marca para copiar de la línea 7 a la 10, con d para borrar)
luego con p ó P en la ubicación deseada

Desactivar autoindent temporalmente para copiar
:set paste
:set nopaste    (set noai?)

Install plugin EMMET:

## install emmet
cd Downloads
git clone https://github.com/mattn/emmet-vim.git
cd ~/.vim
cp -r ~/Downloads/emmet-vim/plugin/ .
cp -r ~/Downloads/emmet-vim/autoload/ .

## redefine trigger key <c-y>  ->  ,,
## add a .vimrc
let g:user_emmet_leader_key=','

Refs.:
https://medium.com/vim-drops/be-a-html-ninja-with-emmet-for-vim-feee15447ef1
https://raw.githubusercontent.com/mattn/emmet-vim/master/TUTORIAL

Insert new line without entering mode insert:
nmap <F8> o<Esc>
nmap <F9> O<Esc>

Registers:


"ry5w                 # register yank 5 palabras,  para copiar: "p"
:reg                    # lista los registros realizados, para copiar:  "Cp 
                            # donde C es el caracter asignado automáticamente por register  

miércoles, 22 de marzo de 2017

Habilitando base de datos espacial Postgres/PostGIS

Asumiendo que se tiene instalado Ubuntu Server 16.04 LTS y Postgres/PostGIS.

Desde la consola de Postgres:

Crear usuario que será dueño de la bd:

postgres=# create user name_user login superuser password 'secret'  ;

Crear bd:

postgres=# create database name_db owner name_user;

Probar conexión:

postgres=# \q

$  psql -h localhost -d name_db -U name_user -W
 (ingresar password 'secret')

Habilitar postgis en bd:

name_dbs=> create extension postgis;
name_dbs=> create extension postgis_topology;

Verificar si Postgres se esta ejecutando y "escucha":
(Debe indicar que escucha en el puerto configurado por defecto 5432 u otro si fue modificado)

$ netstat -na | grep postgres

Habilitar acceso a la bd desde otro(s) equipo(s):
Editar el archivo /etc/postgresql/9.5/main/pg_hba.conf
Adicionar la siguiente línea en la sección #IPv4

host    all    all    0.0.0.0/0     md5

Editar el archivo /etc/postgresql/9.5/main/postgresql.conf
omitir el comentario y reemplazar 'localhost' por '*' en la parte de "Connection settings"

listen_addresses = '*'

Reiniciar el servicio y puede ser accedida desde cualquier equipo y SIG de escritorio:

sudo /etc/init.d/postgresql restart