Está en la página 1de 55

Curso GeneXus

Resumen Conceptual
2da. Parte - Procedimientos
Comando For each

• Se utiliza para acceder a la información de la base de datos.

• ¿Cómo sabe GeneXus cuál tabla de la base de datos tiene que


navegar?
Transacción Base

Flight For each Flight


{ ---------
FlightId* Endfor
FlightDate
Transacción Base
-----
Seat
{
Nombre de la transacción
For each Flight.Seat cuya tabla física asociada
FlightSeatId*
--------- se desea recorrer
FlightSeatChar
Endfor
}
}
Orden

Customer Requerimiento: nos solicitan un listado de todos los


{ clientes ordenados alfabéticamente por su nombre.
CustomerId*
For each Customer order CustomerName
CustomerName
-------
------ Endfor
}

Requerimiento: nos solicitan un listado de todos los


clientes ordenados de forma descendente por su nombre.

For each Customer order (CustomerName)


-------
Endfor
Orden

GeneXus permite ordenar por el valor de un atributo que está o bien en la tabla que
estamos recorriendo (tabla base) o también en su tabla extendida.

For each Customer order CountryName


-------
Endfor
Filtros con Where

Flight For each Flight


{ Where FlightDate = Today()
FlightId* ---------
FlightDate Endfor
-----
Seat
{
FlightSeatId*
FlightSeatChar For each Flight.Seat
} Where FlightId = 1
} --------
Endfor
Filtros + Orden Index

Customer For each Customer order CustomerName


{ Where CustomerName >= &NameFrom
CustomerId* ---------
CustomerName Endfor
CustomerAddress
}

¡Consulta optimizada!
Sintaxis del For each

For each BaseTransaction


skip expression1 count expression2
order att1, att2, … , attn [when condition]
order att1, att2, … , attn [when condition]
unique att1, att2, … , attn
using DataSelector( parm1, parm2, … , parmn)
where condition [when condition]
where condition [when condition]
where att IN DataSelector( parm1, parm2, … , parmn)

main code

When none

Endfor
For each Anidados + Tabla base diferente + Tablas NO relacionadas =
PRODUCTO CARTESIANO

Country Producto Cartesiano 1 - Brasil


ProductA
{ ProductB
CountryId*
For each Country ProductC
CountryName 2 - Uruguay
Print Country ProductA
}
ProductB
For each Product ProductC
Print Product 3 - Chile
ProductA
Product Endfor ProductB
{ ProductC
ProductId* Endfor 4 - Estados Unidos
ProductName ProductA
ProductB
} ProductC
For each Anidados + Tablas bases diferentes + Tablas relacionadas = JOIN

Country
{
CountryId* 1 - Brasil
CountryName Join PAULO SILVEIRA
THIAGO REIS
}
1 For each Country 2 - Uruguay
Print Country

N For each Customer 3 - Chile


Print Customer
Customer Endfor 4 - Estados Unidos
{ ANN SMITH
CustomerId* Endfor
CustomerName
CountryId
CountryName
}
For each Anidados + Misma Tabla base + Tablas relacionadas = CORTE DE CONTROL

Country
Corte de control
{
CountryId*
CountryName For each Customer order CountryId
} Print Country 1 - Brasil
PAULO SILVEIRA
For each Customer THIAGO REIS
Print Customer
Customer 4 - Estados Unidos
Endfor ANN SMITH
{
CustomerId*
Endfor
CustomerName
CountryId
CountryName
}
Resumen

Producto Join Corte de


Cartesiano control

For each Country For each Customer order CountryId


For each Country Print Country
Print Country Print Country

For each Customer For each Customer


For each Product Print Customer
Print Product Print Customer
Endfor Endfor
Endfor
Endfor Endfor
Endfor

Tablas Tablas Misma tabla,


diferentes, sin diferentes, con Agrupando con order
relación relación
Resumen

Producto Join Corte de


Cartesiano control
1 - Brasil 1 - Brasil 1 - Brasil
ProductA PAULO SILVEIRA PAULO SILVEIRA
ProductB THIAGO REIS THIAGO REIS
ProductC
2 - Uruguay 2 - Uruguay 4 - Estados Unidos
ProductA ANN SMITH
ProductB
ProductC 3 - Chile
3 - Chile
ProductA
ProductB 4 - Estados Unidos
ProductC ANN SMITH

“No existe relación entre ambas “Todos los países y sus clientes, “Solo aquellos países que
entidades, mostrar todas las independientemente que tenga tengan clientes”
posibilidades para cada país” clientes o no”
Comunicación entre objetos
Ejemplo: pasaje de parámetros

Por ejemplo, en las Reglas de la trn Country:


Country
{ CustomerList(CountryId) on AfterComplete;
CountryId*
CountryName
}

CustomerList
Customer
{ Parm(in: &CountryId);
CustomerId* Variable
CustomerName For each Customer
CountryId Where CountryId = &CountryId Filtro explícito
CountryName ---------
} Endfor
Ejemplo: pasaje de parámetros

Por ejemplo, en las Reglas de la trn Country:


Country
{ CustomerList(CountryId) on AfterComplete;
CountryId*
CountryName
}

CustomerList
Customer
{ Parm(in: CountryId);
CustomerId* Atributo
CustomerName For each Customer
CountryId Where CountryId = &CountryId Filtro implícito
CountryName ---------
} Endfor
Ejemplo: retorno de un valor

Country Por ejemplo, en las Reglas de la trn Customer:


(
CountryId* &Control = CustomerControl(CustomerId);
CountryName
)

CustomerControl
Customer
( Parm(in: &CustomerId, out: &Control);
CustomerId*
CustomerName For each Customer
CountryId Where CustomerId = &CustomerId
CountryName ---------
) &Control = True
Endfor
Tipos de Datos Compuestos
Concepto

