/[thuban]/branches/WIP-pyshapelib-bramz/libraries/pyshapelib/dbflibmodule.c
ViewVC logotype

Diff of /branches/WIP-pyshapelib-bramz/libraries/pyshapelib/dbflibmodule.c

Parent Directory Parent Directory | Revision Log Revision Log | View Patch Patch

trunk/thuban/libraries/pyshapelib/dbflib.i revision 1917 by bh, Mon Nov 3 17:31:11 2003 UTC branches/WIP-pyshapelib-bramz/libraries/pyshapelib/dbflibmodule.c revision 2745 by bramz, Thu Mar 15 22:27:02 2007 UTC
# Line 1  Line 1 
1  /* SWIG (www.swig.org) interface file for the dbf interface of shapelib  #include "pyshapelib_common.h"
  *  
  * At the moment (Dec 2000) this file is only useful to generate Python  
  * bindings. Invoke swig as follows:  
  *  
  *      swig -python -shadow dbflib.i  
  *  
  * to generate dbflib_wrap.c and dbflib.py. dbflib_wrap.c defines a  
  * bunch of Python-functions that wrap the appripriate dbflib functions  
  * and dbflib.py contains an object oriented wrapper around  
  * dbflib_wrap.c.  
  *  
  * This module defines one object type: DBFFile.  
  */  
   
 /* this is the dbflib module */  
 %module dbflib  
   
 /* first a %{,%} block. These blocks are copied verbatim to the  
  * dbflib_wrap.c file and are not parsed by SWIG. This is the place to  
  * import headerfiles and define helper-functions that are needed by the  
  * automatically generated wrappers.  
  */  
