On 31-10-2010 13:43, mdipierro wrote:
> Can you explain the purpose?
I want to convert my old desktop applications to DAL,
with the minimal effort and even more important:
with a minimal chance of breaking some of the existing code.

Converting to DAL , I think of the following advantages:
1. DAL makes it much easier to maintain the code (compared to scattered SQL)
2. I can easily switch to another database, without the need for changing the 
code
3. for the future it should be much easier to move these desktop application to 
web applications

So the derived database / table classes (or whatever objects they are),
should combine my old methods, with the new DAL methods.

At the moment I've the code working, very ugly,
so maybe one of you might have suggestions fro improvement.
see code below,

thanks,
Stef Mientki


# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import __init__


# ****************************************************************
# Table Definitions
# ****************************************************************
_Afdeling_Table_Def = """
AID              integer  not null  primary key autoincrement
Name             text     not null  unique
"""

# ****************************************************************
# Some intial values for database tables
# ****************************************************************
Afdelingen = """
Medische Psychologie
SVB-ID
"""


# ****************************************************************
# import web2py libs ( not necessary, when web2py is properly istalled)
# ****************************************************************
import sys
sys.path.append ( r'P:\Web2PY\web2py_src\web2py' )
from gluon.sql import DAL, Field, Table, SQLDB



# ***********************************************************************
# ***********************************************************************
class _DAL_DB ( object ) :
  """
This class combines the old methods with the new DAL DB methods.
This class should be initiated with the function "DAL_DB".
  """
  # store variables in memory
  def __init__ ( self, DB ) :
    self.My_DB = DB

  # The old Close method
  def Close ( self ) :
    self.My_DB.close_all_instances ( SQLDB.commit )

def DAL_DB ( Database_Name ) :
  # Create and connect to the database
  My_DB = DAL ( 'sqlite://' + DataBase_Name )

  # store Database in a class
  Create_a_Class = _DAL_DB ( My_DB )

  # Convert DAL methods to old methods and add them to the database
  My_DB.Close = Create_a_Class.Close

  # return the (extended) DAL database
  return My_DB
# ***********************************************************************


# ***********************************************************************
# ***********************************************************************
class DAL_Table ( Table ) :
  """
This class combines the old methods and the new methods of a DAL Table.
  """
  def __init__ ( self, DB, Name, Defs, Drop = False, Mod_Table = False ) :
    # **********************************************
    # Convert the old table definitions into Wbe2Py definitions
    # **********************************************
    Fields = []
    Defs = Defs.splitlines ()
    for Line in Defs :
      Line = Line .strip ()
      if Line :
        line = Line.lower()
        print line
        if not ( ( 'primary' in line ) and ( 'key' in line ) ) :
          Parts = Line.split ()
          FParts = [ Parts[0], Parts[1].lower() ]
          FLine = "Field ( '" + Parts[0] + "','" + Parts[1].lower() + "'"
          if ( 'not ' in line ) and ( ' null' in line ) :
            FLine += ',notnull = True'
          if ( ' unique' in line ) :
            FLine += ',unique = True'
          FLine += ')'
          print FLine
          Fields.append ( eval ( FLine ) )

    # **********************************************
    # Create the web2py table
    # **********************************************
    print 'Define Table', Name, Fields
    #Table.__init__ ( self, DB, Name, *Fields, migrate = Name + '.table' )
    self.My_Table = DB.define_table ( Name, *Fields, migrate = Name + '.table' )

  # **********************************************
  # Replicate all the Web2Py table methods
  # here only insert is done as an example
  # **********************************************
  def insert ( self, *args, **kwargs ) :
    self.My_Table.insert ( *args, **kwargs )

  # **********************************************
  def Insert_Records_from_String ( self, Lines, Auto = False ) :
    """
Inserting of a number of records from a multiline string,
where each line represents a record.
Fields are separated by a '|'.
    """
    #Record = self.Get_New_Dict ()
    Lines = Lines.splitlines()
    for Line in Lines :
      if Line.strip() :
        Parts = Line.split ( '|' )
        #print 'String Insert:',self.Table_Name, Parts
        # Strings starting with '#' ar assumed comments and ignored
        if not ( Parts[0].startswith ( '#' ) ) :
          for i in range ( len ( Parts ) ) :
            Parts[i] = Parts[i].strip()
          '''
          if Auto :
            self.Insert_Auto ( Parts )
          else :
            self.Insert ( Parts )
          '''

          # for some strange reason, unicode strings can't be unpacked !!
          # we always ignore the "id"-field
          KWs = self.My_Table.fields [1:] #self.Def_PKs:]
          MD = {}
          for KW, Value in zip ( KWs, Parts ) :
            MD [ str ( KW ) ] = Value
          print 'INSERT', self.My_Table._tablename, MD
          self.My_Table.insert ( **MD )
