Create table with a variable name - variables

I need to create tables on daily basis with name as date in form at (yyMMdd), I tried this :
dbadmin=> \set table_name 'select to_char(current_date, \'yyMMdd \')'
dbadmin=> :table_name;
to_char
---------
150515
(1 row)
and then tried to create table with table name from the set parameter :table_name, but got this
dbadmin=> create table :table_name(col1 varchar(1));
ERROR 4856: Syntax error at or near "select" at character 14
LINE 1: create table select to_char(current_date, 'yyMMdd ')(col1 va...
Is there a way where i could store a value in a variable and then use that variable as table name or to assign priority that the inner select statement has execute first to give me the name i require.
Please suggest!!!

Try this
for what ever reason the variable stored comes with some space and i had to remove it and also cannot start naming table starting with numbers so i had to add something in form like tbl_
in short you just need to store the value of the exit so you need to do some extra work and execute the query.
\set table_name `vsql -U dbadmin -w d -t -c "select concat('tbl_',replace(to_char(current_date, 'yyMMdd'),' ',''))"`
Create table:
create table :table_name(col1 varchar(1));
(dbadmin#:5433) [dbadmin] *> \d tbl_150515
Schema | public
Table | tbl_150515
Column | col1
Type | varchar(1)
Size | 1
Default |
Not Null | f
Primary Key | f
Foreign Key |

Related

SQL Error [XX000]: ERROR: Already present: The column already exists - Yugabyte DB

SQL Alter script:
alter table table_name ADD COLUMN IF NOT EXISTS chk_col jsonb not null
DEFAULT '{}'::jsonb;
In this script, I am getting "ERROR: Already present: The column already exists" but the column chk_col is not present in the table.
If I remove DB and then create again the same script is executed successfully.
How do I correct it without removing the database?
Can you explain more your setup ?
What version are you using ?
Are there needed other steps to reproduce ?
I can't reproduce in 2.7.1.1:
yugabyte=# create database fshije
yugabyte=# \c fshije
fshije=# create table table_name(id bigint);
fshije=# alter table table_name ADD COLUMN IF NOT EXISTS chk_col jsonb not null DEFAULT '{}'::jsonb;
fshije=# \d table_name
Table "public.table_name"
Column | Type | Collation | Nullable | Default
---------+--------+-----------+----------+-------------
id | bigint | | |
chk_col | jsonb | | not null | '{}'::jsonb

How to separate SQL variable inside a string

In my SQL script I can define variable like:
DEFINE x=100;
and use it like:
CREATE TABLE A&x AS ...;
the result will be CREATE TABLE A100 AS ... (concatenated string).
But I'd like to get CREATE TABLE A100B AS ... in similar query (B suffix):
CREATE TABLE A&xB AS ...;
But Oracle/SQL understands there is xB variable
How to separate variable (name) inside SQL:
CREATE TABLE A&{x}B AS ...;
This does not work!
(e.g. like ${x} i PHP)
It is just a tiny, little dot.
SQL> define x=100
SQL> create table a&x.b as select * from dual;
old 1: create table a&x.b as select * from dual
new 1: create table a100b as select * from dual
Table created.
SQL> select * from a100b;
D
-
X
SQL>
Here, in case you missed it:
create table a&x.b
^
|
here
What's the point? The SQLPlus concatenation character. By default, it is a dot. It tells SQLPlus where the variable name ends.
If you ask for more help:
SQL> help set
SET
---
Sets a system variable to alter the SQL*Plus environment settings
for your current session. For example, to:
- set the display width for data
- customize HTML formatting
- enable or disable printing of column headings
- set the number of lines per page
SET system_variable value
where system_variable and value represent one of the following clauses:
APPI[NFO]{OFF|ON|text} NEWP[AGE] {1|n|NONE}
ARRAY[SIZE] {15|n} NULL text
AUTO[COMMIT] {OFF|ON|IMM[EDIATE]|n} NUMF[ORMAT] format
<snip>
---------------------
CON[CAT] {.|c|ON|OFF} [FOR[MAT] {WRA[PPED] |
---------------------
Here it is!

Postgres - How to cast an array of enum_1 to enum_2?

I'm trying to modify the values of an enum in my schema ("feature" in the below example).
I'm trying to do this by renaming the old enum and introducing a new one that has the values I want, and then altering the table definition to the new enum.
I'm following this blog post here: https://blog.yo1.dog/updating-enum-values-in-postgresql-the-safe-and-easy-way/.
But instead of the column being a simple column of the enum, my column is actually an array of the enum.
When I try to run the alter table statement in the below statements, I get the error:
[42804] ERROR: column "features" is of type feature_old[] but expression is of type feature_v2[] Hint: You will need to rewrite or cast the expression.
alter type feature rename to feature_old;
create type feature_v2 as enum (
'enable_create_keyword',
'enable_make_payment',
'enable_test_data_flags'
);
-- ... cleanup of column array values to be compatible with new enum ...
alter table app_user alter column features type feature_v2
using features::feature_old[]::feature_v2[];
drop type feature_old;
But, I'm lost - what should the cast expression look like?
Postgres version is 9.6
EDIT
This is the relevant part of the previous version's schema DDL for the feature enum and app_user table that was requested by #VaoTsun.
-- feature enum and column
create type feature as enum ('enable_create_keyword', 'enable_make_payment');
comment on type feature is
'if default functionality is disabled feature name starts with enable_, if default is enabled starts with disable_'
;
alter table app_user add column
features feature[] not null default ARRAY[]::feature[];
-- feature data
update app_user
set features = ARRAY['enable_create_keyword', 'enable_make_payment']::feature[]
where email = 'test1#example.com';
update app_user
set features = ARRAY['enable_create_keyword']::feature[]
where email = 'test2#example.com';
Thanks to both Vao Tsun and Nick Barnes; this is the code that appears to work for me. I have marked Vao Tsun's answer as correct. Any answers that provide a more concise version would be gratefully upvoted.
alter type feature rename to feature_old;
create type feature_v2 as enum (
'enable_create_keyword',
'enable_make_payment',
'enable_test_data_flags'
);
alter table app_user alter column features drop default ;
alter table app_user alter column features type feature_v2[]
using features::feature_old[]::text[]::feature_v2[];
alter table app_user alter column features set default ARRAY[]::feature_v2[];
drop type feature_old;
with assumption that old enum has same values, but less, you should be able to simply cast it's value to text and then to a v2:
try this:
t=# create or replace function feature2v2(feature_old) returns feature_v2 as
$$
select $1::text::feature_v2;
$$
language sql strict;
CREATE FUNCTION
t=# create cast (feature_old AS feature_v2) WITH FUNCTION feature2v2(feature_old) AS ASSIGNMENT;
CREATE CAST
gives me:
t=# alter table app_user alter column features type feature_v2[]
using features::feature_v2[];
ALTER TABLE
t=# \d+ app_user
Table "postgres.app_user"
Column | Type | Collation | Nullable | Default | Storage | Stats target | Description
----------+--------------+-----------+----------+------------------------+----------+--------------+-------------
email | text | | | | extended | |
features | feature_v2[] | | not null | ARRAY[]::feature_old[] | extended | |
t=# \dT+ feature_v2
List of data types
Schema | Name | Internal name | Size | Elements | Owner | Access privileges | Description
----------+------------+---------------+------+------------------------+----------+-------------------+-------------
postgres | feature_v2 | feature_v2 | 4 | enable_create_keyword +| postgres | |
| | | | enable_make_payment +| | |
| | | | enable_test_data_flags | | |
(1 row)
which looks like what you expect
UPDATE
catching up with Nick Barnes comments - creating a cast here is overhead and leaves bad defualt for column, the right approach her is:
alter table app_user alter column features drop default;
alter table app_user alter column features type feature_v2[] using features::feature_old[]::text[]::feature_v2[];
alter table app_user alter column features set default ARRAY[]::feature_v2[];
Leaving the previous version untouched to demonstrate the bad approach with hints how it is bad

How can I create an external table using textfile with presto?

I've a csv file in hdfs directory /user/bzhang/filefortable:
123,1
And I use the following to create an external table with presto in hive:
create table hive.testschema.au1 (count bigint, matched bigint) with (format='TEXTFILE', external_location='hdfs://192.168.0.115:9000/user/bzhang/filefortable');
But when I run select * from au1, I got
presto:testschema> select * from au1;
count | matched
-------+---------
NULL | NULL
I changed the comma to the TAB as the delimeter but it still returns NULL. But If I modify the csv as
123
with only 1 column, the select * from au1 gives me:
presto:testschema> select * from au1;
count | matched
-------+---------
123 | NULL
So maybe I'm wrong with the file format or anything else?
I suppose the field delimiter of the table is '\u0001'.
You can change the ',' to '\u0001' or change the field delimiter to ',' , and check your problem was solved

Postgres function upper doesn't work for cyrillic (version 9.4)

This question is similar to Postgres doesn't search case-insensitive unicode regex
But it appears that upper function doesn't work as well?
Also, it seems that encoding on server utf8
I use webfaction private postgres instance on CentOS 6 and don't know how to set locale on cluster creation.
Please, help, how to fix it.
Change collation, like:
b=# select upper('утф' COLLATE "C"), upper('утф' COLLATE "en_US");
upper | upper
-------+-------
утф | УТФ
(1 row)
Changing default like:
b=# create table clt (a text COLLATE "C");
CREATE TABLE
b=# insert into clt select 'утф';
INSERT 0 1
b=# select upper(a) from clt;
upper
-------
утф
(1 row)
b=# alter table clt alter column a set data type text COLLATE "en_US";
ALTER TABLE
b=# select upper(a) from clt;
upper
-------
УТФ
(1 row)
Alternatively you can dump your data and restore it to db with right locale. On restore tables will be built with right collation:
b=# CREATE DATABASE not_c ENCODING 'UTF8'
lc_ctype='en_US.utf-8'
lc_collate='en_US.UTF-8' TEMPLATE=template0;
CREATE DATABASE
b=# \c not_c
You are now connected to database "not_c" as user "postgres".
not_c=# create table clt (a text);
CREATE TABLE
not_c=# insert into clt select 'утф';
INSERT 0 1
not_c=# select upper(a) from clt;
upper
-------
УТФ
(1 row)