2    
3  %{  /* --- DBFFile ------------------------------------------------------------------------------------------------------- */
 #include "shapefil.h"  
4    
5    typedef struct {
6            PyObject_HEAD
7            DBFHandle handle;
8    } DBFFileObject;
9    
 /* Read one attribute from the dbf handle and return it as a new python object  
  *  
  * If an error occurs, set the appropriate Python exception and return  
  * NULL.  
  *  
  * Assume that the values of the record and field arguments are valid.  
  * The name argument will be passed to DBFGetFieldInfo as is and should  
  * thus be either NULL or a pointer to an array of at least 12 chars  
  */  
 static PyObject *  
 do_read_attribute(DBFInfo * handle, int record, int field, char * name)  
 {  
     int type, width;  
     PyObject *value;  
   
     type = DBFGetFieldInfo(handle, field, name, &width, NULL);  
     /* For strings NULL and the empty string are indistinguishable  
      * in DBF files. We prefer empty strings instead for backwards  
      * compatibility reasons because older wrapper versions returned  
      * emtpy strings as empty strings.  
      */  
     if (type != FTString && DBFIsAttributeNULL(handle, record, field))  
     {  
         value = Py_None;  
         Py_INCREF(value);  
     }  
     else  
     {  
         switch (type)  
         {  
         case FTString:  
         {  
             const char * temp = DBFReadStringAttribute(handle, record, field);  
             if (temp)  
             {  
                 value = PyString_FromString(temp);  
             }  
             else  
             {  
                 PyErr_Format(PyExc_IOError,  
                              "Can't read value for row %d column %d",  
                              record, field);  
                 value = NULL;  
             }  
             break;  
         }  
         case FTInteger:  
             value = PyInt_FromLong(DBFReadIntegerAttribute(handle, record,  
                                                            field));  
             break;  
         case FTDouble:  
             value = PyFloat_FromDouble(DBFReadDoubleAttribute(handle, record,  
                                                               field));  
             break;  
         default:  
             PyErr_Format(PyExc_TypeError, "Invalid field data type %d",  
                          type);  
             value = NULL;  
         }  
     }  
     if (!value)  
         return NULL;  
10    
     return value;  
 }      
11    
12  /* the read_attribute method. Return the value of the given record and  /* allocator
13   * field as a python object of the appropriate type.  */
14   *  static PyObject* dbffile_new(PyTypeObject* type, PyObject* args, PyObject* kwds)
15   * In case of error, set a python exception and return NULL. Since that  {
16   * value will be returned to the python interpreter as is, the          DBFFileObject* self;    
17   * interpreter should recognize the exception.          self = (DBFFileObject*) type->tp_alloc(type, 0);
18   */          self->handle = NULL;
19            return (PyObject*) self;
20  static PyObject *  }
21  DBFInfo_read_attribute(DBFInfo * handle, int record, int field)  
 {  
     if (record < 0 || record >= DBFGetRecordCount(handle))  
     {  
         PyErr_Format(PyExc_ValueError,  
                      "record index %d out of bounds (record count: %d)",  
                      record, DBFGetRecordCount(handle));  
         return NULL;  
     }  
22    
     if (field < 0 || field >= DBFGetFieldCount(handle))  
     {  
         PyErr_Format(PyExc_ValueError,  
                      "field index %d out of bounds (field count: %d)",  
                      field, DBFGetFieldCount(handle));  
         return NULL;  
     }  
23    
24      return do_read_attribute(handle, record, field, NULL);  /* deallocator
25    */
26    static void dbffile_dealloc(DBFFileObject* self)
27    {
28            DBFClose(self->handle);
29            self->handle = NULL;
30            self->ob_type->tp_free((PyObject*)self);
31  }  }
       
32    
 /* the read_record method. Return the record record as a dictionary with  
  * whose keys are the names of the fields, and their values as the  
  * appropriate Python type.  
  *  
  * In case of error, set a python exception and return NULL. Since that  
  * value will be returned to the python interpreter as is, the  
  * interpreter should recognize the exception.  
  */  
   
 static PyObject *  
 DBFInfo_read_record(DBFInfo * handle, int record)  
 {  
     int num_fields;  
     int i;  
     int type, width;  
     char name[12];  
     PyObject *dict;  
     PyObject *value;  
   
     if (record < 0 || record >= DBFGetRecordCount(handle))  
     {  
         PyErr_Format(PyExc_ValueError,  
                      "record index %d out of bounds (record count: %d)",  
                      record, DBFGetRecordCount(handle));  
         return NULL;  
     }  
33    
     dict = PyDict_New();  
     if (!dict)  
         return NULL;  
           
     num_fields = DBFGetFieldCount(handle);  
     for (i = 0; i < num_fields; i++)  
     {  
         value = do_read_attribute(handle, record, i, name);  
         if (!value)  
             goto fail;  
   
         PyDict_SetItemString(dict, name, value);  
         Py_DECREF(value);  
     }  
   
     return dict;  
   
  fail:  
     Py_XDECREF(dict);  
     return NULL;  
 }  
   
 /* the write_record method. Write the record record given wither as a  
  * dictionary or a sequence (i.e. a list or a tuple).  
  *  
  * If it's a dictionary the keys must be the names of the fields and  
  * their value must have a suitable type. Only the fields actually  
  * contained in the dictionary are written. Fields for which there's no  
  * item in the dict are not modified.  
  *  
  * If it's a sequence, all fields must be present in the right order.  
  *  
  * In case of error, set a python exception and return NULL. Since that  
  * value will be returned to the python interpreter as is, the  
  * interpreter should recognize the exception.  
  *  
  * The method is implemented with two c-functions, write_field to write  
  * a single field and DBFInfo_write_record as the front-end.  
  */  
34    
35    /* constructor
36    */
37    static int dbffile_init(DBFFileObject* self, PyObject* args, PyObject* kwds)
38    {
39            char* file;
40            char* mode = "rb";
41            static char *kwlist[] = {"name", "mode", NULL};
42            if (!PyArg_ParseTupleAndKeywords(args, kwds, "et|s:__init__", kwlist,
43                    Py_FileSystemDefaultEncoding, &file, &mode)) return -1;
44            
45            self->handle = DBFOpen(file, mode);
46            PyMem_Free(file);
47            
48            return self->handle ? 0 : -1;
49    }
50    
 /* write a single field of a record. */  
 static int  
 write_field(DBFHandle handle, int record, int field, int type,  
             PyObject * value)  
 {  
     char * string_value;  
     int int_value;  
     double double_value;  
   
     if (value == Py_None)  
     {  
         if (!DBFWriteNULLAttribute(handle, record, field))  
         {  
             PyErr_Format(PyExc_IOError,  
                          "can't write NULL field %d of record %d",  
                          field, record);  
             return 0;  
         }  
     }  
     else  
     {  
         switch (type)  
         {  
         case FTString:  
             string_value = PyString_AsString(value);  
             if (!string_value)  
                 return 0;  
             if (!DBFWriteStringAttribute(handle, record, field, string_value))  
             {  
                 PyErr_Format(PyExc_IOError,  
                              "can't write field %d of record %d",  
                              field, record);  
                 return 0;  
             }  
             break;  
   
         case FTInteger:  
             int_value = PyInt_AsLong(value);  
             if (int_value == -1 && PyErr_Occurred())  
                 return 0;  
             if (!DBFWriteIntegerAttribute(handle, record, field, int_value))  
             {  
                 PyErr_Format(PyExc_IOError,  
                              "can't write field %d of record %d",  
                              field, record);  
                 return 0;  
             }  
             break;  
   
         case FTDouble:  
             double_value = PyFloat_AsDouble(value);  
             if (double_value == -1 && PyErr_Occurred())  
                 return 0;  
             if (!DBFWriteDoubleAttribute(handle, record, field, double_value))  
             {  
                 PyErr_Format(PyExc_IOError,  
                              "can't write field %d of record %d",  
                              field, record);  
                 return 0;  
             }  
             break;  
   
         default:  
             PyErr_Format(PyExc_TypeError, "Invalid field data type %d", type);  
             return 0;  
         }  
     }  
   
     return 1;  
 }  
   
 static  
 PyObject *  
 DBFInfo_write_record(DBFHandle handle, int record, PyObject *record_object)  
 {  
     int num_fields;  
     int i, length;  
     int type, width;  
     char name[12];  
     PyObject * value = NULL;  
   
     num_fields = DBFGetFieldCount(handle);  
   
     /* We used to use PyMapping_Check to test whether record_object is a  
      * dictionary like object instead of PySequence_Check to test  
      * whether it's a sequence. Unfortunately in Python 2.3  
      * PyMapping_Check returns true for lists and tuples too so the old  
      * approach doesn't work anymore.  
      */  
     if (PySequence_Check(record_object))  
     {  
         /* It's a sequence object. Iterate through all items in the  
          * sequence and write them to the appropriate field.  
          */  
         length = PySequence_Length(record_object);  
         if (length != num_fields)  
         {  
             PyErr_SetString(PyExc_TypeError,  
                             "record must have one item for each field");  
             goto fail;  
         }  
         for (i = 0; i < length; i++)  
         {  
             type = DBFGetFieldInfo(handle, i, name, &width, NULL);  
             value = PySequence_GetItem(record_object, i);  
             if (value)  
             {  
                 if (!write_field(handle, record, i, type, value))  
                     goto fail;  
                 Py_DECREF(value);  
             }  
             else  
             {  
                 goto fail;  
             }  
         }  
     }  
     else  
     {  
         /* It's a dictionary-like object. Iterate over the names of the  
          * known fields and write the corresponding item  
          */  
         for (i = 0; i < num_fields; i++)  
         {  
             type = DBFGetFieldInfo(handle, i, name, &width, NULL);  
51    
             /* if the dictionary has the key name write that object to  
              * the appropriate field, other wise just clear the python  
              * exception and do nothing.  
              */  
             value = PyMapping_GetItemString(record_object, name);  
             if (value)  
             {  
                 if (!write_field(handle, record, i, type, value))  
                     goto fail;  
                 Py_DECREF(value);  
             }  
             else  
             {  
                 PyErr_Clear();  
             }  
         }  
     }  
   
     Py_INCREF(Py_None);  
     return Py_None;  
   
  fail:  
     Py_XDECREF(value);  
     return NULL;  
 }  
 %}  
   
   
 /*  
  * The SWIG Interface definition.  
  */  
   
 /* include some common SWIG type definitions and standard exception  
    handling code */  
 %include typemaps.i  
 %include exception.i  
   
 /* As for ShapeFile in shapelib.i, We define a new C-struct that holds  
  * the DBFHandle. This is mainly done so we can separate the close()  
  * method from the destructor but it also helps with exception handling.  
  *  
  * After the DBFFile has been opened or created the handle is not NULL.  
  * The close() method closes the file and sets handle to NULL as an  
  * indicator that the file has been closed.  
  */  
