Writing a single table in two seperate pages - postgresql

I want to the user details in two seperate pages but for a single table in SQL. For instance
In SQL a table 'user' with fields
username, name, email, password
I need to get name, email, password in one page when clicked next I want to fill out username in a seperate page. But could not resolve how to do it.
To switch pages in frontend using react
<Router>
<Routes>
<Route exact path="/" element={<HomeScreen/>}/>
<Route exact path="/login" element={!isAuthenticated ? <LoginScreen setAuth={setAuth}/> : <Navigate to='/home'/>}/>
<Route exact path="/signup" element={!isAuthenticated ? <SignupScreen setAuth={setAuth}/> : <Navigate to='/username'/>}/>
<Route exact path="/username" element={isSigned? <UsernameScreen setAuth={setAuth}/> : <Navigate to='/home'/>}/>
<Route exact path="/home" element={isAuthenticated? <LoggedScreen setAuth={setAuth}/> : <Navigate to='/login'/>}/>
<Route exact path="/explore" element={isAuthenticated? <ExploreScreen/>: <Navigate to='/login'/>}/>
</Routes>
</Router>
Table Structure in postgres SQL
CREATE TABLE users(
user_id uuid PRIMARY KEY DEFAULT uuid_generate_v4(),
username VARCHAR(255) NOT NULL,
name VARCHAR(255) NOT NULL,
email VARCHAR(255) NOT NULL,
password VARCHAR(255) NOT NULL,
admin numeric DEFAULT 0
);

Related

sqlalchemy many to many relationships (the value of a duplicate key breaks the unique constraint) flask_user role

can you help me,
when i run this script it works well
class User(db.Model, UserMixin):
__tablename__ = 'users'
id = db.Column(db.Integer, primary_key=True)
active = db.Column('is_active', db.Boolean(), nullable=False, server_default='1')
# User authentication information. The collation='NOCASE' is required
# to search case insensitively when USER_IFIND_MODE is 'nocase_collation'.
email = db.Column(db.String(255, collation='NOCASE'), nullable=False, unique=True)
email_confirmed_at = db.Column(db.DateTime())
password = db.Column(db.String(255), nullable=False, server_default='')
# User information
first_name = db.Column(db.String(100, collation='NOCASE'), nullable=False, server_default='')
last_name = db.Column(db.String(100, collation='NOCASE'), nullable=False, server_default='')
# Define the relationship to Role via UserRoles
roles = db.relationship('Role', secondary='user_roles')
# Define the Role data-model
class Role(db.Model):
__tablename__ = 'roles'
id = db.Column(db.Integer(), primary_key=True)
name = db.Column(db.String(50), unique=True)
# Define the UserRoles association table
class UserRoles(db.Model):
__tablename__ = 'user_roles'
id = db.Column(db.Integer(), primary_key=True)
user_id = db.Column(db.Integer(), db.ForeignKey('users.id', ondelete='CASCADE'))
role_id = db.Column(db.Integer(), db.ForeignKey('roles.id', ondelete='CASCADE'))
# Setup Flask-User and specify the User data-model
user_manager = UserManager(app, db, User)
# Create all database tables
db.create_all()
# Create 'member#example.com' user with no roles
if not User.query.filter(User.email == 'member#example.com').first():
user = User(
email='member#example.com',
email_confirmed_at=datetime.datetime.utcnow(),
password=user_manager.hash_password('Password1'),
)
db.session.add(user)
db.session.commit()
# Create 'admin#example.com' user with 'Admin' and 'Agent' roles
if not User.query.filter(User.email == 'admin#example.com').first():
user = User(
email='admin#example.com',
email_confirmed_at=datetime.datetime.utcnow(),
password=user_manager.hash_password('Password1'),
)
user.roles.append(Role(name='Admin'))
user.roles.append(Role(name='Agent'))
db.session.add(user)
db.session.commit()
at this stage the code is working without problems but the problem is just after when I add another user with a role that already exists
in this case the Admin role or the Agent role
for example if I add the code below an error message displays
if not User.query.filter(User.email == 'admin2#example.com').first():
user = User(
email='admin2#example.com',
email_confirmed_at=datetime.datetime.utcnow(),
password=user_manager.hash_password('Password1'),
)
user.roles.append(Role(name='Admin'))
user.roles.append(Role(name='Agent'))
db.session.add(user)
db.session.commit()
sqlalchemy.exc.IntegrityError: (psycopg2.IntegrityError) ERREUR: la valeur d'une clé dupliquée rompt la contrainte unique « roles_name_key »
DETAIL: La clé « (name)=(Admin) » existe déjà.
[SQL: 'INSERT INTO roles (name) VALUES (%(name)s) RETURNING roles.id'] [parameters: {'name': 'Admin'}] (Background on this error at: http://sqlalche.
me/e/gkpj)
I tried db driver different (pg8000, pygresql, py-postgresql) and still the same problem,
as the error message shows the problem because of the name value which is unique
name = db.Column (db.String (50), unique = True)
can you explain to me what is the error that I made, and what is the role of this part of code
# Define the relationship to Role via UserRoles
roles = db.relationship ('Role', secondary = 'user_roles')
I use flask with flask_user

