SQLite autoincrement regex - regex

I am taking create statement queries from SQLite like this:
CREATE TABLE [users] ([id] INTEGER PRIMARY KEY AUTOINCREMENT, [username] VARCHAR, [password] VARCHAR, [default_project] VARCHAR)
created by using
SELECT sql FROM sqlite_master WHERE type = 'table' AND name = :table
and determining the autoincrement field with a regular expression like this:
/\b\[?id\]?\s+INTEGER\s+PRIMARY\s+KEY\s+AUTOINCREMENT\b/Ui
the problem is that there are different acceptable ways to write keywords such as "id", `id`, 'id'. Shown here http://www.sqlite.org/lang_keywords.html
I wanted to create a regular expression that would explicitly check for these different variations...with some help of others I have gotten to this:
$pattern = "/\b\"(id)|(\"id\")|(\[id\])|(`id`)|('id')\"\s+INTEGER\s+PRIMARY\s+KEY\s+AUTOINCREMENT\b/Ui";
however there are a couple problems with this...one being that the INTEGER PRIMARY KEY AUTOINCREMENT is no longer checked for...and that ('id') isn't being matched properly...however if I were to swap its place with the ("id")...than it would work and ("id") wouldn't.

/(\"id\"|\[id\]|\'id\'|`id`|\\bid)\s+INTEGER\s+PRIMARY\s+KEY\s+AUTOINCREMENT/Ui
seems to work as intended.

[id] doesn't match [id] but only i and d, what you're searching for is probably:
$pattern = "/\s(\"[a-z]+\"|\[[a-z]+\]|'[a-z]+'|[a-z]+)\s+INTEGER\s+PRIMARY\s+KEY\s+AUTOINCREMENT/Ui";
using [a-z]+ so that you can match any alphabetic field name and then find it in the first match (also notice that there can be rowids that don't use the AUTOINCREMENT keyword: they're both valid but with a slightly different meaning).

Related

REGEX: get Create table queries in sql dump

I have an sql dump of different tables each with different amount of fields, I want to insert a query after each one, so I'm trying to find a regex statment that would retreive:
CREATE TABLE cms_audit (
aud_id bigint NOT NULL IDENTITY(1,1),
user_id int DEFAULT NULL,
client_id int NOT NULL,
aud_event varchar(500) NOT NULL,
aud_type varchar(150) NOT NULL,
aud_string varchar(1000) DEFAULT NULL,
aud_date datetime DEFAULT NULL
)
-- --------------------------------------------------------
My regex is CREATE TABLE .*-- (in notepad++ I've checked the box that say's . matches newline) in my head this means get all that starts with "create table" and whatever is after it until you reach "--".
However this statement is retrieving the entire file instead of getting each "create table" query separately, what am I missing?.
I have also tried CREATE TABLE (.*|\n)*--.. didn't work.
You need to use a regex with any character except --. To achieve this you can do:
CREATE TABLE (?:(?!--).)*
EDIT
The ?! is to make a Negative Lookahead of the string --. Nothing with this string will match this expression.
You can see and test it with this link (it's very well explained and a good tool):
https://regex101.com/r/mR9fD4/1

db2 cannot drop foreign key with lowercase name

I am trying to drop a foreign key in DB2 through the command line. I have succeeded in this many times and I am sure that I am using the correct syntax:
db2 "alter table TABLENAME drop constraint fk_keyname"
Output:
DB21034E The command was processed as an SQL statement because it was not a
valid Command Line Processor command. During SQL processing it returned:
SQL0204N "FK_KEYNAME" is an undefined name. SQLSTATE=42704
All my foreign keys are created with an uppercase name. Except for the key I now want to drop. I don't know how to got created with a lowercase name but it seems that it will not drop keys that are lowercase.
When I try to add this foreign key (while it still exists) I get the following message:
DB21034E The command was processed as an SQL statement because it was not a
valid Command Line Processor command. During SQL processing it returned:
SQL0601N The name of the object to be created is identical to the existing
name "fk_keyname" of type "FOREIGN KEY". SQLSTATE=42710
Does anyone know how to drop foreign keys that have a lowercase name?
The answer by mustaccio worked. Tried all kinds of quotes but this way did the trick:
db2 'alter table TABLENAME drop constraint "fk_keyname"'
DB2 will convert object names to uppercase, unless they are quoted. Generally it's not a very good idea to create objects with lower- or mixed-case names. If your foreign key is actually "fk_keyname" (all lowercase), run db2 "alter table TABLENAME drop constraint \"fk_keyname\"" or db2 'alter table TABLENAME drop constraint "fk_keyname"'
This behaviour is not unique to DB2, by the way.

RegEx in the select for DB2

I have a table with one column having a large json object in the format below. The column datatype is VARCHAR
column1
--------
{"key":"value",....}
I'm interested in the first value of the column data
in regex I can do it by .*?:(.*),.* with group(1) giving me the value
How can i use it in the select query
Don't do that, it's bad database design. Shred the keys and values to their own table as columns, or use the XML data type. XML would work fine because you can index the structure well, and you can use XPATH queries on the data. XPATH supports regexp natively.
You can use regular expression with xQuery, you just need to call the function matches from a SQL query or a FLORW query.
This is an example of how to use regular expressions from SQL:
db2 "with val as (
select t.text
from texts t
where xmlcast(xmlquery('fn:matches(\$TEXT,''^[A-Za-z 0-9]*$'')') as integer) = 0
)
select * from val"
For more information:
http://pic.dhe.ibm.com/infocenter/db2luw/v10r5/topic/com.ibm.db2.luw.xml.doc/doc/xqrfnmat.html
http://angocadb2.blogspot.fr/2014/04/regular-expressions-in-db2.html
DB2 doesn't have any built in regex functionality, unfortunately. I did find an article about how to add this with libraries:
http://www.ibm.com/developerworks/data/library/techarticle/0301stolze/0301stolze.html
Without regexes, this operation would be a mess. You could make a function that goes through the string character by character to find the first value. Or, if you will need to do more than this one operation, you could make a procedure that parses the json and throws it into a table of keys/values. Neither one sounds fun, though.
In DB2 for z/OS you will have to pass the variable to XMLQUERY with the PASSING option
db2 "with val as (
select t.text
from texts t
where xmlcast(xmlquery('fn:matches($TEXT,''^[A-Za-z 0-9]*$'')'
PASSING t.text as "TEXT") as integer) = 0
)
select * from val"

