Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
B.RDB$FIELD_SCALE,
CASE
WHEN B.RDB$FIELD_PRECISION > 0 THEN
'NUMERIC('||CAST(B.RDB$FIELD_PRECISION AS
VARCHAR(2))||','||CAST(B.RDB$FIELD_SCALE*-1 AS VARCHAR(2))||')'
WHEN C.RDB$TYPE_NAME='LONG' THEN 'INTEGER'
WHEN C.RDB$TYPE_NAME='SHORT' THEN 'SMALLINT'
WHEN C.RDB$TYPE_NAME='VARYING' THEN
'VARCHAR('||B.RDB$CHARACTER_LENGTH||')'
WHEN C.RDB$TYPE_NAME='TEXT' THEN
'CHAR('||B.RDB$CHARACTER_LENGTH||')'
WHEN C.RDB$TYPE_NAME='BLOB' THEN 'BLOB SUB_TYPE
'||CAST(B.RDB$FIELD_SUB_TYPE AS CHAR(1))
ELSE
C.RDB$TYPE_NAME
END AS F_TIPO,
CASE
WHEN A.RDB$NULL_FLAG IS NULL THEN ''
ELSE
'NOT NULL'
END AS F_NULL,
F.RDB$FIELD_NAME AS F_PRIMARY
FROM
RDB$RELATION_FIELDS
A
LEFT JOIN RDB$FIELDS
B ON A.RDB$FIELD_SOURCE=B.RDB$FIELD_NAME
LEFT JOIN RDB$TYPES
C ON C.RDB$FIELD_NAME='RDB$FIELD_TYPE' AND
B.RDB$FIELD_TYPE=C.RDB$TYPE
LEFT JOIN RDB$RELATION_CONSTRAINTS
E ON A.RDB$RELATION_NAME=E.RDB$RELATION_NAME AND
E.RDB$CONSTRAINT_TYPE='PRIMARY KEY'
LEFT JOIN RDB$INDEX_SEGMENTS
F ON E.RDB$INDEX_NAME=F.RDB$INDEX_NAME AND
A.RDB$FIELD_NAME=F.RDB$FIELD_NAME
WHERE
A.RDB$RELATION_NAME = 'SUA_TABELA'
COMO OBTENER LOS TIPOS DE DATOS SOPORTADOS POR EL FIREBIRD
SELECT RDB$TYPE, RDB$TYPE_NAME
FROM RDB$TYPES WHERE RDB$FIELD_NAME = 'RDB$FIELD_TYPE'
COMO REPARAR UNA BASE DE DATOS
1. Detener el Servidor del Firebird. Esto es muy importante porque aunque ningn
usuario est accediendo a la BD el Servidor puede estar realizando alguna tarea
interna y si no se lo detiene eso puede conducir a ms corrupcin.
2. Hacer una copia de seguridad de la BD.
Un Ejemplo
Para finalizar, har un pequeo ejemplo de cmo crear una pgina web. Tomar como
referencia la tabla personas que se cre en el artculo Pasando de Paradox a InterBase,
parte 2. Esta es la estructura de la tabla:
CREATE TABLE PERSONAS(
CLAVEPERSONA INTEGER NOT NULL,
NOMBRE VARCHAR(40),
APELLIDOS VARCHAR(40),
TELEFONO VARCHAR(40),
EMAIL VARCHAR(100),
PRIMARY KEY(CLAVEPERSONA)
)
Entonces para desplegar esta tabla crearemos un archivo HTML con cdigo integrado
de PHP:
<HTML>
<HEAD></HEAD>
<BODY>
<?php
ibase_pconnect("/opt/interbase/bases/mi_base.gdb", "USU_PHP",
"usu0189xf");
echo "<TABLE WIDTH="100%" BORDER="1">;
$Q = ibase_query("SELECT * FROM PERSONAS;");
while ($R = ibase_fetch_object($Q)) {
echo "<TR><TD>" . $R->CLAVEPERSONA . "</TD>n";
echo "<TD>" . $R->NOMBRE . "</TD>n";
echo "<TD>" . $R->APELLIDOS . "</TD></TR>n";
}
echo "</TABLE>";
?>
</BODY>
</HTML>
S que este artculo es bastante corto y no cubre algunos aspectos bsicos como
instalacin de PHP con Windows o con Linux y activar el soporte a InterBase, pero
tambin estoy consciente que cuando menos ayudar a algunas personas que ya conocen
PHP a utilizar las ventajas de InterBase en esta plataforma de desarrollo tan popular,
como PHP.
Conectarse a Firebird
Ahora vamos a proceder a conectarnos a Firebird desde PHP.
Cdigo para conectar a la base:
Cdigo:
$conn=ibase_connect("localhost:C:\\AppServ\\www\\fdb\\MUSICA.FDB",
"SYSDBA", "masterkey");
if (!$conn)
{ echo "Acceso Denegado!";
exit; }
Cdigo:
bin/fb_lock_print
bin/isql
intl/fbintl
intl/fbintl.conf
firebird.msg
libfbembed.so
libfbembed.so.2.5
libfbembed.so.2.5.0
security2.fdb
Luego de copiar esos archivos en la carpeta mencionada anteriormente, algo como (en
mi caso):
Cdigo:
root@slax:~# cd /root/Desktop/fbembed
Ahora debemos crear un archivo firebird.conf para indicar la ubicacion del fbembed
donde se creara la BD y agregamos las siguientes lineas:
Cdigo:
RAZONES PARA CREAR LAS BASES DE DATOS CON OTRO USUARIO (NO CON
SYSDBA)
Las Bases de Datos y los metadatos (dominios, tablas, procedimientos almacenados,
desencadenantes, etc.) no deben ser creados por el usuario SYSDBA sino por otro usuario, ya
que no siempre se podr conocer la contrasea de SYSDBA.
COMO CONOCER LA VERSIN DEL SERVIDOR
Para conocer cual es la versin del Servidor, se debe escribir esta consulta:
SELECT RDB$GET_CONTEXT(SYSTEM, ENGINE_VERSION) FROM
RDB$DATABASE
FECHAS DE SALIDA DE CADA VERSIN DEL FIREBIRD
Poner una tabla con la fecha en la cual se liber cada versin del Firebird y tambin lo que se le
fue agregando o mejorando.
HAMACHI
Para que funcione la conexin con Hamachi el firewall tiene que estar desactivado.
CONNECT 5.20.83.86:ERP USER WALTER PASSWORD 123456
funciona OK
NDICES
La estadstica de los ndices solamente es calculada despus de un ciclo backup/restore o cuando
un ndice es recreado o activado.
Una estadstica de 0,5 solamente ocurre cuando hay dos valores en esa columna, por ejemplo 0 y
1, S y N, esto es malsimo en trminos de performance.
Cuanto ms cerca est de cero la estadstica, mucho mejor. Cuanto mayor es el valor, es peor.
Caso seu Firebird esteja rodando em uma porta diferente da padro, basta adaptar o
comando para a porta desejada.
Dica enviada por Daniel Pereira Guimares
TRANSACCIONES
OK, time for my lecture on OAT and OIT.
The OIT is the oldest transaction in the system that did not commit usually a transaction that failed but could not roll itself back. They're
more common in Classic that SuperServer because the latter rolls back
transactions after a normal failure. But if one of the client processes is
killed, it will leave all its transactions marked as rolled back. There
are only two ways to increase the OIT. Backup/restore or sweep. The good
news is that an old, stuck OIT doesn't matter much at all. A very long
time ago when we could only dream of have a gig of disk (and not even
imaging a whole gig of memory), keeping a list of the states of old
transactions (at two bits per transaction) between the OIT and current
transaction was a problem. It's not any more.
So don't worry about the difference between the OIT and next, or if you
must worry, run a sweep from time to time.
The OAT is the oldest transaction that the system considers to be active.
It blocks garbage collection and induces database bloat. Transactions
that commit using "commit retaining" do not advance the OAT. Transactions
that are left open for hours - even transactions that have not changed
the database - leave the OAT stuck. Once the OAT is stuck, Firebird must
keep old versions of records that transaction might read if it ever wakes
up and starts working again.
Do worry about a stuck OAT. Use the MON$ tables to identify it and stop it.
Good luck,
Ann
TIPOS DE TRANSACCIONES
SNAPSHOT. Si una transaccin es de este tipo entonces ve a la Base de Datos como estaba en el
momento de iniciarse la transaccin, todos los cambios que ocurran posteriormente en la Base de
Datos (inserciones, borrados, modificaciones) son invisibles para la transaccin de tipo Snapshot,
como si no existieran.
READ COMMITED, Si una transaccin es de este tipo entonces todos los cambios que hayan
ocurrido despus de que inici y que hayan sido commited sern visibles. O sea, si una
transaccin es Read Commited puede ver a todas las transacciones que fueron commit
despus que ella inici.
Snapshot Ve solamente las transacciones que fueron commit antes de que empezara
Read Commited Ve las transacciones que fueron commit antes y despus que empezara
If I access a table in a firebird database from excel using ODBC is that table
automatically in a locked state until i quit Excel?
No. Firebird doesn't lock tables the way you are used to with Access, for example. Firebird
employs what is known as "optimistic locking", whose exact behaviour is determined by the way
the enclosing transaction is configured.
What you will have is a transaction started through the ODBC interface. The isolation level of
that transaction determines how stable your application's view will remain throughout the
transaction and the behaviour when two or more transactions want to modify the same row.
SNAPSHOT isolation (which I think is the default for the Firebird ODBC driver) means that
Excel continues to see the set as it was at the start of the transaction. READ COMMITTED
isolation means that Excel can refresh the set to get an updated view of what other transactions
have committed since its own transaction started.
If another transaction has a pending update on a row in the set that Excel is viewing, a lock
conflict occurs and Excel won't be able to update that row. If Excel has an update pending on a
row in that set, other transactions won't be able to update that row.
./hb
If you succeed, you have fixed the problem and have a functional database. If not, you
can try to create an empty database with the same structure and pump the data to it (see
FAQ #20).
One of the reasons why backup or restore can fail is if some broken database triggers
exist, and prevent connection to the database. For example, a database trigger might use
some table which has a broken index, etc. To work around this, connect to database with
isql tool using -nodbtriggers option and then disable those triggers. You can enable them
later when you fix other problems and get a working database again.
Another reason restore might fail is when you have broken data, so some of validity
constraints (check constraints, etc.) cannot be satisfied. In this case, you can try to
restore your database using -N[O_VALIDITY] command switch to gbak.
If you're interested in a more detailed information of the process of fixing the database,
as well as explanation of some types of corruption, take a look at the following page:
http://www.ibphoenix.com/resources/documents/search/doc_5
If all fails, you can try IBSurgeon tool, which is able to fix most problems and extract
data. Also, IBSurgeon's website has a detailed
explanation of causes of database corruption and ways to fix it:
http://ib-aid.com/option,com_content/task,view/id,58/Itemid,62/
CUAL VERSIN DEL FIREBIRD INSTALAR, 32 BITS 64 BITS?
En el Servidor la versin debe corresponder a la CPU. Eso significa que si la CPU es de
32 bits entonces se debe instalar el Firebird Server de 32 bits. Y si la CPU es de 64 bits entonces
se debe instalar el Firebird Server de 64 bits.
En cuanto a los clientes: si las aplicaciones estn compiladas en 32 bits entonces se debe
usar el cliente de 32 bits en todas las computadoras. Y si las aplicaciones estn compiladas en 64
bits entonces se debe usar el cliente de 64 bits en todas las computadoras.
Versin del Server = CPU
Versin del Cliente = Compilacin de las aplicaciones
EXECUTE STATEMENT
Este comando recibe un argumento y lo ejecuta. Puede devolver resultados o no.
Ejemplo Nro 1:
SET TERM ^ ;
CREATE PROCEDURE OBTENER_NOMBRE_EMPRESA
RETURNS(
NOMEMP TYPE OF COLUMN EMPRESA.EMP_NOMBRE)
AS
DECLARE VARIABLE COMANDO VARCHAR(256);
BEGIN
COMANDO = 'SELECT EMP_NOMBRE FROM EMPRESA';
EXECUTE STATEMENT :COMANDO INTO :NOMEMP;
END^
SET TERM ; ^
Suponiendo que tenemos una tabla llamada EMPRESA que tiene una sola fila (y ninguna
ms) y dentro de esa tabla una columna llamada EMP_NOMBRE, entonces el SP de arriba nos
devolver el nombre de la Empresa. Pero solamente funcionar si la tabla tiene una sola fila.
EXECUTE PROCEDURE OBTENER_NOMBRE_EMPRESA
Ejemplo Nro 2:
SET TERM ^ ;
CREATE PROCEDURE OBTENER_DATOS_CLIENTES
RETURNS(
IDENTI TYPE OF COLUMN CLIENTES.CLI_IDENTI,
NOMCLI TYPE OF COLUMN CLIENTES.CLI_NOMBRE)
AS
DECLARE VARIABLE COMANDO VARCHAR(80);
BEGIN
COMANDO = 'SELECT CLI_IDENTI, CLI_NOMBRE FROM CLIENTES
ORDER BY CLI_CODSUC, CLI_IDENTI';
FOR EXECUTE STATEMENT :COMANDO INTO :IDENTI, :NOMCLI DO
SUSPEND;
END^
SET TERM ; ^
Cuando queremos obtener ms de una fila, debemos escribir un SP similar al de arriba, es
decir utilizando un ciclo FOR DO y el comando SUSPEND. A esta clase de SP se les llama
seleccionables.
Cada vez que se ejecuta el comando SUSPEND se devuelve una fila (y solamente una
fila) al programa que llam a este SP.
Como se trata de un SP seleccionable, para obtener las filas debemos escribir:
SELECT IDENTI, NOMCLI FROM OBTENER_DATOS_CLIENTES
STORED PROCEDURES SELECCIONABLES
Un SP es seleccionable cuando contiene una instruccin SUSPEND, y en tal caso se lo
ejecuta a travs de un SELECT.
RECOLECCIN DE BASURA
New records don't cause garbage collection. "Garbage collection" is the process of removing
record versions that are so old that no running transaction can reference them. A newly inserted
record has only one version (duh!) and doesn't invalidate any other version. Updates and deletes
create new versions. When the transaction that updated or deleted the record commits, it sets the
stage for garbage collection. When all concurrent transactions end, the older versions of the
record are no longer useful and become garbage. (We use graphic language at Firebird. The old
record versions neither smell nor attract flies and rodents.) Sooner or later, the old versions are
removed so the space they used can be reallocated.
There are three types of garbage collection: cooperative, thread-based, and mixed. Cooperative is
the only mode available in Classic or Super Classic. In cooperative garbage collection, when a
transaction reads a row, it checks for unneeded old versions and removes them immediately. In
thread-based garbage collection, when a transaction finds a row that has unneeded old versions,
it puts that row's record number on the queue for the garbage collection thread. Eventually the
garbage collection thread comes by and cleans up. In the mixed mode of garbage collection (80%
certainty), when a transaction reads a row with unneeded old versions, it cleans them
immediately if all the versions are on one page. If the back versions are on a different page, the
transaction puts the record number of the row on the garbage collect list and the garbage
collection thread cleans up.
The problem with cooperative garbage collection is that after a large update or delete operation,
some unfortunate transaction that's just trying to collect data for a report can get saddled with
lots of I/O removing garbage. The problem with thread-based garbage collection is that in a
heavily laden system, the garbage collector thread doesn't get enough cycles, and the information
density of the database goes down. The mixed mode has both problems. See also Postgres: online and off-line vacuuming.
Ann Harrison
SELECT
*
FROM
MiTabla
podra mostrar un mensaje de error por qu eso? Porque para ordenar la tabla segn
MiColumna el Firebird necesita escribir datos intermedios en una carpeta temporal. Si no tiene
acceso a la carpeta temporal o si hay muy poco espacio libre en el disco duro entonces no podr
escribir los datos intermedios que necesita.
La/s carpeta/s temporaria/s se especifican en el archivo FIREBIRD.CONF, por ejemplo
con:
TEMPDIRECTORIES=C:\TEMP; D:\TEMP
Vamos supor que voc j inseriu dados na tabela FUNCIONARIOS. Agora a misso exportar
esses dados para o arquivo texto: "C:\Temp\Funcionarios.txt".
Vamos criar uma tabela que residir no arquivo externo "C:\Temp\Funcionarios.txt", ou seja, essa
nova tabela ser o prprio arquivo texto a ser gerado. Como se trata de um arquivo texto,
utilizaremos apenas colunas/campos do tipo CHAR, pois os outros tipos resultaro em
dados binrios.
*CREATE TABLE EXPORTACAO EXTERNAL FILE 'C:\Temp\Funcionarios.txt' (
-- Nome completo do funcionrio.
NOME CHAR(200) CHARACTER SET ISO8859_1 NOT NULL COLLATE PT_BR,
-- CPF do funcionrio.
CPF VARCHAR(11) CHARACTER SET ISO8859_1 NOT NULL COLLATE PT_BR,
-- Quebra de linha de texto (caracteres CR + LF = CHR(13) + CHR(10) no
caso do MS Windows).
CRLF CHAR(2));*
O arquivo texto foi criado com sucesso, agora podemos excluir essa tabela externa, caso no
precisemos mais dela.
*DROP TABLE EXPORTACAO;*
Nota: Excluindo a tabela externa no exclui tambm o respectivo arquivo. Ento pode exclu-la
sem problema algum.
Esse apenas um pequeno exemplo. Espero que lhe sirva para suprir as suas necessidades.
Espero ter ajudado mais que atrapalhado. :D
Sandro Souza
Administrative Features
114
MON$AUTO_UNDO indicates the auto-undo status set for the transaction, i.e.,
SET TERM ; ^
EXECUTE PROCEDURE SP_UpdateSequences;
--- Fim do SQL --Neste exemplo todos generatores (sequences) possui nomes neste formato:
SQ_NomeDaTabela_NomeDoCampo
Atenciosamente.
Daniel P. Guimares
Tecnobyte Informtica
www.tecnobyte.com.br