# ***********************************************************************


# ***********************************************************************
# ***********************************************************************
if __name__ == '__main__':

  # Create a DAL database with the old method
  #DataBase_Name = r'D:\Data_Python_25\Beheer\ID_TO_Beheer_DAL.db'
  DataBase_Name = 'ID_TO_Beheer_DAL.db'
  DB = DAL_DB ( 'sqlite://' + DataBase_Name )


  # Test the old method to create a table
  Drop      = False
  Mod_Table = False #True
  Afdeling_Table = DAL_Table ( DB, 'Afdeling', _Afdeling_Table_Def,
                                 Drop = Drop, Mod_Table = Mod_Table )

  # print some DAL Database information
  print 'Database Name :', DB._uri
  print 'Database Type :', DB._dbname
  print 'Tables        :', DB.tables

  for Table_Name in DB.tables :
    print '====', Table_Name, '===='
    Table = DB [ Table_Name ]
    for Field_Name in Table.fields :
      Field = Table [ Field_Name ]
      line = '   %-15s' %( Field_Name )
      line += '%-10s' % ( Field.type )
      line += '%-10i' % ( Field.length )
      if Field.notnull :
        line += '   Not Null'
      if Field.unique :
        line += '   Unique'
      print line

  # Store some default values in a DAL Table
  Afdeling_Table.Insert_Records_from_String ( Afdelingen )

  # Test DAL Table insert method
  Afdeling_Table.insert ( Name = 'Oncologie' )

  # Test old Database method
  DB.Close ()



>  You can create a derivative class of
> Table (is it just a table) but this is not the same as model
> inheritance in ORMs, becuase tables (lower case) are not classes in
> DAL. To do model inheritance
>
> db.define_table('a',*fields)
> db.define_table('b',db.a,*other_fields)
>
> On 31 oct, 04:11, Stef Mientki <stef.mien...@gmail.com> wrote:
>> hello,
>>
>> I'ld like to derive a new class from Table
>> (if it succeeds, I can integrate DAL into my existing programs, without 
>> changing anything, except
>> adding an import statement)
>>
>> This seems to be the obvious way,
>> the problem is that although a table seems to be created,
>> the Table is not attached to the database.
>> So writing to the database disappears in the universe.
>>
>> class DAL_Table ( Table ) :
>>     def __init__ ( self, DB, Name, Defs, Drop = False, Mod_Table = False ) :
>>         ... do my preprocessing, generate Fields
>>         Table.__init__ ( self, DB, Name, *Fields, migrate = Name + '.table' )
>>
>> This ones create a table attached to a database,
>> but the DAL_Table doesn't hace the properties of Table
>> class DAL_Table ( object ) :
>>     def __init__ ( self, DB, Name, Defs, Drop = False, Mod_Table = False ) :
>>         ... do my preprocessing, generate Fields
>>         My_Table = DB.define+table ( Name, *Fields, migrate = Name + 
>> '.table' )
>>         ... but now DAL_Table doesn't have the properties of Table
>>
>> thanks,
>> Stef Mientki

Reply via email to