how to extract column parameters from sqlite create string?

in sqlite it is possible to have string by which the table was created:
select sql from sqlite_master where type='table' and tbl_name='MyTable'
this could give:
CREATE TABLE "MyTable" (`id` PRIMARY KEY NOT NULL, [col1] NOT NULL,
"another_col" UNIQUE, '`and`,''another'',"one"' INTEGER, and_so_on);
Now I need to extract with this string any additional parameters that given column name has been set with.
But this is very difficult since the column name could be enclosed with special characters, or put plain, column name may have some special characters that are used as encapsulation etc.
I don't know how to approach it. The result should be having a column name the function should return anything that is after this name and before , so giving it id it should return PRIMARY KEY NOT NULL.
Use the pragma table_info:
http://www.sqlite.org/pragma.html#pragma_table_info
sqlite> pragma table_info(MyTable);
cid|name|type|notnull|dflt_value|pk
0|id||1||1
1|col1||1||0
2|another_col||0||0
3|`and`,'another',"one"|INTEGER|0||0
4|and_so_on||0||0

Wildcard search on Date fields

I use HSQLDB2.0 and JPA2.0 for my current project and have few date columns in DB.
I would like to run wildcard queries on the date columns. How could I do that?
Ex : If my DB contains two rows with date values as : 10-01-2011 and 15-02-2011
and my search criteria will be "%10-01%", then result should be 10-01-2011.
Else if search criteria is "%2011%" then both rows need to be fetched with the select query.
Thanks in advance,
Satya
You can define an autogenerated column of type VARCHAR containing a copy of the date. You can then perform queries with both LIKE predicates and REGEXP_MATCHES() function. An example of the column definition is below:
DATEGEN VARCHAR(10) GENERATED ALWAYS AS (CAST(DATECOL AS VARCHAR(10))
Note the string representation of DATE is in the form '2011-02-26' and your query strings should follow this pattern.
This can be achieved in this format :
select date_birth from member where to_char(date_birth,'MM-yyyy') like '%02-2011%'
select date_birth from member where to_char(date_birth,'MM-dd') like '%02-15%'
select date_birth from member where to_char(date_birth,'dd-yyyy') like '%30-2011%'
Regards,
Satya