Package sage :: Package databases :: Module database :: Class GenericSQLDatabase
[hide private]
[frames] | no frames]

Class GenericSQLDatabase

source code

                      object --+    
                               |    
structure.sage_object.SageObject --+
                                   |
                                  GenericSQLDatabase
Known Subclasses:
graphs.graph_database.GraphDatabase, SQLDatabase


*Immutable* Database class.

INPUT:
    filename -- where to load the database from

TUTORIAL:
The SQLDatabase class is for interactively building databases intended for
queries. This may sound redundant, but it is important. If you want a
database intended for quick lookup of entries in very large tables, much
like a hash table (such as a Python dictionary), a SQLDatabase may not be
what you are looking for. The strength of SQLDatabases is in queries,
searches through the database with complicated criteria.

The class GenericSQLDatabase is for developers to provide a static
database. The class does not support modification, and is meant to be a
base class for specific classes of databases, such as the graph database.

For example, we create a new database for storing isomorphism classes of
simple graphs:
    sage: D = SQLDatabase()

In order to generate representatives for the classes, we will import a
function which generates all labeled graphs (noting that this is not the
optimal way):
    sage: from sage.graphs.graph_isom import all_labeled_graphs

We will need a table in the database in which to store the graphs, and we
specify its structure with a Python dictionary, each of whose keys is the
name of a column:
    sage: table_skeleton = {
    ... 'graph6':{'sql':'TEXT', 'index':True, 'primary_key':True},
    ... 'vertices':{'sql':'INTEGER'},
    ... 'edges':{'sql':'INTEGER'}
    ... }

Then we create the table:
    sage: D.create_table('simon', table_skeleton)
    sage: D.show('simon')
    edges                graph6               vertices            
    ------------------------------------------------------------

Now that we have the table, we will begin to populate the table with
rows. First, add the graph on zero vertices.
    sage: G = Graph()
    
    sage: D.add_row('simon',(0, G.graph6_string(), 0))
    
    sage: D.show('simon')
    edges                graph6               vertices            
    ------------------------------------------------------------
    0                    ?                    0                   

Next, add the graph on one vertex.
    sage: G.add_vertex()
    sage: D.add_row('simon',(0, G.graph6_string(), 1))
    sage: D.show('simon')
    edges                graph6               vertices            
    ------------------------------------------------------------
    0                    ?                    0                   
    0                    @                    1                   

Say we want a database of graphs on four or less vertices:
    sage: labels = {}
    sage: for i in range(2, 5):
    ...       labels[i] = []
    ...       for g in all_labeled_graphs(i):
    ...           g = g.canonical_label()
    ...           if g not in labels[i]:
    ...               labels[i].append(g)
    ...               D.add_row('simon', (g.size(), g.graph6_string(), g.order()))
    ...             
    sage: D.show('simon')
    edges                graph6               vertices            
    ------------------------------------------------------------
    0                    ?                    0                   
    0                    @                    1                   
    0                    A?                   2                   
    1                    A_                   2                   
    0                    B?                   3                   
    1                    BG                   3                   
    2                    BW                   3                   
    3                    Bw                   3                   
    0                    C?                   4                   
    1                    C@                   4                   
    2                    CB                   4                   
    3                    CF                   4                   
    3                    CJ                   4                   
    2                    CK                   4                   
    3                    CL                   4                   
    4                    CN                   4                   
    4                    C]                   4                   
    5                    C^                   4                   
    6                    C~                   4                   

We can then query the database-- let's ask for all the graphs on four
vertices with three edges. We do so by creating two queries and asking for
rows that satisfy them both:
    sage: Q = SQLQuery(D, {'table_name':'simon', 'display_cols':['graph6'], 'expression':['vertices','=',4]})
    sage: Q2 = SQLQuery(D, {'table_name':'simon', 'display_cols':['graph6'], 'expression':['edges','=',3]})
    sage: Q = Q.intersect(Q2)
    sage: Q.run_query()
    [(u'CF', u'CF'), (u'CJ', u'CJ'), (u'CL', u'CL')]

NOTE - The values of display_cols are always concatenated in intersections
and unions.

Of course, we can save the database to file:
    sage: D.save('simon.db')

Now the database's hard link is to this file, and not the temporary db
file. For example, let's say we open the same file with another class
instance. We can load the file as an immutable database:
    sage: E = GenericSQLDatabase('simon.db')
    sage: E.show('simon')
    edges                graph6               vertices            
    ------------------------------------------------------------
    0                    ?                    0                   
    0                    @                    1                   
    0                    A?                   2                   
    1                    A_                   2                   
    0                    B?                   3                   
    1                    BG                   3                   
    2                    BW                   3                   
    3                    Bw                   3                   
    0                    C?                   4                   
    1                    C@                   4                   
    2                    CB                   4                   
    3                    CF                   4                   
    3                    CJ                   4                   
    2                    CK                   4                   
    3                    CL                   4                   
    4                    CN                   4                   
    4                    C]                   4                   
    5                    C^                   4                   
    6                    C~                   4                   
    sage: E.drop_table('simon')
    Traceback (most recent call last):
    ...
    AttributeError: 'GenericSQLDatabase' object has no attribute 'drop_table'
    



Instance Methods [hide private]
 
__init__(self, filename)
x.__init__(...) initializes x; see x.__class__.__doc__ for signature
source code
 
__repr__(self)
File: sage/structure/sage_object.pyx (starting at line 86)
source code
 
copy(self)
Returns an instance of SQLDatabase that points to a copy database, and allows modification.
source code
 
