sqlite3 select where name and value are variables - sqlite

in python my code to fetch data from the table is as follows:
posts = get_db().execute(
'SELECT * FROM post WHERE (? = ?) ORDER BY created DESC', (name, value)
).fetchall()
name and value are variables depending on what the user clicks on the page.
The code won't work... how should it be written???
Addon:
Searching for a solution I bumped into the following:
def get_posts(name, tag):
posts = get_db().execute(
"""SELECT * FROM post WHERE ({} = ?)""".format(name), (tag,)
).fetchall()
But didn't work for me too...

Related

Why is SQLAlchemy expecting 6 rows here when I want to delete two?

I am using Flask-SQLAlchemy and I have the following tables:
tags = db.Table('tags',
db.Column('tag_id', db.Integer, db.ForeignKey('tag.id'), primary_key=True),
db.Column('post_id', db.Integer, db.ForeignKey('post.id'), primary_key=True))
class Post(db.Model):
id = db.Column(db.Integer, primary_key=True)
title = db.Column(db.String(250))
body = db.Column(db.Text)
timestamp = db.Column(db.DateTime, index=True, default=datetime.utcnow)
author = db.Column(db.String(64))
tags = db.relationship('Tag', secondary=tags, lazy='subquery',
backref=db.backref('posts', lazy=True))
published = db.Column(db.Boolean)
slug = db.Column(db.String(300), unique=True, index=True)
def save(self):
if not self.slug:
self.slug = re.sub('[^\w]+', '-', self.title.lower())
def update_time(self):
self.timestamp = datetime.utcnow()
def __repr__(self):
return '<Post {}>'.format(self.title)
class Tag(db.Model):
id = db.Column(db.Integer, primary_key=True)
tag = db.Column(db.String(64), index=True, unique=True)
def __repr__(self):
return '<Tag {}>'.format(self.tag)
Currently I am making a function to allow the user to delete a post entirely with db.session.delete(post) and I am getting the follwing error:
sqlalchemy.orm.exc.StaleDataError: DELETE statement on table 'tags' expected to delete 6 row(s); Only 2 were matched.
Why does the delete statement expect 6 rows? 2 is the correct number and corresponds to how many entries there are in the tags table for that post, two unique tags attached to this post.
It seems the issue here was with my route and not my models.
Bringing the delete function code to the beginning of the route gave me the expected behaviour; the post was deleted from the database and associations in the helper table also removed.
The error was caused by some code in my route that appended selected tags from the submitted form to post.tags multiple times over resulting in the expectation of 6 rows.

wtforms SelectMultipleField returning only 1 selected value

im following this tutorial to implement a multi checkbox field in flask with jinja
https://gist.github.com/doobeh/4668212
It works for the most part but when I go to access the value in my code (products is the field where I used the multicheckbox) like
class CreateBoardForm(Form):
products = MultiCheckboxField(
'Select Products:',
coerce=int,
choices=[(1, 'one'), (2, 'two'), (3, 'three')])
......
if request.method == 'POST':
products=request.form['products']
print name, description, tags
print "Selected products:", products
When I print selected products I only see one value being selected. When I printed the forms object I see this python data structure ImmutableMultiDict([('products', u'1'), ('products', u'3')])
Im not sure how to get all the values for the 'products' key
you will have to use the getlist method in order to return a list of other choices.
request.form.getlist('products')

Select cmis:document with tags or category

Any idea how to select all cmis:document with specified tags or category? I'm using Apache Chemistry. I'm guessing I should use JOINs but can't figure out how to do so, I'm still having trouble drawing relationships between types.
I found this piece of code:
testDoc = session.getObjectByPath("/test/testfolder1/test1.txt")
catIds = testDoc.getPropertyValue("cm:categories")
for (catId in catIds) {
cat = session.getObject(catId)
println(cat.name)
}
But so far I plan to use prepared statement, because i'm interested in the use of IN_FOLDER, just like this:
QueryStatement qs = session.createQueryStatement("SELECT ?, ? FROM ? WHERE ? > TIMESTAMP ? AND IN_FOLDER(?) OR ? IN (?)");
The goal of my request is to get all documents with certain category and contained in a folder (soon I'll have too add criteria on tag)
Thanks for your help
That's how I did for tags:
SELECT * FROM cmis:folder AS F JOIN cm:taggable AS T ON T.cmis:objectId = F.cmis:objectId WHERE T.cmis:name = 'Agency Files'
But it won't work if I decide to add the IN_FOLDER condition

Drupal CCK field select option names, where are they?

I have a custom content type which has a field called "location" which is a long select list (100 or so items). I want to get an array of all locations which have a piece of content associated with them. The numeric value of this field is stored in content_type_[my_content_type], but I can't find anywhere in the database where the name of the values are stored. I hope that's not too confusing - just to be clear, I want to do something like this:
SELECT DISTINCT(field_location_value) FROM content_type_[my_content_type]
and then
SELECT field_location_name_or_something FROM where_on_earth_are_the_names_stored
and then do something with the two arrays to find the names I want.
Can anyone help?
Thanks a lot. Drupal 6, by the way.
If you mean select list field of CCK:
Get all location associated with current node (piece of content?):
$node = node_load('YOUR content ID');
print_r($node->field_location); // $node->field_location - this will array of values.
Get all values of that field (defined in "Allowed values"):
$content_field = content_fields('field_location');
$allowed_values = content_allowed_values($content_field); // array of values
I found this, after much trial and tribulation, in the database table content_node_field_instance, under the field's widget settings field.
This Drupal 6 code snipped will retrieve your cck field value options and put them in the $allowed_values variable as an array. Replace 'YOUR_CCK_FIELD_NAME' with your cck field name (name, not label)
$cck_field_name = 'YOUR_CCK_FIELD_NAME';
$cck_field = db_fetch_object(db_query("SELECT global_settings FROM {content_node_field} WHERE field_name = '%s'", $cck_field_name));
$cck_field_global_settings = unserialize($cck_field->global_settings);
$allowed_values = explode("\r\n", trim($cck_field_global_settings['allowed_values'], "\r\n"));
In Drupal 7 if you have a field of type List (text) then I have written the following function to return an array of options:
function get_drupal_select_options($field_name) {
$options = unserialize(db_query("SELECT c.data
FROM field_config_instance i
INNER JOIN field_config c ON c.id = i.field_id
WHERE i.field_name = :fieldname", array(':fieldname'=>$field_name))->fetchField());
return $options['settings']['allowed_values'];
}

GAE by using GQL, how to use SQL's like query?

def post(self):
selector = self.request.get('search')
search = db.GqlQuery("SELECT * FROM Product WHERE productName = :selector", selector=selector)
products = search.fetch(10)
values = {
'products' : products
}
doRender(self, 'search.html', values)
above code is for search function from my Product category...
Actually i tried to use the code "Select * From Product Where productName like %:selector%"
for my search function, but i couldn't use this code....
Is there anyother GQL code which is substitution of 'SQL-LIKE query'??
There is no equivalent of SQL's LIKE in App Engine. You can however do something like
blurred_product_name = selector[:-2]
search = db.GqlQuery('SELECT * FROM Product where productName > ',
blurred_product_name)
So, if you have products with the name Product-1, Product-2, Product-3 and the search term is "Product", your blirred_product_name will be "Produc" which will return all the three possibilities in this case.
Be careful with indexes however.
Alternatively you can very well use SearchableModel http://www.billkatz.com/2008/8/A-SearchableModel-for-App-Engine and get this done easily.

Resources