Array in Tuple.of (vert.x pgclient) - rest

this is my postgresql CTE's. Works well with various examples.
with vtas_itms as (
insert into ventas (idafip, tipo_venta, nrodoc_persona, tperso_persona, nrodoc_vendedor,
tperso_vendedor, idfinanciacion, cancuotas, fecha_comprobante, punto_venta,
numero_comprobante, cae, fecha_vtocae, situacion_fiscal, nombre_cliente,
numero_remito, coeficiente, bonificacion, obs_generales, obs_comerciales,
obs_afip, estado)
values (6, 'Efectivo', 17412018, 'Cliente', 14808837,
'Vendedor', 1, null, '2020-10-27', 6,
215, '70332083246226', '2020-11-02', 'Consumidor Final', 'Consumidor Final',
null, null, null, null, null,
null, 'Pagada')
returning idventa
)
insert into ventas_items (idventa, idarticulo, cantidad, precio_unitario, descuento_articulo, saldo_articulo)
select vtas_itms.idventa, d1.col1, d1.col2, d1.col3::numeric, d1.col4::numeric, d1.col5::numeric
from vtas_itms
cross join (values (3,2,82.38,null,null), (4,1,43.12,null,null),(1,0.750,286.30,null,null)) as d1(col1,col2,col3,col4,col5)
Pay attention to cross join values: 5 columns with "n" occurrences...it's an array, of course.
Now, on the server side (business):
private static final String INSERT_VENTA = "with vtas_itms as ("
+ "insert into ventas (idafip, tipo_venta, nrodoc_persona, tperso_persona, nrodoc_vendedor, tperso_vendedor, idfinanciacion, cancuotas, fecha_comprobante, punto_venta, "
+ "numero_comprobante, cae, fecha_vtocae, situacion_fiscal, nombre_cliente, numero_remito, coeficiente, bonificacion, obs_generales, obs_comerciales, "
+ "obs_afip, estado) "
+ "values ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16, $17, $18, $19, $20, $21, $22) "
+ "returning idventa) "
+ "insert into ventas_items (idventa, idarticulo, cantidad, precio_unitario, descuento_articulo, saldo_articulo) "
+ "select vtas_itms.idventa, d1.col1, d1.col2, d1.col3::numeric, d1.col4::numeric, d1.col5::numeric "
+ "from vtas_itms "
+ "cross join ($23::text[]) as d1(col1,col2,col3,col4,col5)";
Look at the $23::text[] parameter...I need to put in the prepared query (after "venta.getEstado()") and in the API...and I don't known how
public void putVenta(RoutingContext routingContext) {
Venta venta = Json.decodeValue(routingContext.getBodyAsString(), Venta.class);
HttpServerResponse response = routingContext.response();
pgClient
.preparedQuery(INSERT_VENTA)
.execute(Tuple.of(venta.getIdafip(), venta.getTventa(), venta.getNrodoc_persona(), venta.getTperso_persona(), venta.getNrodoc_vendedor(), venta.getTperso_vendedor(),
venta.getIdfinanciacion(), venta.getCancuotas(), venta.getFecha_comprobante(), venta.getPunto_venta(), venta.getNumero_comprobante(), venta.getCae(),
venta.getFecha_vtocae(), venta.getSituacion_fiscal(), venta.getNombre_cliente(), venta.getNumero_remito(), venta.getCoeficiente(), venta.getBonificacion(),
venta.getObs_generales(), venta.getObs_comerciales(), venta.getObs_afip(), venta.getEstado()), ar -> {
if (ar.succeeded()) {
response.putHeader("content-type", "application/json; charset=utf-8")
.setStatusCode(201)
.end();
} else {
System.out.println("Failure: " + ar.cause().getMessage());
response.putHeader("content-type", "application/json; charset=utf-8")
.end(Json.encodePrettily(ar.cause().getMessage()));
}
});
}
ยดยดยด
API (routes). After parameter /:estado)
// tag::createRoutes[]
router.put("/api/ventas/insertVenta/:idafip/:tipo_venta/:nrodoc_persona/:tperso_persona/:nrodoc_vendedor/:tperso_vendedor/:idfinanciacion"
+ "/:cancuotas/:fecha_comprobante/:punto_venta/:numero_comprobante/:cae/:fecha_vtocae/:situacion_fiscal/:nombre_cliente"
+ "/:nro_remito/:coeficiente/:bonificacion/:obs_generales/:obs_comerciales/:obs_afip/:estado").handler(bizVentas::putVenta);
Any help?. TIA
Ernesto