save(self, filename)
Save the database to the specified location.
source code
 
get_skeleton(self, check=False)
Returns a dictionary representing the hierarchical structure of the database, in the following format.
source code
 
show(self, table_name, max_field_size=20, html_table=False)
Show an entire table from the database.
source code

Inherited from structure.sage_object.SageObject: __hash__, __new__, _axiom_, _axiom_init_, _gap_, _gap_init_, _gp_, _gp_init_, _interface_, _interface_init_, _interface_is_cached_, _kash_, _kash_init_, _macaulay2_, _macaulay2_init_, _magma_, _magma_init_, _maple_, _maple_init_, _mathematica_, _mathematica_init_, _maxima_, _maxima_init_, _octave_, _octave_init_, _pari_, _pari_init_, _r_init_, _sage_, _singular_, _singular_init_, category, db, dump, dumps, plot, rename, reset_name, version

Inherited from object: __delattr__, __getattribute__, __reduce__, __reduce_ex__, __setattr__, __str__

Properties [hide private]

Inherited from object: __class__

Method Details [hide private]

__init__(self, filename)
(Constructor)

source code 
x.__init__(...) initializes x; see x.__class__.__doc__ for signature

Overrides: object.__init__
(inherited documentation)

__repr__(self)
(Representation operator)

source code 
File: sage/structure/sage_object.pyx (starting at line 86)

Overrides: structure.sage_object.SageObject.__repr__
(inherited documentation)

copy(self)

source code 

Returns an instance of SQLDatabase that points to a copy database,
and allows modification.

EXAMPLES:
    sage: DB = SQLDatabase()
    sage: DB.create_table('lucy',{'id':{'sql':'INTEGER', 'primary_key':True, 'index':True},'a1':{'sql':'bool','primary_key':False}, 'b2':{'sql':'int', 'primary_key':False}})
    sage: DB.add_rows('lucy', [(0,1,1),(1,1,4),(2,0,7),(3,1,384),(4,1,978932)],['id','a1','b2'])
    sage: d = DB.copy()
    
    sage: d.show('lucy')
    a1                   id                   b2                  
    ------------------------------------------------------------
    1                    0                    1                   
    1                    1                    4                   
    0                    2                    7                   
    1                    3                    384                 
    1                    4                    978932              
    
    sage: DB.show('lucy')
    a1                   id                   b2                  
    ------------------------------------------------------------
    1                    0                    1                   
    1                    1                    4                   
    0                    2                    7                   
    1                    3                    384                 
    1                    4                    978932              
    
    sage: Q = SQLQuery(DB, {'table_name':'lucy', 'display_cols':['id','a1','b2'], 'expression':['id','>=',3]})
    sage: DB.delete_rows(Q)
    sage: DB.show('lucy')
    a1                   id                   b2                  
    ------------------------------------------------------------
    1                    0                    1                   
    1                    1                    4                   
    0                    2                    7                   
    
    sage: d.show('lucy')
    a1                   id                   b2                  
    ------------------------------------------------------------
    1                    0                    1                   
    1                    1                    4                   
    0                    2                    7                   
    1                    3                    384                 
    1                    4                    978932

save(self, filename)

source code 

Save the database to the specified location.

EXAMPLE:
    sage: MonicPolys = SQLDatabase()
    sage: MonicPolys.create_table('simon', {'n':{'sql':'INTEGER', 'index':True}})
    sage: for n in range(20):
    ...     MonicPolys.add_row('simon', (n,))
    ...     
    sage: MonicPolys.save('sage.db')
    sage: N = GenericSQLDatabase('sage.db')
    sage: N.show('simon')
    n                   
    --------------------
    0                   
    1                   
    2                   
    3                   
    4                   
    5                   
    6                   
    7                   
    8                   
    9                   
    10                  
    11                  
    12                  
    13                  
    14                  
    15                  
    16                  
    17                  
    18                  
    19                  

Overrides: structure.sage_object.SageObject.save

get_skeleton(self, check=False)

source code 

Returns a dictionary representing the hierarchical structure of the
database, in the following format.

    skeleton -- a triple-indexed dictionary
        outer key - table name
            inner key - column name
                inner inner key - one of the following:
        primary_key - boolean, whether column has been set as primary key
        index - boolean, whether column has been set as index
        sql - one of 'TEXT', 'BOOLEAN', 'INTEGER', 'REAL', or other
            user defined type

For example,
{'table1':{'col1':{'primary_key':False, 'index':True, 'sql':'REAL'}}}

INPUT:
    check -- if True, checks to make sure the database's actual structure
    matches the skeleton on record.

EXAMPLES:
    sage: GDB = GraphDatabase()
    sage: GDB.get_skeleton()             # slightly random output
    {u'aut_grp': {u'aut_grp_size': {'index': True,
                        'primary_key': False,
                        'sql': u'INTEGER'},
                        ...
       u'spectrum': {'index': False,
                     'primary_key': False,
                     'sql': u'TEXT'}}}

show(self, table_name, max_field_size=20, html_table=False)

source code 

Show an entire table from the database.

EXAMPLES:
    sage: DB = SQLDatabase()
    sage: DB.create_table('simon',{'a1':{'sql':'bool','primary_key':False}, 'b2':{'sql':'int', 'primary_key':False}})
    sage: DB.add_data('simon',[(0,0),(1,1),(1,2)])
    sage: DB.show('simon')
    a1                   b2                  
    ----------------------------------------
    0                    0                   
    1                    1                   
    1                    2