52    
53  %{  static PyObject* dbffile_close(DBFFileObject* self)
54      typedef struct {  {
55          DBFHandle handle;          DBFClose(self->handle);
56      } DBFFile;          self->handle = NULL;
57  %}          Py_RETURN_NONE;
58    }
59    
60    
 /* The first argument to the DBFFile methods is a DBFFile pointer.  
  * We have to check whether handle is not NULL in most methods but not  
  * all. In the destructor and the close method, it's OK for handle to be  
  * NULL. We achieve this by checking whether the preprocessor macro  
  * NOCHECK_$name is defined. SWIG replaces $name with the name of the  
  * function for which the code is inserted. In the %{,%}-block below we  
  * define the macros for the destructor and the close() method.  
  */  
61    
62  %typemap(python,check) DBFFile *{  static PyObject* dbffile_field_count(DBFFileObject* self)
63  %#ifndef NOCHECK_$name  {
64      if (!$target || !$target->handle)          return PyInt_FromLong((long)DBFGetFieldCount(self->handle));
         SWIG_exception(SWIG_TypeError, "dbffile already closed");  
 %#endif  
65  }  }
66    
 %{  
 #define NOCHECK_delete_DBFFile  
 #define NOCHECK_DBFFile_close  
 %}  
67    
68    
69  /* An exception handle for the constructor and the module level open()  static PyObject* dbffile_record_count(DBFFileObject* self)
70   * and create() functions.  {
71   *          return PyInt_FromLong((long)DBFGetRecordCount(self->handle));
  * Annoyingly, we *have* to put braces around the SWIG_exception()  
  * calls, at least in the python case, because of the way the macro is  
  * written. Of course, always putting braces around the branches of an  
  * if-statement is often considered good practice.  
  */  
 %typemap(python,except) DBFFile * {  
     $function;  
     if (!$source)  
     {  
         SWIG_exception(SWIG_MemoryError, "no memory");  
     }  
     else if (!$source->handle)  
     {  
         SWIG_exception(SWIG_IOError, "$name failed");  
     }  
72  }  }
73    
74  /* Exception handler for the add_field method */  
75  %typemap(python,except) int DBFFile_add_field {  
76      $function;  static PyObject* dbffile_field_info(DBFFileObject* self, PyObject* args)
77      if ($source < 0)  {
78      {          char field_name[12];
79          SWIG_exception(SWIG_RuntimeError, "add_field failed");          int field, width = 0, decimals = 0, field_type;
80      }          
81            if (!PyArg_ParseTuple(args, "i:field_info", &field)) return NULL;
82            
83            field_name[0] = '\0';
84            field_type = DBFGetFieldInfo(self->handle, field, field_name, &width, &decimals);
85            
86            return Py_BuildValue("isii", field_type, field_name, width, decimals);
87  }  }
88    
 /* define and use some typemaps for the field_info() method whose  
  * C-implementation has three output parameters that are returned  
  * through pointers passed into the function. SWIG already has  
  * definitions for common types such as int* and we can use those for  
  * the last two parameters:  
  */  
