Package net.sourceforge.squirrel_sql.plugins.mssql.sql.constraint

Examples of net.sourceforge.squirrel_sql.plugins.mssql.sql.constraint.TableConstraints


  public final static int MSSQL_UNKNOWN = -1;

  public static TableConstraints getTableConstraints(IDatabaseObjectInfo oi, ISQLConnection conn)
    throws java.sql.SQLException
  {
    TableConstraints constraints = new TableConstraints();

    Connection c = conn.getConnection();

    CallableStatement stmt = null;
    ResultSet rs = null;

    try
    {
      stmt = c.prepareCall("{ call sp_helpconstraint ?, ? }");
      stmt.setString(1, oi.getSimpleName());
      stmt.setString(2, "nomsg");

      rs = stmt.executeQuery();

      while (rs.next())
      {
        String constraintType = rs.getString(1);
        String constraintName = rs.getString(2);
        // String deleteAction = rs.getString(3);
        // String updateAction = rs.getString(4);
        // String statusEnabled = rs.getString(5);
        // String statusForReplication = rs.getString(6);
        String constraintKeys = rs.getString(7);

        if (constraintType.startsWith("DEFAULT"))
        {
          DefaultConstraint def = new DefaultConstraint();
          String col = constraintType.substring(18).trim(); // chop off "DEFAULT on column ";

          def.setConstraintName(constraintName);
          def.addConstraintColumn(col);
          def.setDefaultExpression(constraintKeys);

          constraints.addConstraint(def);
        }
        else if (constraintType.startsWith("CHECK"))
        {
          CheckConstraint check = new CheckConstraint();
          String col = constraintType.substring(16).trim(); // chop off "CHECK on column ";

          check.setConstraintName(constraintName);
          check.addConstraintColumn(col);
          check.setCheckExpression(constraintKeys);

          constraints.addConstraint(check);
        }
        else if (constraintType.startsWith("FOREIGN KEY"))
        {
          /* NOTE: there are two rows.
           * NOTE: MssqlConstraint holds the columns in the table participating in the key.
           * NOTE: ForeignKeyConstraint holds the columns in the referenced table IN THE SAME ORDER.
           */
          ForeignKeyConstraint fk = new ForeignKeyConstraint();

          fk.setConstraintName(constraintName);

          String foreignColumns[] = constraintKeys.split(", ");
          for (int i = 0; i < foreignColumns.length; i++)
            fk.addConstraintColumn(foreignColumns[i]);

          rs.next();

          constraintKeys = rs.getString(7);
          // constraintKeys looks like this --> `REFERENCES pubs.dbo.foo (fooid, quuxid)'
          constraintKeys = constraintKeys.substring(11); // chop off "REFERENCES "
          String[] tableAndColumns = constraintKeys.split(" ", 2);
          // now tableAndColumns[0] contains the table name and tableAndColumns[1] contains
          // the bracketed list of columns.
          fk.setReferencedTable(tableAndColumns[0]);
          String primaryColumns[] =
            tableAndColumns[1].substring(1, tableAndColumns[1].length() - 2).split(",");
          for (int i = 0; i < primaryColumns.length; i++)
            fk.addPrimaryColumn(primaryColumns[i]);

          constraints.addConstraint(fk);
        }
        else if (constraintType.startsWith("PRIMARY KEY"))
        {
          PrimaryKeyConstraint pk = new PrimaryKeyConstraint();

          pk.setConstraintName(constraintName);
          pk.setClustered(constraintType.endsWith("(clustered)"));

          String cols[] = constraintKeys.split(", ");
          for (int i = 0; i < cols.length; i++)
            pk.addConstraintColumn(cols[i]);

          constraints.addConstraint(pk);
        }
      }

    }
    catch (java.sql.SQLException ex)
View Full Code Here


  {
    Connection c = conn.getConnection();

    StringBuilder buf = new StringBuilder();

    TableConstraints constraints = MssqlIntrospector.getTableConstraints(oi, conn);

    CallableStatement stmt = null;
    ResultSet rs = null;

    try
    {
      stmt = c.prepareCall("{ call sp_help ? }");
      stmt.setString(1, oi.getSimpleName());

      if (!stmt.execute()) return null;

      /* since .execute() returned true, the first result is a ResultSet. */
      rs = stmt.getResultSet();
      /* Name     Owner       Type        Created_datetime                                      
       * ---------------------------------------------------------
       * billing  dbo         user table  2004-03-08 10:41:05.030
       */
      if (!rs.next()) return null;
      buf.append("CREATE TABLE [");
      buf.append(rs.getString(2));
      buf.append("].[");
      buf.append(rs.getString(1));
      buf.append("] (");
      buf.append("\n");

      if (!stmt.getMoreResults()) return null;
      rs = stmt.getResultSet();
      /* Column_name          Type    Computed    Length  Prec    Scale   Nullable    TrimTrailingBlanks  FixedLenNullInSource    Collation
       * -------------------------------------------------------------------------------------------------------------------------------------------------------
       * Location             char    no          2                       yes         no                  yes                     Latin1_General_CI_AS
       * TotalBilledAmnt      money   no          8       19      4       yes         (n/a)               (n/a)                   NULL
       */
      while (rs.next())
      {
        String colName = rs.getString(1);
        String colType = rs.getString(2);
        buf.append("\t[");
        buf.append(colName);
        buf.append("] [");
        buf.append(colType);
        buf.append("] ");
        if (colType.equals("char") || colType.equals("varchar"))
        {
          buf.append("(");
          buf.append(rs.getInt(4)); // length
          buf.append(") COLLATE ");
          buf.append(rs.getString(10)); // collation
          buf.append(" ");
        }
        if (rs.getString(7).equals("yes")) buf.append("NULL ");
        else buf.append("NOT NULL ");

        if (withConstraints)
        {
          List<DefaultConstraint> defs = constraints.getDefaultsForColumn(colName);
          /* there can be only one default in truth, but the model allows more than one. */

          if (defs != null && defs.size() == 1)
          {
            DefaultConstraint def = defs.get(0);
            buf.append("CONSTRAINT [");
            buf.append(def.getConstraintName());
            buf.append("] DEFAULT ");
            buf.append(def.getDefaultExpression());
            buf.append(" ");
          }
        }

        buf.append(",\n");
      }
    }
    catch (SQLException e)
    {
      s_log.error("generateCreateTableScript: Unexpected exception - " + e.getMessage(), e);
    }
    finally
    {
      closeResultSet(rs);
      closeStatement(stmt);
    }
    if (withConstraints)
    {
      /* there can be only one PK in truth, but the model allows more than one. */
      List<PrimaryKeyConstraint> pks = constraints.getPrimaryKeyConstraints();
      if (pks != null && pks.size() == 1)
      {
        PrimaryKeyConstraint pk = pks.get(0);
        buf.append("\tCONSTRAINT [");
        buf.append(pk.getConstraintName());
        buf.append("] PRIMARY KEY ");
        buf.append(pk.isClustered() ? "CLUSTERED" : "NONCLUSTERED");
        buf.append("\n\t(\n\t\t");
        Object[] cols = pk.getConstraintColumns();
        for (int i = 0; i < cols.length; i++)
        {
          buf.append("[");
          buf.append((String) cols[i]);
          buf.append("]");
          if (i < cols.length - 1) buf.append(", ");
        }
        buf.append("\n\t)\n");
        /* TODO: FILLFACTOR, ON [PRIMARY], etc. */
      }

      List<ForeignKeyConstraint> fks = constraints.getForeignKeyConstraints();
      for (int i = 0; i < fks.size(); i++)
      {
        ForeignKeyConstraint fk = fks.get(i);
        buf.append("\tFOREIGN KEY\n\t(\n\t\t");
        Object[] foreignColumns = fk.getConstraintColumns();
        for (int j = 0; j < foreignColumns.length; j++)
        {
          buf.append("[");
          buf.append((String) foreignColumns[j]);
          buf.append("]");
          if (j < foreignColumns.length - 1) buf.append(", ");
        }
        buf.append("\n\t) REFERENCES [");
        buf.append(fk.getReferencedTable());
        buf.append("] (\n\t\t");
        Object[] primaryColumns = fk.getPrimaryColumns();
        for (int j = 0; j < primaryColumns.length; j++)
        {
          buf.append("[");
          buf.append((String) primaryColumns[j]);
          buf.append("]");
          if (j < primaryColumns.length - 1) buf.append(",\n");
        }
        buf.append("\n\t),");
      }

      for (CheckConstraint check : constraints.getCheckConstraints())
      {
        buf.append("\tCONSTRAINT [");
        buf.append(check.getConstraintName());
        buf.append("] CHECK ");
        buf.append(check.getCheckExpression());
View Full Code Here

    private static final String TEST_COLUMN = "testColumn";
  TableConstraints constraintsUnderTest = null;
   
    @Before
    public void setUp() throws Exception {
        constraintsUnderTest = new TableConstraints();
    }
View Full Code Here

TOP

Related Classes of net.sourceforge.squirrel_sql.plugins.mssql.sql.constraint.TableConstraints

Copyright © 2018 www.massapicom. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.