r2605: *** empty log message ***
[clsql.git] / clsql-base / utils.cl
1 ;;;; -*- Mode: LISP; Syntax: ANSI-Common-Lisp; Base: 10 -*-
2 ;;;; *************************************************************************
3 ;;;; FILE IDENTIFICATION
4 ;;;;
5 ;;;; Name:         utils.cl
6 ;;;; Purpose:      SQL utility functions
7 ;;;; Programmer:   Kevin M. Rosenberg
8 ;;;; Date Started: Mar 2002
9 ;;;;
10 ;;;; $Id: utils.cl,v 1.1 2002/08/01 03:06:26 kevin Exp $
11 ;;;;
12 ;;;; This file, part of CLSQL, is Copyright (c) 2002 by Kevin M. Rosenberg
13 ;;;;
14 ;;;; CLSQL users are granted the rights to distribute and use this software
15 ;;;; as governed by the terms of the Lisp Lesser GNU Public License
16 ;;;; (http://opensource.franz.com/preamble.html), also known as the LLGPL.
17 ;;;; *************************************************************************
18
19 (declaim (optimize (debug 3) (speed 3) (safety 1) (compilation-speed 0)))
20 (in-package :clsql-base-sys)
21
22 (defun number-to-sql-string (num)
23   (etypecase num
24     (integer
25      num)
26     (rational
27      (float-to-sql-string (coerce num 'double-float)))
28     (number
29      (float-to-sql-string num))))
30
31 (defun float-to-sql-string (num)
32   "Convert exponent character for SQL"
33   (substitute #\e #\f (substitute #\e #\d (write-to-string num :readably t))))
34
35 (defun sql-escape (identifier)
36   "Change hyphens to underscores, ensure string"
37   (let* ((unescaped (etypecase identifier
38                       (symbol (symbol-name identifier))
39                       (string identifier)))
40          (escaped (make-string (length unescaped))))
41     (dotimes (i (length unescaped))
42       (setf (char escaped i)
43             (cond ((equal (char unescaped i) #\-)
44                    #\_)
45                   ;; ...
46                   (t
47                    (char unescaped i)))))
48     escaped))
49
50
51 (defun sql-escape-quotes (s)
52   "Escape quotes for SQL string writing"
53   (substitute-string-for-char s #\' "''"))
54
55 (defun substitute-string-for-char (procstr match-char subst-str) 
56 "Substitutes a string for a single matching character of a string"
57   (let ((pos (position match-char procstr)))
58     (if pos
59         (concatenate 'string
60           (subseq procstr 0 pos) subst-str
61           (substitute-string-for-char 
62            (subseq procstr (1+ pos)) match-char subst-str))
63       procstr)))
64
65