Cannot resolve logical: syntax error for sql - sql

Not sure how to correct this logical syntax error, help would be appreciated!
Traceback (most recent call last):
File "c:\Users\M\Desktop\Coding\Course4wk4sql.py", line 7, in
cur.executescript('''
sqlite3.OperationalError: near "#logical": syntax error
PS C:\Users\M\Desktop\Coding> sqlite3.OperationalError: near "#logical": syntax error
Here is the code:
import json
import sqlite3
conn = sqlite3.connect ('rosterdb.sqlite')
cur = conn.cursor()
cur.executescript('''
DROP TABLE IF EXISTS User;
DROP TABLE IF EXISTS Member;
DROP TABLE IF EXISTS Course;
CREATE TABLE User (
id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT UNIQUE,
name TEXT UNIQUE #logical key
);
CREATE TABLE Course (
id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT UNIQUE,
title TEXT UNIQUE
);
CREATE TABLE Member (
user_id INTEGER,
course_id INTEGER,
role INTEGER,
PRIMARY KEY (user_id, course_id) #Going to force combination of these two to be unique
)
''')
filename = "roster_data.json"
jsondata = open(filename)
data = json.load(jsondata)
for entry in data:
user = entry[0]
course = entry[1]
instructor = entry[2]
user_statement = """INSERT OR IGNORE INTO User(name) VALUE 9 ? )"""
SQLparams = (user, )
cur.execue(course_statement, SQLparams)
course_statement = """INSERT OR IGNORE INTO Course(title) VALUES ( ? )"""
sqlparams = (course, )
cur.execute(course_statement, SQLparams)
courseID_statement = """SELECT id FROM Course WHERE title = ?"""
SQLparams = (course, )
cur.execute(courseID_statement. SQLparams)
courseID =cur.fetone()[0]
userID_statement = """SELECT id FROM User WHERE name = ?"""
SQLparams = (user, )
cur.execute(userID_statement, SQLparams)
userID = cur.fetchone()[0]
member_statement = """INSERT INTO Member(user_id, course_id, role)
VALUES(?, ?, ?)"""
SQLparams = (userID, courseID, instructor)
cur.execute(member_statement, SQLparams)
conn.commit()
test_statement = """
SELECT hex(User.name || Course.title || Member.role ) AS X FROM
User JOIN Member JOIN Course
ON User.id = Member.user_id AND Member.course_id = Course.id
ORDER BY X
"""
cur.execute(test_statement)
result = cur.fetchone()
print("RESULT: " + str(result))
#Closing the connection
cur.close()
conn.close()

You are using non-sql style comments eg #logical key in the sql script. While # is used for commenting in python -- or /* multi line comment */ is typically used in sqlite comments.
As a result you are getting a syntax error. You may remove these python style comments or attempt to replace them with sqlite style comments

Related

How to combine two SQL queries with dynamic table name into one in PostgreSQL

I have this SQL function which I'm trying to figure out how to make into one query:
async function verifyInteractiveInstanceAttributeIsUnique(typeId, key, val, attrSchema) {
const tableName = getTableName(attrSchema.type)
const instances = await knex.from(`links`)
.select('id')
.where('parent_id', typeId)
.where('name', 'instance')
const instanceIds = instances.map(x => x.id)
const existingRecord = await knex.from(tableName)
.whereIn('parent_id', instanceIds)
.where('name', key)
.first()
return !existingRecord
}
Essentially I think this is the SQL:
SELECT id FROM links
WHERE parent_id = ${typeId}
AND name = 'instance'
# store in IDS array lets say
SELECT * FROM ${tableName}
WHERE parent_id IN (IDS)
AND name = ${key}
LIMIT 1
How can I write this in plain SQL to do the query in one call?
Based on your sample SQL, you can use a subquery:
SELECT t.*
FROM ${tableName} t
WHERE t.parent_id IN (SELECT l.id
FROM links l
WHERE l.parent_id = ${typeId} AND
lname = 'instance'
) AND
t.l.name = ${key}
LIMIT 1

subrequest in case return error on clickhouse

So i try a make a view , actually this is my code :
drop table if exists computed_datum_hours_base;
create view computed_datum_hours_base
as select
toStartOfHour(datetime_value) as datetime_desc,
computed_id,
computed_kind,
computed_type,
case
when computed_type = 'intensive' then avg(value)
when computed_type = 'extensive.some' then sum(value)
when computed_type = 'extensive.differential' then
(
select value as value_f from ref_computed_datum
where ref_computed_id = computed_id
and ref_computed_kind = computed_kind
and ref_computed_type = computed_type
and ref_datetime_value = toStartOfHour(addHours(datetime_value, 1))
) - (
select value as value_f from ref_computed_datum
where ref_computed_id = computed_id
and ref_computed_kind = computed_kind
and ref_computed_type = computed_type
and ref_datetime_value = toStartOfHour(datetime_value)
)
end as value,
count(uuid) as nb_value
from computed_datum
join ref_computed_datum
on computed_id = ref_computed_id
and computed_kind = ref_computed_kind
and computed_type = ref_computed_type
where uuid = ref_uuid
group by
computed_id,
computed_kind,
computed_type,
toStartOfHour(datetime_value)
;
my issue is on the case for extensive.differential ...
clickhouse say he can found the column for computed_id ... like the subrequest is scoped and didn't have access to the colum from the main requeste ...
So this is another bug of clickhouse ?
Or there are a reel scope and i can't do this like this ...
( so How can do this ? )
Edit: full error
Code: 47, e.displayText() = DB::Exception: Missing columns: 'datetime_value' 'computed_kind' 'computed_type' 'computed_id' 'value' while processing query: 'SELECT value AS value_f FROM api_client.ref_computed_datum WHERE (ref_computed_id = computed_id) AND (ref_computed_kind = computed_kind) AND (ref_computed_type = computed_type) AND (ref_datetime_value = toStartOfHour(addHours(datetime_value, 1)))', required columns: 'value' 'computed_id' 'ref_computed_id' 'ref_computed_kind' 'computed_type' 'ref_computed_type' 'computed_kind' 'ref_datetime_value' 'datetime_value', source columns: 'ref_flags' 'ref_computed_kind' 'ref_computed_id' 'ref_datetime_value' 'ref_computed_type' 'ref_EventDateTime' 'ref_insert' 'ref_value' 'ref_uuid' (version 20.4.2.9 (official build))
computed_datum folow this structure :
EventDateTime DateTime default now(),
insert String,
uuid String default generateUUIDv4(),
datetime_value DateTime,
computed_id Int32,
computed_kind String,
computed_type String,
value Float64,
flags String
```
I make a ref view that only prefix all colum with ref_ for making a walkaround about the alias bug.
At this time clickhouse didn't support correlated query ...
cf: https://github.com/ClickHouse/ClickHouse/issues/6697

PhoneGap sql checking for duplicates

I want to input a query to check the database for duplicate when inserting data into the database so it would prevent the activity Name from being entered more than once in a database
function insertQueryDB(tx) {
var myDB = window.openDatabase("test", "1.0", "Test DB", 1000000);
tx.executeSql('CREATE TABLE IF NOT EXISTS dataEntryTb (id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, activityName TEXT NOT NULL, location TEXT NOT NULL, time NOT NULL, date NOT NULL, reporter NOT NULL)');
var an = document.forms["myForm"]["activityName"].value;
var l = document.forms["myForm"]["location"].value;
var t = document.forms["myForm"]["time"].value;
var d = document.forms["myForm"]["date"].value;
var r = document.forms["myForm"]["reporter"].value;
var query = 'INSERT INTO dataEntryTb ( activityName, location, time, date, reporter) VALUES ( "'+an+'", "'+l+'", "'+t+'", "'+d+'", "'+r+'")';
navigator.notification.alert("Retrieved the following: Activity Name="+an+" and Location="+l);
tx.executeSql(query,[]);
}``
Create the table with name being unique:
CREATE TABLE IF NOT EXISTS dataEntryTb (
id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
activityName TEXT NOT NULL UNIQUE,
location TEXT NOT NULL,
time NOT NULL, date NOT NULL,
reporter NOT NULL
);
Then the database will return an error if the name is already in the table.

How to check if value is already exist in database (SQLAlchemy)

I am trying to check if unique element is already present in postgresdb.
My method in views.py is
def bestfriend(username):
print username
user = Users.query.filter_by(username = username).first()
if user == None:
flash('bestfriend not found.')
return redirect(url_for('index'))
print user
u = g.user.friend(user)
#print bestfriend.id
if u is None:
#flash('Cannot be friend %(username)s.', username = username)
return redirect(url_for('user', username = username))
if db.session.query(bestfriend).filter(bestfriend.id==u.id).first():
flash('Already Exist')
return redirect(url_for('index'))
db.session.add(u)
db.session.commit()
flash('Your bestfriend has been added.')
return redirect(url_for('user', username = username))
My model.py is
bestfriend= db.Table('bestfriend',
db.Column('id',db.Integer, primary_key = True),
db.Column('friendid', db.Integer, db.ForeignKey('users.id'))
)
class Users(db.Model):
__tablename__ = "users"
id = db.Column(db.Integer, primary_key = True)
username = db.Column('username', db.String(20), unique=True , index=True)
password = db.Column('password' , db.String(10))
email = db.Column('email',db.String(50),unique=True , index=True)
registered_on = db.Column('registered_on' , db.DateTime)
posts = db.relationship('Post', backref = 'author', lazy = 'dynamic')
followed = db.relationship('Users',
secondary = followers,
primaryjoin = (followers.c.follower_id == id),
secondaryjoin = (followers.c.followed_id == id),
backref = db.backref('followers', lazy = 'dynamic'),
lazy = 'dynamic')
bestfriends = db.relationship('Users',
secondary = bestfriend,
primaryjoin = (bestfriend.c.friendid == id),
secondaryjoin = (bestfriend.c.id == id),
backref = db.backref('bestfriend', lazy = 'dynamic'),
lazy = 'dynamic')
I am able to insert value in database table bestfriend
Table "public.bestfriend"
Column | Type | Modifiers
----------+---------+-----------
id | integer | not null
friendid | integer |
Indexes:
"bestfriend_pkey" PRIMARY KEY, btree (id)
Foreign-key constraints:
"bestfriend_friendid_fkey" FOREIGN KEY (friendid) REFERENCES users(id)
but after insertion, I have to check if record is already present, using this line
if db.session.query(bestfriend).filter(bestfriend.id==u.id).first():
I am not sure about this statement. I have already tried similar solutions How to elegantly check the existence of an object/instance/variable and simultaneously assign it to variable if it exists in python? but it didn't worked for me.
I didn't receive any reply so adding some more info. I just want to check if id = 8 is already present in bestfriend table
app=> select * from bestfriend;
id | friendid
----+----------
8 | 11
Your statement does not work because bestfriend is a Table, not a mapped class. To fix the typo, just add c. to the query:
exists = db.session.query(bestfriend).filter(bestfriend.c.id==u.id).first()
Given that your relationship is defined as dynamic, you can do it easier with the following:
exists = user.bestfriends.filter(Users.id == u.id).one()
Side remark: Note that your bestfriend table is not structured correctly to allow many-to-many relationship. In order to do that, please change the definition of the table as per below:
bestfriend = db.Table('bestfriend',
db.Column('id',db.Integer, db.ForeignKey('users.id'), primary_key = True),
db.Column('friendid', db.Integer, db.ForeignKey('users.id'), primary_key = True)
)
Another remark: I do not understand the code flow: you add a friend at step u = g.user.friend(user), but later check if it exists. Shall logic not be reversed?
If you want to find if a record exists in a table, You can do it like this:
select 1 from table_name;
or better
select 1 from table_name where rownum=1;
The image below shows the query with output.
If there are any data, it will return 1 in the column.

How To Split Pipe-Delimited Column and insert each value into new table Once?

I have an old database with a gazillion records (more or less) that have a single tags column (with tags being pipe-delimited) that looks like so:
Breakfast
Breakfast|Brunch|Buffet|Burger|Cakes|Crepes|Deli|Dessert|Dim Sum|Fast Food|Fine Wine|Spirits|Kebab|Noodles|Organic|Pizza|Salad|Seafood|Steakhouse|Sushi|Tapas|Vegetarian
Breakfast|Brunch|Buffet|Burger|Deli|Dessert|Fast Food|Fine Wine|Spirits|Noodles|Pizza|Salad|Seafood|Steakhouse|Vegetarian
Breakfast|Brunch|Buffet|Cakes|Crepes|Dessert|Fine Wine|Spirits|Salad|Seafood|Steakhouse|Tapas|Teahouse
Breakfast|Brunch|Burger|Crepes|Salad
Breakfast|Brunch|Cakes|Dessert|Dim Sum|Noodles|Pizza|Salad|Seafood|Steakhouse|Vegetarian
Breakfast|Brunch|Cakes|Dessert|Dim Sum|Noodles|Pizza|Salad|Seafood|Vegetarian
Breakfast|Brunch|Deli|Dessert|Organic|Salad
Breakfast|Brunch|Dessert|Dim Sum|Hot Pot|Seafood
Breakfast|Brunch|Dessert|Dim Sum|Seafood
Breakfast|Brunch|Dessert|Fine Wine|Spirits|Noodles|Pizza|Salad|Seafood
Breakfast|Brunch|Dessert|Fine Wine|Spirits|Salad|Vegetarian
Is there a way one could retrieve each tag and insert it into a new table tag_id | tag_nm using MySQL only?
Here is my attempt which uses PHP..., I imagine this could be more efficient with a clever MySQL query. I've placed the relationship part of it there too. There's no escaping and error checking.
$rs = mysql_query('SELECT `venue_id`, `tag` FROM `venue` AS a');
while ($row = mysql_fetch_array($rs)) {
$tag_array = explode('|',$row['tag']);
$venueid = $row['venue_id'];
foreach ($tag_array as $tag) {
$rs2 = mysql_query("SELECT `tag_id` FROM `tag` WHERE tag_nm = '$tag'");
$tagid = 0;
while ($row2 = mysql_fetch_array($rs2)) $tagid = $row2['tag_id'];
if (!$tagid) {
mysql_execute("INSERT INTO `tag` (`tag_nm`) VALUES ('$tag')");
$tagid = mysql_insert_id;
}
mysql_execute("INSERT INTO `venue_tag_rel` (`venue_id`, `tag_id`) VALUES ($venueid, $tagid)");
}
}
After finding there is no official split function I've solved the issue using only MySQL like so:
1: I created the function strSplit
CREATE FUNCTION strSplit(x varchar(21845), delim varchar(255), pos int) returns varchar(255)
return replace(
replace(
substring_index(x, delim, pos),
substring_index(x, delim, pos - 1),
''
),
delim,
''
);
Second I inserted the new tags into my new table (real names and collumns changed, to keep it simple)
INSERT IGNORE INTO tag (SELECT null, strSplit(`Tag`,'|',1) AS T FROM `old_venue` GROUP BY T)
Rinse and repeat increasing the pos by one for each collumn (in this case I had a maximum of 8 seperators)
Third to get the relationship
INSERT INTO `venue_tag_rel`
(Select a.`venue_id`, b.`tag_id` from `old_venue` a, `tag` b
WHERE
(
a.`Tag` LIKE CONCAT('%|',b.`tag_nm`)
OR a.`Tag` LIKE CONCAT(b.`tag_nm`,'|%')
OR a.`Tag` LIKE CONCAT(CONCAT('%|',b.`tag_nm`),'|%')
OR a.`Tag` LIKE b.`tag_nm`
)
)