Add a trigger on select - sql

Is it possible to create a select trigger? I know there are update insert or delete triggers. But select trigger is what I need for a little url shortener application. Everytime a shorturl is hit I'd like to update counter and last access date. A select trigger would be perfect.
select url where code = :code
whould be the one to trigger the trigger.

Ended up doing this:
create function `get_the_url`(c char(7))
returns varchar(255)
begin
declare result varchar(255);
update code
set
hits = hits + 1,
last_used=current_timestamp()
where code = c;
return (
select url
from code
where code = c
);
end
saving this for prosperity and me.
for this table:
create table `code` (
`code` char(5) not null,
`url` varchar(240) default null,
`last_used` datetime not null default '0000-00-00 00:00:00',
`hits` int(10) unsigned not null default 0,
primary key (`code`) using hash,
key `url` (`url`) using hash
) engine=myisam
For those few php folks interested, this is how I populated the table:
<?php
declare(strict_types=1);
$charset ="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNAOPQRSTUVWXYZ1234567890-_.!~*'()";
$size = 8;
function getCode(): string {
global $size;
global $charset;
$length = strlen($charset)-1;
$result =
$charset[rand(0,$length)]
.$charset[rand(0,$length)]
.$charset[rand(0,$length)]
.$charset[rand(0,$length)]
.$charset[rand(0,$length)];
return $result;
}
$db = new \PDO("mysql:dbname=qr","qr","qr");
$insert = $db-> prepare("insert into code(code,url,last_used,hits)values(:code,null,default,default)");
$code = getCode();
$insert->bindParam(':code',$code);
for($i=1000; $i>0; $i--) {
$code = getCode();
$insert-> execute() or die($insert->errorInfo()[2]);
}
and yes, populating this upfront probably makes sense as storage space is cheap and computing power is not.

Related

How do I retrieve scope identity with ExecuteNonQuery?

My project is using .NET Core 3.1 and I have my stored procedures executing in my repository class. I want to insert and return the scope identity(the id of the record that just inserted UserNumber) so I can use it for another stored proc within this same method. The problem I have here is that parameters[1].Value value is returning zero.
Here is an abbreviation of my stored proc:
ALTER PROCEDURE [dbo].[InsertUser]
#iUserNumber int OUTPUT,
As
INSERT dbo.tblUser (
CreatedBy
)
VALUES (#LoginUserId)
IF ##ERROR <> 0 GOTO ERRHANDLER
SET #UserNumber = SCOPE_IDENTITY() /** this is the primary Key **/
RETURN(#UserNumber)
Here is a sample of my repository
public int InsertUsers(int LoginUserId, int UserNumber)
{
SqlParameter[] parameters = new List<SqlParameter>()
{
_dbContext.CreateSqlParameter(StoredProcedureConstants.LoginUserId,SqlDbType.Int,LoginUserId.ToSafeInt()),
_dbContext.CreateSqlParameter(StoredProcedureConstants.UserNumber,SqlDbType.Int,UserNumber.ToSafeInt())
}.ToArray();
var intResult = _dbContext.ExecuteNonQuery(StoredProcedureConstants.InsertUsers, parameters);
var result2 = parameters[1].Value; //This comes back as zero
How do I assign the scope identity to result2?
Should be something like:
CREATE OR ALTER PROCEDURE [dbo].[InsertUser]
#LoginUserId int,
#iUserNumber int OUTPUT
As
INSERT dbo.tblUser (CreatedBy)
VALUES (#LoginUserId)
SET #iUserNumber = SCOPE_IDENTITY() /** this is the primary Key **/
and
SqlParameter[] parameters = new List<SqlParameter>()
{
_dbContext.CreateSqlParameter("#LoginuserId",SqlDbType.Int,LoginUserId),
_dbContext.CreateSqlParameter("#iUserNumber",SqlDbType.Int)
}.ToArray();
parameters[1].Direction = ParameterDirection.Output;
_dbContext.ExecuteNonQuery(StoredProcedureConstants.InsertUsers, parameters);
var result2 = parameters[1].Value;

How to pass a param for a binding in PostgreSQL - COPY (... ) TO STDOUT (FORMAT binary)?

I have some simple test table in postgres like below:
--DROP TABLE test_point
CREATE TABLE test_point
(
serie_id INT NOT NULL,
version_ts INT NOT NULL,
PRIMARY KEY (serie_id, version_ts)
);
I try to load a data from it by using COPY TO STDOUT and binary buffers. This is sql definition I use in a test case:
COPY (
SELECT version_ts
FROM test_point
WHERE
serie_id = $1::int
) TO STDOUT (FORMAT binary);
It works ok, if I don't provide any param to bind to in SQL. If I use simple select it recognizes params also as well.
I was trying to provide explicit info about param type during stmt preparation also, but results were similar (it doesn't recognize param).
This is a message I receive during the test case:
0x000001740a288ab0 "ERROR: bind message supplies 1 parameters, but prepared statement \"test1\" requires 0\n"
How to properly provide a param for COPY() statement?
I don't want to cut/concatenate strings for timestamp params and similar types.
Below is a test case showing the issue.
TEST(TSStorage, CopyParamTest)
{
auto sql = R"(
COPY (
SELECT version_ts
FROM test_point
WHERE
serie_id = $1::int
) TO STDOUT (FORMAT binary);
)";
auto connPtr = PQconnectdb("postgresql://postgres:pswd#localhost/some_db");
auto result = PQprepare(connPtr, "test1", sql, 0, nullptr);
// Lambda to test result status
auto testRes = [&](ExecStatusType status)
{
if (PQresultStatus(result) != status)
{
PQclear(result);
auto errorMsg = PQerrorMessage(connPtr);
PQfinish(connPtr);
throw std::runtime_error(errorMsg);
}
};
testRes(PGRES_COMMAND_OK);
PQclear(result);
int seriesIdParam = htonl(5);
const char *paramValues[] = {(const char *)&seriesIdParam};
const int paramLengths[] = {sizeof(seriesIdParam)};
const int paramFormats[] = {1}; // 1 means binary
// Execute prepared statement
result = PQexecPrepared(connPtr,
"test1",
1, //nParams,
paramValues,
paramLengths,
paramFormats,
1); // Output format - binary
// Ensure it's in COPY_OUT state
//testRes(PGRES_COPY_OUT);
if (PQresultStatus(result) != PGRES_COPY_OUT)
{
auto errorMsg = PQerrorMessage(connPtr);
int set_breakpoint_here = 0; // !!! !!! !!!
}
PQclear(result);
PQfinish(connPtr);
}

POST method in RESTfull problem with the sql or with the Statement to generate id?

GET, PUT and DELETE work, but trying to do the POST method it doesn't work. In my data base, 'usuario' has an id, a name and age (edad).
#POST
#Consumes({MediaType.APPLICATION_XML,MediaType.APPLICATION_JSON})
public Response crearUsuario(Usuario usuario) {
try {
String sql = "INSERT INTO `RedLibros`.`usuario`(`nombre`,`edad`) " + "VALUES('"
+ usuario.getnombre() + "', '" + usuario.getedad() + "');";
PreparedStatement ps = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
int affectedRows = ps.executeUpdate();
ResultSet generatedID = ps.getGeneratedKeys();
if (generatedID.next()) {
usuario.setidusuario(generatedID.getInt(1));
String location = uriInfo.getAbsolutePath() + "/" + usuario.getidusuario();
return Response.status(Response.Status.CREATED).entity(usuario).header("Location", location).header("Content-Location", location).build();
}
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity("No se pudo crear el usuario").build();
} catch (SQLException e) {
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity("No se pudo crear el usuario\n" + e.getStackTrace()).build();
}
}
I'm using Postman and the body of my input is:
</usuario idusuario="1">
<edad>43</edad>
<nombre>George</nombre>
</usuario>
The error is: Ljava.lang.StackTraceElement;#1aeb297
And this is the script of my db, im not sure if its because the character set, im using UTF-8.
-- MySQL Script generated by MySQL Workbench
-- lun 19 abr 2021 14:13:50 CEST
-- Model: New Model Version: 1.0
SET #OLD_UNIQUE_CHECKS=##UNIQUE_CHECKS, UNIQUE_CHECKS=0;
SET #OLD_FOREIGN_KEY_CHECKS=##FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0;
SET #OLD_SQL_MODE=##SQL_MODE, SQL_MODE='TRADITIONAL,ALLOW_INVALID_DATES';
-- -----------------------------------------------------
-- Schema RedLibros
-- -----------------------------------------------------
CREATE SCHEMA IF NOT EXISTS `RedLibros` DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci ;
USE `RedLibros` ;
-- -----------------------------------------------------
-- Table `RedLibros`.`usuario`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `RedLibros`.`usuario` (
`idusuario` INT NOT NULL,
`nombre` VARCHAR(45) NULL,
`edad` VARCHAR(45) NULL,
PRIMARY KEY (`idusuario`))
ENGINE = InnoDB;
I think you are not passing idusuario from POST call. If you expect this to be auto increment, then you need to define the table accordingly. You should use auto_increment syntax like below -
CREATE TABLE IF NOT EXISTS RedLibros.usuario ( idusuario INT NOT NULL AUTO_INCREMENT, nombre VARCHAR(45) NULL, edad VARCHAR(45) NULL, PRIMARY KEY (idusuario));

Can Snowflake DB UDF's execute SQL commands?

I have a requirement in Snowflake where I must generate a bit of SQL and then execute it to create a new table.
I have successfully generated the create table statement by creating a UDF (hard-coded at the moment)
CREATE OR REPLACE FUNCTION COOL_CARGO.test()
RETURNS STRING
AS
$$
SELECT substr(regexp_replace(GET_DDL('TABLE', 'COOL_CARGO.DIM_BRANCH'),('DIM_BRANCH'),'COOL_CARGO.DIM_BRANCH_ERR'), 0, LENGTH(regexp_replace(GET_DDL('TABLE', 'COOL_CARGO.DIM_BRANCH'),('DIM_BRANCH'),'COOL_CARGO.DIM_BRANCH_ERR')) -2)||','||' etl_err_date timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
etl_id_run int DEFAULT NULL,
etl_err_noe int DEFAULT NULL,
etl_err_desc varchar(512) DEFAULT NULL,
etl_err_col varchar(256) DEFAULT NULL,
etl_err_cod varchar(256) DEFAULT NULL'||');'
$$
;
This outputs the following
create or replace TABLE COOL_CARGO.DIM_BRANCH_ERR (
TK_BRANCH NUMBER(38,0),
GB_BRANCH_CODE VARCHAR(256),
GB_BRANCH_NAME VARCHAR(256),
GB_BRANCH_CITY VARCHAR(256),
GB_BRANCH_STATE VARCHAR(256),
BG_BRANCH_HOME_PORT VARCHAR(256),
BG_BRANCH_COUNTRY_CODE VARCHAR(256),
BG_BRANCH_COUNTRY_NAME VARCHAR(256)
, etl_err_date timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
etl_id_run int DEFAULT NULL,
etl_err_noe int DEFAULT NULL,
etl_err_desc varchar(512) DEFAULT NULL,
etl_err_col varchar(256) DEFAULT NULL,
etl_err_cod varchar(256) DEFAULT NULL);
I now need to create a UDF that will execute this create table statement but as it only seems to return things like strings, I cannot get it to execute by calling it from another function for example.
CREATE OR REPLACE FUNCTION COOL_CARGO.run_test()
RETURNS string
AS
$$
COOL_CARGO.test()
$$
;
Then I try and run the function to create the table with
select COOL_CARGO.run_test();
I do not know if what I want can be done and I would be pretty annoyed if its not possible...
Can this be done in Snowflake DB?
You can achieve this with Snowflake's new Stored Procedures feature that launched in 2019. It allows you to build an arbitrary SQL string and perform an execution in either SQL or JavaScript.
Your existing method can easily be adapted into a stored procedure (example below is illustrative and hasn't been specifically tested):
create or replace procedure test()
returns null
language javascript
as
$$
var orig_ddl_qry = "SELECT GET_DDL('TABLE', 'COOL_CARGO.DIM_BRANCH')";
var get_ddl_stmt = snowflake.createStatement(
{
sqlText: orig_ddl_qry
}
);
var get_ddl_res = get_ddl_stmt.execute();
get_ddl_res.next();
var orig_ddl_str = res.getColumnValue(1);
var replaced_ddl_open = orig_ddl_str.replace("DIM_BRANCH", "COOL_CARGO.DIM_BRANCH_ERR").slice(0, -1);
var new_ddl = replaced_ddl_open + ", etl_err_date timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, etl_id_run int DEFAULT NULL, etl_err_noe int DEFAULT NULL, etl_err_desc varchar(512) DEFAULT NULL, etl_err_col varchar(256) DEFAULT NULL, etl_err_cod varchar(256) DEFAULT NULL);";
var create_stmt = snowflake.createStatement(
{
sqlText: new_ddl
}
);
var create_ddl_res = create_stmt.execute();
$$
;
CALL test();

Return value from MySQL stored procedure

So I've finally decided to get around to learning how to use stored procedures, and although I do have them working, I'm unsure if I'm doing it correctly - aka. the best way. So here's what I've got.
Three procedures: TryAddTag, CheckTagExists, and AddTag.
TryAddTag is the procedure that is my intermediary between other code (eg. PHP, etc...) and the other two procedures, so this is the one that gets called.
TryAddTag
DELIMITER //
CREATE PROCEDURE TryAddTag(
IN tagName VARCHAR(255)
)
BEGIN
-- Check if tag already exists
CALL CheckTagExists(tagName, #doesTagExist);
-- If it does not exist, add it
IF #doesTagExist = FALSE THEN
CALL AddTag(tagName);
END IF;
END //
DELIMITER ;
AddTag
DELIMITER //
CREATE PROCEDURE AddTag(
IN tagName VARCHAR(255)
)
BEGIN
INSERT INTO
tags
VALUES(
NULL,
tagName
);
END //
DELIMITER ;
CheckTagExists
DELIMITER //
CREATE PROCEDURE CheckTagExists(
IN
tagName VARCHAR(255),
OUT
doesTagExist BOOL
)
BEGIN
-- Check if tag exists
SELECT
EXISTS(
SELECT
*
FROM
tags
WHERE
tags.NAME = tagName
)
INTO
doesTagExist;
END //
DELIMITER ;
My problems stem from this and use of #doesTagExist.
-- Check if tag already exists
CALL CheckTagExists(tagName, #doesTagExist);
Is the the correct way to use one of these variables? And/or, how can I use a DECLARE'd variable to store the result of CheckTagExists within TryAddTag? I expected something along the lines of
...
DECLARE doesTagExist BOOL;
SET doesTagExist = CheckTagExist('str');
...
or something like that...
your stored procedure is a little over-engineered for my liking - keep it simple :)
MySQL
drop table if exists tags;
create table tags
(
tag_id int unsigned not null auto_increment primary key,
name varchar(255) unique not null
)
engine=innodb;
drop procedure if exists insert_tag;
delimiter #
create procedure insert_tag
(
in p_name varchar(255)
)
proc_main:begin
declare v_tag_id int unsigned default 0;
if exists (select 1 from tags where name = p_name) then
select -1 as tag_id, 'duplicate name' as msg; -- could use multiple out variables...i prefer this
leave proc_main;
end if;
insert into tags (name) values (p_name);
set v_tag_id = last_insert_id();
-- do stuff with v_tag_id...
-- return success
select v_tag_id as tag_id, 'OK' as msg;
end proc_main #
delimiter ;
PHP
<?php
ob_start();
try{
$conn = new mysqli("localhost", "foo_dbo", "pass", "foo_db", 3306);
$conn->autocommit(FALSE); // start transaction
// create the tag
$name = 'f00';
$sql = sprintf("call insert_tag('%s')", $conn->real_escape_string($name));
$result = $conn->query($sql);
$row = $result->fetch_array();
$result->close();
$conn->next_result();
$tagID = $row["tag_id"]; // new tag_id returned by sproc
if($tagID < 0) throw new exception($row["msg"]);
$conn->commit();
echo sprintf("tag %d created<br/>refresh me...", $tagID);
}
catch(exception $ex){
ob_clean();
//handle errors and rollback
$conn->rollback();
echo sprintf("oops error - %s<br/>", $ex->getMessage());
}
// finally
$conn->close();
ob_end_flush();
?>
Stored PROCEDURES can return a resultset. The last thing you SELECT in a stored procedure is available as a resultset to the calling environment.. Stored FUNCTIONS can return only a single result primitive.
You may also mark your parameters as INOUT parameters.
If you want this:
DECLARE doesTagExist BOOL;
SET doesTagExist = CheckTagExist('str');
then you should use functions:
DELIMITER //
CREATE FUNCTION CheckTagExists(
tagName VARCHAR(255)
)
BEGIN
DECLARE doesTagExist BOOL;
-- Check if tag exists
SELECT
EXISTS(
SELECT
*
FROM
tags
WHERE
tags.NAME = tagName
)
INTO
doesTagExist;
RETURN doesTagExist;
END //
DELIMITER ;
DECLARE doesTagExist BOOL;
SET CheckTagExist('str',doesTagExist);
is the correct way of doing it with just store procedures. There are no 'regular' return values.