Set default value of an integer column in SQLite - database

I am creating an SQLite database.
db.execSQL("CREATE TABLE " + DATABASE_TABLE + " ("
+ KEY_ROWID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
+ KEY_NAME + " TEXT NOT NULL, "
+ KEY_WORKED + " INTEGER, "
+ KEY_NOTE + " INTEGER);");
Is it possible to set the default value of KEY_NOTE (which is an integer) for every row created to be 0 (zero)? If so, what should be the correct code?

Use the SQLite keyword default
db.execSQL("CREATE TABLE " + DATABASE_TABLE + " ("
+ KEY_ROWID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
+ KEY_NAME + " TEXT NOT NULL, "
+ KEY_WORKED + " INTEGER, "
+ KEY_NOTE + " INTEGER DEFAULT 0);");
This link is useful: http://www.sqlite.org/lang_createtable.html

A column with default value:
CREATE TABLE <TableName>(
...
<ColumnName> <Type> DEFAULT <DefaultValue>
...
)
<DefaultValue> is a placeholder for a:
value literal
( expression )
Examples:
Count INTEGER DEFAULT 0,
LastSeen TEXT DEFAULT (datetime('now'))

It happens that I'm just starting to learn coding and I needed something similar as you have just asked in SQLite (I´m using [SQLiteStudio] (3.1.1)).
It happens that you must define the column's 'Constraint' as 'Not Null' then entering your desired definition using 'Default' 'Constraint' or it will not work (I don't know if this is an SQLite or the program requirment).
Here is the code I used:
CREATE TABLE <MY_TABLE> (
<MY_TABLE_KEY> INTEGER UNIQUE
PRIMARY KEY,
<MY_TABLE_SERIAL> TEXT DEFAULT (<MY_VALUE>)
NOT NULL
<THE_REST_COLUMNS>
);

Related

Flink Table print connector not being called