You're looking to create a virtual table from a single string.
That's actually possible with Postres.
You can provide your string in an array syntax, using {}, and then use unnest to split every string into a separate row.
Then you use string_to_array to split every row into separate columns.
select a[1], a[2], a[3], a[4], a[5]
from (
select string_to_array(nest.l, ',') as a
from (
select unnest('{"3,2,82.38,null,null","4,1,43.12,null,null"}'::text[]) as l
) nest) b
You can replace your values () part now with this query.
From Vert.x side, you'll have to create exactly this string, and bind it.

Related

JPQL: How to rewrite postgres native query to JPQL query that uses filter keyword

Im trying to avoid using native query. I have this query that uses the filter function, how could I rewrite this to not use that and work in regular jpql?
#Query(
"SELECT time_bucket(make_interval(:intervalType), d.time) as groupedDate, " +
"CAST(d.team_Id as varchar) as teamId, CAST(d.service_Id as varchar) as serviceId, CAST(d.work_id as varchar) as workId, " +
"ROUND(CAST(count(d.value) filter ( where d.type = 'A') AS numeric) /" +
" (CAST(count(d.value) filter ( where d.type = 'B') AS numeric)), 4) as total " +
"FROM datapoint d " +
"WHERE d.team_Id = :teamId and d.service_id in :serviceIds and d.work_id = :workspaceId and d.type in ('A', 'B') " +
"AND d.time > :startDate " +
"GROUP BY groupedDate, d.team_Id, d.service_Id, d.workspace_Id " +
"ORDER BY groupedDate DESC",
nativeQuery = true
)
in the FROM statement you have to use the DAO object instead of the table name

Exception due to insert query taking a long time

