Mostrando entradas con la etiqueta postgres. Mostrar todas las entradas
Mostrando entradas con la etiqueta postgres. Mostrar todas las entradas

domingo, 3 de julio de 2016

posgresql administracion

https://darkchicles.wordpress.com/2009/04/15/cambiar-la-codificacin-de-caracteres-en-postgres/
http://www.postgresql.org.ar/trac/wiki/PreguntasFrecuentes
http://www.postgresql.org.ar/trac/wiki/PgAdmin#HerramientadeRestauración

martes, 28 de junio de 2016

Procedimientos almacenados en postgres


Language Structure

PL/pgSQL is termed a block-structured language. A block is a sequence of statements between a matched set (conjunto combinado) of DECLARE/BEGIN and END statements. Blocks can be nested meaning (lo que significa) that one block can entirely contain another block, which in turn can contain other blocks, and so on. For example, here is a PL/pgSQL function:
 1 --
 2 -- ch07.sql
 3 --
 4
 5 CREATE OR REPLACE FUNCTION my_factorial(value INTEGER) RETURNS INTEGER AS $$
 6   DECLARE
 7     arg INTEGER;
 8   BEGIN
 9
10     arg := value;
11
12     IF arg IS NULL OR arg < 0 THEN
13          RAISE NOTICE 'Invalid Number';
14          RETURN NULL;
15     ELSE
16         IF arg = 1 THEN
17           RETURN 1;
18         ELSE
19           DECLARE
20             next_value INTEGER;
21           BEGIN
22             next_value := my_factorial(arg - 1) * arg;
23             RETURN next_value;
24           END;
25        END IF;
26     END IF;
27   END;
28 $$ LANGUAGE 'plpgsql';

This function contains two blocks of code. The first block starts at line 6 and 
ends at line 27. The second block, which is nested inside the first, starts at 
line 19 and ends at line 24. The first block is called an outer block because it contains the inner block.
Source: PostgreSQL: The comprehensive guide to building, programming, and 
administering
--------------------- 


Que es eso de $$...$$ o $func$..$func$?

...the body of a PL/pgSQL function is itself a string...

The body of my_factorial() is actually the string between the opening dollar quotes (following the word AS) and the closing dollar quotes (just before the word LANGUAGE).



http://stackoverflow.com/questions/12144284/what-are-used-for-in-pl-pgsql
---------------
https://www.postgresql.org/docs/current/static/sql-syntax-lexical.html#SQL-SYNTAX-DOLLAR-QUOTING

PostgreSQL provides another way, called "dollar quoting", to write string constants. A dollar-quoted string constant consists of a dollar sign ($), an optional "tag" of zero or more characters, another dollar sign, an arbitrary sequence of characters that makes up the string content, a dollar sign, the same tag that began this dollar quote, and a dollar sign.
----------
http://stackoverflow.com/questions/12144284/what-are-used-for-in-pl-pgsql
In fact if you look under "4.1.2.2. Dollar-Quoted String Constants" in the manual, you will see that you can even use characters in between the dollar symbols and it will all count as one delimiter.
OSEA QUE ANTES TENIAN QUE SER VACIOS esas cadenas constantes $$
-----------
The dollar signs are used for dollar quoting and are in no way specific to function definitions. It can be used to replace single quotes practically anywhere in SQL scripts.
(yo vi en ebook antiguo de posgresql,que para delimitar el cuerpo de una función utilizaban  comillas simples)

The body of a function happens to be a string literal which has to be enclosed in single quotes. Dollar-quoting is a PostgreSQL-specific substitute for single quotes to avoid quoting issues inside the function body. You could write your function definition with single-quotes just as well. But then you'd have to escape all single-quotes in the body:
CREATE OR REPLACE FUNCTION check_phone_number(text)
RETURNS boolean AS
'
BEGIN
  IF NOT $1 ~  e''^\\+\\d{3}\\ \\d{3} \\d{3} \\d{3}$'' THEN
    RAISE EXCEPTION ''Malformed string "%". Expected format is +999 999'';
  END IF;
  RETURN true; 
END;
' LANGUAGE plpgsql STRICT IMMUTABLE;
This isn't such a good idea. Use dollar-quoting instead, more specifically also put a token between the$$ to make it unique - you might want to use $-quotes inside the function body, too. I do that a lot, actually.

CREATE OR REPLACE FUNCTION check_phone_number(text)
  RETURNS boolean  LANGUAGE plpgsql STRICT IMMUTABLE AS
$func$
BEGIN
 ...
END;
$func$;
***********

The SQL needed to create a new function is CREATE FUNCTION, which has the following basicsyntax:CREATE FUNCTION name ( [ ftype [, ...] ] )RETURNS rtype
AS definition
LANGUAGE 'langname'
The parts of the function definition do not need to be in this order, and a popular choice isto state the language being used before the definition, like this:
CREATE FUNCTION name ( [ ftype [, ...] ] )
RETURNS rtype
LANGUAGE 'langname'
AS definition


viernes, 10 de junio de 2016

matar conexiones en postgresql

todas las conexiones
SELECT pg_terminate_backend(pid) FROM pg_stat_activity WHERE datname='siam_siar';

solo una
SELECT pg_terminate_backend(1952);

jueves, 26 de mayo de 2016

Tutorial de postgresql