I am using the Flink table API to pull data from a kinesis topic into a table. I want to periodically pull that data into a temporary table and run a custom scalar function on it. However, I notice that my scalar function is not being called at all.
Here is the code for the Kinesis table :
this.tableEnv.executeSql("CREATE TABLE transactions (\n" +
" entry STRING,\n" +
" sequence_number VARCHAR(128) NOT NULL METADATA FROM 'sequence-number' VIRTUAL,\n" +
" shard_id VARCHAR(128) NOT NULL METADATA FROM 'shard-id' VIRTUAL,\n" +
" arrival_time TIMESTAMP(3) METADATA FROM 'timestamp' VIRTUAL,\n" +
" WATERMARK FOR arrival_time AS arrival_time - INTERVAL '5' SECOND\n" +
") WITH (\n" +
" 'connector' = 'kinesis',\n" +
" 'stream' = '" + streamName + "',\n" +
" 'aws.region' = 'us-west-2', \n" +
" 'format' = 'raw'\n" +
")");
Then, I want to periodically call a tumble every second which pulls data from kinesis and updates a temporary table.
My temporary table is defined like this:
this.tableEnv.executeSql("CREATE TABLE temporaryTable (\n" +
" entry STRING,\n" +
" sequence_number VARCHAR(128) NOT NULL,\n" +
" shard_id VARCHAR(128) NOT NULL,\n" +
" arrival_time TIMESTAMP(3),\n" +
" record_list STRING NOT NULL,\n" +
" PRIMARY KEY (shard_id, sequence_number) NOT ENFORCED" +
") WITH (\n" +
" 'connector' = 'print'\n" +
")");
I then have a code to do the tumbling :
Table inMemoryTable = transactions.
window(Tumble.over(lit(1).second()).on($("arrival_time")).as("log_ts"))
.groupBy($("entry"), $("sequence_number"), $("log_ts"), $("shard_id"), $("arrival_time"))
.select(
$("entry"),
$("sequence_number"), $("shard_id"), $("arrival_time"),
(call(CustomFunction.class, $("entry")).as("record_list")));
inMemoryTable.executeInsert(temporaryTable)
The CustomFunction class looks like this :
public class CustomFunction extends ScalarFunction {
#DataTypeHint("STRING")
public String eval(
#DataTypeHint("STRING") String serializedEntry) throws IOException {
return "asd";
}
When I run this code in Flink, I dont get anything in the stdout so obviously I am missing something.
Here is the Flink UI:
Image as link as I dont have enough rep
Thanks for any help.
I am able to get the stream to print with:
driver.tableEnv.getConfig().getConfiguration().setString("table.exec.source.idle", "10000 ms");
driver.env.getConfig().setAutoWatermarkInterval(5000);

'(', ')', <column constraint> or comma expected, got 'INTEGER'

I am trying to write my first Kotlin app using SQLite and here is the problematic part:
override fun onCreate(p0: SQLiteDatabase?) {
p0!!.execSQL("CREATE TABLE IF NOT EXISTS $CAR_TABLE(" +
"$CAR_ID INTEGER PRIMARY KEY AUTOINCREMENT, $CAR_NAME TEXT," +
"$CAR_COLOR TEXT, $CAR_MODEL INTEGER)")
I am facing this error message:
'(', ')', or comma expected, got 'INTEGER'
interestingly enough if I delete the last part like this:
override fun onCreate(p0: SQLiteDatabase?) {
p0!!.execSQL("CREATE TABLE IF NOT EXISTS $CAR_TABLE(" +
"$CAR_ID INTEGER PRIMARY KEY AUTOINCREMENT, $CAR_NAME TEXT," +
"$CAR_COLOR TEXT)")
there won't be any error messages. Could you help me with it please?
Android Studio "Bumblebee".
Thank you in advance

Nested match_recognize query not supported in flink SQL?

I am using flink 1.11 and trying nested query where match_recognize is inside, as shown below :
select * from events where id = (SELECT * FROM events MATCH_RECOGNIZE (PARTITION BY org_id ORDER BY proctime MEASURES A.id AS startId ONE ROW PER MATCH PATTERN (A C* B) DEFINE A AS A.tag = 'tag1', C AS C.tag <> 'tag2', B AS B.tag = 'tag2'));
And I am getting an error as : org.apache.calcite.sql.validate.SqlValidatorException: Table 'A' not found
Is this not supported ? If not what's the alternative ?
I was able to get something working by doing this:
Table events = tableEnv.fromDataStream(input,
$("sensorId"),
$("ts").rowtime(),
$("kwh"));
tableEnv.createTemporaryView("events", events);
Table matches = tableEnv.sqlQuery(
"SELECT id " +
"FROM events " +
"MATCH_RECOGNIZE ( " +
"PARTITION BY sensorId " +
"ORDER BY ts " +
"MEASURES " +
"this_step.sensorId AS id " +
"AFTER MATCH SKIP TO NEXT ROW " +
"PATTERN (this_step next_step) " +
"DEFINE " +
"this_step AS TRUE, " +
"next_step AS TRUE " +
")"
);
tableEnv.createTemporaryView("mmm", matches);
Table results = tableEnv.sqlQuery(
"SELECT * FROM events WHERE events.sensorId IN (select * from mmm)");
tableEnv
.toAppendStream(results, Row.class)
.print();
For some reason, I couldn't get it to work without defining a view. I kept getting Calcite errors.
I guess you are trying to avoid enumerating all of the columns from A in the MEASURES clause of the MATCH_RECOGNIZE. You may want to compare the resulting execution plans to see if there's any significant difference.

What to substitute for array_agg in a PostgreSQL subquery when switching to Derby?

I have a java application that for some installations acceses a PostgreSQL database, while in others it acceses essentially the same database in Derby.
I have a SQL query that returns an examination record from the examination table. There is an exam_procedure table that relates to the examination table in a one (examination) to many fashion. I need to concatenate the potentially multiple string records in the exam_procedure table so that I can add a single string value to the query return that represents all the related exam_procedure records. For a variety of reasons (eg, joins return too many records, especially when multiple subqueries are needed for other related one to many tables), I need to do this via a subquery in the SELECT section of the main query. The following SQL works just fine for PostgreSQL, but my understanding is that array_agg is not available in Derby. What Derby subquery can I substitute for the PostgreSQL subquery?
Many thanks.
// part of the query
"SELECT "
+ "patient_id, "
+ "examination_date, "
+ "examination_number, "
+ "operating_physician_id, "
+ "referring_physician_id, "
+ "patient.last_name AS pt_last_name, "
+ "patient.first_name AS pt_first_name, "
+ "patient.middle_name AS pt_middle_name, "
+ "("
+ "SELECT "
+ "array_agg(prose) "
+ "FROM "
+ "exam_procedure "
+ "WHERE examination_id = " + examId
+ " GROUP BY examination_id"
+ ") AS agg_procedures, "
+ "FROM "
+ "examination "
+ "JOIN patient ON patient.id = examination.patient_id "
+ "WHERE "
+ "examination.id = ?"
;

h2 drop column after drop constraint failes

Problem:
We try to run your update script in h2 for testing.
With every version we have a update.sql to run the updates on the DB.
But we get a problem when trying to delete a constraint (foreign key):
Error:
Exception in thread "main" org.h2.jdbc.JdbcSQLException: Index "FP_ACL_PERMISSION_UNQ" belongs to constraint "CONSTRAINT_31B"; SQL statement:
ALTER TABLE FP_ACL_PERMISSION DROP INDEX FP_ACL_PERMISSION_UNQ; [90085-191]
at org.h2.message.DbException.getJdbcSQLException(DbException.java:345)
at org.h2.message.DbException.get(DbException.java:179)
at org.h2.command.ddl.DropIndex.update(DropIndex.java:63)
at org.h2.command.CommandContainer.update(CommandContainer.java:98)
at org.h2.command.Command.executeUpdate(Command.java:258)
at org.h2.jdbc.JdbcStatement.executeInternal(JdbcStatement.java:184)
at org.h2.jdbc.JdbcStatement.execute(JdbcStatement.java:158)
at com.rbs.mib.portal.HelloWorld.main(HelloWorld.java:63)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:144)
Code to reproduce the problem:
public class ReproduceH2Problem{
public static void main(String... args) throws Exception {
Class.forName("org.h2.Driver");
Connection conn = DriverManager.getConnection("jdbc:h2:~/test;MODE=ORACLE", "sa", "sa");
Statement stat = conn.createStatement();
stat.execute("DROP ALL OBJECTS");
// init v1.0.0
stat.execute("CREATE TABLE FP_ACL" +
"(" +
" ACL_ID INTEGER NOT NULL," +
" REPORT_KEY VARCHAR2(100) NOT NULL," +
" PARENT_ACL_ID INTEGER" +
");");
stat.execute("CREATE TABLE FP_ACL_PERMISSION" +
"(" +
" PERMISSION_ID INTEGER NOT NULL," +
" ACL_ID INTEGER NOT NULL," +
" NAME VARCHAR2(100)" +
");");
stat.execute("CREATE UNIQUE INDEX FP_ACL_PERMISSION_UNQ ON FP_ACL_PERMISSION" +
"(ACL_ID, NAME);");
stat.execute("ALTER TABLE FP_ACL_PERMISSION ADD " +
"CHECK (ACL_ID IS NOT NULL);");
stat.execute("ALTER TABLE FP_ACL_PERMISSION ADD " +
"PRIMARY KEY " +
"(PERMISSION_ID);");
stat.execute("ALTER TABLE FP_ACL_PERMISSION ADD " +
"CONSTRAINT FP_ACL_PERMISSION_UNQ " +
"UNIQUE (ACL_ID, NAME);");
// !! this seems to be the "bad guy" !!
stat.execute("ALTER TABLE FP_ACL_PERMISSION ADD " +
"FOREIGN KEY (ACL_ID) " +
"REFERENCES FP_ACL (ACL_ID);");
//update v1.0.1
stat.execute("ALTER TABLE FP_ACL_PERMISSION DROP CONSTRAINT FP_ACL_PERMISSION_UNQ;");
//here the problems start
stat.execute("ALTER TABLE FP_ACL_PERMISSION DROP INDEX FP_ACL_PERMISSION_UNQ;");
stat.execute("ALTER TABLE FP_ACL_PERMISSION DROP COLUMN ACL_ID;");
stat.execute("ALTER TABLE FP_ACL_PERMISSION ADD CONSTRAINT FP_ACL_PERMISSION_UNQ UNIQUE (NAME);");
stat.close();
conn.close();
}
}
I had to do a workaround by adding meta commands in the sql scripts as
cannot rename the constraints (h2 does not support)
direct subselect does not work
alter table TABLE_NAME drop constraint
(select unique_index_name
from information_schema.constraints
where table_name='TABLE_NAME' and CONSTRAINT_TYPE='REFERENTIAL' and COLUMN_LIST= ='SHORT_ID')
Workaround:
Meta Command in update.sql script:
--H2-DROP-REFERENCE TABLE::FP_ACL_PERMISSION:: COLUMN::ACL_ID::
ALTER TABLE FP_ACL_PERMISSION DROP INDEX FP_ACL_PERMISSION_UNQ;
Filter meta command in groovy test:
public static enum H2_META_COMMAND {
DROP_REFERENCE("--H2-DROP-REFERENCE")
private String command;
H2_META_COMMAND(String command){
this.command = command
}
String getCommand(){
return command;
}
}
and
/**
* This checks for custom H2 Meta commands to close oracle compatibility gap
* #param sqlCommand a single command
*/
public static void executeH2MetaCommands(String sqlSingleCommand, Statement statement){
if(sqlCommand.contains(H2_META_COMMAND.DROP_REFERENCE.getCommand())){
int tableStart = sqlCommand.indexOf("TABLE::", sqlCommand.indexOf(H2_META_COMMAND.DROP_REFERENCE.getCommand()) + H2_META_COMMAND.DROP_REFERENCE.getCommand().size() ) + 7
String table = sqlCommand.substring(tableStart, sqlCommand.indexOf("::",tableStart))
int colStart = sqlCommand.indexOf("COLUMN::") + 8
String col = sqlCommand.substring(colStart, sqlCommand.indexOf("::",colStart))
ResultSet rs = statement.executeQuery("select CONSTRAINT_NAME from information_schema.constraints where table_name='"+ table+"' and CONSTRAINT_TYPE='REFERENTIAL' and COLUMN_LIST= '"+col+"'")
rs.next()
String constraintName = rs.getString(1)
rs.close()
statement.execute("ALTER TABLE FP_ACL_PERMISSION DROP constraint " + constraintName)
}
}

Resources