#!/usr/bin/env python

#
# A very simple benchmark of some Django ORMs
#
# Copyright (C) 2009  Grahame Bowland
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
#

import os, sys, getopt

def make_db(db_path):
    import sqlite3
    conn = sqlite3.connect(db_path)
    c = conn.cursor()
    c.execute("CREATE TABLE test_test (id PRIMARY KEY, i integer);")
    for i in xrange(100000):
        c.execute("INSERT INTO test_test (id, i) VALUES (%d, %d)" % (i, i))
    conn.commit()

def bench_storm():
    import storm
    from storm.locals import create_database, Store, Storm, Int
    class Test(Storm):
        __storm_table__ = 'test_test'
        i = Int(primary=True)
    database = create_database("sqlite:%s" % db_path)
    store = Store(database)
    for obj in store.find(Test):
        pass

def bench_raw():
    import sqlite3
    conn = sqlite3.connect(db_path)
    c = conn.cursor()
    c.execute("SELECT i FROM test_test")
    for row in c:
        pass

def bench_raw_obj():
    import sqlite3
    class DummyObject(object):
        def __init__(self, row):
            self.row = row
    conn = sqlite3.connect(db_path)
    c = conn.cursor()
    c.execute("SELECT i FROM test_test")
    for row in c:
        do = DummyObject(row)
    c.close()

DEBUG = False
DATABASE_ENGINE = "sqlite3"
DATABASE_NAME = "test.db"
def bench_django():
    os.environ['DJANGO_SETTINGS_MODULE'] = 'bench'
    from django.db import models
    class Test(models.Model):
        i = models.IntegerField()
        class Meta:
            app_label = "test"
    for i in Test.objects.all():
        pass

if __name__ == "__main__":
    opt, args = getopt.getopt(sys.argv[1:], "p")
    db_path, fn_name = args

    profile = ('-p', '') in opt

    if not os.access(db_path, os.R_OK):
        make_db(db_path)

    fn = locals()[fn_name]

    if profile:
        import hotshot
        import hotshot.stats

        prof = hotshot.Profile("bench.prof")
        prof.runcall(fn)
        prof.close()

        print >>sys.stderr, "generating profile output"

        stats = hotshot.stats.load("bench.prof")
        stats.strip_dirs()
        stats.sort_stats('time', 'calls')
        stats.print_stats()
    else:
        fn()

# vim: expandtab:ts=4:sw=4:
