Easy way of changing the delimiter in postgreSQL - mysql

I want to know how to do this, because after looking around, all I found are long and complicated ways to do this seemingly easy job.
In MySQL, we had
DELIMITER //
...function start
INSERT INTO table VALUES (1);
...function end//
DELIMITER ;
which was really useful when we wanted to use stored procedures or funtions. I'm looking for the equivalent of this in postgreSQL, if there is one.
Thanks in advance!

The issue with the MySQL DELIMITER plays out quite differently in PostgreSQL. (First of all, most programmers would not use the psql command line to enter a function; instead you'd write a SQL script file and execute that, but this is besides the point of your question.)
In PostgreSQL the function body is basically a long string. That string can be delimited by basically anything that does not conflict with anything else. In the SQL standard - and also in the PostgreSQL documentation - single quotes ' are used, instead of just starting the function body unquoted like in MySQL. So when you write a function header (CREATE FUNCTION ...) you would write a quote to start the function body before you write any semi-colon to terminate statements inside the function. That means that the MySQL problem with the semi-colon does not exist in PostgreSQL: the parser is just reading a string and waiting for that string to be completed with a closing quote and then the command terminated with a semi-colon.
There is more to it, however.
In PostgreSQL the convention is to use $$ or $anything_goes_here$, the so-called dollar quoting, instead of a ' to start the function body. The reason for this is that it avoids having to escape embedded quotes in the function body. See the docs for an explanation of this feature.
The generic function definition looks somewhat like this:
CREATE FUNCTION my_func(arg1 data_type, ...) RETURNS data_type AS $body$
INSERT INTO foo(my_column) VALUES(arg1)
RETURNING some_column;
$body$ LANGUAGE sql;
Note that there are also other programming languages in PostgreSQL - most notably PL/pgSQL, the built-in procedural languages, but also variants of Perl, Python, Tcl, C, ... - and all use the same function definition syntax (as per the SQL standard) including the delimiters, only the function body will differ.
You can use different delimiters for different functions too, but the opening and closing delimiters of a single function need to match.

Related

Inserting a delimiter

MySql has a function CONCAT_WS that I use to export multiple fields with a delimiter into a single field. Works great!
There are multiple fields being stored in a database I query off of that has data that I need to extract each field individually but within each field the data need to include a delimiter. I can most certainly do a concatenate but that does take awhile to set-up if my data requires up to 100 unique values. Below is an example of what I am talking about
Stored Data 01020304050607
End Result 01,02,03,04,05,06,07
Stored Data 01101213
End Result 01,10,12,13
Is there a function in MySQL that does the above?
I am not that familiar with mysql but I have seen questions like this come up before where a regular expression function would be useful. There are user-defined functions available that allow Oracle-like regular expression functions to be used as their support is weak in mysql. See here: https://github.com/hholzgra/mysql-udf-regexp
So you could do something like this:
select trim(TRAILING ',' FROM regexp_replace(your_column, '(.{2})', '\1,') )
from your_table;
This adds a comma every 2 character then chops off the last one. Maybe this will give you some ideas.

how to replace special characters in any query on mysql by function method?

I have a query which does lot of
REPLACE... REPLACE(REPLACE(REPLACE(REPLACE(strip_tags(p.products_description),'\t',''),'\n',''),',',' '),'\r','') ...
Is there any easier way of handling it from mysql itself?
My code does not look good and complicated.
A simpler mysql function would be much better.
This code won't look nice if you do it in MySQL because mysql replace allows to replace only one string and not an array.
You should do such replaces in PHP using str_replace function and you will be able to replace many strings

What's the name and use of "#" operator in MySql?

I am a novice programmer and I'm currently working with functions and stored procedures in MySQL using Workbench 5.6 . I've been searching for some time now here on SO and on the Web for a formal definition of the "#" operator in MySQL and it's proper use, but I wasn't able to find some concrete explanation.
Let's say that I have this :
/*..... Stored Procedure... */
declare i int ;
set #i = 1 ;
select #i ;
/* do some other stuff */
End;
The result of select will be 1 ,instead, if I do:
select i ;
I will get a Null result.
From my intuition so far, I think that is accessing the direction in the memory of a stored variable and prints/modifies its content,still I'm not quite sure.Could you shed some more light?
Are there any other uses of it?
Thanks a priori.
It isn't an operator (I suspect you come from PHP, where it is an operator). It's the syntax for user-defined variables:
User variables are written as #var_name, where the variable name
var_name consists of alphanumeric characters, “.”, “_”, and “$”. A
user variable name can contain other characters if you quote it as a
string or identifier (for example, #'my-var', #"my-var", or
#my-var).
The # denotes a variable, you prefix your variables with the # to prevent confusing them with column names and other schema, it also makes life a lot easier when looking at code. When you enter select I from x;, your looking for column I, which doesn't exist in the table, hence the null.

smart solution of SQL injection

These is one keyword confliction issue in the query module of my application,please see if you can tell me a smart solution.
First,In query module,each query condition contains three parts in UI:
1.field name,its value is fixed,e.g origin,finalDest...
2.operator,it is a select list which includes "like","not like","in","not in","=","!="
3.value,this part is input by user.then in back-end,it will assemble the SQL statement according to UI's query criteria,e.g if user type/select following stuff in UI
Field Name Operator Value
origin like CHI
finalDest in SEL
In back-end,it will generate following SQL:
select * from Booking where origin like '%CHI%' and finalDest in ('SEL').
But there is a bug,e.g if user type some of special symbol in "value",e.g "'","_" etc,it will lead to the generated SQL also contain ' or _ ,e.g:
select * from Booking where origin like '%C_HI%' and finalDest in ('S'EL').
you could see as there is special symbol in "where" block,the SQL can't be executed
For this problem,my solution is add escape character "/" in front of the special symbol before executing it,but what i know is just ' or _ that would conflict with the SQL keywords,do you know if there is any others similar symbol that i need to handle or do you guys have any better idea that can avoid the injection
Sorry,forgot told you what language i am using,i am using java,the DB is mysql,i also use hibernate,there are a lot of people said why i didn't use PreparedStatement,this is a little complex,simply speaking,in my company,we had a FW called dynamic query,we pre-defined the SQL fragment in a XML file,then we will assemble the SQL according to the UI pass in criteria with the jxel expression,as the SQL is kinda of pre-defined stuff,i afraid if change to use PreparedStatement,it will involve a lot of change for our FW,so what we care is just on how to fix the SQL injection issue with a simple way.
The code should begin attempting to stop SQL injection on the server side prior to sending any information to the database. I'm not sure what language you are using, but this is normally accomplished by creating a statement that contains bind variables of some sort. In Java, this is a PreparedStatement, other languages contains similar features.
Using bind variables or parameters in a statement will leverage built in protection against SQL injection, which honestly is going to be better than anything you or I write on the database. If your doing any String concatenation on the server side to form a complete SQL statement, this is an indicator of a SQL injection risk.
0 An ASCII NUL (0x00) character.
' A single quote (“'”) character.
" A double quote (“"”) character.
b A backspace character.
n A newline (linefeed) character.
r A carriage return character.
t A tab character.
Z ASCII 26 (Control+Z). See note following the table.
\ A backslash (“\”) character.
% A “%” character. See note following the table.
_ A “_” character. See note following the table
Reference
Stack Similar Question
You should use bind variables in your SQL statement. As already mentioned this is done with PreparedStatements in Java.
To make sure, only valid column names are used, you can validate the input against the database. MySQL provides schema information like columns of each table as part of the INFORMATION_SCHEMA. For further information, check the MySQL documentation:
"The INFORMATION_SCHEMA COLUMNS Table"

MySQL function to quote identifiers with backticks

Is there a MySQL built-in function that surrounds indentifiers (simple or qualified) with backticks? I.e. such function f would work like:
f('my') would return `my`,
f('my.table') would return `my`.`table`, and
f(`my`) would return `my`
Usually this is a function of your database driver and not your database. The backticks are used by the MySQL statement parser to properly tokenize your statement, so a function that returns values like that would be meaningless since those would be strings and not table or column tokens.
Your database driver may have a function for escaping table names, and if so, use that. Otherwise you'll need to roll your own somehow.
concat('`',replace(your_identifier,'`','``'),'`')