#rest #vert.x
#rest #vert.x
Вопрос:
это мой postgresql CTE. Хорошо работает с различными примерами.
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)
Обратите внимание на значения перекрестных соединений: 5 столбцов с «n» вхождениями…конечно, это массив.
Теперь, на стороне сервера (бизнес):
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)";
Посмотрите на параметр $23::text[] …Мне нужно ввести подготовленный запрос (после «venta.getEstado()») и в API … и я не знаю, как
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
Ответ №1:
Вы хотите создать виртуальную таблицу из одной строки.
Это действительно возможно с помощью Postres.
Вы можете указать свою строку в синтаксисе массива, используя {}
, а затем использовать unnest для разделения каждой строки на отдельную строку.
Затем вы используете string_to_array
для разделения каждой строки на отдельные столбцы.
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
Теперь вы можете заменить свою values ()
часть этим запросом.
Со стороны Vert.x вам нужно будет создать именно эту строку и связать ее.
Комментарии:
1. Привет @Alexey Soshin … CTE из postgres требуют параметров в правильном положении. Невозможно объединить все параметры в одном перекрестном соединении… в любом случае спасибо!
2. Это возможно, но я изначально не понял ваш вопрос. Я обновлю свой ответ.