I am Using the below mentioned query for insert operation and sometimes when the data is large it's taking long time for execution because of which I am getting exception error.I want to know how can I reduce the execution time for insert query for large data.
#"DO $$
DECLARE maxversionnumber integer;
BEGIN
select max(versionnumber) into maxversionnumber from reissue.holdingsclose;
IF maxversionnumber IS NULL THEN
select 1 into maxversionnumber;
ELSE
select max(versionnumber)+1 into maxversionnumber from reissue.holdingsclose;
END IF;
INSERT INTO reissue.holdingsclose (feedid,
filename,
asofdate,
returntypeid,
currencyid,
securityid,
indexid,
indexname,
securitycode,
sizemarkercode,
icbclassificationkey,
rgsclassificationkey,
securitycountry,
securitycurrency,
pricecurrency,
sizemarkerkey,
startmarketcap,
closemarketcap,
marketcapbeforeinvestability,
marketcapafterinvestability,
adjustmentfactor,
marketcapafteradjustmentfactor,
grossmarketcap,
netmarketcap,
xddividendmarketcap,
xddividendnetmarketcap,
openprice,
closeprice,
shares,
sharechg,
investabilityweight,
dividendyield,
pctindexweight,
growthfactor,
valuefactor,
marketcapgrowthfactor,
marketcapvaluefactor,
dailypriceperformance,
dailytotalperformance,
dailynetperformance,
insertiontime,
classificationnareitkey,
classificationnomurakey,
growthshares,
valueshares,
smid,
meena,
eurozone150flag,
euro40,
paneurope60,
top100flag,
top200flag,
r2500,
developedemerging,
europe,
europeexuk,
frontier,
g123,
gccflag,
gicsindustry,
methodologycode,
createdate,
createuserid,
modifieduser,
modifieddate,
reissueflag,
productcode,versionnumber)
SELECT feedid,
filename,
asofdate,
returntypeid,
currencyid,
securityid,
indexid,
indexname,
securitycode,
sizemarkercode,
icbclassificationkey,
rgsclassificationkey,
securitycountry,
securitycurrency,
pricecurrency,
sizemarkerkey,
startmarketcap,
closemarketcap,
marketcapbeforeinvestability,
marketcapafterinvestability,
adjustmentfactor,
marketcapafteradjustmentfactor,
grossmarketcap,
netmarketcap,
xddividendmarketcap,
xddividendnetmarketcap,
openprice,
closeprice,
shares,
sharechg,
investabilityweight,
dividendyield,
pctindexweight,
growthfactor,
valuefactor,
marketcapgrowthfactor,
marketcapvaluefactor,
dailypriceperformance,
dailytotalperformance,
dailynetperformance,
insertiontime,
classificationnareitkey,
classificationnomurakey,
growthshares,
valueshares,
smid,
meena,
eurozone150flag,
euro40,
paneurope60,
top100flag,
top200flag,
r2500,
developedemerging,
europe,
europeexuk,
frontier,
g123,
gccflag,
gicsindustry,
methodologycode,
createdate,
createuserid,
modifieduser,
modifieddate,
reissueflag,
productcode
,maxversionnumber as versionnumber
FROM fct.holdingsclose
WHERE feedid =" + feedId + " ;" +
"DELETE FROM fct.holdingsclose WHERE feedid =" + feedId + " ;" + "END $$;";

Select statement should return only one record

I want to fetch and print only one record from database mysql.
#Select backlogs
{
my $backlog_req = "select id, name, startDate, endDate, parent_id " .
" from backlogs " ;
"where backlogtype='Iteration' and id = $iteration" ;
print "ITERATION_ID : " . $iteration . "\n";
my $sth = $dbh->prepare( $backlog_req );
$sth->execute() ;
$sth->bind_columns( undef, \$backlog_id, \$bl_name, \$bl_sd, \$bl_ed, \$prod_id ) ;
while( $sth->fetch() ) {
$Backlogs->{ $backlog_id } = { name => $bl_name, start_date => substr($bl_sd, 0, 10), end_date => substr($bl_ed, 0, 10) } ;
print "$bl_name ($backlog_id): $bl_sd -> $bl_ed\n";
}
this returns all the rows with Iteration as backlogtype. I want only backlogtype as Iteration and Id which i am providing through command line argument. as i specified in where.
Change this:
" from backlogs " ;
to this:
" from backlogs " .
to include the WHERE-clause in your query.
Also, you should add use warnings; to the start of your script. It would have warned you about this (by complaining that your WHERE-clause-only statement was a Useless use of string in void context).

Unknown issue with insert statment

I have a sub form with staff records on it within a main form. I am trying to allow the user to select a record from the sub form and add it to a table, here is my code which, to me, looks correct. However it gives me an error saying "Syntax error in INSERT INTO"
Private Sub Command3_Click()
Dim dbs As Database
Dim sqlstr As String
Set dbs = CurrentDb
Forename = Nz(Forms!frm_Capex_Submission!frm_staffSub.Form.shy_forename, "")
Surname = Nz(Forms!frm_Capex_Submission!frm_staffSub.Form.shy_surname, "")
emp_no = Nz(Forms!frm_Capex_Submission!frm_staffSub.Form.shy_empno, "")
CAP_ID = Forms!frm_Capex_Submission!CAP_ID
sqlstr = "INSERT INTO tbl_CapexStaff ( Forename, Surname, EmployeeID, CAP_ID) )" _
& " SELECT '" & Nz(Me!shy_forename, "") & "' AS Expr1, '" & Nz(Me!shy_surname, "") & "' AS Expr2, '" & Nz(Me!shy_empno, "") & " AS Expr3, " & Forms!frm_Capex_Submission.CAP_ID & " as expr4, """
dbs.Execute (sqlstr)
tbl_CapexStaff.Requery
End Sub
There is an extra ")" in your query
INSERT INTO tbl_CapexStaff ( Forename, Surname, EmployeeID, CAP_ID) )

