{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2019-01-19T10:53:16.094220Z",
     "start_time": "2019-01-19T10:53:16.029909Z"
    }
   },
   "outputs": [],
   "source": [
    "from module_generator import ModelDefinitions, create_model_def\n",
    "import io_utils"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2019-01-19T11:14:18.259826Z",
     "start_time": "2019-01-19T11:14:18.231838Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "base_model Base model\n",
      "\tabstract True\n",
      "people People\n",
      "planet Planet\n",
      "cockroachdb://maxroach@localhost:26257/bank\n",
      "{'sslmode': 'disable'}\n",
      "planet\n",
      "people\n",
      "planet\n"
     ]
    }
   ],
   "source": [
    "model_def=create_model_def(\"model_planet.yaml\")\n",
    "db=model_def.database_root\n",
    "print(db['url'])\n",
    "print(str(db['connect_args']))\n",
    "print(model_def.doc_root[\"name\"])\n",
    "for m in model_def.models:\n",
    "    print(m)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2019-01-19T09:26:08.638947Z",
     "start_time": "2019-01-19T09:26:08.632084Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "from sqlalchemy import create_engine\n",
      "from sqlalchemy.ext.declarative import declarative_base\n",
      "from sqlalchemy.orm import scoped_session, sessionmaker\n",
      "\n",
      "## Create database engine: cockroach\n",
      "db_name = 'local cockroachdb'\n",
      "connect_args = {'sslmode': 'disable'}\n",
      "\n",
      "engine = create_engine(\n",
      "    'cockroachdb://maxroach@localhost:26257/bank',\n",
      "    connect_args=connect_args,\n",
      "    echo=True                   # Log SQL queries to stdout\n",
      ")\n",
      "\n",
      "# Declarative base model to create database tables and classes\n",
      "Base = declarative_base()\n",
      "Base.metadata.bind = engine  # Bind engine to metadata of the base class\n",
      "\n",
      "# Create database session object\n",
      "db_session = scoped_session(sessionmaker(bind=engine, expire_on_commit=False))\n",
      "Base.query = db_session.query_property()  # Used by graphql to execute queries\n",
      "\n",
      "\n"
     ]
    }
   ],
   "source": [
    "database_def='''from sqlalchemy import create_engine\n",
    "from sqlalchemy.ext.declarative import declarative_base\n",
    "from sqlalchemy.orm import scoped_session, sessionmaker\n",
    "\n",
    "## Create database engine: cockroach\n",
    "db_name = '{db[name]}'\n",
    "connect_args = {db[connect_args]}\n",
    "\n",
    "engine = create_engine(\n",
    "    '{db[url]}',\n",
    "    connect_args=connect_args,\n",
    "    echo=True                   # Log SQL queries to stdout\n",
    ")\n",
    "\n",
    "# Declarative base model to create database tables and classes\n",
    "Base = declarative_base()\n",
    "Base.metadata.bind = engine  # Bind engine to metadata of the base class\n",
    "\n",
    "# Create database session object\n",
    "db_session = scoped_session(sessionmaker(bind=engine, expire_on_commit=False))\n",
    "Base.query = db_session.query_property()  # Used by graphql to execute queries\n",
    "\n",
    "'''\n",
    "\n",
    "print(database_def.format(db=model_def.database_root))\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2019-01-19T11:01:06.986502Z",
     "start_time": "2019-01-19T11:01:06.962292Z"
    }
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'./output/planet/utils.py'"
      ]
     },
     "execution_count": 3,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "from shutil import copyfile\n",
    "# copyfile(src, dst)\n",
    "prefix=\"./output/\"\n",
    "module_name=\"planet\"\n",
    "module_path=prefix+module_name\n",
    "io_utils.create_dir(module_path)\n",
    "db_path=module_path+\"/database\"\n",
    "seed_path=module_path+\"/database/data\"\n",
    "io_utils.create_dir(seed_path)\n",
    "\n",
    "copyfile(\"./templates/api.py\", module_path+\"/api.py\")\n",
    "copyfile(\"./templates/utils.py\", module_path+\"/utils.py\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2019-01-19T11:11:08.744417Z",
     "start_time": "2019-01-19T11:11:08.738201Z"
    }
   },
   "outputs": [],
   "source": [
    "import os\n",
    "for path in io_utils.list_files(\"./seeds/\"+module_name):\n",
    "    copyfile(path, seed_path+\"/\"+os.path.basename(path))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2019-01-19T11:40:55.133273Z",
     "start_time": "2019-01-19T11:40:55.104479Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "created = Column('created', String,  doc=\"Record created date.\")\n",
      "edited = Column('edited', String,  doc=\"Record last updated date.\")\n"
     ]
    }
   ],
   "source": [
    "## process model extends\n",
    "from module_generator import ModelDefinitions, create_model_def\n",
    "model_def=create_model_def(\"model_planet.yaml\")\n",
    "model=model_def.models['people']\n",
    "\n",
    "field_def='''{fld_name} = Column('{fld_name}', {fld_type}, {pk_part} doc=\"{field[doc]}\")'''\n",
    "field_builder=[]\n",
    "\n",
    "if 'extends' in model:\n",
    "    base_model=model_def.base_models[model['extends']]\n",
    "    for k, fld in base_model['fields'].items():\n",
    "        # print(k)\n",
    "        field_builder.append(field_def.format(fld_name=k, \n",
    "                           fld_type=fld['type'].capitalize(),\n",
    "                           pk_part=\"\",\n",
    "                           field=fld))\n",
    "print(\"\\n\".join(field_builder))        "
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.4"
  },
  "varInspector": {
   "cols": {
    "lenName": 16,
    "lenType": 16,
    "lenVar": 40
   },
   "kernels_config": {
    "python": {
     "delete_cmd_postfix": "",
     "delete_cmd_prefix": "del ",
     "library": "var_list.py",
     "varRefreshCmd": "print(var_dic_list())"
    },
    "r": {
     "delete_cmd_postfix": ") ",
     "delete_cmd_prefix": "rm(",
     "library": "var_list.r",
     "varRefreshCmd": "cat(var_dic_list()) "
    }
   },
   "types_to_exclude": [
    "module",
    "function",
    "builtin_function_or_method",
    "instance",
    "_Feature"
   ],
   "window_display": false
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