https://www.postgresql.org/docs/9.2/static/auth-pg-hba-conf.html
0.0.0.0/0 representa todas las direcciones IPv4 y :: 0/0 representa todas las direcciones IPv6.
------------ En PGADMIN III al guardar una contraseña sale un mensaje

Indicando que la contraseña del usuario elegido se guardará en un fichero de texto plano, accesible por cualquier aplicación. Si estamos seguros pulsaremos "Aceptar" en la ventana anterior.
http://www.ajpdsoft.com/modules.php?name=News&file=article&sid=490

%APPDATA%\PostgreSQL\pgpass.conf 

-----------------


pgadmin creates the .pgpass file that all libpq programs use to easily 
connect a user to a database. 

-----------------------
COMO CAMBIAR EL PASSWORD DE PGADMIN EN FORMA GRAFICA
http://www.homebrewandtechnology.com/blog/graphicallychangepostgresadminpassword
-------------------------

***************************


Que es un cluster?
Segun video es una instancia de postgresql en el equipo
https://networkfaculty.com/es/video/detail/1062-postgresql---instalacion-basica-en-distribuciones-basadas-en-debian-y-redhat
--------------------

schema
schema is a named collection of tables. A schema can also contain views, indexes, sequences, data types, operators, and functions. Schemas are analogous to directories at the operating system level, except that schemas cannot be nested. PostgreSQL statement CREATE SCHEMA creates a schema


Advantages of using a Schema


  • It allows many users to use one database without interfering with each other.
  • It organizes database objects into logical groups to make them more manageable.
  • Third-party applications can be put into separate schemas so they do not collide with the names of other objects.
----------------
Problema que me paso
http://postgresql.nabble.com/FATAL-no-pg-hba-conf-entry-for-host-1-td1873063.html
****************

  • Why does pgAdmin pick up my IPv6 address and not my normal IP?


IPv6 is used because you are connecting to localhostlocalhost resolves to both 127.0.0.1 and::1.
Because operating systems prefer IPv6 over IPv4, that is the reason why IPv6 is used (although on Linux, this can be configured through /etc/gai.conf). The address ::1 is never used as a source address, and you don’t have a global address (2000::/3), which leaves the link-local address (fe80::/10) as the source address.
All perfectly logical, normal, expected behaviour when you think about it.
http://dba.stackexchange.com/questions/43608/postgres-connection-access-denied-on-ipv6-address

PostgresSQL, pgadmin pg_dump

pg_dump es una utilidad para copias de seguridad de una base de datos PostgreSQL. Este hace que las copias de seguridad coherentes, incluso si la base de datos se está utilizando al mismo tiempo. pg_dump no bloquea otros usuarios que acceden a la base de datos (lectores o escritores).


--section = sectionname
Sólo vuelca la sección mencionada. El nombre de sección puede ser pre-data, data, or post-data pre-datos. Esta opción se puede especificar más de una vez para seleccionar varias secciones (YO: por ejemplo como: --section=pre-data --section=post-data.). El valor por defecto es para volcar todas las secciones.


La sección data contiene los datos reales de la tabla, los contenidos de objetos largos y valores de secuencia. Los elementos post-data  incluyen las definiciones de índices, disparadores, reglas y restricciones con excepción de las restricciones de validacion   (validated check). Los elementos pre-data incluyen todos los demás elementos de definición de datos.


-a

--data-only
Vuelca sólo los datos, no el esquema (las definiciones). datos de tablas, objetos grandes, y los valores de secuencia son objeto son volcados.

Esta opción es similar a, pero por razones históricas no idéntica a especificar --section=data.

-s
--schema-only

(esquema solamente)

Vuelca solo el esquema (schema) (las definiciones), no la data.

Esta opción es la inversa de --data-only. Es similar a, pero por razones históricas no idénticos a, especificar







--section=pre-data --section=post-data.

(No confunda esto con la opción --schema, el cual utiliza el término "esquema" en un sentido diferente.)

Para excluir datos de la tabla de sólo un subconjunto de tablas en la base de datos, vease 
 --exclude-table-data

-b
--blobs
Incluye objetos grandes en el volcado (blobs). Este es el comportamiento por defecto (OSEA QUE POR DEFECTO SE LOS INCLUYE SI NO SE INDICA LO CONTRARIO), excepto cuando sólo se especifica            --schema--table, or --schema-only, por lo que el parámetro -b sólo es útil para añadir objetos de gran tamaño a volcados selectivos (selective dumps) (osea en la mayoria de los casos se omite esta opcion ya que esta activada por defecto).

-v
--verbose
(MENSAJES DETALLADOS) Especifica el modo detallado (verbose). Esto hará que pg_dump de salida detallada de objetos, comentarios y las veces de inicio/pare a el archivo de volcado, y el progreso de los mensajes al error estándar.


--------------------------
Si hago un backup y no activo el vervose me manda solo  un breve mensaje de exito

D:/DBMS/bin\pg_dump.exe --host localhost --port 5432 --username "postgres" --no-password  --format custom --blobs --file "D:\pruebadump\pruebadump.backup" "usuarios"

Process returned exit code 0.

--------------------------
http://es.tldp.org/Postgresql-es/web/navegable/user/app-pgdump.html
http://docwiki.embarcadero.com/DBArtisan/2016/en/Database_Backup_(PostgreSQL)
file:///D:/DBMS/doc/postgresql/html/app-pgdump.html