| 1 | from trac.db import DatabaseManager, Table, Column |
|---|
| 2 | from trac.test import EnvironmentStub |
|---|
| 3 | |
|---|
| 4 | def test_db_table(): |
|---|
| 5 | # Create a EnvironmentStub |
|---|
| 6 | env = EnvironmentStub() |
|---|
| 7 | |
|---|
| 8 | # Create a test table |
|---|
| 9 | table = Table('test', key=['id'])[ |
|---|
| 10 | Column('id', type='integer'), |
|---|
| 11 | Column('name', type='text') |
|---|
| 12 | ] |
|---|
| 13 | # Get The Databse Manager |
|---|
| 14 | dbm = DatabaseManager(env) |
|---|
| 15 | # Get the Connector Object for the current DB schema |
|---|
| 16 | connector, args = dbm._get_connector() |
|---|
| 17 | # Ask the connector to generate the proper DDL for the table |
|---|
| 18 | ddl_gen = connector.to_sql(table) |
|---|
| 19 | # Get a DB Connection from the pool, create a cursor and the table |
|---|
| 20 | conn = dbm.get_connection() |
|---|
| 21 | try: |
|---|
| 22 | cursor = conn.cursor() |
|---|
| 23 | for statement in ddl_gen: |
|---|
| 24 | print "Table: %s\n%s" % (table.name, statement) |
|---|
| 25 | cursor.execute(statement) |
|---|
| 26 | conn.commit() |
|---|
| 27 | print "Successfully Created Table %s" % table.name |
|---|
| 28 | except Exception, e: |
|---|
| 29 | conn.rollback() |
|---|
| 30 | print "[ERROR]: Unable to Create Table %s, an error occurred: %s" % \ |
|---|
| 31 | (table.name, str(e)) |
|---|
| 32 | # Now try to do something with the table... |
|---|
| 33 | try: |
|---|
| 34 | cursor = conn.cursor() |
|---|
| 35 | cursor.execute('INSERT INTO test (id, name) VALUES (1, "Name me how you want")') |
|---|
| 36 | conn.commit() |
|---|
| 37 | print "Successfully Inserted 1 row" |
|---|
| 38 | except Exception, e: |
|---|
| 39 | conn.rollback() |
|---|
| 40 | print "[ERROR]: An error occurred: %s" % \ |
|---|
| 41 | (table.name, str(e)) |
|---|
| 42 | |
|---|
| 43 | if __name__ == '__main__': |
|---|
| 44 | test_db_table() |
|---|