89    
 %apply int * OUTPUT { int * output_width }  
 %apply int * OUTPUT { int * output_decimals }  
90    
91  /* the fieldname has to be defined manually: */  static PyObject* dbffile_add_field(DBFFileObject* self, PyObject* args)
92  %typemap(python,ignore) char *fieldname_out(char temp[12]) {  {
93      $target = temp;          char* name;
94            int type, width, decimals;
95            int field;
96            
97            if (!PyArg_ParseTuple(args, "siii:add_field", &name, &type, &width, &decimals)) return NULL;
98            
99            field = DBFAddField(self->handle, name, (DBFFieldType)type, width, decimals);
100            
101            if (field < 0)
102            {
103                    PyErr_SetString(PyExc_ValueError, "Failed to add field due to inappropriate field definition");
104                    return NULL;
105            }
106            return PyInt_FromLong((long)field);
107  }  }
108    
 %typemap(python,argout) char *fieldname_out() {  
     PyObject * string = PyString_FromString($source);  
     $target = t_output_helper($target,string);  
 }  
109    
110    
111    /* Read one attribute from the dbf handle and return it as a new python object
112    *
113    * If an error occurs, set the appropriate Python exception and return
114    * NULL.
115    *
116    * Assume that the values of the record and field arguments are valid.
117    * The name argument will be passed to DBFGetFieldInfo as is and should
118    * thus be either NULL or a pointer to an array of at least 12 chars
119    */
120    static PyObject* do_read_attribute(DBFHandle handle, int record, int field, char * name)
121    {
122            int type, width;
123            const char* temp;
124            type = DBFGetFieldInfo(handle, field, name, &width, NULL);
125            
126            /* For strings NULL and the empty string are indistinguishable
127            * in DBF files. We prefer empty strings instead for backwards
128            * compatibility reasons because older wrapper versions returned
129            * emtpy strings as empty strings.
130            */
131            if (type != FTString && DBFIsAttributeNULL(handle, record, field))
132            {
133                    Py_RETURN_NONE;
134            }
135            else
136            {
137                    switch (type)
138                    {
139                    case FTString:
140                            temp = DBFReadStringAttribute(handle, record, field);
141                            if (temp) return PyString_FromString(temp);
142    
143                    case FTInteger:
144                            return PyInt_FromLong((long)DBFReadIntegerAttribute(handle, record, field));
145    
146                    case FTDouble:
147                            return PyFloat_FromDouble(DBFReadDoubleAttribute(handle, record, field));
148                            
149                    case FTLogical:
150                            temp = DBFReadLogicalAttribute(handle, record, field);
151                            if (temp)
152                            {
153                                    switch (temp[0])
154                                    {
155                                    case 'F':
156                                    case 'N':
157                                            Py_RETURN_FALSE;
158                                    case 'T':
159                                    case 'Y':
160                                            Py_RETURN_TRUE;
161                                    }
162                            }
163                            break;
164    
165                    default:
166                            PyErr_Format(PyExc_TypeError, "Invalid field data type %d", type);
167                            return NULL;
168                    }
169            }
170            
171            PyErr_Format(PyExc_IOError,     "Can't read value for row %d column %d", record, field);
172            return NULL;
173    }    
174    
 /*  
  * The SWIG-version of the DBFFile struct  
  */  
