Exemplo n.º 1
0
def cstr(input_, doquote=True, doescape=True):
    """
    Returns a formatted string safe for use in SQL. If None is passed, it
    will return 'NULL' so as to insert a NULL value into the database.
    Single quotes will be escaped.
    
    @param input_: String to be cleaned
    @type input_: String
    @param doquote: I{OPTIONAL}: Wrapped in single quotes, defaults to B{True}
    @type doquote: bool
    @param doescape: I{OPTIONAL}: Escape single quotes, defaults to B{True}
    @type doescape: bool
    @return: String, or 'NULL'
    
    >>> print 'SET description = %s;' % cstr("I don't")
    SET description = 'I don''t';
    >>> print 'SET now = %s;' % cstr("CURRENT_TIME", doquote=False)
    SET now = CURRENT_TIME;
    """
    
    if input_ is None:
        return 'NULL'
    
    input_ = str(input_) 
    if doescape:
        escape = {"'":"''", "\\":"\\\\"}
        input_ = data.replace_all(escape, input_)

    if doquote:
        return data.wrap(input_, "'")
    else:
        return input_
Exemplo n.º 2
0
def cstr(string, doquote=True, doescape=True):
    """
    Returns a formatted string safe for use in SQL. If :class:`None`
    is passed, it will return ``NULL`` so as to insert a NULL value
    into the database.  Single quotes will be escaped.

    :param string: String to be cleaned
    :type string: :class:`str`
    :param doquote: Optionally wrap in single quotes, default is :class:`True`
    :type doquote: bool
    :param doescape: Optionally escape single quotes, default is :class:`True`
    :type doescape: :class:`bool`
    :rtype: :class:`str`, or ``NULL``

    >>> from chula.db import functions
    >>> print 'SET description = %s;' % functions.cstr("I don't")
    SET description = 'I don''t';
    >>>
    >>> print 'SET now = %s;' % functions.cstr("CURRENT_TIME", doquote=False)
    SET now = CURRENT_TIME;
    """

    if string is None:
        return 'NULL'

    string = str(string)
    if doescape:
        escape = {"'":"''", "\\":"\\\\"}
        string = data.replace_all(escape, string)

    if doquote:
        return data.wrap(string, "'")
    else:
        return string