WEB API Entity-Framework Parent Child Posting to SQL Database

I am writing my first WEB-API service based on data that a 3rd party will be sending. Below is the layout they will be sending:
<StandardTitleOrderRequest>
<Authentication>
<UserName>{$USERNAME}</UserName>
<Password>{$PASSWORD}</Password>
</Authentication>
<Borrowers>
<Borrower>
<FirstName>{$BORROWER_FIRST_NAME}</FirstName>
<MiddleName>{$BORROWER_MIDDLE_NAME}</MiddleName>
<LastName>{$BORROWER_LAST_NAME}</LastName>
<SSN>{$BORROWER_SSN}</SSN>
</Borrower>
</Borrowers>-
<Property>
<Address>{$SUBJECT_ADDRESS_STREET}</Address>
<City>{$SUBJECT_ADDRESS_CITY}</City>
<State>{$SUBJECT_ADDRESS_STATE}</State>
<Zip>{$SUBJECT_ADDRESS_ZIP}</Zip>
<County>{$SUBJECT_ADDRESS_COUNTY}</County>
</Property>-
<Contact>
<Name>{$CONTACT_NAME}</Name>
<Phone>{$CONTACT_PHONE}</Phone>
<Fax>{$CONTACT_FAX}</Fax>
<Email>{$CONTACT_EMAIL}</Email>
</Contact>-
<OrderInfo>
<LoanNumber>{$LOAN_NUMBER}</LoanNumber>
<LoanAmount>{$LOAN_AMOUNT}</LoanAmount>
<ToBeInsured/>
<FileNumber>{$FileID}</FileNumber>
<OrderId>{$ORDER_ID}</OrderId >
<CostCenter>{$BRANCH_NAME}</CostCenter>
<Product>{$PRODUCT_NUMBER}</Product>
<Notes>{$ORDER_NOTES}</Notes>
<ResponseURL>{$RESPONSE_URL}</ResponseURL>
<PID></PID>
<PayOffLoanNumber></PayOffLoanNumber>
<ClientCode>{$CLIENT_ID}</ClientCode>
</OrderInfo>
I have created a database with the following 4 tables (Orders, Borrowers, Contacts, Properties) the OrderID is common to each table. The order will have multiple borrowers and 1 contact and 1 property. I have a basic web api built that (using Fiddler) will allow me to GET/POST/PUT/DELETE an order or contact or borrower or property. I am not sure how to add the logic that posts the order and then each of the child elements for that order (borrower(s), contact, property). I am using VS 2017 and EF 6.
I am assuming (perhaps wrongly) that I need to add foreign keys to my tables that reference back to each other and then update the data model but when I do that I start to get various errors.
The 3rd party will be posting 1 transaction at a time so the incoming data will not be in bulk and will be transmitted as XML.
I have tried looking at various tutorials on the whole web api service but 90% of them just deal with a single table POST. Nothing really that goes into specific details about receiving XML data and posting to a parent and 1 or more children. Plus my app will currently only accept the incoming data in JSON format. Below is the code in the OrdersController that will be the basis for the post to the database (POST https://localhost:xxxx/api/Orders)am looking for some direction.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using OrdersDataAccess;
namespace waEtitle.Controllers
{
public class OrdersController : ApiController
{
/// <summary>
/// Get Order Information
/// </summary>
/// <returns></returns>
///
public IEnumerable<Order> Get()
{
using (FirstCloseEntities entities = new FirstCloseEntities())
{
return entities.Orders.ToList();
}
}
public HttpResponseMessage Get(int id)
{
using (FirstCloseEntities entities = new FirstCloseEntities())
{
var entity = entities.Orders.FirstOrDefault(o => o.OrderID == id);
if (entity != null)
{
return Request.CreateResponse(HttpStatusCode.OK, entity);
}
else
{
return Request.CreateErrorResponse(HttpStatusCode.NotFound, "Order with id = " + id.ToString() + " not found.");
}
}
}
public HttpResponseMessage Post([FromBody] Order order)
{
try
{
using (FirstCloseEntities entities = new FirstCloseEntities())
{
entities.Orders.Add(order);
entities.SaveChanges();
var message = Request.CreateResponse(HttpStatusCode.Created, order);
message.Headers.Location = new Uri(Request.RequestUri + order.OrderID.ToString());
return message;
}
}
catch (Exception ex)
{
return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex);
}
}
public HttpResponseMessage Delete(int ID)
{
try
{
using (FirstCloseEntities entities = new FirstCloseEntities())
{
var entity = entities.Orders.FirstOrDefault(c => c.OrderID == ID);
if (entity == null)
{
return Request.CreateErrorResponse(HttpStatusCode.NotFound, "Order with ID = " + ID.ToString() + " not found to delete.");
}
else
{
entities.Orders.Remove(entity);
entities.SaveChanges();
return Request.CreateResponse(HttpStatusCode.OK);
}
}
}
catch (Exception ex)
{
return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex);
}
}
public HttpResponseMessage Put(int id, [FromBody]Order order)
{
try
{
using (FirstCloseEntities entities = new FirstCloseEntities())
{
var entity = entities.Orders.FirstOrDefault(c => c.OrderID== id);
if (entity == null)
{
return Request.CreateErrorResponse(HttpStatusCode.NotFound, "Order with Id = " + id.ToString() + " not found to update.");
}
else
{
entity.LoanNumber = order.LoanNumber;
entity.LoanAmount = order.LoanAmount;
entity.ToBeInsured = order.ToBeInsured;
entity.FileNumber = order.FileNumber;
entity.CostCenter = order.CostCenter;
entity.Product = order.Product;
entity.Notes = order.Notes;
entity.ResponseURL = order.ResponseURL;
entity.PID = order.PID;
entity.PayOffLoanNumber = order.PayOffLoanNumber;
entity.ClientCode = order.ClientCode;
entities.SaveChanges();
return Request.CreateResponse(HttpStatusCode.OK, entity);
}
}
}
catch (Exception ex)
{
return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex);
}
}
}
}
Tables:
/* ==Scripting Parameters==
Source Server Version : SQL Server 2008 R2 (10.50.1617)
Source Database Engine Edition : Microsoft SQL Server Enterprise Edition
Source Database Engine Type : Standalone SQL Server
Target Server Version : SQL Server 2017
Target Database Engine Edition : Microsoft SQL Server Standard Edition
Target Database Engine Type : Standalone SQL Server
*/
USE [FirstCloseAPI]
GO
/****** Object: Table [dbo].[Borrowers] Script Date: 9/26/2017 1:50:18 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Borrowers](
[borID] [int] IDENTITY(1,1) NOT NULL,
[OrderID] [int] NULL,
[FirstName] [varchar](max) NULL,
[MiddleName] [varchar](max) NULL,
[LastName] [varchar](max) NULL,
[SSN] [varchar](max) NULL,
CONSTRAINT [PK_Borrowers] PRIMARY KEY CLUSTERED
(
[borID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO
/****** Object: Table [dbo].[Contacts] Script Date: 9/26/2017 1:50:18 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Contacts](
[conId] [int] IDENTITY(1,1) NOT NULL,
[OrderID] [int] NULL,
[Name] [varchar](max) NULL,
[Phone] [varchar](max) NULL,
[Fax] [varchar](max) NULL,
[Email] [varchar](max) NULL,
CONSTRAINT [PK_Contacts] PRIMARY KEY CLUSTERED
(
[conId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO
/****** Object: Table [dbo].[Orders] Script Date: 9/26/2017 1:50:18 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Orders](
[OrderID] [int] NOT NULL,
[LoanNumber] [varchar](max) NULL,
[LoanAmount] [money] NULL,
[ToBeInsured] [bit] NULL,
[FileNumber] [varchar](max) NULL,
[CostCenter] [varchar](max) NULL,
[Product] [varchar](max) NULL,
[Notes] [varchar](max) NULL,
[ResponseURL] [varchar](max) NULL,
[PID] [int] NULL,
[PayOffLoanNumber] [varchar](max) NULL,
[ClientCode] [varchar](max) NULL,
CONSTRAINT [PK_OrderHeader] PRIMARY KEY CLUSTERED
(
[OrderID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO
/****** Object: Table [dbo].[Properties] Script Date: 9/26/2017 1:50:18 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Properties](
[proID] [int] IDENTITY(1,1) NOT NULL,
[OrderID] [int] NULL,
[Address] [varchar](max) NULL,
[City] [varchar](max) NULL,
[State] [varchar](max) NULL,
[Zip] [varchar](max) NULL,
[County] [varchar](max) NULL,
CONSTRAINT [PK_Property] PRIMARY KEY CLUSTERED
(
[proID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO
ALTER TABLE [dbo].[Borrowers] WITH NOCHECK ADD CONSTRAINT [FK_Borrowers_Orders] FOREIGN KEY([OrderID])
REFERENCES [dbo].[Orders] ([OrderID])
GO
ALTER TABLE [dbo].[Borrowers] NOCHECK CONSTRAINT [FK_Borrowers_Orders]
GO
ALTER TABLE [dbo].[Contacts] WITH NOCHECK ADD CONSTRAINT [FK_Contacts_Orders] FOREIGN KEY([OrderID])
REFERENCES [dbo].[Orders] ([OrderID])
GO
ALTER TABLE [dbo].[Contacts] NOCHECK CONSTRAINT [FK_Contacts_Orders]
GO
ALTER TABLE [dbo].[Properties] WITH NOCHECK ADD CONSTRAINT [FK_Properties_Orders] FOREIGN KEY([OrderID])
REFERENCES [dbo].[Orders] ([OrderID])
GO
ALTER TABLE [dbo].[Properties] NOCHECK CONSTRAINT [FK_Properties_Orders]
GO
Currently my GET is returning
<Order>
<Borrowers />
<ClientCode>cc1</ClientCode>
<Contacts />
<CostCenter>900-111</CostCenter>
<FileNumber>11111</FileNumber>
<LoanAmount>1111.0000</LoanAmount>
<LoanNumber>111</LoanNumber>
<Notes>notes1</Notes>
<OrderID>1</OrderID>
<PID>1</PID>
<PayOffLoanNumber>po1</PayOffLoanNumber>
<Product>letter</Product>
<Properties />
<ResponseURL>yahoo.com</ResponseURL>
<ToBeInsured>true</ToBeInsured>
</Order>
and as you can see there are no contacts or borrowers etc.
**
UPDATE: ---------------------------------------------------
**
I was able to get my Get and GET (int ID) commands to work and return the correct data by changing the procedures as:
public IEnumerable<Order> Get()
{
using (FirstCloseAPIEntities entities = new FirstCloseAPIEntities())
{
var entity = entities.Orders.ToList();
List<Borrower> borrowers = entities.Borrowers.ToList();
List<Contact> contacts = entities.Contacts.ToList();
List<Property> properties = entities.Properties.ToList();
//return entities.Orders.ToList() ;
return entity;
}
}
public HttpResponseMessage Get(int id)
{
using (FirstCloseAPIEntities entities = new FirstCloseAPIEntities())
{
var entity = entities.Orders.FirstOrDefault(o => o.OrderID == id);
List<Borrower> borrowers = entities.Borrowers.Where(b => b.OrderID == id).ToList();
List<Contact> contacts = entities.Contacts.Where(c => c.OrderID == id).ToList();
List<Property> properties = entities.Properties.Where(p => p.OrderID == id).ToList();
if (entity != null)
{
return Request.CreateResponse(HttpStatusCode.OK, entity);
}
else
{
return Request.CreateErrorResponse(HttpStatusCode.NotFound, "Order with id = " + id.ToString() + " not found.");
}
}
}
However, because I am requesting as HTML I then was getting the error:
The 'ObjectContent`1' type failed to serialize the response body for content type 'application/json; charset=utf-8'
So I had to add the following to the Global.asax.cs file:
GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
GlobalConfiguration.Configuration.Formatters.Remove(GlobalConfiguration.Configuration.Formatters.XmlFormatter);
This gave me back a successful response, however, no matter what I put in the headers for type application/xml application/json I am always getting the reponse back as JSON.
Content-Type: application/xml
accept: application/xml
accept-encoding: gzip, deflate
accept-language: en-US,en;q=0.8
user-agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.113 Safari/537.36
Cache-Control: no-cache
Content-Length: 707
Content-Type: application/json; charset=utf-8
Date: Tue, 26 Sep 2017 19:46:42 GMT
Expires: -1
Pragma: no-cache
Server: Microsoft-IIS/10.0
X-Aspnet-Version: 4.0.30319
X-Powered-By: ASP.NET
X-Sourcefiles: =?UTF-8?B?YzpcdXNlcnNcZG91Zy5oYW1pbHRvblxkb2N1bWVudHNcdmlzdWFsIHN0dWRpbyAyMDE3XFByb2plY3RzXHdzRXRpdGxlXHdzRXRpdGxlXGFwaVxPcmRlcnNcMQ==?=
Raw
JSON
{
"OrderID": 1,
"LoanNumber": "111",
"LoanAmount": 1111,
"ToBeInsured": true,
"FileNumber": "11111",
"CostCenter": "900-111",
"Product": "letter",
"Notes": "notes1",
"ResponseURL": "yahoo.com",
"PID": 1,
"PayOffLoanNumber": "po1",
"ClientCode": "cc1",
"Borrowers": [
{
"borID": 1,
"OrderID": 1,
"FirstName": "Ura",
"MiddleName": "O",
"LastName": "Pepper",
"SSN": "111-11-1111"
},
{
"borID": 3,
"OrderID": 1,
"FirstName": "Ima",
"MiddleName": "J",
"LastName": "Pepper",
"SSN": "222-22-2222"
}
],
"Contacts": [
{
"conId": 1,
"OrderID": 1,
"Name": "Jackie the box",
"Phone": "414-555-1243",
"Fax": "414-222-1245",
"Email": "j#test.com"
}
],
"Properties": [
{
"proID": 1,
"OrderID": 1,
"Address": "123 Main Street",
"City": "Anytown",
"State": "WI",
"Zip": "10012
"County": "Westchester"
}
],
}
So I am still confused as to how to get the response in XML and then the last part is to be able to take the information that will be supplied as shown at the top of this post and POST it to the correct tables.
My code changes in the "UPDATED" remarks of my original post allowed me to GET and POST by JSON data to the web api I created on the local host so I was able to work through my issue.
My current additional issues are related to POSTing the data as XML instead of JSON and being able to move the web api to an already existing public facing website. I will post those as separate questions.

First wordpress plugin making

I am making my very first wordpress plugin in that I want to make table in my database when I activate the plugin. I write the code exactly what wordpress community said but it's not working. I tried the same several times but the results is the same. I also want to know my plugin showing 2 submenus in my main plugin menu, It's like
My Plugin
-- My Plugin
-- My Submenu Page
Please help I am very new to plugin development.
// Registering plugin
register_activation_hook(__FILE__, 'myplugin_activate');
//Deactivate plugin
register_deactivation_hook(__FILE__, 'myplugin_deactivate');
function myplugin_activate() {
global $wpdb, $table_prefix;
global $favoritethis_db_version;
$table_name = $table_prefix.
'my-plugin-table';
$charset_collate = $wpdb - > get_charset_collate();
if ($wpdb - > get_var("show tables like '$table_name'") != $table_name) {
require_once(ABSPATH.
'wp-admin/upgrade-functions.php');
$sql = "CREATE TABLE ".$table_name.
" (
id mediumint(9) NOT NULL AUTO_INCREMENT,
time datetime DEFAULT '0000-00-00 00:00:00'
NOT NULL,
name tinytext NOT NULL,
text text NOT NULL,
url varchar(55) DEFAULT ''
NOT NULL,
UNIQUE KEY id(id)
) $charset_collate;
";
}
require_once(ABSPATH.
'wp-admin/includes/upgrade.php');
dbDelta($sql);
}
function myplugin_deactivate() {
// Deactivation code here...
echo "<script>alert('Ohhh.. no baby the plugin is deactivated now..')</script>";
}
also I found the solution of the problem, I was facing as getting extra sub menu as same name as the main menu is.
Solution
//Main admin menus
add_action('admin_menu', 'add_my_custom_menu');
function add_my_custom_menu() {
//add an item to the menu
add_menu_page(
'My Plugin',
'My Plugin',
10,
plugin_dir_path(__FILE__).
'admin/plugin-form.php',
'',
plugin_dir_url(__FILE__).
'img/contact.png'
);
add_submenu_page(
'my-plugin-name/admin/plugin-form.php',
'Plugin Setting',
'Plugin Setting',
10,
plugin_dir_path(__FILE__).
'admin/plugin-form.php',
'myplugin_options_page'
);
add_submenu_page(
'my-plugin-name/admin/plugin-form.php',
'Plugin Entries',
'Plugin Entries',
10,
plugin_dir_path(__FILE__).
'admin/entries.php',
''
);
}
reason is that every first sub-menu's destination page/function will be the same as main menu destination.
ok I got the answer myself
// Registering plugin
register_activation_hook(__FILE__, 'myplugin_activate');
//Deactivate plugin
register_deactivation_hook(__FILE__, 'myplugin_deactivate');
function myplugin_activate() {
global $wpdb;
$table_name = $wpdb - > prefix.
'my-plugin-table';
//nstalled_ver = get_option('my-voting-version');
if ($wpdb - > get_var("show tables like '$table_name' ") != $table_name) {
require_once(ABSPATH.
'wp-admin/upgrade-functions.php');
$sql = "CREATE TABLE IF NOT EXISTS `".str_replace('`', '', $table_name).
"` (
id mediumint(9) NOT NULL AUTO_INCREMENT,
time datetime DEFAULT '0000-00-00 00:00:00'
NOT NULL,
name tinytext NOT NULL,
text text NOT NULL,
url varchar(55) DEFAULT ''
NOT NULL,
UNIQUE KEY id(id)
);
";
}
require_once(ABSPATH.
'wp-admin/includes/upgrade.php');
dbDelta($sql);
}

conditionally execute <selectKey> in MyBatis

I have this problem. I need to execute selectKey to provide me with an id only when the supplied bookTypeId is null. Can it be done?
This is the insert function mapping:
<insert id="insert" parameterType="BookType">
<selectKey resultType="Integer" keyProperty="bookTypeId" order="BEFORE">
SELECT nextval('seq_book_type')
</selectKey>
INSERT INTO book_type(
book_type_id,
book_type_desc
)
VALUES(
#{bookTypeId},
#{bookTypeDesc}
)
</insert>
This is what I did after all:
<insert id="insert" parameterType="BookType">
<selectKey resultType="Integer" keyProperty="bookTypeId" order="BEFORE">
<if test="bookTypeId == null">SELECT nextval('seq_book_type')</if>
<if test="bookTypeId != null">SELECT #{bookTypeId}</if>
</selectKey>
INSERT INTO book_type(
book_type_id,
book_type_desc
)
VALUES(
#{bookTypeId},
#{bookTypeDesc}
)
</insert>
It works like a charm. Please anyone with myBatis experience, let me know if there is a better way than this.

Primary key column(s) (id) are not columns in this table ()

I am following the: http://framework.zend.com/manual/en/learning.quickstart.create-model.html.
Keep hitting wall after wall of issues. My current one is the following error:
An error occurred
Application error
Exception information:
Message: Primary key column(s) (id) are not columns in this table ()
Stack trace:
#0 C:\wamp\www\zendtest\quickstart\library\Zend\Db\Table\Abstract.php(982): Zend_Db_Table_Abstract->_setupPrimaryKey()
#1 C:\wamp\www\zendtest\quickstart\library\Zend\Db\Table\Select.php(100): Zend_Db_Table_Abstract->info()
#2 C:\wamp\www\zendtest\quickstart\library\Zend\Db\Table\Select.php(78): Zend_Db_Table_Select->setTable(Object(Application_Model_DbTable_Guestbook))
#3 C:\wamp\www\zendtest\quickstart\library\Zend\Db\Table\Abstract.php(1018): Zend_Db_Table_Select->__construct(Object(Application_Model_DbTable_Guestbook))
#4 C:\wamp\www\zendtest\quickstart\library\Zend\Db\Table\Abstract.php(1326): Zend_Db_Table_Abstract->select()
#5 C:\wamp\www\zendtest\quickstart\application\models\GuestbookMapper.php(58): Zend_Db_Table_Abstract->fetchAll()
#6 C:\wamp\www\zendtest\quickstart\application\controllers\GuestbookController.php(14): Application_Model_GuestbookMapper->fetchAll()
#7 C:\wamp\www\zendtest\quickstart\library\Zend\Controller\Action.php(516): GuestbookController->indexAction()
#8 C:\wamp\www\zendtest\quickstart\library\Zend\Controller\Dispatcher\Standard.php(295): Zend_Controller_Action->dispatch('indexAction')
#9 C:\wamp\www\zendtest\quickstart\library\Zend\Controller\Front.php(954): Zend_Controller_Dispatcher_Standard->dispatch(Object(Zend_Controller_Request_Http), Object(Zend_Controller_Response_Http))
#10 C:\wamp\www\zendtest\quickstart\library\Zend\Application\Bootstrap\Bootstrap.php(97): Zend_Controller_Front->dispatch()
#11 C:\wamp\www\zendtest\quickstart\library\Zend\Application.php(366): Zend_Application_Bootstrap_Bootstrap->run()
#12 C:\wamp\www\zendtest\quickstart\public\index.php(26): Zend_Application->run()
#13 {main}
Request Parameters:
array (
'controller' => 'guestbook',
'action' => 'index',
'module' => 'default',
)
But I am sure my table has a primary key id for table:
CREATE TABLE guestbook (
id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
email VARCHAR(32) NOT NULL DEFAULT 'noemail#test.com',
comment TEXT NULL,
created DATETIME NOT NULL
);
CREATE INDEX "id" ON "guestbook" ("id");
Don't understand why getting error.
How can I see if it is even picking up the right database
Zend_Db_Table_Abstract contains a protected property called _primary which defaults to id.
It assumes that id is the table's primary key and is a sequence (auto increment).
Since your table definition says that id is a primary key, you should get rid of the second SQL command that adds an index on the id column. Since its already a primary key, it is an index.
Delete the table and re-create it using the create table statement you have in your question, just don't do the CREATE INDEX part. After that you should be able to continue.
I think that your SQL schema is incorrect. Try to create table with primary kyy like this:
CREATE TABLE guestbook (
id INTEGER NOT NULL AUTO_INCREMENT,
email VARCHAR(32) NOT NULL DEFAULT 'noemail#test.com',
comment TEXT NULL,
created DATETIME NOT NULL,
PRIMARY KEY (id)
);
This error might be induced by (accidentally) using md5(null) as the cache ID. Or any other customary values, for that matter, e.g. 1, 0, true, false. However, null is very likely to be the culprit in this context, as it could be produced by an undefined variable.
A fix could be as simple as:
$cache = Zend_Registry::get('cache');
$cache->remove(md5(null));
I had the same issue. The problem was that database was created in guestbook-dev.db instead of guestbook.db. You can check it by looking into this files. The solution was to change scripts/load.sqlite.php from
defined('APPLICATION_ENV')
|| define('APPLICATION_ENV', (null === $env) ? 'development' : $env);
to:
defined('APPLICATION_ENV')
|| define('APPLICATION_ENV', (null === $env) ? 'production' : $env);
and, of course, running the script once again.