Using IndexOf and/Or Substring to parse data into separate columns

I am working on migrating data from one database to another for a hospital. In the old database, the doctor's specialty IDs are all in one column (swvar_specialties), each separated by commas. In the new database, each specialty ID will have it's own column (example: Specialty1_PrimaryID, Specialty2_PrimaryID, Specialty3_PrimaryID, etc). I am trying to export the data out of the old database and separate these into these separate columns. I know I can use indexof and substring to do this - I just need help with the syntax.
So this query:
Select swvar_specialties as Specialty1_PrimaryID
From PhysDirectory
might return results similar to 39,52,16. I need this query to display Specialty1_PrimaryID = 39, Specialty2_PrimaryID = 52, and Specialty3_PrimaryID = 16 in the results. Below is my query so far. I will eventually have a join to pull the specialty names from the specialties table. I just need to get this worked out first.
Select pd.ref as PrimaryID, pd.swvar_name_first as FirstName, pd.swvar_name_middle as MiddleName,
pd.swvar_name_last as LastName, pd.swvar_name_suffix + ' ' + pd.swvar_name_degree as NameSuffix,
pd.swvar_birthdate as DateOfBirth,pd.swvar_notes as AdditionalInformation, 'images/' + '' + pd.swvar_photo as ImageURL,
pd.swvar_philosophy as PhilosophyOfCare, pd.swvar_gender as Gender, pd.swvar_specialties as Specialty1_PrimaryID, pd.swvar_languages as Language1_Name
From PhysDirectory as pd
The article Split function equivalent in T-SQL? provides some details on how to use a split function to split a comma-delimited string.
By modifying the table-valued function in presented in this article to provide an identity column we can target a specific row such as Specialty1_PrimaryID:
/*
Splits string into parts delimitered with specified character.
*/
CREATE FUNCTION [dbo].[SDF_SplitString]
(
#sString nvarchar(2048),
#cDelimiter nchar(1)
)
RETURNS #tParts TABLE (id bigint IDENTITY, part nvarchar(2048) )
AS
BEGIN
if #sString is null return
declare #iStart int,
#iPos int
if substring( #sString, 1, 1 ) = #cDelimiter
begin
set #iStart = 2
insert into #tParts
values( null )
end
else
set #iStart = 1
while 1=1
begin
set #iPos = charindex( #cDelimiter, #sString, #iStart )
if #iPos = 0
set #iPos = len( #sString )+1
if #iPos - #iStart > 0
insert into #tParts
values ( substring( #sString, #iStart, #iPos-#iStart ))
else
insert into #tParts
values( null )
set #iStart = #iPos+1
if #iStart > len( #sString )
break
end
RETURN
END
Your query can the utilise this split function as follows:
Select
pd.ref as PrimaryID,
pd.swvar_name_first as FirstName,
pd.swvar_name_middle as MiddleName,
pd.swvar_name_last as LastName,
pd.swvar_name_suffix + ' ' + pd.swvar_name_degree as LastName,
pd.swvar_birthdate as DateOfBirth,pd.swvar_notes as AdditionalInformation,
'images/' + '' + pd.swvar_photo as ImageURL,
pd.swvar_philosophy as PhilosophyOfCare, pd.swvar_gender as Gender,
(Select part from SDF_SplitString(pd.swvar_specialties, ',') where id=1) as Specialty1_PrimaryID,
(Select part from SDF_SplitString(pd.swvar_specialties, ',') where id=2) as Specialty2_PrimaryID,
pd.swvar_languages as Language1_Name
From PhysDirectory as pd