175    
176  typedef struct  
177    /* the read_attribute method. Return the value of the given record and
178    * field as a python object of the appropriate type.
179    */
180    static PyObject* dbffile_read_attribute(DBFFileObject* self, PyObject* args)
181  {  {
182      %addmethods {          int record, field;
183          DBFFile(const char *file, const char * mode = "rb") {  
184              DBFFile * self = malloc(sizeof(DBFFile));          if (!PyArg_ParseTuple(args, "ii:read_field", &record, &field)) return NULL;
185              if (self)          
186                  self->handle = DBFOpen(file, mode);          if (record < 0 || record >= DBFGetRecordCount(self->handle))
187              return self;          {
188          }                  PyErr_Format(PyExc_ValueError,
189                                                "record index %d out of bounds (record count: %d)",
190          ~DBFFile() {                                  record, DBFGetRecordCount(self->handle));
191              if (self->handle)                  return NULL;
                 DBFClose(self->handle);  
             free(self);  
192          }          }
193    
194          void close() {          if (field < 0 || field >= DBFGetFieldCount(self->handle))
195              if (self->handle)          {
196                  DBFClose(self->handle);                  PyErr_Format(PyExc_ValueError,
197              self->handle = NULL;                                  "field index %d out of bounds (field count: %d)",
198                                    field, DBFGetFieldCount(self->handle));
199                    return NULL;
200          }          }
201    
202          int field_count() {          return do_read_attribute(self->handle, record, field, NULL);
203              return DBFGetFieldCount(self->handle);  }
204    
205    
206    
207    /* the read_record method. Return the record record as a dictionary with
208    * whose keys are the names of the fields, and their values as the
209    * appropriate Python type.
210    */
211    static PyObject* dbffile_read_record(DBFFileObject* self, PyObject* args)
212    {
213            int record;
214            int num_fields;
215            int i;
216            char name[12];
217            PyObject *dict;
218            PyObject *value = NULL;
219    
220            if (!PyArg_ParseTuple(args, "i:read_record", &record)) return NULL;
221    
222            if (record < 0 || record >= DBFGetRecordCount(self->handle))
223            {
224                    PyErr_Format(PyExc_ValueError,
225                            "record index %d out of bounds (record count: %d)",
226                            record, DBFGetRecordCount(self->handle));
227                    return NULL;
228          }          }
229    
230          int record_count() {          dict = PyDict_New();
231              return DBFGetRecordCount(self->handle);          if (!dict) return NULL;
232            
233            num_fields = DBFGetFieldCount(self->handle);
234            for (i = 0; i < num_fields; i++)
235            {
236                    value = do_read_attribute(self->handle, record, i, name);
237                    if (!value || PyDict_SetItemString(dict, name, value) < 0) goto fail;
238                    Py_DECREF(value);
239                    value = NULL;
240          }          }
241    
242          int field_info(int iField, char * fieldname_out,          return dict;
243                         int * output_width, int * output_decimals) {  
244              return DBFGetFieldInfo(self->handle, iField, fieldname_out,  fail:
245                                     output_width, output_decimals);          Py_XDECREF(value);
246            Py_DECREF(dict);
247            return NULL;
248    }
249    
250    
251    
252    /* write a single field of a record. */
253    static int do_write_field(DBFHandle handle, int record, int field, int type, PyObject* value)
254    {
255            char * string_value;
256            int int_value;
257            double double_value;
258            int logical_value;
259    
260            if (value == Py_None)
261            {
262                    if (DBFWriteNULLAttribute(handle, record, field)) return 1;
263          }          }
264                        else
265          PyObject * read_record(int record) {          {
266              return DBFInfo_read_record(self->handle, record);                  switch (type)
267                    {
268                    case FTString:
269                            string_value = PyString_AsString(value);
270                            if (!string_value) return 0;
271                            if (DBFWriteStringAttribute(handle, record, field, string_value)) return 1;
272                            break;
273    
274                    case FTInteger:
275                            int_value = PyInt_AsLong(value);
276                            if (int_value == -1 && PyErr_Occurred()) return 0;
277                            if (DBFWriteIntegerAttribute(handle, record, field, int_value)) return 1;
278                            break;
279    
280                    case FTDouble:
281                            double_value = PyFloat_AsDouble(value);
282                            if (double_value == -1 && PyErr_Occurred()) return 0;
283                            if (DBFWriteDoubleAttribute(handle, record, field, double_value)) return 1;
284                            break;
285                            
286                    case FTLogical:
287                            logical_value = PyObject_IsTrue(value);
288                            if (logical_value == -1) return 0;
289                            if (DBFWriteLogicalAttribute(handle, record, field, logical_value ? 'T' : 'F')) return 1;
290                            break;
291    
292                    default:
293                            PyErr_Format(PyExc_TypeError, "Invalid field data type %d", type);
294                            return 0;
295                    }
296          }          }
297    
298          PyObject * read_attribute(int record, int field) {          PyErr_Format(PyExc_IOError,     "can't write field %d of record %d", field, record);
299              return DBFInfo_read_attribute(self->handle, record, field);          return 0;
300          }  }
301    
302    
303    
304          int add_field(const char * pszFieldName, DBFFieldType eType,  static PyObject* dbffile_write_field(DBFFileObject* self, PyObject* args)
305                        int nWidth, int nDecimals) {  {
306              return DBFAddField(self->handle, pszFieldName, eType, nWidth,          int record, field;
307                                 nDecimals);          PyObject* value;
308            int type;
309    
310            if (!PyArg_ParseTuple(args, "iiO:write_field", &record, &field, &value)) return NULL;
311            
312            if (field < 0 || field >= DBFGetFieldCount(self->handle))
313            {
314                    PyErr_Format(PyExc_ValueError,
315                                    "field index %d out of bounds (field count: %d)",
316                                    field, DBFGetFieldCount(self->handle));
317                    return NULL;
318          }          }
319    
320          PyObject *write_record(int record, PyObject *dict_or_sequence) {          type = DBFGetFieldInfo(self->handle, field, NULL, NULL, NULL);
321              return DBFInfo_write_record(self->handle, record,          if (!do_write_field(self->handle, record, field, type, value)) return NULL;
322                                          dict_or_sequence);          Py_RETURN_NONE;
323    }
324    
325    
326    
327    static PyObject* dbffile_write_record(DBFFileObject* self, PyObject* args)
328    {
329            int record;
330            PyObject* record_object;
331            int i, num_fields;
332            
333            int type;
334            char name[12];
335            PyObject* value = NULL;
336            
337            if (!PyArg_ParseTuple(args, "iO:write_record", &record, &record_object)) return NULL;
338            
339            num_fields = DBFGetFieldCount(self->handle);
340            
341            /* mimic ShapeFile functionality where id = -1 means appending */
342            if (record == -1)
343            {
344                    record = num_fields;
345          }          }
346    
347          int commit() {          if (PySequence_Check(record_object))
348              return DBFCommit(self->handle);          {
349                    /* It's a sequence object. Iterate through all items in the
350                    * sequence and write them to the appropriate field.
351                    */
352                    if (PySequence_Length(record_object) != num_fields)
353                    {
354                            PyErr_SetString(PyExc_TypeError, "record must have one item for each field");
355                            return NULL;
356                    }
357                    for (i = 0; i < num_fields; ++i)
358                    {
359                            type = DBFGetFieldInfo(self->handle, i, NULL, NULL, NULL);
360                            value = PySequence_GetItem(record_object, i);
361                            if (!value) return NULL;
362                            if (!do_write_field(self->handle, record, i, type, value))
363                            {
364                                    Py_DECREF(value);
365                                    return NULL;
366                            }
367                            Py_DECREF(value);
368                    }
369            }
370            else
371            {
372                    /* It's a dictionary-like object. Iterate over the names of the
373                    * known fields and write the corresponding item
374                    */
375                    for (i = 0; i < num_fields; ++i)
376                    {
377                            name[0] = '\0';
378                            type = DBFGetFieldInfo(self->handle, i, name, NULL, NULL);
379                            value = PyDict_GetItemString(record_object, name);
380                            if (value && !do_write_field(self->handle, record, i, type, value)) return NULL;
381                    }
382          }          }
383            
384            return PyInt_FromLong((long)record);
385    }
386    
     }  
 } DBFFile;  