John Smith 3 variables

5th. Avenue 1234


customer

1 1 variable de tipo de
John Smith datos compuesto
5th. Avenue 1234
Definición

1- Se crea objeto de tipo: Structured Data Type + definición manual

2- Se crea objeto de tipo: Structured Data Type + drag & drop de Transacción
Carga

1 - En algún objeto de la KB con sentencias escritas manualmente…

&OneCustomer: variable basada en el tipo de datos SDTCustomer

2 - Con un objeto Data Provider…


Data Providers
Id: 1
Name: John Smith Un cliente
Address: 5th. Avenue 1234

SDTCustomer
Id: 2
s
Id: 1 Id: 3 Id: 4
Name: Susan
Name: John Smith Name: Robert Hill Name: Peter Jensen
Brown
Address: 5th. Ave. Address: 81th. St.. Address: St,Paul Rd.
Address: 7th.Ave.

Colección de Clientes
Ejemplo: Ranking de cantidad de atracciones por país

Pais Cantidad
atracciones

BRASIL 4
ESTADOS UNIDOS 3
URUGUAY 2
CHILE 1

….

Ejemplo: Ranking de cantidad de atracciones por país

SDTCountries

Una colección de países

Id: 2
Id: 1 Id: 3 Id: 4
Name: ESTADOS
Name: URUGUAY Name: BRASIL Name: CHILE
UNIDOS
AttractionQuantity: 2 AttractionQuantity: 4 AttractionQuantity: 1
AttractionQuantity: 3
Ejemplo: Ranking de cantidad de atracciones por país

Country
{
CountryId*
CountryName
}

Attraction
{
AttractionId*
AttractionName
CountryId
CountryName
}
Ejemplo: Ranking de cantidad de atracciones por país

Where…
Ejemplo: Ranking de atracciones por país País Cant. Atracc.

BRASIL 4
ESTADOS UNIDOS 3
URUGUAY 2
Country CHILE 1
{
CountryId*
CountryName
}

Attraction
{
AttractionId*
AttractionName
CountryId
CountryName
}
Variables Colección
&numbers

&Countries
Business Components
Concepto: Transacción que podrá ser ejecutada sin su form

• Se crea Data Type: Category en la KB.


• Es posible definir variables del tipo Category en objetos de
la KB.
Ejemplos: inserción y modificación utilizando el método Save()

&Category : Variable basada en el tipo de datos Category


Category
{
CategoryId*
CategoryName Insert
}

Update
Ejemplo: eliminación

&Category : Variable basada en el tipo de datos Category

Category
{
CategoryId* Delete
CategoryName
}
Métodos Insert y Update
&Category : Variable basada en el tipo de datos Category

Category Insert
{
CategoryId*
CategoryName
}

Update
Método InsertOrUpdate

Category
{
CategoryId*
CategoryName &Category : Variable basada en el tipo de datos Category
}

InsertOrUpdate
Insert / Update en transacción de dos Insert
niveles
Insert / Update en transacción de dos Insert
niveles
Insert / Update en transacción de dos Insert
niveles
Métodos en Colecciones BC Attraction

AttractionId
AttractionName
CountryId
CityId
CategoryId
AttractionPhoto

BC BC BC
Attraction Attraction Attraction

&attractions
&attractions.Update()
&attractions.Insert()
&attractions.InsertOrUpdate()
Insert / Update / InsertOrUpdate

Aconsejamos la utilización de los métodos Insert, Update e InsertOrUpdate ya que:

- Usando los métodos Load y Save para modificar se accede dos veces a la base de datos
-lo que disminuye la performance- mientras que con el Update o InsertOrUpdate se
accede solamente una vez

- Los nombres de estos nuevos métodos ya dan la pauta del objetivo claramente
Manejo de errores trabajando con BC

Por cada variable Business Component


se carga en memoria una colección con
todos los mensajes de advertencia o error
que se produzcan como consecuencia de las
operaciones.
Poblado de Datos
Transacción
Inicializar datos de forma automática

GeneXus ofrece una alternativa muy fácil para definir los datos con los cuales se desean
poblar las tablas físicas que se crean asociadas a las transacciones, lo que evita tener que
resolver las cargas de datos de otras maneras.
Inicializar datos

No cargamos el CategoryId
ya que fue definido como autonumerado
Inicializar datos: Solo lectura

Country
{
CountryId*
CountryName
}
Poblado de Datos
Business Components y Data Providers
DPCountries
Ejemplo

Country
{
CountryId* Autonumber = True
CountryName
}
Poblado de Datos con Procedimientos
Comandos New / For each / Delete
Consideraciones

Los comandos New / For Each / Delete sirven para insertar, actualizar y eliminar información de
la base de datos, pero solo pueden ser usados en Procedimientos

Si bien los siguientes comandos sirven para insertar, actualizar y eliminar información de la
base de datos, recomendamos la utilización de Business Component, ya que los mismos:

- Controlan la integridad referencial

- Disparan las reglas definidas en la


transacción
Inserción – Comando NEW

Category
{
CategoryId*
CategoryName
}

Si el atributo es autonumerado
no lo inserto
Modificación / Comando FOR EACH

Category
{
CategoryId*
CategoryName
}

Country Attraction
{ {
CountryId* AttractionId*
CountryName AttractionName
City CategoryId
{ CategoryName
CityId* CountryId
CityName CountryName
} CityId
} CitlyName
}
Eliminación – Comando DELETE

Attraction
{
AttractionId*
AttractionName
CategoryId
CategoryName
CountryId
CountryName
CityId
CitlyName
}
To be continued …

También podría gustarte