String to StringLiteral
Any ideas how I might convert a String to a StringLiteral? I'm trying to interact with a postgres database and if I don't have the parameters as a StringLiteral it doesn't want to work. Not sure how I might get around this. For example the following works if you pass the name as a StringLiteral but not as a String and I don't know how I might convert a String to a StringLiteral for the purposes of using this function: fn get_name(cursor: PythonObject, name: StringLiteral) raises -> PythonObject:
let np = Python.import_module("numpy")
var name_array = np.array(())
let sql = """
SELECT *
FROM customer
WHERE name = %s
"""
let data = (name,)
try: cursor.execute(sql, data) var names = cursor.fetchall() name_array = names except Exception: print("Error: ", Exception) return name_array
try: cursor.execute(sql, data) var names = cursor.fetchall() name_array = names except Exception: print("Error: ", Exception) return name_array
3 Replies
You can’t 🙂. As the name says StringLiteral is a string literal, meaning that strings which you define in your code e.g. “hello” are literals and get the type StringLiteral assigned by the compiler. So when the compiler parses your code it identifies the string literals in your code, put them in the binary as is and you can refer to them as StringLiterals later. At runtime you can convert StringLiteral into a String, this is done by copying the bytes which StringLiteral points to into a new DynamicVector which String type is a wrapper of. Now a String can be mutated and worked with through String API. But you can’t go the other way around.
The API above expects you to know the name at compile time, hence it Asks for StringLiteral not a String. I am not sure if it is a reasonable restriction of the API though.
Ah Maxim. Thank you 🙂 I had tried to do all sorts of callisthenics to get around this but to no avail. It started out because I've got a PythonObject (a return type from the database query) which is actually a string (or rather I want to deal with it as such). From this PythonObject which is a string I wanted to make another query to the database and I can only get it to work if it is a StringLiteral. The only way I could see how to convert a PythonObject to anything like a string was with str(PythonObject) but of course that gives me a String not a StringLiteral, so I feel like I've been chasing my tail a bit with this one. I might be overlooking something very obvious here... Thank you for reaching out and trying to help :).
Congrats @Aloysius, you just advanced to level 2!