387    
388    
389  /*  static PyObject* dbffile_repr(DBFFileObject* self)
390   * Two module level functions, open() and create() that correspond to  {
391   * DBFOpen and DBFCreate respectively. open() is equivalent to the          /* TODO: it would be nice to do something like "dbflib.DBFFile(filename, mode)" instead */
392   * DBFFile constructor.          return PyString_FromFormat("<dbflib.DBFFile object at %p>", self->handle);
393   */  }
394    
395    
 %{  
     DBFFile * open_DBFFile(const char * file, const char * mode)  
     {  
         DBFFile * self = malloc(sizeof(DBFFile));  
         if (self)  
             self->handle = DBFOpen(file, mode);  
         return self;  
     }  
 %}  
396    
397  %name(open) %new DBFFile * open_DBFFile(const char * file,  /* The commit method implementation
398                                          const char * mode = "rb");  *
399    * The method relies on the DBFUpdateHeader method which is not
400    * available in shapelib <= 1.2.10.  setup.py defines
401    * HAVE_UPDATE_HEADER's value depending on whether the function is
402    * available in the shapelib version the code is compiled with.
403    */
404    #if HAVE_UPDATE_HEADER
405    static PyObject* dbffile_commit(DBFFileObject* self)
406    {
407            DBFUpdateHeader(self->handle);
408            Py_RETURN_NONE;
409    }
410    #endif
411    
412  %{  
413      DBFFile * create_DBFFile(const char * file)  
414      {  static struct PyMethodDef dbffile_methods[] =
415          DBFFile * self = malloc(sizeof(DBFFile));  {
416          if (self)          {"close", (PyCFunction)dbffile_close, METH_NOARGS,
417              self->handle = DBFCreate(file);                  "close() -> None\n\n"
418          return self;                  "closes DBFFile"},
419      }          {"field_count", (PyCFunction)dbffile_field_count, METH_NOARGS,
420  %}                  "field_count() -> integer\n\n"
421  %name(create) %new DBFFile * create_DBFFile(const char * file);                  "returns number of fields currently defined"},
422            {"record_count", (PyCFunction)dbffile_record_count, METH_NOARGS,
423                    "record_count() -> integer\n\n"
424                    "returns number of records that currently exist"},
425            {"field_info", (PyCFunction)dbffile_field_info, METH_VARARGS,
426                    "field_info(field_index) -> (type, name, width, decimals)\n\n"
427                    "returns info of a field as a tuple with:\n"
428                    "- type: the type of the field corresponding to the integer value of one "
429                    " of the constants FTString, FTInteger, ...\n"
430                    "- name: the name of the field as a string\n"
431                    "- width: the width of the field as a number of characters\n"
432                    "- decimals: the number of decimal digits" },
433            {"add_field", (PyCFunction)dbffile_add_field, METH_VARARGS,
434                    "add_field(type, name, width, decimals) -> field_index\n\n"
435                    "adds a new field and returns field index if successful\n"
436                    "- type: the type of the field corresponding to the integer value of one "
437                    " of the constants FTString, FTInteger, ...\n"
438                    "- name: the name of the field as a string\n"
439                    "- width: the width of the field as a number of characters\n"
440                    "- decimals: the number of decimal digits" },
441            {"read_attribute", (PyCFunction)dbffile_read_attribute, METH_VARARGS,
442                    "read_attribute(record_index, field_index) -> value\n\n"
443                    "returns the value of one field of a record"},
444            {"read_record", (PyCFunction)dbffile_read_record, METH_VARARGS,
445                    "read_record(record_index) -> dict\n\n"
446                    "returns an entire record as a dictionary of field names and values"},
447            {"write_field", (PyCFunction)dbffile_write_field, METH_VARARGS,
448                    "write_field(record_index, field_index, new_value)\n"
449                    "writes a single field of a record"},
450            {"write_record", (PyCFunction)dbffile_write_record, METH_VARARGS,
451                    "write_record(record_index, record) -> record_index\n\n"
452                    "Writes an entire record as a dict or a sequence, and return index of record\n"
453                    "Record can either be a dictionary in which case the keys are used as field names, "
454                    "or a sequence that must have an item for every field (length = field_count())"},
455    #if HAVE_UPDATE_HEADER
456            {"commit", (PyCFunction)dbffile_read_record, METH_NOARGS,
457                    "commit() -> None"},
458    #endif
459            {NULL}
460    };
461    
462    
463    
464    static struct PyGetSetDef dbffile_getsetters[] =
465    {
466            {NULL}
467    };
468    
469    
470    
471    static PyTypeObject DBFFileType = PYSHAPELIB_DEFINE_TYPE(DBFFileObject, dbffile, "shapelib.DBFFile", 0);
472    
473    
474    
475  /* constant definitions copied from shapefil.h */  /* --- dbflib -------------------------------------------------------------------------------------------------------- */
476  typedef enum {  
477    FTString,  static PyObject* dbflib_open(PyObject* module, PyObject* args)
478    FTInteger,  {
479    FTDouble,          return PyObject_CallObject((PyObject*)&DBFFileType, args);
480    FTInvalid  }
481  } DBFFieldType;  
482    
483    
484    static PyObject* dbflib_create(PyObject* module, PyObject* args)
485    {
486            char* file;
487            DBFFileObject* result;
488            
489            if (!PyArg_ParseTuple(args, "et:create", Py_FileSystemDefaultEncoding, &file)) return NULL;
490            
491            result = PyObject_New(DBFFileObject, &DBFFileType);
492            if (!result)
493            {
494                    return PyErr_NoMemory();
495            }
496            
497            result->handle = DBFCreate(file);
498            if (!result->handle)
499            {
500                    PyObject_Del((PyObject*)result);
501                    PyErr_SetString(PyExc_RuntimeError, "Failed to create DBFFile");
502                    return NULL;
503            }
504            
505            return (PyObject*) result;
506    }
507    
508    
509    
510    static struct PyMethodDef dbflib_methods[] =
511    {
512            {"open", (PyCFunction)dbflib_open, METH_VARARGS,
513                    "open(name [, mode]) -> DBFFile\n\n"
514                    "opens a DBFFile" },
515            {"create", (PyCFunction)dbflib_create, METH_VARARGS,
516                    "create(name) -> DBFFile\n\n"
517                    "create a DBFFile" },
518            {NULL}
519    };
520    
521    
522    
523    PyMODINIT_FUNC initdbflib(void)
524    {
525            PyObject* module = Py_InitModule("dbflib", dbflib_methods);
526            if (!module) return;
527            
528            PYSHAPELIB_ADD_TYPE(DBFFileType, "DBFFile");
529            
530            PYSHAPELIB_ADD_CONSTANT(FTString);
531            PYSHAPELIB_ADD_CONSTANT(FTInteger);
532            PYSHAPELIB_ADD_CONSTANT(FTDouble);
533            PYSHAPELIB_ADD_CONSTANT(FTLogical);
534            PYSHAPELIB_ADD_CONSTANT(FTInvalid);
535            PyModule_AddIntConstant(module, "_have_commit", HAVE_UPDATE_HEADER);
536    }

Legend:
Removed from v.1917  
changed lines
  Added in v.2745

[email protected]
ViewVC Help
Powered by ViewVC 1.1.26